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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
238da2b71784eba36b2310387191e5378280bb93 | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /hott/init/hedberg.hlean | 603f23797348ad06a0e2f3e622406a38e083fbd4 | [
"Apache-2.0"
] | permissive | jroesch/lean | 30ef0860fa905d35b9ad6f76de1a4f65c9af6871 | 3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2 | refs/heads/master | 1,586,090,835,348 | 1,455,142,203,000 | 1,455,142,277,000 | 51,536,958 | 1 | 0 | null | 1,455,215,811,000 | 1,455,215,811,000 | null | UTF-8 | Lean | false | false | 1,513 | hlean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
Hedberg's Theorem: every type with decidable equality is a hset
-/
prelude
import init.trunc
open eq eq.ops nat is_trunc sigma
-- TODO(Leo): move const coll and path_coll to a different file?
private definition const {A B : Type} (f : A → B) := ∀ x y, f x = f y
private definition coll (A : Type) := Σ f : A → A, const f
private definition path_coll (A : Type) := ∀ x y : A, coll (x = y)
section
parameter {A : Type}
hypothesis [h : decidable_eq A]
variables {x y : A}
private definition pc [reducible] : path_coll A :=
λ a b, decidable.rec_on (h a b)
(λ p : a = b, ⟨(λ q, p), λ q r, rfl⟩)
(λ np : ¬ a = b, ⟨(λ q, q), λ q r, absurd q np⟩)
private definition f [reducible] : x = y → x = y :=
sigma.rec_on (pc x y) (λ f c, f)
private definition f_const (p q : x = y) : f p = f q :=
sigma.rec_on (pc x y) (λ f c, c p q)
private definition aux (p : x = y) : p = (f (refl x))⁻¹ ⬝ (f p) :=
have aux : refl x = (f (refl x))⁻¹ ⬝ (f (refl x)), from
eq.rec_on (f (refl x)) rfl,
eq.rec_on p aux
definition is_hset_of_decidable_eq : is_hset A :=
is_hset.mk A (λ x y p q, calc
p = (f (refl x))⁻¹ ⬝ (f p) : aux
... = (f (refl x))⁻¹ ⬝ (f q) : f_const
... = q : aux)
end
attribute is_hset_of_decidable_eq [instance] [priority 600]
|
a93cf0207f5c32ab6eedc90bba57a05ac0e5e038 | 947b78d97130d56365ae2ec264df196ce769371a | /stage0/src/Lean/Compiler/ConstFolding.lean | b335c824baf6268a5a5591a1b2bc0e0ebd87bce3 | [
"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 | 6,870 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Expr
import Lean.Compiler.Util
/- Constant folding for primitives that have special runtime support. -/
namespace Lean
namespace Compiler
def BinFoldFn := Bool → Expr → Expr → Option Expr
def UnFoldFn := Bool → Expr → Option Expr
def mkUIntTypeName (nbytes : Nat) : Name :=
mkNameSimple ("UInt" ++ toString nbytes)
structure NumScalarTypeInfo :=
(nbits : Nat)
(id : Name := mkUIntTypeName nbits)
(ofNatFn : Name := mkNameStr id "ofNat")
(toNatFn : Name := mkNameStr id "toNat")
(size : Nat := 2^nbits)
def numScalarTypes : List NumScalarTypeInfo :=
[{nbits := 8}, {nbits := 16}, {nbits := 32}, {nbits := 64},
{id := `USize, nbits := System.Platform.numBits}]
def isOfNat (fn : Name) : Bool :=
numScalarTypes.any (fun info => info.ofNatFn == fn)
def isToNat (fn : Name) : Bool :=
numScalarTypes.any (fun info => info.toNatFn == fn)
def getInfoFromFn (fn : Name) : List NumScalarTypeInfo → Option NumScalarTypeInfo
| [] => none
| info::infos =>
if info.ofNatFn == fn then some info
else getInfoFromFn infos
def getInfoFromVal : Expr → Option NumScalarTypeInfo
| Expr.app (Expr.const fn _ _) _ _ => getInfoFromFn fn numScalarTypes
| _ => none
@[export lean_get_num_lit]
def getNumLit : Expr → Option Nat
| Expr.lit (Literal.natVal n) _ => some n
| Expr.app (Expr.const fn _ _) a _ => if isOfNat fn then getNumLit a else none
| _ => none
def mkUIntLit (info : NumScalarTypeInfo) (n : Nat) : Expr :=
mkApp (mkConst info.ofNatFn) (mkNatLit (n%info.size))
def mkUInt32Lit (n : Nat) : Expr :=
mkUIntLit {nbits := 32} n
def foldBinUInt (fn : NumScalarTypeInfo → Bool → Nat → Nat → Nat) (beforeErasure : Bool) (a₁ a₂ : Expr) : Option Expr := do
n₁ ← getNumLit a₁;
n₂ ← getNumLit a₂;
info ← getInfoFromVal a₁;
pure $ mkUIntLit info (fn info beforeErasure n₁ n₂)
def foldUIntAdd := foldBinUInt $ fun _ _ => HasAdd.add
def foldUIntMul := foldBinUInt $ fun _ _ => HasMul.mul
def foldUIntDiv := foldBinUInt $ fun _ _ => HasDiv.div
def foldUIntMod := foldBinUInt $ fun _ _ => HasMod.mod
def foldUIntSub := foldBinUInt $ fun info _ a b => (a + (info.size - b))
def preUIntBinFoldFns : List (Name × BinFoldFn) :=
[(`add, foldUIntAdd), (`mul, foldUIntMul), (`div, foldUIntDiv),
(`mod, foldUIntMod), (`sub, foldUIntSub)]
def uintBinFoldFns : List (Name × BinFoldFn) :=
numScalarTypes.foldl (fun r info => r ++ (preUIntBinFoldFns.map (fun ⟨suffix, fn⟩ => (info.id ++ suffix, fn)))) []
def foldNatBinOp (fn : Nat → Nat → Nat) (a₁ a₂ : Expr) : Option Expr := do
n₁ ← getNumLit a₁;
n₂ ← getNumLit a₂;
pure $ mkNatLit (fn n₁ n₂)
def foldNatAdd (_ : Bool) := foldNatBinOp HasAdd.add
def foldNatMul (_ : Bool) := foldNatBinOp HasMul.mul
def foldNatDiv (_ : Bool) := foldNatBinOp HasDiv.div
def foldNatMod (_ : Bool) := foldNatBinOp HasMod.mod
-- TODO: add option for controlling the limit
def natPowThreshold := 256
def foldNatPow (_ : Bool) (a₁ a₂ : Expr) : Option Expr := do
n₁ ← getNumLit a₁;
n₂ ← getNumLit a₂;
if n₂ < natPowThreshold then pure $ mkNatLit (n₁ ^ n₂) else none
def mkNatEq (a b : Expr) : Expr :=
mkAppN (mkConst `Eq [levelOne]) #[(mkConst `Nat), a, b]
def mkNatLt (a b : Expr) : Expr :=
mkAppN (mkConst `HasLt.lt [levelZero]) #[mkConst `Nat, mkConst `Nat.HasLt, a, b]
def mkNatLe (a b : Expr) : Expr :=
mkAppN (mkConst `HasLt.le [levelZero]) #[mkConst `Nat, mkConst `Nat.HasLe, a, b]
def toDecidableExpr (beforeErasure : Bool) (pred : Expr) (r : Bool) : Expr :=
match beforeErasure, r with
| false, true => mkDecIsTrue neutralExpr neutralExpr
| false, false => mkDecIsFalse neutralExpr neutralExpr
| true, true => mkDecIsTrue pred (mkLcProof pred)
| true, false => mkDecIsFalse pred (mkLcProof pred)
def foldNatBinPred (mkPred : Expr → Expr → Expr) (fn : Nat → Nat → Bool)
(beforeErasure : Bool) (a₁ a₂ : Expr) : Option Expr := do
n₁ ← getNumLit a₁;
n₂ ← getNumLit a₂;
pure $ toDecidableExpr beforeErasure (mkPred a₁ a₂) (fn n₁ n₂)
def foldNatDecEq := foldNatBinPred mkNatEq (fun a b => a = b)
def foldNatDecLt := foldNatBinPred mkNatLt (fun a b => a < b)
def foldNatDecLe := foldNatBinPred mkNatLe (fun a b => a ≤ b)
def natFoldFns : List (Name × BinFoldFn) :=
[(`Nat.add, foldNatAdd),
(`Nat.mul, foldNatMul),
(`Nat.div, foldNatDiv),
(`Nat.mod, foldNatMod),
(`Nat.pow, foldNatPow),
(`Nat.pow._main, foldNatPow),
(`Nat.decEq, foldNatDecEq),
(`Nat.decLt, foldNatDecLt),
(`Nat.decLe, foldNatDecLe)]
def getBoolLit : Expr → Option Bool
| Expr.const `Bool.true _ _ => some true
| Expr.const `Bool.false _ _ => some false
| _ => none
def foldStrictAnd (_ : Bool) (a₁ a₂ : Expr) : Option Expr :=
let v₁ := getBoolLit a₁;
let v₂ := getBoolLit a₂;
match v₁, v₂ with
| some true, _ => a₂
| some false, _ => a₁
| _, some true => a₁
| _, some false => a₂
| _, _ => none
def foldStrictOr (_ : Bool) (a₁ a₂ : Expr) : Option Expr :=
let v₁ := getBoolLit a₁;
let v₂ := getBoolLit a₂;
match v₁, v₂ with
| some true, _ => a₁
| some false, _ => a₂
| _, some true => a₂
| _, some false => a₁
| _, _ => none
def boolFoldFns : List (Name × BinFoldFn) :=
[(`strictOr, foldStrictOr), (`strictAnd, foldStrictAnd)]
def binFoldFns : List (Name × BinFoldFn) :=
boolFoldFns ++ uintBinFoldFns ++ natFoldFns
def foldNatSucc (_ : Bool) (a : Expr) : Option Expr := do
n ← getNumLit a;
pure $ mkNatLit (n+1)
def foldCharOfNat (beforeErasure : Bool) (a : Expr) : Option Expr := do
guard (!beforeErasure);
n ← getNumLit a;
pure $
if isValidChar n.toUInt32 then mkUInt32Lit n
else mkUInt32Lit 0
def foldToNat (_ : Bool) (a : Expr) : Option Expr := do
n ← getNumLit a;
pure $ mkNatLit n
def uintFoldToNatFns : List (Name × UnFoldFn) :=
numScalarTypes.foldl (fun r info => (info.toNatFn, foldToNat) :: r) []
def unFoldFns : List (Name × UnFoldFn) :=
[(`Nat.succ, foldNatSucc),
(`Char.ofNat, foldCharOfNat)]
++ uintFoldToNatFns
def findBinFoldFn (fn : Name) : Option BinFoldFn :=
binFoldFns.lookup fn
def findUnFoldFn (fn : Name) : Option UnFoldFn :=
unFoldFns.lookup fn
@[export lean_fold_bin_op]
def foldBinOp (beforeErasure : Bool) (f : Expr) (a : Expr) (b : Expr) : Option Expr :=
match f with
| Expr.const fn _ _ => do
foldFn ← findBinFoldFn fn;
foldFn beforeErasure a b
| _ => none
@[export lean_fold_un_op]
def foldUnOp (beforeErasure : Bool) (f : Expr) (a : Expr) : Option Expr :=
match f with
| Expr.const fn _ _ => do
foldFn ← findUnFoldFn fn;
foldFn beforeErasure a
| _ => none
end Compiler
end Lean
|
7eba441ba05359761e6ef1ea89e2bf251a9212a1 | e38e95b38a38a99ecfa1255822e78e4b26f65bb0 | /src/certigrad/estimators.lean | 0b32e6b83125198d6727a6df0be8e3792f884c32 | [
"Apache-2.0"
] | permissive | ColaDrill/certigrad | fefb1be3670adccd3bed2f3faf57507f156fd501 | fe288251f623ac7152e5ce555f1cd9d3a20203c2 | refs/heads/master | 1,593,297,324,250 | 1,499,903,753,000 | 1,499,903,753,000 | 97,075,797 | 1 | 0 | null | 1,499,916,210,000 | 1,499,916,210,000 | null | UTF-8 | Lean | false | false | 13,312 | lean | /-
Copyright (c) 2017 Daniel Selsam. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Daniel Selsam
Estimators.
-/
import .util .tactics .tensor .id .graph .expected_value .tgrads
namespace certigrad
namespace estimators
open list
lemma score {ishapes : list S} {oshape tshape : S} (op : rand.op ishapes oshape) (args : T tshape → dvec T ishapes) (θ : T tshape)
(H_op_pre : op^.pre (args θ))
(f : T oshape → ℝ)
(H_pdf_diff : ∀ (v : T oshape), T.is_cdifferentiable (λ x₀, op^.pdf (args x₀) v) θ)
(H_f_uint : T.is_uniformly_integrable_around (λ θ₀ x, rand.op.pdf op (args θ₀) x ⬝ f x) θ)
(H_f_grad_uint : T.is_uniformly_integrable_around (λ θ₀ x, ∇ (λ θ₀, rand.op.pdf op (args θ₀) x ⬝ f x) θ₀) θ) :
∇ (λ θ₀, E (sprog.prim op (args θ₀)) (λ x, f x^.head)) θ
=
E (sprog.prim op (args θ)) (λ x₀, f x₀^.head ⬝ ∇ (λ θ₀, T.log (op^.pdf (args θ₀) x₀^.head)) θ) :=
have H_pdf_pos : ∀ x, op^.pdf (args θ) x > 0, from rand.op.pdf_pos op (args θ) H_op_pre,
have H_f_diff : ∀ x, T.is_cdifferentiable (λ θ₀, rand.op.pdf op (args θ₀) x ⬝ f x) θ, from
assume x, iff.mp (T.is_cdifferentiable_fscale _ _ _) (H_pdf_diff x),
begin
dunfold E T.dintegral,
erw T.grad_integral _ _ H_f_diff H_f_uint H_f_grad_uint,
apply congr_arg,
apply funext,
intro x,
dunfold dvec.head rand.op.pdf,
rw (T.grad_log_f θ _ (H_pdf_pos x)),
erw [-T.smul_group, -T.smul_group],
dsimp,
rw [mul_assoc, mul_comm (f x), -mul_assoc],
rw (T.mul_inv_cancel (H_pdf_pos x)),
rw one_mul,
rw -T.grad_scale_f,
apply T.grad_congr, intro y, rw T.smul_comm
end
lemma pathwise {ishapes : list S} {oshape tshape : S} {f : T oshape → T tshape → ℝ}
(op : rand.op ishapes oshape) (args : dvec T ishapes) (θ : T tshape)
(H_f_diff : ∀ (x : T oshape), T.is_cdifferentiable (f x) θ)
(H_uint : T.is_uniformly_integrable_around (λ θ₀ x, rand.op.pdf op args x ⬝ f x θ₀) θ)
(H_grad_uint : T.is_uniformly_integrable_around (λ θ₀ x, ∇ (λ θ₁, rand.op.pdf op args x ⬝ f x θ₁) θ₀) θ) :
∇ (λ θ₀, E (sprog.prim op args) (λ x, f x^.head θ₀)) θ
=
E (sprog.prim op args) (λ x, ∇ (λ θ₀, f x^.head θ₀) θ) :=
show ∇ (λ (θ₀ : T tshape), ∫ (λ (x : T oshape), op^.pdf args x ⬝ f x θ₀)) θ
=
∫ (λ (x : T oshape), op^.pdf args x ⬝ ∇ (λ (θ₀ : T tshape), f x θ₀) θ), from
have H_pdf_f_diff : ∀ x, T.is_cdifferentiable (λ θ₀, op^.pdf args x ⬝ f x θ₀) θ, from
assume x, iff.mp (T.is_cdifferentiable_scale_f _ _ _) (H_f_diff x),
suffices H_suffices :
∫ (λ (x : T oshape), ∇ (λ (θ₀ : T tshape), op^.pdf args x ⬝ f x θ₀) θ)
=
∫ (λ (x : T oshape), op^.pdf args x ⬝ ∇ (λ (θ₀ : T tshape), f x θ₀) θ), from
begin rw T.grad_integral _ _ H_pdf_f_diff H_uint H_grad_uint, exact H_suffices end,
suffices H_suffices : ∀ (x : T oshape),
∇ (λ (θ₀ : T tshape), op^.pdf args x ⬝ f x θ₀) θ
=
op^.pdf args x ⬝ ∇ (λ (θ₀ : T tshape), f x θ₀) θ, begin apply T.integral_congr, exact H_suffices end,
assume (x : T oshape),
by apply T.grad_scale_f
lemma hybrid_general {parents : list reference} {tgt : reference} {oshape : S} (m : env)
(H_tgt_in_inputs : env.has_key tgt m)
(op : rand.op parents^.p2 oshape)
(H_op_pre : op^.pre (env.get_ks parents m))
(f : T oshape → T tgt.2 → ℝ)
-- Just a convenience, so we can write θ
-- TODO(dhs): when I make θ implicit, nothing happens
(θ : T tgt.2) (H_θ : θ = env.get tgt m)
(H_f_diff : ∀ (x : T oshape), T.is_cdifferentiable (f x) θ)
(H_f_uint : T.is_uniformly_integrable_around (λ (θ₀ : T (tgt.snd)) (x : T oshape), rand.op.pdf op (env.get_ks parents (env.insert tgt θ m)) x ⬝ f x θ₀) θ)
(H_f_grad_uint : T.is_uniformly_integrable_around (λ (θ₀ : T (tgt.snd)) (x : T oshape), ∇ (λ (θ₁ : T (tgt.snd)), rand.op.pdf op (env.get_ks parents (env.insert tgt θ m)) x ⬝ f x θ₁) θ₀) θ)
(H_d'_pdf_diff : ∀ {idx : ℕ}, at_idx parents idx tgt →
∀ (v : T oshape), T.is_cdifferentiable (λ (x₀ : T (tgt.snd)), rand.op.pdf op (dvec.update_at x₀ (env.get_ks parents (env.insert tgt θ m)) idx) v) θ)
(H_d'_uint : ∀ {idx : ℕ}, at_idx parents idx tgt →
T.is_uniformly_integrable_around (λ (θ₀ : T (tgt.snd)) (x : T oshape),
rand.op.pdf op (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ m)) idx) x ⬝ f x θ) θ)
(H_d'_grad_uint : ∀ {idx : ℕ}, at_idx parents idx tgt →
T.is_uniformly_integrable_around (λ (θ₀ : T (tgt.snd)) (x : T oshape),
∇ (λ (θ₀ : T (tgt.snd)), rand.op.pdf op (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ m)) idx) x ⬝ f x θ) θ₀) θ)
:
let g : dvec T parents^.p2 → T tgt.2 → ℝ := (λ (xs : dvec T parents^.p2) (θ : T tgt.2), E (sprog.prim op xs) (λ (y : dvec T [oshape]), f y^.head θ)) in
∀ (H_diff₁ : T.is_cdifferentiable (λ (θ₀ : T (tgt.snd)), g (env.get_ks parents (env.insert tgt θ m)) θ₀) θ)
(H_diff₂ : T.is_cdifferentiable (λ (θ₀ : T (tgt.snd)), sumr (map (λ (idx : ℕ), g (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ m)) idx) θ)
(filter (λ (idx : ℕ), tgt = dnth parents idx) (riota (length parents))))) θ)
(H_int₁ : E.is_eintegrable (sprog.prim op (env.get_ks parents (env.insert tgt θ m))) (λ (x : dvec T [oshape]), ∇ (f x^.head) θ))
(H_int₂ : E.is_eintegrable (sprog.prim op (env.get_ks parents (env.insert tgt θ m)))
(λ (x : dvec T [oshape]), sumr (map (λ (idx : ℕ), f x^.head θ ⬝ ∇ (λ (θ₀ : T (tgt.snd)), T.log (rand.op.pdf op (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ m)) idx) (dvec.head x))) θ) (filter (λ (idx : ℕ), tgt = dnth parents idx) (riota (length parents)))))),
∇ (λ θ₀, E (sprog.prim op (env.get_ks parents (env.insert tgt θ₀ m))) (λ x₀, f x₀^.head θ₀)) θ
=
E (sprog.prim op (env.get_ks parents (env.insert tgt θ m)))
(λ x₀, ∇ (λ θ₀, f x₀^.head θ₀) θ
+ sumr (map (λ (idx : ℕ),
f x₀^.head θ ⬝ ∇ (λ θ₀, T.log (op^.pdf (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ m)) idx) x₀^.head)) θ)
(filter (λ idx, tgt = dnth parents idx) (riota $ length parents)))) :=
let g : dvec T parents^.p2 → T tgt.2 → ℝ := (λ (xs : dvec T parents^.p2) (θ : T tgt.2), E (sprog.prim op xs) (λ (y : dvec T [oshape]), f y^.head θ)) in
assume H_diff₁ H_diff₂ H_int₁ H_int₂,
show
∇ (λ θ₀, g (env.get_ks parents (env.insert tgt θ₀ m)) θ₀) θ
=
E (sprog.prim op (env.get_ks parents (env.insert tgt θ m)))
(λ x₀, ∇ (λ θ₀, f x₀^.head θ₀) θ
+ sumr (map (λ (idx : ℕ),
f x₀^.head θ ⬝ ∇ (λ θ₀, T.log (op^.pdf (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ m)) idx) x₀^.head)) θ)
(filter (λ idx, tgt = dnth parents idx) (riota $ length parents)))), from
suffices H_suffices :
∇ (λ (θ₀ : T tgt.2),
E (sprog.prim op (env.get_ks parents (env.insert tgt θ m)))
(λ (y : dvec T [oshape]), f y^.head θ₀))
θ
+
sumr (map (λ (idx : ℕ),
∇ (λ (θ₀ : T tgt.2),
E (sprog.prim op (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ m)) idx))
(λ (y : dvec T [oshape]), f y^.head θ))
θ)
(filter (λ (idx : ℕ), tgt = dnth parents idx) (riota (length parents))))
=
E (sprog.prim op (env.get_ks parents (env.insert tgt θ m)))
(λ (x₀ : dvec T [oshape]), ∇ (λ (θ₀ : T tgt.2), f x₀^.head θ₀) θ)
+
E (sprog.prim op (env.get_ks parents (env.insert tgt θ m)))
(λ (x₀ : dvec T [oshape]),
sumr (map (λ (idx : ℕ),
f x₀^.head θ ⬝ ∇ (λ (θ₀ : T tgt.2), T.log (op^.pdf (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ m)) idx) x₀^.head)) θ)
(filter (λ (idx : ℕ), tgt = dnth parents idx) (riota (length parents))))), from
begin
rw T.multiple_args_general, revert g, dsimp, rw E.E_add _ _ _ H_int₁ H_int₂, exact H_suffices, exact H_diff₁, exact H_diff₂
end,
have H_term₁ :
∇ (λ (θ₀ : T tgt.2),
E (sprog.prim op (env.get_ks parents (env.insert tgt θ m)))
(λ (y : dvec T [oshape]), f y^.head θ₀))
θ
=
E (sprog.prim op (env.get_ks parents (env.insert tgt θ m)))
(λ (x₀ : dvec T [oshape]), ∇ (λ (θ₀ : T tgt.2), f x₀^.head θ₀) θ), from
pathwise _ _ _ H_f_diff H_f_uint H_f_grad_uint,
suffices H_suffices :
sumr (map (λ (idx : ℕ),
∇ (λ (θ₀ : T tgt.2),
E (sprog.prim op (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ m)) idx))
(λ (y : dvec T [oshape]), f y^.head θ))
θ)
(filter (λ (idx : ℕ), tgt = dnth parents idx) (riota (length parents))))
=
E (sprog.prim op (env.get_ks parents (env.insert tgt θ m)))
(λ (x₀ : dvec T [oshape]),
sumr (map (λ (idx : ℕ),
f x₀^.head θ ⬝ ∇ (λ (θ₀ : T tgt.2), T.log (op^.pdf (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ m)) idx) x₀^.head)) θ)
(filter (λ (idx : ℕ), tgt = dnth parents idx) (riota (length parents))))), begin rw H_term₁, apply congr_arg, exact H_suffices end,
suffices H_suffices :
sumr (map (λ (idx : ℕ),
∇ (λ (θ₀ : T tgt.2),
E (sprog.prim op (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ m)) idx))
(λ (y : dvec T [oshape]), f y^.head θ))
θ)
(filter (λ (idx : ℕ), tgt = dnth parents idx) (riota (length parents))))
=
sumr (map (λ (x : ℕ),
E (sprog.prim op (env.get_ks parents (env.insert tgt θ m)))
(λ (y : dvec T [oshape]),
f y^.head θ ⬝ ∇ (λ (θ₀ : T tgt.2),
T.log (op^.pdf (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ m)) x) y^.head)) θ))
(filter (λ (idx : ℕ), tgt = dnth parents idx) (riota (length parents)))), from
begin rw -E.E_pull_out_of_sum _ _ _ _ _ H_int₂, exact H_suffices, rw H_θ, rw env.insert_get_same H_tgt_in_inputs, exact H_op_pre end,
suffices H_suffices :
∀ (idx : ℕ), idx ∈ riota (length parents) → tgt = dnth parents idx →
∇ (λ (θ₀ : T tgt.2),
E (sprog.prim op (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ m)) idx))
(λ (y : dvec T [oshape]), f y^.head θ))
θ
=
E (sprog.prim op (env.get_ks parents (env.insert tgt θ m)))
(λ (y : dvec T [oshape]),
f y^.head θ ⬝ ∇ (λ (θ₀ : T tgt.2),
T.log (op^.pdf (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ m)) idx) y^.head)) θ), from
begin apply congr_arg, apply map_filter_congr, exact H_suffices end,
assume (idx : ℕ)
(H_idx_in_riota : idx ∈ riota (length parents))
(H_tgt_eq_dnth_idx : tgt = dnth parents idx),
let mk_args : T tgt.2 → dvec T parents^.p2 :=
(λ (v : T tgt.2),
dvec.update_at v (env.get_ks parents (env.insert tgt θ m)) idx) in
show
∇ (λ (θ₀ : T tgt.2),
E (sprog.prim op (mk_args θ₀))
(λ (y : dvec T [oshape]), f y^.head θ))
θ
=
E (sprog.prim op (env.get_ks parents (env.insert tgt θ m)))
(λ (y : dvec T [oshape]),
f y^.head θ ⬝ ∇ (λ (θ₀ : T tgt.2),
T.log (op^.pdf (dvec.update_at θ₀ (env.get_ks parents (env.insert tgt θ m)) idx) y^.head)) θ), from
have H_idx_lt_len_parents : idx < length parents, from in_riota_lt H_idx_in_riota,
have H_tgt_at_idx : at_idx parents idx tgt, from ⟨in_riota_lt H_idx_in_riota, H_tgt_eq_dnth_idx⟩,
have H_tgt_in_parents : tgt ∈ parents, from mem_of_at_idx H_tgt_at_idx,
have H_op'_pre : op^.pre (mk_args θ),
begin dsimp, rw H_θ, rw env.insert_get_same H_tgt_in_inputs, rw (env.dvec_update_at_env _ H_tgt_at_idx), exact H_op_pre end,
suffices H_suffices :
E (sprog.prim op (dvec.update_at θ (env.get_ks parents (env.insert tgt θ m)) idx))
(λ (x₀ : dvec T [oshape]),
f x₀^.head θ ⬝ ∇ (λ (θ₀ : T tgt.2), T.log (op^.pdf (mk_args θ₀) x₀^.head)) θ)
=
E (sprog.prim op (env.get_ks parents (env.insert tgt θ m)))
(λ (y : dvec T [oshape]),
f y^.head θ ⬝ ∇ (λ (θ₀ : T tgt.2), T.log (op^.pdf (mk_args θ₀) y^.head)) θ),
begin rw (score op mk_args θ H_op'_pre (λ y, f y θ) (H_d'_pdf_diff H_tgt_at_idx) (H_d'_uint H_tgt_at_idx) (H_d'_grad_uint H_tgt_at_idx)),
exact H_suffices end,
have H_remove_dvec_update : dvec.update_at θ (env.get_ks parents (env.insert tgt θ m)) idx = env.get_ks parents (env.insert tgt θ m),
begin
rw [H_θ, env.insert_get_same H_tgt_in_inputs],
rw (env.dvec_update_at_env m ⟨H_idx_lt_len_parents, H_tgt_eq_dnth_idx⟩)
end,
by rw H_remove_dvec_update
end estimators
end certigrad
|
77207b1cdc009d3daa9f9f4429663abab9eeb2c6 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/pnat/factors.lean | 2786a692510db701dd5260f857bc105e7406cc38 | [
"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 | 14,411 | lean | /-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Neil Strickland
-/
import data.pnat.prime
import data.multiset.sort
/-!
# Prime factors of nonzero naturals
This file defines the factorization of a nonzero natural number `n` as a multiset of primes,
the multiplicity of `p` in this factors multiset being the p-adic valuation of `n`.
## Main declarations
* `prime_multiset`: Type of multisets of prime numbers.
* `factor_multiset n`: Multiset of prime factors of `n`.
-/
/-- The type of multisets of prime numbers. Unique factorization
gives an equivalence between this set and ℕ+, as we will formalize
below. -/
@[derive [inhabited, has_repr, canonically_ordered_add_monoid, distrib_lattice,
semilattice_sup, order_bot, has_sub, has_ordered_sub]]
def prime_multiset := multiset nat.primes
namespace prime_multiset
/-- The multiset consisting of a single prime -/
def of_prime (p : nat.primes) : prime_multiset := ({p} : multiset nat.primes)
theorem card_of_prime (p : nat.primes) : multiset.card (of_prime p) = 1 := rfl
/-- We can forget the primality property and regard a multiset
of primes as just a multiset of positive integers, or a multiset
of natural numbers. In the opposite direction, if we have a
multiset of positive integers or natural numbers, together with
a proof that all the elements are prime, then we can regard it
as a multiset of primes. The next block of results records
obvious properties of these coercions.
-/
def to_nat_multiset : prime_multiset → multiset ℕ :=
λ v, v.map (λ p, (p : ℕ))
instance coe_nat : has_coe prime_multiset (multiset ℕ) := ⟨to_nat_multiset⟩
/-- `prime_multiset.coe`, the coercion from a multiset of primes to a multiset of
naturals, promoted to an `add_monoid_hom`. -/
def coe_nat_monoid_hom : prime_multiset →+ multiset ℕ :=
{ to_fun := coe,
.. multiset.map_add_monoid_hom coe }
@[simp] lemma coe_coe_nat_monoid_hom :
(coe_nat_monoid_hom : prime_multiset → multiset ℕ) = coe := rfl
theorem coe_nat_injective : function.injective (coe : prime_multiset → multiset ℕ) :=
multiset.map_injective nat.primes.coe_nat_inj
theorem coe_nat_of_prime (p : nat.primes) :
((of_prime p) : multiset ℕ) = {p} := rfl
theorem coe_nat_prime (v : prime_multiset)
(p : ℕ) (h : p ∈ (v : multiset ℕ)) : p.prime :=
by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩,
exact h_eq ▸ hp' }
/-- Converts a `prime_multiset` to a `multiset ℕ+`. -/
def to_pnat_multiset : prime_multiset → multiset ℕ+ :=
λ v, v.map (λ p, (p : ℕ+))
instance coe_pnat : has_coe prime_multiset (multiset ℕ+) := ⟨to_pnat_multiset⟩
/-- `coe_pnat`, the coercion from a multiset of primes to a multiset of positive
naturals, regarded as an `add_monoid_hom`. -/
def coe_pnat_monoid_hom : prime_multiset →+ multiset ℕ+ :=
{ to_fun := coe,
.. multiset.map_add_monoid_hom coe }
@[simp] lemma coe_coe_pnat_monoid_hom :
(coe_pnat_monoid_hom : prime_multiset → multiset ℕ+) = coe := rfl
theorem coe_pnat_injective : function.injective (coe : prime_multiset → multiset ℕ+) :=
multiset.map_injective nat.primes.coe_pnat_inj
theorem coe_pnat_of_prime (p : nat.primes) :
((of_prime p) : multiset ℕ+) = {(p : ℕ+)} := rfl
theorem coe_pnat_prime (v : prime_multiset)
(p : ℕ+) (h : p ∈ (v : multiset ℕ+)) : p.prime :=
by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩,
exact h_eq ▸ hp' }
instance coe_multiset_pnat_nat : has_coe (multiset ℕ+) (multiset ℕ) :=
⟨λ v, v.map (λ n, (n : ℕ))⟩
theorem coe_pnat_nat (v : prime_multiset) :
((v : (multiset ℕ+)) : (multiset ℕ)) = (v : multiset ℕ) :=
by { change (v.map (coe : nat.primes → ℕ+)).map subtype.val = v.map subtype.val,
rw [multiset.map_map], congr }
/-- The product of a `prime_multiset`, as a `ℕ+`. -/
def prod (v : prime_multiset) : ℕ+ := (v : multiset pnat).prod
theorem coe_prod (v : prime_multiset) : (v.prod : ℕ) = (v : multiset ℕ).prod :=
begin
let h : (v.prod : ℕ) = ((v.map coe).map coe).prod :=
(pnat.coe_monoid_hom.map_multiset_prod v.to_pnat_multiset),
rw [multiset.map_map] at h,
have : (coe : ℕ+ → ℕ) ∘ (coe : nat.primes → ℕ+) = coe := funext (λ p, rfl),
rw[this] at h, exact h,
end
theorem prod_of_prime (p : nat.primes) : (of_prime p).prod = (p : ℕ+) :=
multiset.prod_singleton _
/-- If a `multiset ℕ` consists only of primes, it can be recast as a `prime_multiset`. -/
def of_nat_multiset
(v : multiset ℕ) (h : ∀ (p : ℕ), p ∈ v → p.prime) : prime_multiset :=
@multiset.pmap ℕ nat.primes nat.prime (λ p hp, ⟨p, hp⟩) v h
theorem to_of_nat_multiset (v : multiset ℕ) (h) :
((of_nat_multiset v h) : multiset ℕ) = v :=
begin
unfold_coes,
dsimp [of_nat_multiset, to_nat_multiset],
have : (λ (p : ℕ) (h : p.prime), ((⟨p, h⟩ : nat.primes) : ℕ)) = (λ p h, id p) :=
by {funext p h, refl},
rw [multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id]
end
theorem prod_of_nat_multiset (v : multiset ℕ) (h) :
((of_nat_multiset v h).prod : ℕ) = (v.prod : ℕ) :=
by rw[coe_prod, to_of_nat_multiset]
/-- If a `multiset ℕ+` consists only of primes, it can be recast as a `prime_multiset`. -/
def of_pnat_multiset
(v : multiset ℕ+) (h : ∀ (p : ℕ+), p ∈ v → p.prime) : prime_multiset :=
@multiset.pmap ℕ+ nat.primes pnat.prime (λ p hp, ⟨(p : ℕ), hp⟩) v h
theorem to_of_pnat_multiset (v : multiset ℕ+) (h) :
((of_pnat_multiset v h) : multiset ℕ+) = v :=
begin
unfold_coes, dsimp[of_pnat_multiset, to_pnat_multiset],
have : (λ (p : ℕ+) (h : p.prime), ((coe : nat.primes → ℕ+) ⟨p, h⟩)) = (λ p h, id p) :=
by {funext p h, apply subtype.eq, refl},
rw[multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id]
end
theorem prod_of_pnat_multiset (v : multiset ℕ+) (h) :
((of_pnat_multiset v h).prod : ℕ+) = v.prod :=
by { dsimp [prod], rw [to_of_pnat_multiset] }
/-- Lists can be coerced to multisets; here we have some results
about how this interacts with our constructions on multisets. -/
def of_nat_list (l : list ℕ) (h : ∀ (p : ℕ), p ∈ l → p.prime) : prime_multiset :=
of_nat_multiset (l : multiset ℕ) h
theorem prod_of_nat_list (l : list ℕ) (h) : ((of_nat_list l h).prod : ℕ) = l.prod :=
by { have := prod_of_nat_multiset (l : multiset ℕ) h,
rw [multiset.coe_prod] at this, exact this }
/-- If a `list ℕ+` consists only of primes, it can be recast as a `prime_multiset` with
the coercion from lists to multisets. -/
def of_pnat_list (l : list ℕ+) (h : ∀ (p : ℕ+), p ∈ l → p.prime) : prime_multiset :=
of_pnat_multiset (l : multiset ℕ+) h
theorem prod_of_pnat_list (l : list ℕ+) (h) : (of_pnat_list l h).prod = l.prod :=
by { have := prod_of_pnat_multiset (l : multiset ℕ+) h,
rw [multiset.coe_prod] at this, exact this }
/-- The product map gives a homomorphism from the additive monoid
of multisets to the multiplicative monoid ℕ+. -/
theorem prod_zero : (0 : prime_multiset).prod = 1 :=
by { dsimp [prod], exact multiset.prod_zero }
theorem prod_add (u v : prime_multiset) : (u + v).prod = u.prod * v.prod :=
begin
change (coe_pnat_monoid_hom (u + v)).prod = _,
rw coe_pnat_monoid_hom.map_add,
exact multiset.prod_add _ _,
end
theorem prod_smul (d : ℕ) (u : prime_multiset) :
(d • u).prod = u.prod ^ d :=
by { induction d with d ih, refl,
rw [succ_nsmul, prod_add, ih, nat.succ_eq_add_one, pow_succ, mul_comm] }
end prime_multiset
namespace pnat
/-- The prime factors of n, regarded as a multiset -/
def factor_multiset (n : ℕ+) : prime_multiset :=
prime_multiset.of_nat_list (nat.factors n) (@nat.prime_of_mem_factors n)
/-- The product of the factors is the original number -/
theorem prod_factor_multiset (n : ℕ+) : (factor_multiset n).prod = n :=
eq $ by { dsimp [factor_multiset],
rw [prime_multiset.prod_of_nat_list],
exact nat.prod_factors n.pos }
theorem coe_nat_factor_multiset (n : ℕ+) :
((factor_multiset n) : (multiset ℕ)) = ((nat.factors n) : multiset ℕ) :=
prime_multiset.to_of_nat_multiset (nat.factors n) (@nat.prime_of_mem_factors n)
end pnat
namespace prime_multiset
/-- If we start with a multiset of primes, take the product and
then factor it, we get back the original multiset. -/
theorem factor_multiset_prod (v : prime_multiset) :
v.prod.factor_multiset = v :=
begin
apply prime_multiset.coe_nat_injective,
rw [v.prod.coe_nat_factor_multiset, prime_multiset.coe_prod],
rcases v with ⟨l⟩,
unfold_coes,
dsimp [prime_multiset.to_nat_multiset],
rw [multiset.coe_prod],
let l' := l.map (coe : nat.primes → ℕ),
have : ∀ (p : ℕ), p ∈ l' → p.prime :=
λ p hp, by {rcases list.mem_map.mp hp with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩,
exact h_eq ▸ hp'},
exact multiset.coe_eq_coe.mpr (@nat.factors_unique _ l' rfl this).symm,
end
end prime_multiset
namespace pnat
/-- Positive integers biject with multisets of primes. -/
def factor_multiset_equiv : ℕ+ ≃ prime_multiset :=
{ to_fun := factor_multiset,
inv_fun := prime_multiset.prod,
left_inv := prod_factor_multiset,
right_inv := prime_multiset.factor_multiset_prod }
/-- Factoring gives a homomorphism from the multiplicative
monoid ℕ+ to the additive monoid of multisets. -/
theorem factor_multiset_one : factor_multiset 1 = 0 :=
by simp [factor_multiset, prime_multiset.of_nat_list, prime_multiset.of_nat_multiset]
theorem factor_multiset_mul (n m : ℕ+) :
factor_multiset (n * m) = (factor_multiset n) + (factor_multiset m) :=
begin
let u := factor_multiset n,
let v := factor_multiset m,
have : n = u.prod := (prod_factor_multiset n).symm, rw[this],
have : m = v.prod := (prod_factor_multiset m).symm, rw[this],
rw[← prime_multiset.prod_add],
repeat {rw[prime_multiset.factor_multiset_prod]},
end
theorem factor_multiset_pow (n : ℕ+) (m : ℕ) :
factor_multiset (n ^ m) = m • (factor_multiset n) :=
begin
let u := factor_multiset n,
have : n = u.prod := (prod_factor_multiset n).symm,
rw[this, ← prime_multiset.prod_smul],
repeat {rw[prime_multiset.factor_multiset_prod]},
end
/-- Factoring a prime gives the corresponding one-element multiset. -/
theorem factor_multiset_of_prime (p : nat.primes) :
(p : ℕ+).factor_multiset = prime_multiset.of_prime p :=
begin
apply factor_multiset_equiv.symm.injective,
change (p : ℕ+).factor_multiset.prod = (prime_multiset.of_prime p).prod,
rw[(p : ℕ+).prod_factor_multiset, prime_multiset.prod_of_prime],
end
/-- We now have four different results that all encode the
idea that inequality of multisets corresponds to divisibility
of positive integers. -/
theorem factor_multiset_le_iff {m n : ℕ+} :
factor_multiset m ≤ factor_multiset n ↔ m ∣ n :=
begin
split,
{ intro h,
rw [← prod_factor_multiset m, ← prod_factor_multiset m],
apply dvd.intro (n.factor_multiset - m.factor_multiset).prod,
rw [← prime_multiset.prod_add, prime_multiset.factor_multiset_prod,
add_tsub_cancel_of_le h, prod_factor_multiset] },
{ intro h,
rw [← mul_div_exact h, factor_multiset_mul],
exact le_self_add }
end
theorem factor_multiset_le_iff' {m : ℕ+} {v : prime_multiset}:
factor_multiset m ≤ v ↔ m ∣ v.prod :=
by { let h := @factor_multiset_le_iff m v.prod,
rw [v.factor_multiset_prod] at h, exact h }
end pnat
namespace prime_multiset
theorem prod_dvd_iff {u v : prime_multiset} : u.prod ∣ v.prod ↔ u ≤ v :=
by { let h := @pnat.factor_multiset_le_iff' u.prod v,
rw [u.factor_multiset_prod] at h, exact h.symm }
theorem prod_dvd_iff' {u : prime_multiset} {n : ℕ+} : u.prod ∣ n ↔ u ≤ n.factor_multiset :=
by { let h := @prod_dvd_iff u n.factor_multiset,
rw [n.prod_factor_multiset] at h, exact h }
end prime_multiset
namespace pnat
/-- The gcd and lcm operations on positive integers correspond
to the inf and sup operations on multisets. -/
theorem factor_multiset_gcd (m n : ℕ+) :
factor_multiset (gcd m n) = (factor_multiset m) ⊓ (factor_multiset n) :=
begin
apply le_antisymm,
{ apply le_inf_iff.mpr; split; apply factor_multiset_le_iff.mpr,
exact gcd_dvd_left m n, exact gcd_dvd_right m n},
{ rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset],
apply dvd_gcd; rw[prime_multiset.prod_dvd_iff'],
exact inf_le_left, exact inf_le_right}
end
theorem factor_multiset_lcm (m n : ℕ+) :
factor_multiset (lcm m n) = (factor_multiset m) ⊔ (factor_multiset n) :=
begin
apply le_antisymm,
{ rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset],
apply lcm_dvd; rw[← factor_multiset_le_iff'],
exact le_sup_left, exact le_sup_right},
{ apply sup_le_iff.mpr; split; apply factor_multiset_le_iff.mpr,
exact dvd_lcm_left m n, exact dvd_lcm_right m n },
end
/-- The number of occurrences of p in the factor multiset of m
is the same as the p-adic valuation of m. -/
theorem count_factor_multiset (m : ℕ+) (p : nat.primes) (k : ℕ) :
(p : ℕ+) ^ k ∣ m ↔ k ≤ m.factor_multiset.count p :=
begin
intros,
rw [multiset.le_count_iff_repeat_le],
rw [← factor_multiset_le_iff, factor_multiset_pow, factor_multiset_of_prime],
congr' 2,
apply multiset.eq_repeat.mpr,
split,
{ rw [multiset.card_nsmul, prime_multiset.card_of_prime, mul_one] },
{ intros q h, rw [prime_multiset.of_prime, multiset.nsmul_singleton _ k] at h,
exact multiset.eq_of_mem_repeat h }
end
end pnat
namespace prime_multiset
theorem prod_inf (u v : prime_multiset) :
(u ⊓ v).prod = pnat.gcd u.prod v.prod :=
begin
let n := u.prod,
let m := v.prod,
change (u ⊓ v).prod = pnat.gcd n m,
have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this],
have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this],
rw [← pnat.factor_multiset_gcd n m, pnat.prod_factor_multiset]
end
theorem prod_sup (u v : prime_multiset) :
(u ⊔ v).prod = pnat.lcm u.prod v.prod :=
begin
let n := u.prod,
let m := v.prod,
change (u ⊔ v).prod = pnat.lcm n m,
have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this],
have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this],
rw[← pnat.factor_multiset_lcm n m, pnat.prod_factor_multiset]
end
end prime_multiset
|
5edc4c0dce6ae5fe2f43a005a19c9230677478da | 4727251e0cd73359b15b664c3170e5d754078599 | /src/tactic/wlog.lean | 044e2d4c8fbdc4c17e21314bc89822f6724ab003 | [
"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,077 | 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
Without loss of generality tactic.
-/
import data.list.perm
open expr
setup_tactic_parser
namespace tactic
private meta def update_pp_name : expr → name → expr
| (local_const n _ bi d) pp := local_const n pp bi d
| e n := e
private meta def elim_or : ℕ → expr → tactic (list expr)
| 0 h := fail "zero cases"
| 1 h := return [h]
| (n + 1) h := do
[(_, [hl], []), (_, [hr], [])] ← induction h, -- there should be no dependent terms
[gl, gr] ← get_goals,
set_goals [gr],
hsr ← elim_or n hr,
gsr ← get_goals,
set_goals (gl :: gsr),
return (hl :: hsr)
private meta def dest_or : expr → tactic (list expr) | e := do
`(%%a ∨ %%b) ← whnf e | return [e],
lb ← dest_or b,
return (a :: lb)
private meta def match_perms (pat : pattern) : expr → tactic (list $ list expr) | t :=
(do
m ← match_pattern pat t,
guard (m.2.all expr.is_local_constant),
return [m.2]) <|>
(do
`(%%l ∨ %%r) ← whnf t,
m ← match_pattern pat l,
rs ← match_perms r,
return (m.2 :: rs))
meta def wlog (vars' : list expr) (h_cases fst_case : expr) (perms : list (list expr)) :
tactic unit := do
guard h_cases.is_local_constant,
-- reorder s.t. context is Γ ⬝ vars ⬝ cases ⊢ ∀deps, …
nr ← revert_lst (vars' ++ [h_cases]),
vars ← intron' vars'.length,
h_cases ← intro h_cases.local_pp_name,
cases ← infer_type h_cases,
h_fst_case ←
mk_local_def h_cases.local_pp_name
(fst_case.instantiate_locals $ (vars'.zip vars).map $ λ⟨o, n⟩, (o.local_uniq_name, n)),
((), pr) ← solve_aux cases (repeat $ exact h_fst_case <|> left >> skip),
t ← target,
fixed_vars ← vars.mmap update_type,
let t' := (instantiate_local h_cases.local_uniq_name pr t).pis (fixed_vars ++ [h_fst_case]),
(h, [g]) ← local_proof `this t' (do
clear h_cases,
vars.mmap clear,
intron nr),
h₀ :: hs ← elim_or perms.length h_cases,
solve1 (do
exact (h.mk_app $ vars ++ [h₀])),
focus ((hs.zip perms.tail).map $ λ⟨h_case, perm⟩, do
let p_v := (vars'.zip vars).map (λ⟨p, v⟩, (p.local_uniq_name, v)),
let p := perm.map (λp, p.instantiate_locals p_v),
note `this none (h.mk_app $ p ++ [h_case]),
clear h,
return ()),
gs ← get_goals,
set_goals (g :: gs)
namespace interactive
open interactive interactive.types expr
private meta def parse_permutations : option (list (list name)) → tactic (list (list expr))
| none := return []
| (some []) := return []
| (some perms@(p₀ :: ps)) := do
(guard p₀.nodup <|> fail
"No permutation `xs_i` in `using [xs_1, …, xs_n]` should contain the same variable twice."),
(guard (perms.all $ λp, p.perm p₀) <|>
fail ("The permutations `xs_i` in `using [xs_1, …, xs_n]` must be permutations of the same" ++
" variables.")),
perms.mmap (λp, p.mmap get_local)
/-- Without loss of generality: reduces to one goal under variables permutations.
Given a goal of the form `g xs`, a predicate `p` over a set of variables, as well as variable
permutations `xs_i`. Then `wlog` produces goals of the form
The case goal, i.e. the permutation `xs_i` covers all possible cases:
`⊢ p xs_0 ∨ ⋯ ∨ p xs_n`
The main goal, i.e. the goal reduced to `xs_0`:
`(h : p xs_0) ⊢ g xs_0`
The invariant goals, i.e. `g` is invariant under `xs_i`:
`(h : p xs_i) (this : g xs_0) ⊢ gs xs_i`
Either the permutation is provided, or a proof of the disjunction is provided to compute the
permutation. The disjunction need to be in assoc normal form, e.g. `p₀ ∨ (p₁ ∨ p₂)`. In many cases
the invariant goals can be solved by AC rewriting using `cc` etc.
Example:
On a state `(n m : ℕ) ⊢ p n m` the tactic `wlog h : n ≤ m using [n m, m n]` produces the following
states:
`(n m : ℕ) ⊢ n ≤ m ∨ m ≤ n`
`(n m : ℕ) (h : n ≤ m) ⊢ p n m`
`(n m : ℕ) (h : m ≤ n) (this : p n m) ⊢ p m n`
`wlog` supports different calling conventions. The name `h` is used to give a name to the introduced
case hypothesis. If the name is avoided, the default will be `case`.
(1) `wlog : p xs0 using [xs0, …, xsn]`
Results in the case goal `p xs0 ∨ ⋯ ∨ ps xsn`, the main goal `(case : p xs0) ⊢ g xs0` and the
invariance goals `(case : p xsi) (this : g xs0) ⊢ g xsi`.
(2) `wlog : p xs0 := r using xs0`
The expression `r` is a proof of the shape `p xs0 ∨ ⋯ ∨ p xsi`, it is also used to compute the
variable permutations.
(3) `wlog := r using xs0`
The expression `r` is a proof of the shape `p xs0 ∨ ⋯ ∨ p xsi`, it is also used to compute the
variable permutations. This is not as stable as (2), for example `p` cannot be a disjunction.
(4) `wlog : R x y using x y` and `wlog : R x y`
Produces the case `R x y ∨ R y x`. If `R` is ≤, then the disjunction discharged using linearity.
If `using x y` is avoided then `x` and `y` are the last two variables appearing in the
expression `R x y`. -/
meta def wlog
(h : parse ident?)
(pat : parse (tk ":" *> texpr)?)
(cases : parse (tk ":=" *> texpr)?)
(perms : parse (tk "using" *> (list_of (ident*) <|> (λx, [x]) <$> ident*))?)
(discharger : tactic unit :=
(tactic.solve_by_elim <|> tactic.tautology {classical := tt} <|>
using_smt (smt_tactic.intros >> smt_tactic.solve_goals))) :
tactic unit := do
perms ← parse_permutations perms,
(pat, cases_pr, cases_goal, vars, perms) ← (match cases with
| some r := do
vars::_ ← return perms |
fail "At least one set of variables expected, i.e. `using x y` or `using [x y, y x]`.",
cases_pr ← to_expr r,
cases_pr ← (if cases_pr.is_local_constant
then return $ match h with some n := update_pp_name cases_pr n | none := cases_pr end
else do
note (h.get_or_else `case) none cases_pr),
cases ← infer_type cases_pr,
(pat, perms') ← match pat with
| some pat := do
pat ← to_expr pat,
let vars' := vars.filter $ λv, v.occurs pat,
case_pat ← mk_pattern [] vars' pat [] vars',
perms' ← match_perms case_pat cases,
return (pat, perms')
| none := do
(p :: ps) ← dest_or cases,
let vars' := vars.filter $ λv, v.occurs p,
case_pat ← mk_pattern [] vars' p [] vars',
perms' ← (p :: ps).mmap (λp, do m ← match_pattern case_pat p, return m.2),
return (p, perms')
end,
let vars_name := vars.map local_uniq_name,
guard (perms'.all $ λp, p.all $ λv, v.is_local_constant ∧ v.local_uniq_name ∈ vars_name) <|>
fail "Cases contains variables not declared in `using x y z`",
perms ← (if perms.length = 1
then do
return (perms'.map $ λ p,
p ++ vars.filter (λ v, p.all (λ v', v'.local_uniq_name ≠ v.local_uniq_name)))
else do
guard (perms.length = perms'.length) <|>
fail "The provided permutation list has a different length then the provided cases.",
return perms),
return (pat, cases_pr, @none expr, vars, perms)
| none := do
let name_h := h.get_or_else `case,
some pat ← return pat | fail "Either specify cases or a pattern with permutations",
pat ← to_expr pat,
(do
[x, y] ← match perms with
| [] := return pat.list_local_consts
| [l] := return l
| _ := failed
end,
let cases := mk_or_lst
[pat, pat.instantiate_locals [(x.local_uniq_name, y), (y.local_uniq_name, x)]],
(do
`(%%x' ≤ %%y') ← return pat,
(cases_pr, []) ← local_proof name_h cases (exact ``(le_total %%x' %%y')),
return (pat, cases_pr, none, [x, y], [[x, y], [y, x]]))
<|>
(do
(cases_pr, [g]) ← local_proof name_h cases skip,
return (pat, cases_pr, some g, [x, y], [[x, y], [y, x]]))) <|>
(do
guard (perms.length ≥ 2) <|>
fail ("To generate cases at least two permutations are required, i.e. `using [x y, y x]`" ++
" or exactly 0 or 2 variables"),
(vars :: perms') ← return perms,
let names := vars.map local_uniq_name,
let cases := mk_or_lst (pat :: perms'.map (λp, pat.instantiate_locals (names.zip p))),
(cases_pr, [g]) ← local_proof name_h cases skip,
return (pat, cases_pr, some g, vars, perms))
end),
let name_fn := if perms.length = 2 then λ _, `invariant else
λ i, mk_simple_name ("invariant_" ++ to_string (i + 1)),
with_enable_tags $ tactic.focus1 $ do
t ← get_main_tag,
tactic.wlog vars cases_pr pat perms,
tactic.focus (set_main_tag (mk_num_name `_case 0 :: `main :: t) ::
(list.range (perms.length - 1)).map (λi, do
set_main_tag (mk_num_name `_case 0 :: name_fn i :: t),
try discharger)),
match cases_goal with
| some g := do
set_tag g (mk_num_name `_case 0 :: `cases :: t),
gs ← get_goals,
set_goals (g :: gs)
| none := skip
end
add_tactic_doc
{ name := "wlog",
category := doc_category.tactic,
decl_names := [``wlog],
tags := ["logic"] }
end interactive
end tactic
|
72671c7630757b53d096395f4e23ef4976235671 | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /tactic/interactive.lean | 40130cfab3a29c70014ef033b803e430c794e40b | [
"Apache-2.0"
] | permissive | kckennylau/mathlib | 21fb810b701b10d6606d9002a4004f7672262e83 | 47b3477e20ffb5a06588dd3abb01fe0fe3205646 | refs/heads/master | 1,634,976,409,281 | 1,542,042,832,000 | 1,542,319,733,000 | 109,560,458 | 0 | 0 | Apache-2.0 | 1,542,369,208,000 | 1,509,867,494,000 | Lean | UTF-8 | Lean | false | false | 24,472 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Sebastien Gouezel, Scott Morrison
-/
import data.dlist data.dlist.basic data.prod category.basic
tactic.basic tactic.rcases tactic.generalize_proofs
tactic.split_ifs logic.basic tactic.ext tactic.tauto tactic.replacer
open lean
open lean.parser
local postfix `?`:9001 := optional
local postfix *:9001 := many
namespace tactic
namespace interactive
open interactive interactive.types expr
/--
The `rcases` tactic is the same as `cases`, but with more flexibility in the
`with` pattern syntax to allow for recursive case splitting. The pattern syntax
uses the following recursive grammar:
```
patt ::= (patt_list "|")* patt_list
patt_list ::= id | "_" | "⟨" (patt ",")* patt "⟩"
```
A pattern like `⟨a, b, c⟩ | ⟨d, e⟩` will do a split over the inductive datatype,
naming the first three parameters of the first constructor as `a,b,c` and the
first two of the second constructor `d,e`. If the list is not as long as the
number of arguments to the constructor or the number of constructors, the
remaining variables will be automatically named. If there are nested brackets
such as `⟨⟨a⟩, b | c⟩ | d` then these will cause more case splits as necessary.
If there are too many arguments, such as `⟨a, b, c⟩` for splitting on
`∃ x, ∃ y, p x`, then it will be treated as `⟨a, ⟨b, c⟩⟩`, splitting the last
parameter as necessary.
`rcases` also has special support for quotient types: quotient induction into Prop works like
matching on the constructor `quot.mk`.
`rcases? e` will perform case splits on `e` in the same way as `rcases e`,
but rather than accepting a pattern, it does a maximal cases and prints the
pattern that would produce this case splitting. The default maximum depth is 5,
but this can be modified with `rcases? e : n`.
-/
meta def rcases : parse rcases_parse → tactic unit
| (p, sum.inl ids) := tactic.rcases p ids
| (p, sum.inr depth) := do
patt ← tactic.rcases_hint p depth,
pe ← pp p,
trace $ ↑"snippet: rcases " ++ pe ++ " with " ++ to_fmt patt
/--
The `rintro` tactic is a combination of the `intros` tactic with `rcases` to
allow for destructuring patterns while introducing variables. See `rcases` for
a description of supported patterns. For example, `rintros (a | ⟨b, c⟩) ⟨d, e⟩`
will introduce two variables, and then do case splits on both of them producing
two subgoals, one with variables `a d e` and the other with `b c d e`.
`rintro?` will introduce and case split on variables in the same way as
`rintro`, but will also print the `rintro` invocation that would have the same
result. Like `rcases?`, `rintro? : n` allows for modifying the
depth of splitting; the default is 5.
-/
meta def rintro : parse rintro_parse → tactic unit
| (sum.inl []) := intros []
| (sum.inl l) := tactic.rintro l
| (sum.inr depth) := do
ps ← tactic.rintro_hint depth,
trace $ ↑"snippet: rintro" ++ format.join (ps.map $ λ p,
format.space ++ format.group (p.format tt))
/-- Alias for `rintro`. -/
meta def rintros := rintro
/--
This is a "finishing" tactic modification of `simp`. The tactic `simpa [rules, ...] using e`
will simplify the hypothesis `e` using `rules`, then simplify the goal using `rules`, and
try to close the goal using `assumption`. If `e` is a term instead of a local constant,
it is first added to the local context using `have`.
-/
meta def simpa (use_iota_eqn : parse $ (tk "!")?) (no_dflt : parse only_flag)
(hs : parse simp_arg_list) (attr_names : parse with_ident_list)
(tgt : parse (tk "using" *> texpr)?) (cfg : simp_config_ext := {}) : tactic unit :=
let simp_at (lc) := try (simp use_iota_eqn no_dflt hs attr_names (loc.ns lc) cfg) >> (assumption <|> trivial) in
match tgt with
| none := get_local `this >> simp_at [some `this, none] <|> simp_at [none]
| some e := do
e ← i_to_expr e <|> do {
ty ← target,
e ← i_to_expr_strict ``(%%e : %%ty), -- for positional error messages, don't care about the result
pty ← pp ty, ptgt ← pp e,
-- Fail deliberately, to advise regarding `simp; exact` usage
fail ("simpa failed, 'using' expression type not directly " ++
"inferrable. Try:\n\nsimpa ... using\nshow " ++
to_fmt pty ++ ",\nfrom " ++ ptgt : format) },
match e with
| local_const _ lc _ _ := simp_at [some lc, none]
| e := do
t ← infer_type e,
assertv `this t e >> simp_at [some `this, none]
end
end
/-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal.
Never fails. Useful for debugging. -/
meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit :=
do max ← i_to_expr_strict max >>= tactic.eval_expr nat,
λ s, match _root_.try_for max (tac s) with
| some r := r
| none := (tactic.trace "try_for timeout, using sorry" >> admit) s
end
/-- Multiple subst. `substs x y z` is the same as `subst x, subst y, subst z`. -/
meta def substs (l : parse ident*) : tactic unit :=
l.mmap' (λ h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible)
/-- Unfold coercion-related definitions -/
meta def unfold_coes (loc : parse location) : tactic unit :=
unfold [
``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe,
``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift,
``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc
/-- Unfold auxiliary definitions associated with the current declaration. -/
meta def unfold_aux : tactic unit :=
do tgt ← target,
name ← decl_name,
let to_unfold := (tgt.list_names_with_prefix name),
guard (¬ to_unfold.empty),
-- should we be using simp_lemmas.mk_default?
simp_lemmas.mk.dsimplify to_unfold.to_list tgt >>= tactic.change
/-- For debugging only. This tactic checks the current state for any
missing dropped goals and restores them. Useful when there are no
goals to solve but "result contains meta-variables". -/
meta def recover : tactic unit :=
metavariables >>= tactic.set_goals
/-- Like `try { tac }`, but in the case of failure it continues
from the failure state instead of reverting to the original state. -/
meta def continue (tac : itactic) : tactic unit :=
λ s, result.cases_on (tac s)
(λ a, result.success ())
(λ e ref, result.success ())
/-- Move goal `n` to the front. -/
meta def swap (n := 2) : tactic unit :=
do gs ← get_goals,
match gs.nth (n-1) with
| (some g) := set_goals (g :: gs.remove_nth (n-1))
| _ := skip
end
/-- Generalize proofs in the goal, naming them with the provided list. -/
meta def generalize_proofs : parse ident_* → tactic unit :=
tactic.generalize_proofs
/-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/
meta def clear_ : tactic unit := tactic.repeat $ do
l ← local_context,
l.reverse.mfirst $ λ h, do
name.mk_string s p ← return $ local_pp_name h,
guard (s.front = '_'),
cl ← infer_type h >>= is_class, guard (¬ cl),
tactic.clear h
/--
Same as the `congr` tactic, but takes an optional argument which gives
the depth of recursive applications. This is useful when `congr`
is too aggressive in breaking down the goal. For example, given
`⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y`
and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`. -/
meta def congr' : parse (with_desc "n" small_nat)? → tactic unit
| (some 0) := failed
| o := focus1 (assumption <|> (congr_core >>
all_goals (reflexivity <|> `[apply proof_irrel_heq] <|>
`[apply proof_irrel] <|> try (congr' (nat.pred <$> o)))))
/--
Acts like `have`, but removes a hypothesis with the same name as
this one. For example if the state is `h : p ⊢ goal` and `f : p → q`,
then after `replace h := f h` the goal will be `h : q ⊢ goal`,
where `have h := f h` would result in the state `h : p, h : q ⊢ goal`.
This can be used to simulate the `specialize` and `apply at` tactics
of Coq. -/
meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit :=
do let h := h.get_or_else `this,
old ← try_core (get_local h),
«have» h q₁ q₂,
match old, q₂ with
| none, _ := skip
| some o, some _ := tactic.clear o
| some o, none := swap >> tactic.clear o >> swap
end
/--
`apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head`
where `head` matches the current goal.
alternatively, when encountering an assumption of the form `sg₀ → ¬ sg₁`,
after the main approach failed, the goal is dismissed and `sg₀` and `sg₁`
are made into the new goal.
optional arguments:
- asms: list of rules to consider instead of the local constants
- tac: a tactic to run on each subgoals after applying an assumption; if
this tactic fails, the corresponding assumption will be rejected and
the next one will be attempted.
-/
meta def apply_assumption
(asms : tactic (list expr) := local_context)
(tac : tactic unit := return ()) : tactic unit :=
tactic.apply_assumption asms tac
open nat
meta def mk_assumption_set (no_dflt : bool) (hs : list simp_arg_type) (attr : list name): tactic (list expr) :=
do (hs, gex, hex, all_hyps) ← decode_simp_arg_list hs,
hs ← hs.mmap i_to_expr_for_apply,
l ← attr.mmap $ λ a, attribute.get_instances a,
let l := l.join,
m ← list.mmap mk_const l,
let hs := (hs ++ m).filter $ λ h, expr.const_name h ∉ gex,
hs ← if no_dflt then
return hs
else
do { congr_fun ← mk_const `congr_fun,
congr_arg ← mk_const `congr_arg,
return (congr_fun :: congr_arg :: hs) },
if ¬ no_dflt ∨ all_hyps then do
ctx ← local_context,
return $ hs.append (ctx.filter (λ h, h.local_uniq_name ∉ hex)) -- remove local exceptions
else return hs
/--
`solve_by_elim` calls `apply_assumption` on the main goal to find an assumption whose head matches
and then repeatedly calls `apply_assumption` on the generated subgoals until no subgoals remain,
performing at most `max_rep` recursive steps.
`solve_by_elim` discharges the current goal or fails
`solve_by_elim` performs back-tracking if `apply_assumption` chooses an unproductive assumption
By default, the assumptions passed to apply_assumption are the local context, `congr_fun` and
`congr_arg`.
`solve_by_elim [h₁, h₂, ..., hᵣ]` also applies the named lemmas.
`solve_by_elim with attr₁ ... attrᵣ also applied all lemmas tagged with the specified attributes.
`solve_by_elim only [h₁, h₂, ..., hᵣ]` does not include the local context, `congr_fun`, or `congr_arg`
unless they are explicitly included.
`solve_by_elim [-id]` removes a specified assumption.
optional arguments:
- discharger: a subsidiary tactic to try at each step (e.g. `cc` may be helpful)
- max_rep: number of attempts at discharging generated sub-goals
-/
meta def solve_by_elim (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : by_elim_opt := { }) : tactic unit :=
do asms ← mk_assumption_set no_dflt hs attr_names,
tactic.solve_by_elim { assumptions := return asms ..opt }
/--
`tautology` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _`
and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged
using `reflexivity` or `solve_by_elim`
-/
meta def tautology (c : parse $ (tk "!")?) := tactic.tautology c.is_some
/-- Shorter name for the tactic `tautology`. -/
meta def tauto (c : parse $ (tk "!")?) := tautology c
/-- Make every propositions in the context decidable -/
meta def classical := tactic.classical
private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name)
| (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x)
| _ := fail "parse error"
private meta def generalize_arg_p : parser (pexpr × name) :=
with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux
lemma {u} generalize_a_aux {α : Sort u}
(h : ∀ x : Sort u, (α → x) → x) : α := h α id
/--
Like `generalize` but also considers assumptions
specified by the user. The user can also specify to
omit the goal.
-/
meta def generalize_hyp (h : parse ident?) (_ : parse $ tk ":")
(p : parse generalize_arg_p)
(l : parse location) :
tactic unit :=
do h' ← get_unused_name `h,
x' ← get_unused_name `x,
g ← if ¬ l.include_goal then
do refine ``(generalize_a_aux _),
some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h')
else pure none,
n ← l.get_locals >>= tactic.revert_lst,
generalize h () p,
intron n,
match g with
| some (x',h') :=
do tactic.apply h',
tactic.clear h',
tactic.clear x'
| none := return ()
end
/--
Similar to `refine` but generates equality proof obligations
for every discrepancy between the goal and the type of the rule.
-/
meta def convert (sym : parse (with_desc "←" (tk "<-")?)) (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit :=
do v ← mk_mvar,
if sym.is_some
then refine ``(eq.mp %%v %%r)
else refine ``(eq.mpr %%v %%r),
gs ← get_goals,
set_goals [v],
congr' n,
gs' ← get_goals,
set_goals $ gs' ++ gs
meta def clean_ids : list name :=
[``id, ``id_rhs, ``id_delta]
/--
Remove identity functions from a term. These are normally
automatically generated with terms like `show t, from p` or
`(p : t)` which translate to some variant on `@id t p` in
order to retain the type. -/
meta def clean (q : parse texpr) : tactic unit :=
do tgt : expr ← target,
e ← i_to_expr_strict ``(%%q : %%tgt),
tactic.exact $ e.replace (λ e n,
match e with
| (app (app (const n _) _) e') :=
if n ∈ clean_ids then some e' else none
| (app (lam _ _ _ (var 0)) e') := some e'
| _ := none
end)
meta def source_fields (missing : list name) (e : pexpr) : tactic (list (name × pexpr)) :=
do e ← to_expr e,
t ← infer_type e,
let struct_n : name := t.get_app_fn.const_name,
fields ← expanded_field_list struct_n,
let exp_fields := fields.filter (λ x, x.2 ∈ missing),
exp_fields.mmap $ λ ⟨p,n⟩,
(prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e]
meta def collect_struct' : pexpr → state_t (list $ expr×structure_instance_info) tactic pexpr | e :=
do some str ← pure (e.get_structure_instance_info)
| e.traverse collect_struct',
v ← monad_lift mk_mvar,
modify (list.cons (v,str)),
pure $ to_pexpr v
meta def collect_struct (e : pexpr) : tactic $ pexpr × list (expr×structure_instance_info) :=
prod.map id list.reverse <$> (collect_struct' e).run []
meta def refine_one (str : structure_instance_info) :
tactic $ list (expr×structure_instance_info) :=
do tgt ← target,
let struct_n : name := tgt.get_app_fn.const_name,
exp_fields ← expanded_field_list struct_n,
let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names),
(src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$> str.sources.mmap (source_fields $ missing_f.map prod.snd),
let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names),
let missing_f' := missing_f.filter (λ x, x.2 ∉ src_field_names),
vs ← mk_mvar_list missing_f'.length,
(field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _),
e' ← to_expr $ pexpr.mk_structure_instance
{ struct := some struct_n
, field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names
, field_values := field_values ++ vs.map to_pexpr ++ src_field_vals },
tactic.exact e',
gs ← with_enable_tags (
mzip_with (λ (n : name × name) v, do
set_goals [v],
try (interactive.unfold (provided.map $ λ ⟨s,f⟩, f.update_prefix s) (loc.ns [none])),
apply_auto_param
<|> apply_opt_param
<|> (set_main_tag [`_field,n.2,n.1]),
get_goals)
missing_f' vs),
set_goals gs.join,
return new_goals.join
meta def refine_recursively : expr × structure_instance_info → tactic (list expr) | (e,str) :=
do set_goals [e],
rs ← refine_one str,
gs ← get_goals,
gs' ← rs.mmap refine_recursively,
return $ gs'.join ++ gs
/--
`refine_struct { .. }` acts like `refine` but works only with structure instance
literals. It creates a goal for each missing field and tags it with the name of the
field so that `have_field` can be used to generically refer to the field currently
being refined.
As an example, we can use `refine_struct` to automate the construction semigroup
instances:
```
refine_struct ( { .. } : semigroup α ),
-- case semigroup, mul
-- α : Type u,
-- ⊢ α → α → α
-- case semigroup, mul_assoc
-- α : Type u,
-- ⊢ ∀ (a b c : α), a * b * c = a * (b * c)
```
-/
meta def refine_struct : parse texpr → tactic unit | e :=
do (x,xs) ← collect_struct e,
refine x,
gs ← get_goals,
xs' ← xs.mmap refine_recursively,
set_goals (xs'.join ++ gs)
/--
`guard_hyp h := t` fails if the hypothesis `h` does not have type `t`.
We use this tactic for writing tests.
Fixes `guard_hyp` by instantiating meta variables
-/
meta def guard_hyp' (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit :=
do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p
meta def guard_hyp_nums (n : ℕ) : tactic unit :=
do k ← local_context,
guard (n = k.length) <|> fail format!"{k.length} hypotheses found"
meta def guard_tags (tags : parse ident*) : tactic unit :=
do (t : list name) ← get_main_tag,
guard (t = tags)
meta def get_current_field : tactic name :=
do [_,field,str] ← get_main_tag,
expr.const_name <$> resolve_name (field.update_prefix str)
meta def field (n : parse ident) (tac : itactic) : tactic unit :=
do gs ← get_goals,
ts ← gs.mmap get_tag,
([g],gs') ← pure $ (list.zip gs ts).partition (λ x, x.snd.nth 1 = some n),
set_goals [g.1],
tac, done,
set_goals $ gs'.map prod.fst
/--
`have_field`, used after `refine_struct _` poses `field` as a local constant
with the type of the field of the current goal:
```
refine_struct ({ .. } : semigroup α),
{ have_field, ... },
{ have_field, ... },
```
behaves like
```
refine_struct ({ .. } : semigroup α),
{ have field := @semigroup.mul, ... },
{ have field := @semigroup.mul_assoc, ... },
```
-/
meta def have_field : tactic unit :=
propagate_tags $
get_current_field
>>= mk_const
>>= note `field none
>> return ()
/-- `apply_field` functions as `have_field, apply field, clear field` -/
meta def apply_field : tactic unit :=
propagate_tags $
get_current_field >>= applyc
/--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the
first goal and the resulting subgoals, iteratively, at most `n` times.
`n` is 50 by default. `hs` can contain user attributes: in this case all theorems with this
attribute are added to the list of rules.
example, with or without user attribute:
```
@[user_attribute]
meta def mono_rules : user_attribute :=
{ name := `mono_rules,
descr := "lemmas usable to prove monotonicity" }
attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right
lemma my_test {a b c d e : real} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) :
a + c * e + a + c + 0 ≤ b + d * e + b + d + e :=
by apply_rules mono_rules
-- any of the following lines would also work:
-- add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3
-- by apply_rules [add_le_add, mul_le_mul_of_nonneg_right]
-- by apply_rules [mono_rules]
```
-/
meta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) : tactic unit :=
tactic.apply_rules hs n
meta def return_cast (f : option expr) (t : option (expr × expr))
(es : list (expr × expr × expr))
(e x x' eq_h : expr) :
tactic (option (expr × expr) × list (expr × expr × expr)) :=
(do guard (¬ e.has_var),
unify x x',
u ← mk_meta_univ,
f ← f <|> to_expr ``(@id %%(expr.sort u : expr)),
t' ← infer_type e,
some (f',t) ← pure t | return (some (f,t'), (e,x',eq_h) :: es),
infer_type e >>= is_def_eq t,
unify f f',
return (some (f,t), (e,x',eq_h) :: es)) <|>
return (t, es)
meta def list_cast_of_aux (x : expr) (t : option (expr × expr))
(es : list (expr × expr × expr)) :
expr → tactic (option (expr × expr) × list (expr × expr × expr))
| e@`(cast %%eq_h %%x') := return_cast none t es e x x' eq_h
| e@`(eq.mp %%eq_h %%x') := return_cast none t es e x x' eq_h
| e@`(eq.mpr %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast none t es e x x'
| e@`(@eq.subst %%α %%p %%a %%b %%eq_h %%x') := return_cast p t es e x x' eq_h
| e@`(@eq.substr %%α %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x'
| e@`(@eq.rec %%α %%a %%f %%x' _ %%eq_h) := return_cast f t es e x x' eq_h
| e@`(@eq.rec_on %%α %%a %%f %%b %%eq_h %%x') := return_cast f t es e x x' eq_h
| e := return (t,es)
meta def list_cast_of (x tgt : expr) : tactic (list (expr × expr × expr)) :=
(list.reverse ∘ prod.snd) <$> tgt.mfold (none, []) (λ e i es, list_cast_of_aux x es.1 es.2 e)
private meta def h_generalize_arg_p_aux : pexpr → parser (pexpr × name)
| (app (app (macro _ [const `heq _ ]) h) (local_const x _ _ _)) := pure (h, x)
| _ := fail "parse error"
private meta def h_generalize_arg_p : parser (pexpr × name) :=
with_desc "expr == id" $ parser.pexpr 0 >>= h_generalize_arg_p_aux
/--
`h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with
`x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple
times (not necessarily with the same proof), they are all replaced by `x`. `cast`
`eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated
as casts.
`h_generalize Hx : e == x with h` adds hypothesis `α = β` with `e : α, x : β`.
`h_generalize Hx : e == x with _` chooses automatically chooses the name of
assumption `α = β`.
`h_generalize! Hx : e == x` reverts `Hx`.
when `Hx` is omitted, assumption `Hx : e == x` is not added.
-/
meta def h_generalize (rev : parse (tk "!")?)
(h : parse ident_?)
(_ : parse (tk ":"))
(arg : parse h_generalize_arg_p)
(eqs_h : parse ( (tk "with" >> pure <$> ident_) <|> pure [])) :
tactic unit :=
do let (e,n) := arg,
let h' := if h = `_ then none else h,
h' ← (h' : tactic name) <|> get_unused_name ("h" ++ n.to_string : string),
e ← to_expr e,
tgt ← target,
((e,x,eq_h)::es) ← list_cast_of e tgt | fail "no cast found",
interactive.generalize h' () (to_pexpr e, n),
asm ← get_local h',
v ← get_local n,
hs ← es.mmap (λ ⟨e,_⟩, mk_app `eq [e,v]),
(eqs_h.zip [e]).mmap' (λ ⟨h,e⟩, do
h ← if h ≠ `_ then pure h else get_unused_name `h,
() <$ note h none eq_h ),
hs.mmap' (λ h,
do h' ← assert `h h,
tactic.exact asm,
try (rewrite_target h'),
tactic.clear h' ),
when h.is_some (do
(to_expr ``(heq_of_eq_rec_left %%eq_h %%asm)
<|> to_expr ``(heq_of_eq_mp %%eq_h %%asm))
>>= note h' none >> pure ()),
tactic.clear asm,
when rev.is_some (interactive.revert [n])
/-- `choose a b h using hyp` takes an hypothesis `hyp` of the form
`∀ (x : X) (y : Y), ∃ (a : A) (b : B), P x y a b` for some `P : X → Y → A → B → Prop` and outputs
into context a function `a : X → Y → A`, `b : X → Y → B` and a proposition `h` stating
`∀ (x : X) (y : Y), P x y (a x y) (b x y)`. It presumably also works with dependent versions.
Example:
```lean
example (h : ∀n m : ℕ, ∃i j, m = n + i ∨ m + j = n) : true :=
begin
choose i j h using h,
guard_hyp i := ℕ → ℕ → ℕ,
guard_hyp j := ℕ → ℕ → ℕ,
guard_hyp h := ∀ (n m : ℕ), m = n + i n m ∨ m + j n m = n,
trivial
end
```
-/
meta def choose (first : parse ident) (names : parse ident*) (tgt : parse (tk "using" *> texpr)?) :
tactic unit := do
tgt ← match tgt with
| none := get_local `this
| some e := tactic.i_to_expr_strict e
end,
tactic.choose tgt (first :: names),
try (tactic.clear tgt)
end interactive
end tactic
|
9851b3d5d336f93c145040769c3c6f81c0627d74 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /test/random.lean | dc764e5acc6b2d5efa79ba9fdffc7e4e4e064b39 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 2,353 | lean | import system.random.basic
import data.nat.prime
import data.zmod.basic
/-- fermat's primality test -/
def primality_test (p : ℕ) : rand bool :=
if h : 2 ≤ p-1 then do
n ← rand.random_r 2 (p-1) h,
-- we do arithmetic with `zmod n` so that modulo and multiplication are interleaved
return $ (n : zmod p)^(p-1) = 1
else return (p = 2)
/-- `iterated_primality_test_aux p h n` generating `n` candidate witnesses that `p` is a
composite number and concludes that `p` is prime if none of them is a valid witness -/
def iterated_primality_test_aux (p : ℕ) : ℕ → rand bool
| 0 := pure tt
| (n+1) := do
b ← primality_test p,
if b
then iterated_primality_test_aux n
else pure ff
def iterated_primality_test (p : ℕ) : rand bool :=
iterated_primality_test_aux p 10
/-- `find_prime_aux p h n` generates a candidate prime number, tests
it as well as the 19 odd numbers following it. If none of them is
(probably) prime, try again `n-1` times. -/
def find_prime_aux (p : ℕ) (h : 1 ≤ p / 2) : ℕ → rand (option ℕ)
| 0 := pure none
| (n+1) := do
k ← rand.random_r 1 (p / 2) h,
let xs := (list.range' k 20).map (λ i, 2*i+1),
some r ← option_t.run $
xs.mfirst (λ n, option_t.mk $ mcond (iterated_primality_test n) (pure (some n)) (pure none))
| find_prime_aux n,
pure r
def find_prime (p : ℕ) : rand (option ℕ) :=
if h : 1 ≤ p / 2 then
find_prime_aux p h 20
else pure none
open tactic
/- `ps` should be `[97, 101, 103, 107, 109, 113]` but
it uses a pseudo primality test and some composite numbers
also sneak in -/
run_cmd do
let xs := list.range' 90 30,
ps ← tactic.run_rand (xs.mfilter iterated_primality_test),
when (ps ≠ [97, 101, 103, 107, 109, 113])
(trace!"The random primality test also included some composite numbers: {ps}")
/- `ps` should be `[97, 101, 103, 107, 109, 113]`. This
test is deterministic because we pick the random seed -/
run_cmd do
let xs := list.range' 90 30,
let ps : list ℕ := (xs.mfilter iterated_primality_test).eval ⟨ mk_std_gen 10 ⟩,
guard (ps = [97, 101, 103, 107, 109, 113]) <|> fail "wrong list of prime numbers"
/- this finds a random probably-prime number -/
run_cmd do
some p ← tactic.run_rand (find_prime 100000) | trace "no prime found, gave up",
when (¬ nat.prime p) (trace!"The number {p} fooled Fermat's test")
|
5f74300cc3802f21c352cdaf951cf7cc527802d9 | a7dd8b83f933e72c40845fd168dde330f050b1c9 | /src/category_theory/whiskering.lean | e97466c9748ad86c57db64fbeb548b7433579cbc | [
"Apache-2.0"
] | permissive | NeilStrickland/mathlib | 10420e92ee5cb7aba1163c9a01dea2f04652ed67 | 3efbd6f6dff0fb9b0946849b43b39948560a1ffe | refs/heads/master | 1,589,043,046,346 | 1,558,938,706,000 | 1,558,938,706,000 | 181,285,984 | 0 | 0 | Apache-2.0 | 1,568,941,848,000 | 1,555,233,833,000 | Lean | UTF-8 | Lean | false | false | 7,570 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import category_theory.isomorphism
import category_theory.functor_category
namespace category_theory
universes u₁ v₁ u₂ v₂ u₃ v₃ u₄ v₄
section
variables (C : Sort u₁) [𝒞 : category.{v₁} C]
(D : Sort u₂) [𝒟 : category.{v₂} D]
(E : Sort u₃) [ℰ : category.{v₃} E]
include 𝒞 𝒟 ℰ
def whiskering_left : (C ⥤ D) ⥤ ((D ⥤ E) ⥤ (C ⥤ E)) :=
{ obj := λ F,
{ obj := λ G, F ⋙ G,
map := λ G H α,
{ app := λ c, α.app (F.obj c),
naturality' := by intros X Y f; rw [functor.comp_map, functor.comp_map, α.naturality] } },
map := λ F G τ,
{ app := λ H,
{ app := λ c, H.map (τ.app c),
naturality' := λ X Y f, begin dsimp, rw [←H.map_comp, ←H.map_comp, ←τ.naturality] end },
naturality' := λ X Y f, begin ext1, dsimp, rw [f.naturality] end } }
def whiskering_right : (D ⥤ E) ⥤ ((C ⥤ D) ⥤ (C ⥤ E)) :=
{ obj := λ H,
{ obj := λ F, F ⋙ H,
map := λ _ _ α,
{ app := λ c, H.map (α.app c),
naturality' := by intros X Y f;
rw [functor.comp_map, functor.comp_map, ←H.map_comp, ←H.map_comp, α.naturality] } },
map := λ G H τ,
{ app := λ F,
{ app := λ c, τ.app (F.obj c),
naturality' := λ X Y f, begin dsimp, rw [τ.naturality] end },
naturality' := λ X Y f, begin ext1, dsimp, rw [←nat_trans.naturality] end } }
variables {C} {D} {E}
def whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) : (F ⋙ G) ⟶ (F ⋙ H) :=
((whiskering_left C D E).obj F).map α
@[simp] lemma whiskering_left_obj_obj (F : C ⥤ D) (G : D ⥤ E) :
((whiskering_left C D E).obj F).obj G = F ⋙ G :=
rfl
@[simp] lemma whiskering_left_obj_map (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) :
((whiskering_left C D E).obj F).map α = whisker_left F α :=
rfl
@[simp] lemma whiskering_left_map_app_app {F G : C ⥤ D} (τ : F ⟶ G) (H : D ⥤ E) (c) :
(((whiskering_left C D E).map τ).app H).app c = H.map (τ.app c) :=
rfl
@[simp] lemma whisker_left.app (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) (X : C) :
(whisker_left F α).app X = α.app (F.obj X) :=
rfl
def whisker_right {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) : (G ⋙ F) ⟶ (H ⋙ F) :=
((whiskering_right C D E).obj F).map α
@[simp] lemma whiskering_right_obj_obj (G : C ⥤ D) (F : D ⥤ E) :
((whiskering_right C D E).obj F).obj G = G ⋙ F :=
rfl
@[simp] lemma whiskering_right_obj_map {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) :
((whiskering_right C D E).obj F).map α = whisker_right α F :=
rfl
@[simp] lemma whiskering_right_map_app_app (F : C ⥤ D) {G H : D ⥤ E} (τ : G ⟶ H) (c) :
(((whiskering_right C D E).map τ).app F).app c = τ.app (F.obj c) :=
rfl
@[simp] lemma whisker_right.app {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) (X : C) :
(whisker_right α F).app X = F.map (α.app X) :=
rfl
@[simp] lemma whisker_left_id (F : C ⥤ D) {G : D ⥤ E} :
whisker_left F (nat_trans.id G) = nat_trans.id (F.comp G) :=
rfl
@[simp] lemma whisker_left_id' (F : C ⥤ D) {G : D ⥤ E} :
whisker_left F (𝟙 G) = 𝟙 (F.comp G) :=
rfl
@[simp] lemma whisker_right_id {G : C ⥤ D} (F : D ⥤ E) :
whisker_right (nat_trans.id G) F = nat_trans.id (G.comp F) :=
((whiskering_right C D E).obj F).map_id _
@[simp] lemma whisker_right_id' {G : C ⥤ D} (F : D ⥤ E) :
whisker_right (𝟙 G) F = 𝟙 (G.comp F) :=
((whiskering_right C D E).obj F).map_id _
@[simp] lemma whisker_left_comp (F : C ⥤ D) {G H K : D ⥤ E} (α : G ⟶ H) (β : H ⟶ K) :
whisker_left F (α ≫ β) = (whisker_left F α) ≫ (whisker_left F β) :=
rfl
@[simp] lemma whisker_right_comp {G H K : C ⥤ D} (α : G ⟶ H) (β : H ⟶ K) (F : D ⥤ E) :
whisker_right (α ≫ β) F = (whisker_right α F) ≫ (whisker_right β F) :=
((whiskering_right C D E).obj F).map_comp α β
def iso_whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) : (F ⋙ G) ≅ (F ⋙ H) :=
((whiskering_left C D E).obj F).map_iso α
@[simp] lemma iso_whisker_left_hom (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) :
(iso_whisker_left F α).hom = whisker_left F α.hom :=
rfl
@[simp] lemma iso_whisker_left_inv (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) :
(iso_whisker_left F α).inv = whisker_left F α.inv :=
rfl
def iso_whisker_right {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : (G ⋙ F) ≅ (H ⋙ F) :=
((whiskering_right C D E).obj F).map_iso α
@[simp] lemma iso_whisker_right_hom {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) :
(iso_whisker_right α F).hom = whisker_right α.hom F :=
rfl
@[simp] lemma iso_whisker_right_inv {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) :
(iso_whisker_right α F).inv = whisker_right α.inv F :=
rfl
variables {B : Sort u₄} [ℬ : category.{v₄} B]
include ℬ
local attribute [elab_simple] whisker_left whisker_right
@[simp] lemma whisker_left_twice (F : B ⥤ C) (G : C ⥤ D) {H K : D ⥤ E} (α : H ⟶ K) :
whisker_left F (whisker_left G α) = whisker_left (F ⋙ G) α :=
rfl
@[simp] lemma whisker_right_twice {H K : B ⥤ C} (F : C ⥤ D) (G : D ⥤ E) (α : H ⟶ K) :
whisker_right (whisker_right α F) G = whisker_right α (F ⋙ G) :=
rfl
lemma whisker_right_left (F : B ⥤ C) {G H : C ⥤ D} (α : G ⟶ H) (K : D ⥤ E) :
whisker_right (whisker_left F α) K = whisker_left F (whisker_right α K) :=
rfl
end
namespace functor
universes u₅ v₅
variables {A : Sort u₁} [𝒜 : category.{v₁} A]
variables {B : Sort u₂} [ℬ : category.{v₂} B]
include 𝒜 ℬ
def left_unitor (F : A ⥤ B) : ((functor.id _) ⋙ F) ≅ F :=
{ hom := { app := λ X, 𝟙 (F.obj X) },
inv := { app := λ X, 𝟙 (F.obj X) } }
@[simp] lemma left_unitor_hom_app {F : A ⥤ B} {X} : F.left_unitor.hom.app X = 𝟙 _ := rfl
@[simp] lemma left_unitor_inv_app {F : A ⥤ B} {X} : F.left_unitor.inv.app X = 𝟙 _ := rfl
def right_unitor (F : A ⥤ B) : (F ⋙ (functor.id _)) ≅ F :=
{ hom := { app := λ X, 𝟙 (F.obj X) },
inv := { app := λ X, 𝟙 (F.obj X) } }
@[simp] lemma right_unitor_hom_app {F : A ⥤ B} {X} : F.right_unitor.hom.app X = 𝟙 _ := rfl
@[simp] lemma right_unitor_inv_app {F : A ⥤ B} {X} : F.right_unitor.inv.app X = 𝟙 _ := rfl
variables {C : Sort u₃} [𝒞 : category.{v₃} C]
variables {D : Sort u₄} [𝒟 : category.{v₄} D]
include 𝒞 𝒟
def associator (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) : ((F ⋙ G) ⋙ H) ≅ (F ⋙ (G ⋙ H)) :=
{ hom := { app := λ _, 𝟙 _ },
inv := { app := λ _, 𝟙 _ } }
@[simp] lemma associator_hom_app {F : A ⥤ B} {G : B ⥤ C} {H : C ⥤ D} {X} :
(associator F G H).hom.app X = 𝟙 _ := rfl
@[simp] lemma associator_inv_app {F : A ⥤ B} {G : B ⥤ C} {H : C ⥤ D} {X} :
(associator F G H).inv.app X = 𝟙 _ := rfl
omit 𝒟
lemma triangle (F : A ⥤ B) (G : B ⥤ C) :
(associator F (functor.id B) G).hom ≫ (whisker_left F (left_unitor G).hom) =
(whisker_right (right_unitor F).hom G) :=
begin
ext1,
dsimp [associator, left_unitor, right_unitor],
simp
end
variables {E : Sort u₅} [ℰ : category.{v₅} E]
include 𝒟 ℰ
variables (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) (K : D ⥤ E)
lemma pentagon :
(whisker_right (associator F G H).hom K) ≫ (associator F (G ⋙ H) K).hom ≫ (whisker_left F (associator G H K).hom) =
((associator (F ⋙ G) H K).hom ≫ (associator F G (H ⋙ K)).hom) :=
begin
ext1,
dsimp [associator],
simp,
end
end functor
end category_theory
|
cdd5a41981c9ee9fde20013097bca3d920b01672 | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/topology/subset_properties.lean | fa42d232be4ac70273ba017cd36cc9788d722f20 | [
"Apache-2.0"
] | permissive | dexmagic/mathlib | ff48eefc56e2412429b31d4fddd41a976eb287ce | 7a5d15a955a92a90e1d398b2281916b9c41270b2 | refs/heads/master | 1,693,481,322,046 | 1,633,360,193,000 | 1,633,360,193,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 69,532 | 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, Yury Kudryashov
-/
import topology.bases
import data.finset.order
import data.set.accumulate
import tactic.tfae
/-!
# Properties of subsets of topological spaces
In this file we define various properties of subsets of a topological space, and some classes on
topological spaces.
## Main definitions
We define the following properties for sets in a topological space:
* `is_compact`: each open cover has a finite subcover. This is defined in mathlib using filters.
The main property of a compact set is `is_compact.elim_finite_subcover`.
* `is_clopen`: a set that is both open and closed.
* `is_irreducible`: a nonempty set that has contains no non-trivial pair of disjoint opens.
See also the section below in the module doc.
For each of these definitions (except for `is_clopen`), we also have a class stating that the whole
space satisfies that property:
`compact_space`, `irreducible_space`
Furthermore, we have two more classes:
* `locally_compact_space`: for every point `x`, every open neighborhood of `x` contains a compact
neighborhood of `x`. The definition is formulated in terms of the neighborhood filter.
* `sigma_compact_space`: a space that is the union of a countably many compact subspaces.
## On the definition of irreducible and connected sets/spaces
In informal mathematics, irreducible spaces are assumed to be nonempty.
We formalise the predicate without that assumption as `is_preirreducible`.
In other words, the only difference is whether the empty space counts as irreducible.
There are good reasons to consider the empty space to be “too simple to be simple”
See also https://ncatlab.org/nlab/show/too+simple+to+be+simple,
and in particular
https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions.
-/
open set filter classical topological_space
open_locale classical topological_space filter
universes u v
variables {α : Type u} {β : Type v} [topological_space α] {s t : set α}
/- compact sets -/
section compact
/-- A set `s` is compact if for every nontrivial filter `f` that contains `s`,
there exists `a ∈ s` such that every set of `f` meets every neighborhood of `a`. -/
def is_compact (s : set α) := ∀ ⦃f⦄ [ne_bot f], f ≤ 𝓟 s → ∃a∈s, cluster_pt a f
/-- The complement to a compact set belongs to a filter `f` if it belongs to each filter
`𝓝 a ⊓ f`, `a ∈ s`. -/
lemma is_compact.compl_mem_sets (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, sᶜ ∈ 𝓝 a ⊓ f) :
sᶜ ∈ f :=
begin
contrapose! hf,
simp only [not_mem_iff_inf_principal_compl, compl_compl, inf_assoc, ← exists_prop] at hf ⊢,
exact @hs _ hf inf_le_right
end
/-- The complement to a compact set belongs to a filter `f` if each `a ∈ s` has a neighborhood `t`
within `s` such that `tᶜ` belongs to `f`. -/
lemma is_compact.compl_mem_sets_of_nhds_within (hs : is_compact s) {f : filter α}
(hf : ∀ a ∈ s, ∃ t ∈ 𝓝[s] a, tᶜ ∈ f) :
sᶜ ∈ f :=
begin
refine hs.compl_mem_sets (λ a ha, _),
rcases hf a ha with ⟨t, ht, hst⟩,
replace ht := mem_inf_principal.1 ht,
apply mem_inf_of_inter ht hst,
rintros x ⟨h₁, h₂⟩ hs,
exact h₂ (h₁ hs)
end
/-- If `p : set α → Prop` is stable under restriction and union, and each point `x`
of a compact set `s` has a neighborhood `t` within `s` such that `p t`, then `p s` holds. -/
@[elab_as_eliminator]
lemma is_compact.induction_on {s : set α} (hs : is_compact s) {p : set α → Prop} (he : p ∅)
(hmono : ∀ ⦃s t⦄, s ⊆ t → p t → p s) (hunion : ∀ ⦃s t⦄, p s → p t → p (s ∪ t))
(hnhds : ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, p t) :
p s :=
let f : filter α :=
{ sets := {t | p tᶜ},
univ_sets := by simpa,
sets_of_superset := λ t₁ t₂ ht₁ ht, hmono (compl_subset_compl.2 ht) ht₁,
inter_sets := λ t₁ t₂ ht₁ ht₂, by simp [compl_inter, hunion ht₁ ht₂] } in
have sᶜ ∈ f, from hs.compl_mem_sets_of_nhds_within (by simpa using hnhds),
by simpa
/-- The intersection of a compact set and a closed set is a compact set. -/
lemma is_compact.inter_right (hs : is_compact s) (ht : is_closed t) :
is_compact (s ∩ t) :=
begin
introsI f hnf hstf,
obtain ⟨a, hsa, ha⟩ : ∃ a ∈ s, cluster_pt a f :=
hs (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))),
have : a ∈ t :=
(ht.mem_of_nhds_within_ne_bot $ ha.mono $
le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))),
exact ⟨a, ⟨hsa, this⟩, ha⟩
end
/-- The intersection of a closed set and a compact set is a compact set. -/
lemma is_compact.inter_left (ht : is_compact t) (hs : is_closed s) : is_compact (s ∩ t) :=
inter_comm t s ▸ ht.inter_right hs
/-- The set difference of a compact set and an open set is a compact set. -/
lemma is_compact.diff (hs : is_compact s) (ht : is_open t) : is_compact (s \ t) :=
hs.inter_right (is_closed_compl_iff.mpr ht)
/-- A closed subset of a compact set is a compact set. -/
lemma compact_of_is_closed_subset (hs : is_compact s) (ht : is_closed t) (h : t ⊆ s) :
is_compact t :=
inter_eq_self_of_subset_right h ▸ hs.inter_right ht
lemma is_compact.adherence_nhdset {f : filter α}
(hs : is_compact s) (hf₂ : f ≤ 𝓟 s) (ht₁ : is_open t) (ht₂ : ∀a∈s, cluster_pt a f → a ∈ t) :
t ∈ f :=
classical.by_cases mem_of_eq_bot $
assume : f ⊓ 𝓟 tᶜ ≠ ⊥,
let ⟨a, ha, (hfa : cluster_pt a $ f ⊓ 𝓟 tᶜ)⟩ := @@hs ⟨this⟩ $ inf_le_of_left_le hf₂ in
have a ∈ t,
from ht₂ a ha (hfa.of_inf_left),
have tᶜ ∩ t ∈ 𝓝[tᶜ] a,
from inter_mem_nhds_within _ (is_open.mem_nhds ht₁ this),
have A : 𝓝[tᶜ] a = ⊥,
from empty_mem_iff_bot.1 $ compl_inter_self t ▸ this,
have 𝓝[tᶜ] a ≠ ⊥,
from hfa.of_inf_right.ne,
absurd A this
lemma is_compact_iff_ultrafilter_le_nhds :
is_compact s ↔ (∀f : ultrafilter α, ↑f ≤ 𝓟 s → ∃a∈s, ↑f ≤ 𝓝 a) :=
begin
refine (forall_ne_bot_le_iff _).trans _,
{ rintro f g hle ⟨a, has, haf⟩,
exact ⟨a, has, haf.mono hle⟩ },
{ simp only [ultrafilter.cluster_pt_iff] }
end
alias is_compact_iff_ultrafilter_le_nhds ↔ is_compact.ultrafilter_le_nhds _
/-- For every open directed cover of a compact set, there exists a single element of the
cover which itself includes the set. -/
lemma is_compact.elim_directed_cover {ι : Type v} [hι : nonempty ι] (hs : is_compact s)
(U : ι → set α) (hUo : ∀i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) (hdU : directed (⊆) U) :
∃ i, s ⊆ U i :=
hι.elim $ λ i₀, is_compact.induction_on hs ⟨i₀, empty_subset _⟩
(λ s₁ s₂ hs ⟨i, hi⟩, ⟨i, subset.trans hs hi⟩)
(λ s₁ s₂ ⟨i, hi⟩ ⟨j, hj⟩, let ⟨k, hki, hkj⟩ := hdU i j in
⟨k, union_subset (subset.trans hi hki) (subset.trans hj hkj)⟩)
(λ x hx, let ⟨i, hi⟩ := mem_Union.1 (hsU hx) in
⟨U i, mem_nhds_within_of_mem_nhds (is_open.mem_nhds (hUo i) hi), i, subset.refl _⟩)
/-- For every open cover of a compact set, there exists a finite subcover. -/
lemma is_compact.elim_finite_subcover {ι : Type v} (hs : is_compact s)
(U : ι → set α) (hUo : ∀i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) :
∃ t : finset ι, s ⊆ ⋃ i ∈ t, U i :=
hs.elim_directed_cover _ (λ t, is_open_bUnion $ λ i _, hUo i) (Union_eq_Union_finset U ▸ hsU)
(directed_of_sup $ λ t₁ t₂ h, bUnion_subset_bUnion_left h)
lemma is_compact.elim_nhds_subcover' (hs : is_compact s) (U : Π x ∈ s, set α)
(hU : ∀ x ∈ s, U x ‹x ∈ s› ∈ 𝓝 x) :
∃ t : finset s, s ⊆ ⋃ x ∈ t, U (x : s) x.2 :=
(hs.elim_finite_subcover (λ x : s, interior (U x x.2)) (λ x, is_open_interior)
(λ x hx, mem_Union.2 ⟨⟨x, hx⟩, mem_interior_iff_mem_nhds.2 $ hU _ _⟩)).imp $ λ t ht,
subset.trans ht $ bUnion_subset_bUnion_right $ λ _ _, interior_subset
lemma is_compact.elim_nhds_subcover (hs : is_compact s) (U : α → set α) (hU : ∀ x ∈ s, U x ∈ 𝓝 x) :
∃ t : finset α, (∀ x ∈ t, x ∈ s) ∧ s ⊆ ⋃ x ∈ t, U x :=
let ⟨t, ht⟩ := hs.elim_nhds_subcover' (λ x _, U x) hU
in ⟨t.image coe, λ x hx, let ⟨y, hyt, hyx⟩ := finset.mem_image.1 hx in hyx ▸ y.2,
by rwa finset.set_bUnion_finset_image⟩
/-- For every family of closed sets whose intersection avoids a compact set,
there exists a finite subfamily whose intersection avoids this compact set. -/
lemma is_compact.elim_finite_subfamily_closed {s : set α} {ι : Type v} (hs : is_compact s)
(Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) :
∃ t : finset ι, s ∩ (⋂ i ∈ t, Z i) = ∅ :=
let ⟨t, ht⟩ := hs.elim_finite_subcover (λ i, (Z i)ᶜ) (λ i, (hZc i).is_open_compl)
(by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using hsZ)
in
⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using ht⟩
/-- If `s` is a compact set in a topological space `α` and `f : ι → set α` is a locally finite
family of sets, then `f i ∩ s` is nonempty only for a finitely many `i`. -/
lemma locally_finite.finite_nonempty_inter_compact {ι : Type*} {f : ι → set α}
(hf : locally_finite f) {s : set α} (hs : is_compact s) :
finite {i | (f i ∩ s).nonempty} :=
begin
choose U hxU hUf using hf,
rcases hs.elim_nhds_subcover U (λ x _, hxU x) with ⟨t, -, hsU⟩,
refine (t.finite_to_set.bUnion (λ x _, hUf x)).subset _,
rintro i ⟨x, hx⟩,
rcases mem_bUnion_iff.1 (hsU hx.2) with ⟨c, hct, hcx⟩,
exact mem_bUnion hct ⟨x, hx.1, hcx⟩
end
/-- To show that a compact set intersects the intersection of a family of closed sets,
it is sufficient to show that it intersects every finite subfamily. -/
lemma is_compact.inter_Inter_nonempty {s : set α} {ι : Type v} (hs : is_compact s)
(Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : ∀ t : finset ι, (s ∩ ⋂ i ∈ t, Z i).nonempty) :
(s ∩ ⋂ i, Z i).nonempty :=
begin
simp only [← ne_empty_iff_nonempty] at hsZ ⊢,
apply mt (hs.elim_finite_subfamily_closed Z hZc), push_neg, exact hsZ
end
/-- Cantor's intersection theorem:
the intersection of a directed family of nonempty compact closed sets is nonempty. -/
lemma is_compact.nonempty_Inter_of_directed_nonempty_compact_closed
{ι : Type v} [hι : nonempty ι] (Z : ι → set α) (hZd : directed (⊇) Z)
(hZn : ∀ i, (Z i).nonempty) (hZc : ∀ i, is_compact (Z i)) (hZcl : ∀ i, is_closed (Z i)) :
(⋂ i, Z i).nonempty :=
begin
apply hι.elim,
intro i₀,
let Z' := λ i, Z i ∩ Z i₀,
suffices : (⋂ i, Z' i).nonempty,
{ exact nonempty.mono (Inter_subset_Inter $ assume i, inter_subset_left (Z i) (Z i₀)) this },
rw ← ne_empty_iff_nonempty,
intro H,
obtain ⟨t, ht⟩ : ∃ (t : finset ι), ((Z i₀) ∩ ⋂ (i ∈ t), Z' i) = ∅,
from (hZc i₀).elim_finite_subfamily_closed Z'
(assume i, is_closed.inter (hZcl i) (hZcl i₀)) (by rw [H, inter_empty]),
obtain ⟨i₁, hi₁⟩ : ∃ i₁ : ι, Z i₁ ⊆ Z i₀ ∧ ∀ i ∈ t, Z i₁ ⊆ Z' i,
{ rcases directed.finset_le hZd t with ⟨i, hi⟩,
rcases hZd i i₀ with ⟨i₁, hi₁, hi₁₀⟩,
use [i₁, hi₁₀],
intros j hj,
exact subset_inter (subset.trans hi₁ (hi j hj)) hi₁₀ },
suffices : ((Z i₀) ∩ ⋂ (i ∈ t), Z' i).nonempty,
{ rw ← ne_empty_iff_nonempty at this, contradiction },
refine nonempty.mono _ (hZn i₁),
exact subset_inter hi₁.left (subset_bInter hi₁.right)
end
/-- Cantor's intersection theorem for sequences indexed by `ℕ`:
the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/
lemma is_compact.nonempty_Inter_of_sequence_nonempty_compact_closed
(Z : ℕ → set α) (hZd : ∀ i, Z (i+1) ⊆ Z i)
(hZn : ∀ i, (Z i).nonempty) (hZ0 : is_compact (Z 0)) (hZcl : ∀ i, is_closed (Z i)) :
(⋂ i, Z i).nonempty :=
have Zmono : _, from @monotone_nat_of_le_succ (order_dual _) _ Z hZd,
have hZd : directed (⊇) Z, from directed_of_sup Zmono,
have ∀ i, Z i ⊆ Z 0, from assume i, Zmono $ zero_le i,
have hZc : ∀ i, is_compact (Z i), from assume i, compact_of_is_closed_subset hZ0 (hZcl i) (this i),
is_compact.nonempty_Inter_of_directed_nonempty_compact_closed Z hZd hZn hZc hZcl
/-- For every open cover of a compact set, there exists a finite subcover. -/
lemma is_compact.elim_finite_subcover_image {b : set β} {c : β → set α}
(hs : is_compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) :
∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i :=
begin
rcases hs.elim_finite_subcover (λ i, c i : b → set α) _ _ with ⟨d, hd⟩;
[skip, simpa using hc₁, simpa using hc₂],
refine ⟨↑(d.image coe), _, finset.finite_to_set _, _⟩,
{ simp },
{ rwa [finset.coe_image, bUnion_image] }
end
/-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`,
there exists a finite subfamily whose intersection avoids `s`. -/
theorem is_compact_of_finite_subfamily_closed
(h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) :
is_compact s :=
assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, cluster_pt x f),
have hf : ∀x∈s, 𝓝 x ⊓ f = ⊥,
by simpa only [cluster_pt, not_exists, not_not, ne_bot_iff],
have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t,
from assume ⟨x, hxs, hx⟩,
have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_mem_iff_bot, hf x hxs],
let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_iff] at this; exact this in
have ∅ ∈ 𝓝[t₂] x,
by { rw [ht, inter_comm], exact inter_mem_nhds_within _ ht₁ },
have 𝓝[t₂] x = ⊥,
by rwa [empty_mem_iff_bot] at this,
by simp only [closure_eq_cluster_pts] at hx; exact (hx t₂ ht₂).ne this,
let ⟨t, ht⟩ := h (λ i : f.sets, closure i.1) (λ i, is_closed_closure)
(by simpa [eq_empty_iff_forall_not_mem, not_exists]) in
have (⋂i∈t, subtype.val i) ∈ f,
from t.Inter_mem_sets.2 $ assume i hi, i.2,
have s ∩ (⋂i∈t, subtype.val i) ∈ f,
from inter_mem (le_principal_iff.1 hfs) this,
have ∅ ∈ f,
from mem_of_superset this $ assume x ⟨hxs, hx⟩,
let ⟨i, hit, hxi⟩ := (show ∃i ∈ t, x ∉ closure (subtype.val i),
by { rw [eq_empty_iff_forall_not_mem] at ht, simpa [hxs, not_forall] using ht x }) in
have x ∈ closure i.val, from subset_closure (mem_bInter_iff.mp hx i hit),
show false, from hxi this,
hfn.ne $ by rwa [empty_mem_iff_bot] at this
/-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/
lemma is_compact_of_finite_subcover
(h : Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) →
s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) :
is_compact s :=
is_compact_of_finite_subfamily_closed $
assume ι Z hZc hsZ,
let ⟨t, ht⟩ := h (λ i, (Z i)ᶜ) (assume i, is_open_compl_iff.mpr $ hZc i)
(by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using hsZ)
in
⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using ht⟩
/-- A set `s` is compact if and only if
for every open cover of `s`, there exists a finite subcover. -/
lemma is_compact_iff_finite_subcover :
is_compact s ↔ (Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) →
s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) :=
⟨assume hs ι, hs.elim_finite_subcover, is_compact_of_finite_subcover⟩
/-- A set `s` is compact if and only if
for every family of closed sets whose intersection avoids `s`,
there exists a finite subfamily whose intersection avoids `s`. -/
theorem is_compact_iff_finite_subfamily_closed :
is_compact s ↔ (Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) :=
⟨assume hs ι, hs.elim_finite_subfamily_closed, is_compact_of_finite_subfamily_closed⟩
@[simp]
lemma is_compact_empty : is_compact (∅ : set α) :=
assume f hnf hsf, not.elim hnf.ne $
empty_mem_iff_bot.1 $ le_principal_iff.1 hsf
@[simp]
lemma is_compact_singleton {a : α} : is_compact ({a} : set α) :=
λ f hf hfa, ⟨a, rfl, cluster_pt.of_le_nhds'
(hfa.trans $ by simpa only [principal_singleton] using pure_le_nhds a) hf⟩
lemma set.subsingleton.is_compact {s : set α} (hs : s.subsingleton) : is_compact s :=
subsingleton.induction_on hs is_compact_empty $ λ x, is_compact_singleton
lemma set.finite.compact_bUnion {s : set β} {f : β → set α} (hs : finite s)
(hf : ∀i ∈ s, is_compact (f i)) :
is_compact (⋃i ∈ s, f i) :=
is_compact_of_finite_subcover $ assume ι U hUo hsU,
have ∀i : subtype s, ∃t : finset ι, f i ⊆ (⋃ j ∈ t, U j), from
assume ⟨i, hi⟩, (hf i hi).elim_finite_subcover _ hUo
(calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi
... ⊆ ⋃j, U j : hsU),
let ⟨finite_subcovers, h⟩ := axiom_of_choice this in
by haveI : fintype (subtype s) := hs.fintype; exact
let t := finset.bUnion finset.univ finite_subcovers in
have (⋃i ∈ s, f i) ⊆ (⋃ i ∈ t, U i), from bUnion_subset $
assume i hi, calc
f i ⊆ (⋃ j ∈ finite_subcovers ⟨i, hi⟩, U j) : (h ⟨i, hi⟩)
... ⊆ (⋃ j ∈ t, U j) : bUnion_subset_bUnion_left $
assume j hj, finset.mem_bUnion.mpr ⟨_, finset.mem_univ _, hj⟩,
⟨t, this⟩
lemma finset.compact_bUnion (s : finset β) {f : β → set α} (hf : ∀i ∈ s, is_compact (f i)) :
is_compact (⋃i ∈ s, f i) :=
s.finite_to_set.compact_bUnion hf
lemma compact_accumulate {K : ℕ → set α} (hK : ∀ n, is_compact (K n)) (n : ℕ) :
is_compact (accumulate K n) :=
(finite_le_nat n).compact_bUnion $ λ k _, hK k
lemma compact_Union {f : β → set α} [fintype β]
(h : ∀i, is_compact (f i)) : is_compact (⋃i, f i) :=
by rw ← bUnion_univ; exact finite_univ.compact_bUnion (λ i _, h i)
lemma set.finite.is_compact (hs : finite s) : is_compact s :=
bUnion_of_singleton s ▸ hs.compact_bUnion (λ _ _, is_compact_singleton)
lemma finite_of_is_compact_of_discrete [discrete_topology α] (s : set α) (hs : is_compact s) :
s.finite :=
begin
have := hs.elim_finite_subcover (λ x : α, ({x} : set α))
(λ x, is_open_discrete _),
simp only [set.subset_univ, forall_prop_of_true, set.Union_of_singleton] at this,
rcases this with ⟨t, ht⟩,
suffices : (⋃ (i : α) (H : i ∈ t), {i} : set α) = (t : set α),
{ rw this at ht, exact t.finite_to_set.subset ht },
ext x,
simp only [exists_prop, set.mem_Union, set.mem_singleton_iff, exists_eq_right', finset.mem_coe]
end
lemma is_compact.union (hs : is_compact s) (ht : is_compact t) : is_compact (s ∪ t) :=
by rw union_eq_Union; exact compact_Union (λ b, by cases b; assumption)
lemma is_compact.insert (hs : is_compact s) (a) : is_compact (insert a s) :=
is_compact_singleton.union hs
/-- If `V : ι → set α` is a decreasing family of closed compact sets then any neighborhood of
`⋂ i, V i` contains some `V i`. We assume each `V i` is compact *and* closed because `α` is
not assumed to be Hausdorff. See `exists_subset_nhd_of_compact` for version assuming this. -/
lemma exists_subset_nhd_of_compact' {ι : Type*} [nonempty ι] {V : ι → set α} (hV : directed (⊇) V)
(hV_cpct : ∀ i, is_compact (V i)) (hV_closed : ∀ i, is_closed (V i))
{U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U :=
begin
set Y := ⋂ i, V i,
obtain ⟨W, hsubW, W_op, hWU⟩ : ∃ W, Y ⊆ W ∧ is_open W ∧ W ⊆ U,
from exists_open_set_nhds hU,
suffices : ∃ i, V i ⊆ W,
{ rcases this with ⟨i, hi⟩,
refine ⟨i, set.subset.trans hi hWU⟩ },
by_contradiction H,
push_neg at H,
replace H : ∀ i, (V i ∩ Wᶜ).nonempty := λ i, set.inter_compl_nonempty_iff.mpr (H i),
have : (⋂ i, V i ∩ Wᶜ).nonempty,
{ apply is_compact.nonempty_Inter_of_directed_nonempty_compact_closed _ _ H,
{ intro i,
exact (hV_cpct i).inter_right W_op.is_closed_compl },
{ intro i,
apply (hV_closed i).inter W_op.is_closed_compl },
{ intros i j,
rcases hV i j with ⟨k, hki, hkj⟩,
use k,
split ; intro x ; simp only [and_imp, mem_inter_eq, mem_compl_eq] ; tauto } },
have : ¬ (⋂ (i : ι), V i) ⊆ W,
by simpa [← Inter_inter, inter_compl_nonempty_iff],
contradiction
end
namespace filter
/-- `filter.cocompact` is the filter generated by complements to compact sets. -/
def cocompact (α : Type*) [topological_space α] : filter α :=
⨅ (s : set α) (hs : is_compact s), 𝓟 (sᶜ)
lemma has_basis_cocompact : (cocompact α).has_basis is_compact compl :=
has_basis_binfi_principal'
(λ s hs t ht, ⟨s ∪ t, hs.union ht, compl_subset_compl.2 (subset_union_left s t),
compl_subset_compl.2 (subset_union_right s t)⟩)
⟨∅, is_compact_empty⟩
lemma mem_cocompact : s ∈ cocompact α ↔ ∃ t, is_compact t ∧ tᶜ ⊆ s :=
has_basis_cocompact.mem_iff.trans $ exists_congr $ λ t, exists_prop
lemma mem_cocompact' : s ∈ cocompact α ↔ ∃ t, is_compact t ∧ sᶜ ⊆ t :=
mem_cocompact.trans $ exists_congr $ λ t, and_congr_right $ λ ht, compl_subset_comm
lemma _root_.is_compact.compl_mem_cocompact (hs : is_compact s) : sᶜ ∈ filter.cocompact α :=
has_basis_cocompact.mem_of_mem hs
/-- `filter.coclosed_compact` is the filter generated by complements to closed compact sets.
In a Hausdorff space, this is the same as `filter.cocompact`. -/
def coclosed_compact (α : Type*) [topological_space α] : filter α :=
⨅ (s : set α) (h₁ : is_closed s) (h₂ : is_compact s), 𝓟 (sᶜ)
lemma has_basis_coclosed_compact :
(filter.coclosed_compact α).has_basis (λ s, is_closed s ∧ is_compact s) compl :=
begin
simp only [filter.coclosed_compact, infi_and'],
refine has_basis_binfi_principal' _ ⟨∅, is_closed_empty, is_compact_empty⟩,
rintro s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩,
exact ⟨s ∪ t, ⟨⟨hs₁.union ht₁, hs₂.union ht₂⟩, compl_subset_compl.2 (subset_union_left _ _),
compl_subset_compl.2 (subset_union_right _ _)⟩⟩
end
lemma mem_coclosed_compact : s ∈ coclosed_compact α ↔ ∃ t, is_closed t ∧ is_compact t ∧ tᶜ ⊆ s :=
by simp [has_basis_coclosed_compact.mem_iff, and_assoc]
lemma mem_coclosed_compact' : s ∈ coclosed_compact α ↔ ∃ t, is_closed t ∧ is_compact t ∧ sᶜ ⊆ t :=
by simp only [mem_coclosed_compact, compl_subset_comm]
lemma cocompact_le_coclosed_compact : cocompact α ≤ coclosed_compact α :=
infi_le_infi $ λ s, le_infi $ λ _, le_rfl
end filter
section tube_lemma
variables [topological_space β]
/-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes
a product of an open neighborhood of `s` by an open neighborhood of `t`. -/
def nhds_contain_boxes (s : set α) (t : set β) : Prop :=
∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n),
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n
lemma nhds_contain_boxes.symm {s : set α} {t : set β} :
nhds_contain_boxes s t → nhds_contain_boxes t s :=
assume H n hn hp,
let ⟨u, v, uo, vo, su, tv, p⟩ :=
H (prod.swap ⁻¹' n)
(hn.preimage continuous_swap)
(by rwa [←image_subset_iff, image_swap_prod]) in
⟨v, u, vo, uo, tv, su,
by rwa [←image_subset_iff, image_swap_prod] at p⟩
lemma nhds_contain_boxes.comm {s : set α} {t : set β} :
nhds_contain_boxes s t ↔ nhds_contain_boxes t s :=
iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm
lemma nhds_contain_boxes_of_singleton {x : α} {y : β} :
nhds_contain_boxes ({x} : set α) ({y} : set β) :=
assume n hn hp,
let ⟨u, v, uo, vo, xu, yv, hp'⟩ :=
is_open_prod_iff.mp hn x y (hp $ by simp) in
⟨u, v, uo, vo, by simpa, by simpa, hp'⟩
lemma nhds_contain_boxes_of_compact {s : set α} (hs : is_compact s) (t : set β)
(H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t :=
assume n hn hp,
have ∀x : subtype s, ∃uv : set α × set β,
is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n,
from assume ⟨x, hx⟩,
have set.prod {x} t ⊆ n, from
subset.trans (prod_mono (by simpa) (subset.refl _)) hp,
let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩,
let ⟨uvs, h⟩ := classical.axiom_of_choice this in
have us_cover : s ⊆ ⋃i, (uvs i).1, from
assume x hx, subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1),
let ⟨s0, s0_cover⟩ :=
hs.elim_finite_subcover _ (λi, (h i).1) us_cover in
let u := ⋃(i ∈ s0), (uvs i).1 in
let v := ⋂(i ∈ s0), (uvs i).2 in
have is_open u, from is_open_bUnion (λi _, (h i).1),
have is_open v, from is_open_bInter s0.finite_to_set (λi _, (h i).2.1),
have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1),
have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩,
have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx',
let ⟨i,is0,hi⟩ := this in
(h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩,
⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩
/-- If `s` and `t` are compact sets and `n` is an open neighborhood of `s × t`, then there exist
open neighborhoods `u ⊇ s` and `v ⊇ t` such that `u × v ⊆ n`. -/
lemma generalized_tube_lemma {s : set α} (hs : is_compact s) {t : set β} (ht : is_compact t)
{n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) :
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n :=
have _, from
nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $
nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton,
this n hn hp
end tube_lemma
/-- Type class for compact spaces. Separation is sometimes included in the definition, especially
in the French literature, but we do not include it here. -/
class compact_space (α : Type*) [topological_space α] : Prop :=
(compact_univ : is_compact (univ : set α))
@[priority 10] -- see Note [lower instance priority]
instance subsingleton.compact_space [subsingleton α] : compact_space α :=
⟨subsingleton_univ.is_compact⟩
lemma is_compact_univ_iff : is_compact (univ : set α) ↔ compact_space α := ⟨λ h, ⟨h⟩, λ h, h.1⟩
lemma compact_univ [h : compact_space α] : is_compact (univ : set α) := h.compact_univ
lemma cluster_point_of_compact [compact_space α] (f : filter α) [ne_bot f] :
∃ x, cluster_pt x f :=
by simpa using compact_univ (show f ≤ 𝓟 univ, by simp)
lemma compact_space.elim_nhds_subcover {α : Type*} [topological_space α] [compact_space α]
(U : α → set α) (hU : ∀ x, U x ∈ 𝓝 x) :
∃ t : finset α, (⋃ x ∈ t, U x) = ⊤ :=
begin
obtain ⟨t, -, s⟩ := is_compact.elim_nhds_subcover compact_univ U (λ x m, hU x),
exact ⟨t, by { rw eq_top_iff, exact s }⟩,
end
theorem compact_space_of_finite_subfamily_closed {α : Type u} [topological_space α]
(h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
(⋂ i, Z i) = ∅ → ∃ (t : finset ι), (⋂ i ∈ t, Z i) = ∅) :
compact_space α :=
{ compact_univ :=
begin
apply is_compact_of_finite_subfamily_closed,
intros ι Z, specialize h Z,
simpa using h
end }
lemma is_closed.is_compact [compact_space α] {s : set α} (h : is_closed s) :
is_compact s :=
compact_of_is_closed_subset compact_univ h (subset_univ _)
lemma filter.cocompact_ne_bot_tfae (α : Type*) [topological_space α] :
tfae [ne_bot (filter.cocompact α),
ne_bot (filter.coclosed_compact α),
¬is_compact (univ : set α),
¬compact_space α] :=
begin
tfae_have : 1 → 2, from λ h, h.mono filter.cocompact_le_coclosed_compact,
tfae_have : 3 ↔ 4, from not_congr is_compact_univ_iff,
tfae_have : 2 → 3, from λ h₁ h₂, (filter.has_basis_coclosed_compact.ne_bot_iff.1 h₁
⟨is_closed_univ, h₂⟩).ne_empty compl_univ,
tfae_have : 3 → 1,
{ refine λ h₁, filter.has_basis_cocompact.ne_bot_iff.2 (λ s hs, _),
contrapose! h₁, rw [not_nonempty_iff_eq_empty, compl_empty_iff] at h₁,
rwa ← h₁ },
tfae_finish
end
/-- `ne_bot (cocompact α)` is the canonical way to say that `α` is not a compact space using
typeclasses. -/
instance [ne_bot (filter.cocompact α)] : ne_bot (filter.coclosed_compact α) :=
((filter.cocompact_ne_bot_tfae α).out 0 1).mp ‹_›
/-- A compact discrete space is finite. -/
noncomputable
def fintype_of_compact_of_discrete [compact_space α] [discrete_topology α] :
fintype α :=
fintype_of_univ_finite $ finite_of_is_compact_of_discrete _ compact_univ
lemma finite_cover_nhds_interior [compact_space α] {U : α → set α} (hU : ∀ x, U x ∈ 𝓝 x) :
∃ t : finset α, (⋃ x ∈ t, interior (U x)) = univ :=
let ⟨t, ht⟩ := compact_univ.elim_finite_subcover (λ x, interior (U x)) (λ x, is_open_interior)
(λ x _, mem_Union.2 ⟨x, mem_interior_iff_mem_nhds.2 (hU x)⟩)
in ⟨t, univ_subset_iff.1 ht⟩
lemma finite_cover_nhds [compact_space α] {U : α → set α} (hU : ∀ x, U x ∈ 𝓝 x) :
∃ t : finset α, (⋃ x ∈ t, U x) = univ :=
let ⟨t, ht⟩ := finite_cover_nhds_interior hU in ⟨t, univ_subset_iff.1 $
ht ▸ bUnion_subset_bUnion_right (λ x hx, interior_subset)⟩
/-- If `α` is a compact space, then a locally finite family of sets of `α` can have only finitely
many nonempty elements. -/
lemma locally_finite.finite_nonempty_of_compact {ι : Type*} [compact_space α] {f : ι → set α}
(hf : locally_finite f) :
finite {i | (f i).nonempty} :=
by simpa only [inter_univ] using hf.finite_nonempty_inter_compact compact_univ
/-- If `α` is a compact space, then a locally finite family of nonempty sets of `α` can have only
finitely many elements, `set.finite` version. -/
lemma locally_finite.finite_of_compact {ι : Type*} [compact_space α] {f : ι → set α}
(hf : locally_finite f) (hne : ∀ i, (f i).nonempty) :
finite (univ : set ι) :=
by simpa only [hne] using hf.finite_nonempty_of_compact
/-- If `α` is a compact space, then a locally finite family of nonempty sets of `α` can have only
finitely many elements, `fintype` version. -/
noncomputable def locally_finite.fintype_of_compact {ι : Type*} [compact_space α] {f : ι → set α}
(hf : locally_finite f) (hne : ∀ i, (f i).nonempty) :
fintype ι :=
fintype_of_univ_finite (hf.finite_of_compact hne)
variables [topological_space β]
lemma is_compact.image_of_continuous_on {f : α → β} (hs : is_compact s) (hf : continuous_on f s) :
is_compact (f '' s) :=
begin
intros l lne ls,
have : ne_bot (l.comap f ⊓ 𝓟 s) :=
comap_inf_principal_ne_bot_of_image_mem lne (le_principal_iff.1 ls),
obtain ⟨a, has, ha⟩ : ∃ a ∈ s, cluster_pt a (l.comap f ⊓ 𝓟 s) := @@hs this inf_le_right,
use [f a, mem_image_of_mem f has],
have : tendsto f (𝓝 a ⊓ (comap f l ⊓ 𝓟 s)) (𝓝 (f a) ⊓ l),
{ convert (hf a has).inf (@tendsto_comap _ _ f l) using 1,
rw nhds_within,
ac_refl },
exact @@tendsto.ne_bot _ this ha,
end
lemma is_compact.image {f : α → β} (hs : is_compact s) (hf : continuous f) :
is_compact (f '' s) :=
hs.image_of_continuous_on hf.continuous_on
/-- The comap of the cocompact filter on `β` by a continuous function `f : α → β` is less than or
equal to the cocompact filter on `α`.
This is a reformulation of the fact that images of compact sets are compact. -/
lemma filter.comap_cocompact {f : α → β} (hf : continuous f) :
(filter.cocompact β).comap f ≤ filter.cocompact α :=
begin
rw (filter.has_basis_cocompact.comap f).le_basis_iff filter.has_basis_cocompact,
intros t ht,
refine ⟨f '' t, ht.image hf, _⟩,
simpa using t.subset_preimage_image f
end
lemma is_compact_range [compact_space α] {f : α → β} (hf : continuous f) :
is_compact (range f) :=
by rw ← image_univ; exact compact_univ.image hf
/-- If X is is_compact then pr₂ : X × Y → Y is a closed map -/
theorem is_closed_proj_of_is_compact
{X : Type*} [topological_space X] [compact_space X]
{Y : Type*} [topological_space Y] :
is_closed_map (prod.snd : X × Y → Y) :=
begin
set πX := (prod.fst : X × Y → X),
set πY := (prod.snd : X × Y → Y),
assume C (hC : is_closed C),
rw is_closed_iff_cluster_pt at hC ⊢,
assume y (y_closure : cluster_pt y $ 𝓟 (πY '' C)),
have : ne_bot (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)),
{ suffices : ne_bot (map πY (comap πY (𝓝 y) ⊓ 𝓟 C)),
by simpa only [map_ne_bot_iff],
convert y_closure,
calc map πY (comap πY (𝓝 y) ⊓ 𝓟 C) =
𝓝 y ⊓ map πY (𝓟 C) : filter.push_pull' _ _ _
... = 𝓝 y ⊓ 𝓟 (πY '' C) : by rw map_principal },
resetI,
obtain ⟨x, hx⟩ : ∃ x, cluster_pt x (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)),
from cluster_point_of_compact _,
refine ⟨⟨x, y⟩, _, by simp [πY]⟩,
apply hC,
rw [cluster_pt, ← filter.map_ne_bot_iff πX],
convert hx,
calc map πX (𝓝 (x, y) ⊓ 𝓟 C)
= map πX (comap πX (𝓝 x) ⊓ comap πY (𝓝 y) ⊓ 𝓟 C) : by rw [nhds_prod_eq, filter.prod]
... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C ⊓ comap πX (𝓝 x)) : by ac_refl
... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x : by rw filter.push_pull
... = 𝓝 x ⊓ map πX (comap πY (𝓝 y) ⊓ 𝓟 C) : by rw inf_comm
end
lemma exists_subset_nhd_of_compact_space [compact_space α] {ι : Type*} [nonempty ι]
{V : ι → set α} (hV : directed (⊇) V) (hV_closed : ∀ i, is_closed (V i))
{U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U :=
exists_subset_nhd_of_compact' hV (λ i, (hV_closed i).is_compact) hV_closed hU
lemma embedding.is_compact_iff_is_compact_image {f : α → β} (hf : embedding f) :
is_compact s ↔ is_compact (f '' s) :=
iff.intro (assume h, h.image hf.continuous) $ assume h, begin
rw is_compact_iff_ultrafilter_le_nhds at ⊢ h,
intros u us',
have : ↑(u.map f) ≤ 𝓟 (f '' s), begin
rw [ultrafilter.coe_map, map_le_iff_le_comap, comap_principal], convert us',
exact preimage_image_eq _ hf.inj
end,
rcases h (u.map f) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩,
refine ⟨a, ha, _⟩,
rwa [hf.induced, nhds_induced, ←map_le_iff_le_comap]
end
/-- A closed embedding is proper, ie, inverse images of compact sets are contained in compacts. -/
lemma closed_embedding.tendsto_cocompact
{f : α → β} (hf : closed_embedding f) : tendsto f (filter.cocompact α) (filter.cocompact β) :=
begin
rw filter.has_basis_cocompact.tendsto_iff filter.has_basis_cocompact,
intros K hK,
refine ⟨f ⁻¹' (K ∩ (set.range f)), _, λ x hx, by simpa using hx⟩,
apply hf.to_embedding.is_compact_iff_is_compact_image.mpr,
rw set.image_preimage_eq_of_subset (set.inter_subset_right _ _),
exact hK.inter_right hf.closed_range,
end
lemma compact_iff_compact_in_subtype {p : α → Prop} {s : set {a // p a}} :
is_compact s ↔ is_compact ((coe : _ → α) '' s) :=
embedding_subtype_coe.is_compact_iff_is_compact_image
lemma is_compact_iff_is_compact_univ {s : set α} : is_compact s ↔ is_compact (univ : set s) :=
by rw [compact_iff_compact_in_subtype, image_univ, subtype.range_coe]; refl
lemma is_compact_iff_compact_space {s : set α} : is_compact s ↔ compact_space s :=
is_compact_iff_is_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩
lemma is_compact.prod {s : set α} {t : set β} (hs : is_compact s) (ht : is_compact t) :
is_compact (set.prod s t) :=
begin
rw is_compact_iff_ultrafilter_le_nhds at hs ht ⊢,
intros f hfs,
rw le_principal_iff at hfs,
obtain ⟨a : α, sa : a ∈ s, ha : map prod.fst ↑f ≤ 𝓝 a⟩ :=
hs (f.map prod.fst) (le_principal_iff.2 $ mem_map.2 $ mem_of_superset hfs (λ x, and.left)),
obtain ⟨b : β, tb : b ∈ t, hb : map prod.snd ↑f ≤ 𝓝 b⟩ :=
ht (f.map prod.snd) (le_principal_iff.2 $ mem_map.2 $
mem_of_superset hfs (λ x, and.right)),
rw map_le_iff_le_comap at ha hb,
refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩,
rw nhds_prod_eq, exact le_inf ha hb
end
lemma inducing.is_compact_iff {f : α → β} (hf : inducing f) {s : set α} :
is_compact (f '' s) ↔ is_compact s :=
begin
split,
{ introsI hs F F_ne_bot F_le,
obtain ⟨_, ⟨x, x_in : x ∈ s, rfl⟩, hx : cluster_pt (f x) (map f F)⟩ :=
hs (calc map f F ≤ map f (𝓟 s) : map_mono F_le
... = 𝓟 (f '' s) : map_principal),
use [x, x_in],
suffices : (map f (𝓝 x ⊓ F)).ne_bot, by simpa [filter.map_ne_bot_iff],
rwa calc map f (𝓝 x ⊓ F) = map f ((comap f $ 𝓝 $ f x) ⊓ F) : by rw hf.nhds_eq_comap
... = 𝓝 (f x) ⊓ map f F : filter.push_pull' _ _ _ },
{ intro hs,
exact hs.image hf.continuous }
end
/-- Finite topological spaces are compact. -/
@[priority 100] instance fintype.compact_space [fintype α] : compact_space α :=
{ compact_univ := finite_univ.is_compact }
/-- The product of two compact spaces is compact. -/
instance [compact_space α] [compact_space β] : compact_space (α × β) :=
⟨by { rw ← univ_prod_univ, exact compact_univ.prod compact_univ }⟩
/-- The disjoint union of two compact spaces is compact. -/
instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) :=
⟨begin
rw ← range_inl_union_range_inr,
exact (is_compact_range continuous_inl).union (is_compact_range continuous_inr)
end⟩
/-- The coproduct of the cocompact filters on two topological spaces is the cocompact filter on
their product. -/
lemma filter.coprod_cocompact {β : Type*} [topological_space β]:
(filter.cocompact α).coprod (filter.cocompact β) = filter.cocompact (α × β) :=
begin
ext S,
simp only [mem_coprod_iff, exists_prop, mem_comap, filter.mem_cocompact],
split,
{ rintro ⟨⟨A, ⟨t, ht, hAt⟩, hAS⟩, B, ⟨t', ht', hBt'⟩, hBS⟩,
refine ⟨t.prod t', ht.prod ht', _⟩,
refine subset.trans _ (union_subset hAS hBS),
rw compl_subset_comm at ⊢ hAt hBt',
refine subset.trans _ (set.prod_mono hAt hBt'),
intros x,
simp only [compl_union, mem_inter_eq, mem_prod, mem_preimage, mem_compl_eq],
tauto },
{ rintros ⟨t, ht, htS⟩,
refine ⟨⟨(prod.fst '' t)ᶜ, _, _⟩, ⟨(prod.snd '' t)ᶜ, _, _⟩⟩,
{ exact ⟨prod.fst '' t, ht.image continuous_fst, subset.rfl⟩ },
{ rw preimage_compl,
rw compl_subset_comm at ⊢ htS,
exact subset.trans htS (subset_preimage_image prod.fst _) },
{ exact ⟨prod.snd '' t, ht.image continuous_snd, subset.rfl⟩ },
{ rw preimage_compl,
rw compl_subset_comm at ⊢ htS,
exact subset.trans htS (subset_preimage_image prod.snd _) } }
end
section tychonoff
variables {ι : Type*} {π : ι → Type*} [∀ i, topological_space (π i)]
/-- **Tychonoff's theorem** -/
lemma is_compact_pi_infinite {s : Π i, set (π i)} :
(∀ i, is_compact (s i)) → is_compact {x : Π i, π i | ∀ i, x i ∈ s i} :=
begin
simp only [is_compact_iff_ultrafilter_le_nhds, nhds_pi, exists_prop, mem_set_of_eq, le_infi_iff,
le_principal_iff],
intros h f hfs,
have : ∀i:ι, ∃a, a∈s i ∧ tendsto (λx:Πi:ι, π i, x i) f (𝓝 a),
{ refine λ i, h i (f.map _) (mem_map.2 _),
exact mem_of_superset hfs (λ x hx, hx i) },
choose a ha,
exact ⟨a, assume i, (ha i).left, assume i, (ha i).right.le_comap⟩
end
/-- A version of Tychonoff's theorem that uses `set.pi`. -/
lemma is_compact_univ_pi {s : Π i, set (π i)} (h : ∀ i, is_compact (s i)) :
is_compact (pi univ s) :=
by { convert is_compact_pi_infinite h, simp only [pi, forall_prop_of_true, mem_univ] }
instance pi.compact_space [∀ i, compact_space (π i)] : compact_space (Πi, π i) :=
⟨by { rw [← pi_univ univ], exact is_compact_univ_pi (λ i, compact_univ) }⟩
/-- Product of compact sets is compact -/
lemma filter.Coprod_cocompact {δ : Type*} {κ : δ → Type*} [Π d, topological_space (κ d)] :
filter.Coprod (λ d, filter.cocompact (κ d)) = filter.cocompact (Π d, κ d) :=
begin
ext S,
simp only [mem_coprod_iff, exists_prop, mem_comap, filter.mem_cocompact],
split,
{ intros h,
rw filter.mem_Coprod_iff at h,
choose t ht1 ht2 using h,
choose t1 ht11 ht12 using λ d, filter.mem_cocompact.mp (ht1 d),
refine ⟨set.pi set.univ t1, _, _⟩,
{ convert is_compact_pi_infinite ht11,
ext,
simp },
{ refine subset.trans _ (set.Union_subset ht2),
intros x,
simp only [mem_Union, mem_univ_pi, exists_imp_distrib, mem_compl_eq, not_forall],
intros d h,
exact ⟨d, ht12 d h⟩ } },
{ rintros ⟨t, h1, h2⟩,
rw filter.mem_Coprod_iff,
intros d,
refine ⟨((λ (k : Π (d : δ), κ d), k d) '' t)ᶜ, _, _⟩,
{ rw filter.mem_cocompact,
refine ⟨(λ (k : Π (d : δ), κ d), k d) '' t, _, set.subset.refl _⟩,
exact is_compact.image h1 (continuous_pi_iff.mp (continuous_id) d) },
refine subset.trans _ h2,
intros x hx,
simp only [not_exists, mem_image, mem_preimage, mem_compl_eq] at hx,
simpa using mt (hx x) },
end
end tychonoff
instance quot.compact_space {r : α → α → Prop} [compact_space α] :
compact_space (quot r) :=
⟨by { rw ← range_quot_mk, exact is_compact_range continuous_quot_mk }⟩
instance quotient.compact_space {s : setoid α} [compact_space α] :
compact_space (quotient s) :=
quot.compact_space
/-- There are various definitions of "locally compact space" in the literature, which agree for
Hausdorff spaces but not in general. This one is the precise condition on X needed for the
evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the
compact-open topology. -/
class locally_compact_space (α : Type*) [topological_space α] : Prop :=
(local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s)
lemma compact_basis_nhds [locally_compact_space α] (x : α) :
(𝓝 x).has_basis (λ s, s ∈ 𝓝 x ∧ is_compact s) (λ s, s) :=
has_basis_self.2 $ by simpa only [and_comm] using locally_compact_space.local_compact_nhds x
lemma locally_compact_space_of_has_basis {ι : α → Type*} {p : Π x, ι x → Prop}
{s : Π x, ι x → set α} (h : ∀ x, (𝓝 x).has_basis (p x) (s x))
(hc : ∀ x i, p x i → is_compact (s x i)) :
locally_compact_space α :=
⟨λ x t ht, let ⟨i, hp, ht⟩ := (h x).mem_iff.1 ht in ⟨s x i, (h x).mem_of_mem hp, ht, hc x i hp⟩⟩
instance locally_compact_space.prod (α : Type*) (β : Type*) [topological_space α]
[topological_space β] [locally_compact_space α] [locally_compact_space β] :
locally_compact_space (α × β) :=
have _ := λ x : α × β, (compact_basis_nhds x.1).prod_nhds' (compact_basis_nhds x.2),
locally_compact_space_of_has_basis this $ λ x s ⟨⟨_, h₁⟩, _, h₂⟩, h₁.prod h₂
/-- A reformulation of the definition of locally compact space: In a locally compact space,
every open set containing `x` has a compact subset containing `x` in its interior. -/
lemma exists_compact_subset [locally_compact_space α] {x : α} {U : set α}
(hU : is_open U) (hx : x ∈ U) : ∃ (K : set α), is_compact K ∧ x ∈ interior K ∧ K ⊆ U :=
begin
rcases locally_compact_space.local_compact_nhds x U (hU.mem_nhds hx) with ⟨K, h1K, h2K, h3K⟩,
exact ⟨K, h3K, mem_interior_iff_mem_nhds.2 h1K, h2K⟩,
end
/-- In a locally compact space every point has a compact neighborhood. -/
lemma exists_compact_mem_nhds [locally_compact_space α] (x : α) :
∃ K, is_compact K ∧ K ∈ 𝓝 x :=
let ⟨K, hKc, hx, H⟩ := exists_compact_subset is_open_univ (mem_univ x)
in ⟨K, hKc, mem_interior_iff_mem_nhds.1 hx⟩
/-- In a locally compact space, every compact set is contained in the interior of a compact set. -/
lemma exists_compact_superset [locally_compact_space α] {K : set α} (hK : is_compact K) :
∃ K', is_compact K' ∧ K ⊆ interior K' :=
begin
choose U hUc hxU using λ x : K, exists_compact_mem_nhds (x : α),
have : K ⊆ ⋃ x, interior (U x),
from λ x hx, mem_Union.2 ⟨⟨x, hx⟩, mem_interior_iff_mem_nhds.2 (hxU _)⟩,
rcases hK.elim_finite_subcover _ _ this with ⟨t, ht⟩,
{ refine ⟨_, t.compact_bUnion (λ x _, hUc x), λ x hx, _⟩,
rcases mem_bUnion_iff.1 (ht hx) with ⟨y, hyt, hy⟩,
exact interior_mono (subset_bUnion_of_mem hyt) hy },
{ exact λ _, is_open_interior }
end
lemma ultrafilter.le_nhds_Lim [compact_space α] (F : ultrafilter α) :
↑F ≤ 𝓝 (@Lim _ _ (F : filter α).nonempty_of_ne_bot F) :=
begin
rcases compact_univ.ultrafilter_le_nhds F (by simp) with ⟨x, -, h⟩,
exact le_nhds_Lim ⟨x,h⟩,
end
theorem is_closed.exists_minimal_nonempty_closed_subset [compact_space α]
{S : set α} (hS : is_closed S) (hne : S.nonempty) :
∃ (V : set α),
V ⊆ S ∧ V.nonempty ∧ is_closed V ∧
(∀ (V' : set α), V' ⊆ V → V'.nonempty → is_closed V' → V' = V) :=
begin
let opens := {U : set α | Sᶜ ⊆ U ∧ is_open U ∧ Uᶜ.nonempty},
obtain ⟨U, ⟨Uc, Uo, Ucne⟩, h⟩ := zorn.zorn_subset opens (λ c hc hz, begin
by_cases hcne : c.nonempty,
{ obtain ⟨U₀, hU₀⟩ := hcne,
haveI : nonempty {U // U ∈ c} := ⟨⟨U₀, hU₀⟩⟩,
obtain ⟨U₀compl, U₀opn, U₀ne⟩ := hc hU₀,
use ⋃₀ c,
refine ⟨⟨_, _, _⟩, λ U hU a ha, ⟨U, hU, ha⟩⟩,
{ exact λ a ha, ⟨U₀, hU₀, U₀compl ha⟩ },
{ exact is_open_sUnion (λ _ h, (hc h).2.1) },
{ convert_to (⋂(U : {U // U ∈ c}), U.1ᶜ).nonempty,
{ ext,
simp only [not_exists, exists_prop, not_and, set.mem_Inter, subtype.forall,
set.mem_set_of_eq, set.mem_compl_eq, subtype.val_eq_coe],
refl, },
apply is_compact.nonempty_Inter_of_directed_nonempty_compact_closed,
{ rintros ⟨U, hU⟩ ⟨U', hU'⟩,
obtain ⟨V, hVc, hVU, hVU'⟩ := zorn.chain.directed_on hz U hU U' hU',
exact ⟨⟨V, hVc⟩, set.compl_subset_compl.mpr hVU, set.compl_subset_compl.mpr hVU'⟩, },
{ exact λ U, (hc U.2).2.2, },
{ exact λ U, (is_closed_compl_iff.mpr (hc U.2).2.1).is_compact, },
{ exact λ U, (is_closed_compl_iff.mpr (hc U.2).2.1), } } },
{ use Sᶜ,
refine ⟨⟨set.subset.refl _, is_open_compl_iff.mpr hS, _⟩, λ U Uc, (hcne ⟨U, Uc⟩).elim⟩,
rw compl_compl,
exact hne, }
end),
refine ⟨Uᶜ, set.compl_subset_comm.mp Uc, Ucne, is_closed_compl_iff.mpr Uo, _⟩,
intros V' V'sub V'ne V'cls,
have : V'ᶜ = U,
{ refine h V'ᶜ ⟨_, is_open_compl_iff.mpr V'cls, _⟩ (set.subset_compl_comm.mp V'sub),
exact set.subset.trans Uc (set.subset_compl_comm.mp V'sub),
simp only [compl_compl, V'ne], },
rw [←this, compl_compl],
end
/-- A σ-compact space is a space that is the union of a countable collection of compact subspaces.
Note that a locally compact separable T₂ space need not be σ-compact.
The sequence can be extracted using `topological_space.compact_covering`. -/
class sigma_compact_space (α : Type*) [topological_space α] : Prop :=
(exists_compact_covering : ∃ K : ℕ → set α, (∀ n, is_compact (K n)) ∧ (⋃ n, K n) = univ)
@[priority 200] -- see Note [lower instance priority]
instance compact_space.sigma_compact [compact_space α] : sigma_compact_space α :=
⟨⟨λ _, univ, λ _, compact_univ, Union_const _⟩⟩
lemma sigma_compact_space.of_countable (S : set (set α)) (Hc : countable S)
(Hcomp : ∀ s ∈ S, is_compact s) (HU : ⋃₀ S = univ) : sigma_compact_space α :=
⟨(exists_seq_cover_iff_countable ⟨_, is_compact_empty⟩).2 ⟨S, Hc, Hcomp, HU⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance sigma_compact_space_of_locally_compact_second_countable [locally_compact_space α]
[second_countable_topology α] : sigma_compact_space α :=
begin
choose K hKc hxK using λ x : α, exists_compact_mem_nhds x,
rcases countable_cover_nhds hxK with ⟨s, hsc, hsU⟩,
refine sigma_compact_space.of_countable _ (hsc.image K) (ball_image_iff.2 $ λ x _, hKc x) _,
rwa sUnion_image
end
variables (α) [sigma_compact_space α]
open sigma_compact_space
/-- A choice of compact covering for a `σ`-compact space, chosen to be monotone. -/
def compact_covering : ℕ → set α :=
accumulate exists_compact_covering.some
lemma is_compact_compact_covering (n : ℕ) : is_compact (compact_covering α n) :=
compact_accumulate (classical.some_spec sigma_compact_space.exists_compact_covering).1 n
lemma Union_compact_covering : (⋃ n, compact_covering α n) = univ :=
begin
rw [compact_covering, Union_accumulate],
exact (classical.some_spec sigma_compact_space.exists_compact_covering).2
end
@[mono] lemma compact_covering_subset ⦃m n : ℕ⦄ (h : m ≤ n) :
compact_covering α m ⊆ compact_covering α n :=
monotone_accumulate h
variable {α}
lemma exists_mem_compact_covering (x : α) : ∃ n, x ∈ compact_covering α n :=
Union_eq_univ_iff.mp (Union_compact_covering α) x
/-- If `α` is a `σ`-compact space, then a locally finite family of nonempty sets of `α` can have
only countably many elements, `set.countable` version. -/
lemma locally_finite.countable_of_sigma_compact {ι : Type*} {f : ι → set α} (hf : locally_finite f)
(hne : ∀ i, (f i).nonempty) :
countable (univ : set ι) :=
begin
have := λ n, hf.finite_nonempty_inter_compact (is_compact_compact_covering α n),
refine (countable_Union (λ n, (this n).countable)).mono (λ i hi, _),
rcases hne i with ⟨x, hx⟩,
rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩,
exact mem_Union.2 ⟨n, x, hx, hn⟩
end
/-- In a topological space with sigma compact topology, if `f` is a function that sends each point
`x` of a closed set `s` to a neighborhood of `x` within `s`, then for some countable set `t ⊆ s`,
the neighborhoods `f x`, `x ∈ t`, cover the whole set `s`. -/
lemma countable_cover_nhds_within_of_sigma_compact {f : α → set α} {s : set α} (hs : is_closed s)
(hf : ∀ x ∈ s, f x ∈ 𝓝[s] x) : ∃ t ⊆ s, countable t ∧ s ⊆ ⋃ x ∈ t, f x :=
begin
simp only [nhds_within, mem_inf_principal] at hf,
choose t ht hsub using λ n, ((is_compact_compact_covering α n).inter_right hs).elim_nhds_subcover
_ (λ x hx, hf x hx.right),
refine ⟨⋃ n, (t n : set α), Union_subset $ λ n x hx, (ht n x hx).2,
countable_Union $ λ n, (t n).countable_to_set, λ x hx, mem_bUnion_iff.2 _⟩,
rcases exists_mem_compact_covering x with ⟨n, hn⟩,
rcases mem_bUnion_iff.1 (hsub n ⟨hn, hx⟩) with ⟨y, hyt : y ∈ t n, hyf : x ∈ s → x ∈ f y⟩,
exact ⟨y, mem_Union.2 ⟨n, hyt⟩, hyf hx⟩
end
/-- In a topological space with sigma compact topology, if `f` is a function that sends each
point `x` to a neighborhood of `x`, then for some countable set `s`, the neighborhoods `f x`,
`x ∈ s`, cover the whole space. -/
lemma countable_cover_nhds_of_sigma_compact {f : α → set α}
(hf : ∀ x, f x ∈ 𝓝 x) : ∃ s : set α, countable s ∧ (⋃ x ∈ s, f x) = univ :=
begin
simp only [← nhds_within_univ] at hf,
rcases countable_cover_nhds_within_of_sigma_compact is_closed_univ (λ x _, hf x)
with ⟨s, -, hsc, hsU⟩,
exact ⟨s, hsc, univ_subset_iff.1 hsU⟩
end
end compact
/-- An [exhaustion by compact sets](https://en.wikipedia.org/wiki/Exhaustion_by_compact_sets) of a
topological space is a sequence of compact sets `K n` such that `K n ⊆ interior (K (n + 1))` and
`(⋃ n, K n) = univ`.
If `X` is a locally compact sigma compact space, then `compact_exhaustion.choice X` provides
a choice of an exhaustion by compact sets. This choice is also available as
`(default : compact_exhaustion X)`. -/
structure compact_exhaustion (X : Type*) [topological_space X] :=
(to_fun : ℕ → set X)
(is_compact' : ∀ n, is_compact (to_fun n))
(subset_interior_succ' : ∀ n, to_fun n ⊆ interior (to_fun (n + 1)))
(Union_eq' : (⋃ n, to_fun n) = univ)
namespace compact_exhaustion
instance : has_coe_to_fun (compact_exhaustion α) := ⟨_, to_fun⟩
variables {α} (K : compact_exhaustion α)
protected lemma is_compact (n : ℕ) : is_compact (K n) := K.is_compact' n
lemma subset_interior_succ (n : ℕ) : K n ⊆ interior (K (n + 1)) :=
K.subset_interior_succ' n
lemma subset_succ (n : ℕ) : K n ⊆ K (n + 1) :=
subset.trans (K.subset_interior_succ n) interior_subset
@[mono] protected lemma subset ⦃m n : ℕ⦄ (h : m ≤ n) : K m ⊆ K n :=
show K m ≤ K n, from monotone_nat_of_le_succ K.subset_succ h
lemma subset_interior ⦃m n : ℕ⦄ (h : m < n) : K m ⊆ interior (K n) :=
subset.trans (K.subset_interior_succ m) $ interior_mono $ K.subset h
lemma Union_eq : (⋃ n, K n) = univ := K.Union_eq'
lemma exists_mem (x : α) : ∃ n, x ∈ K n := Union_eq_univ_iff.1 K.Union_eq x
/-- The minimal `n` such that `x ∈ K n`. -/
protected noncomputable def find (x : α) : ℕ := nat.find (K.exists_mem x)
lemma mem_find (x : α) : x ∈ K (K.find x) := nat.find_spec (K.exists_mem x)
lemma mem_iff_find_le {x : α} {n : ℕ} : x ∈ K n ↔ K.find x ≤ n :=
⟨λ h, nat.find_min' (K.exists_mem x) h, λ h, K.subset h $ K.mem_find x⟩
/-- Prepend the empty set to a compact exhaustion `K n`. -/
def shiftr : compact_exhaustion α :=
{ to_fun := λ n, nat.cases_on n ∅ K,
is_compact' := λ n, nat.cases_on n is_compact_empty K.is_compact,
subset_interior_succ' := λ n, nat.cases_on n (empty_subset _) K.subset_interior_succ,
Union_eq' := Union_eq_univ_iff.2 $ λ x, ⟨K.find x + 1, K.mem_find x⟩ }
@[simp] lemma find_shiftr (x : α) : K.shiftr.find x = K.find x + 1 :=
nat.find_comp_succ _ _ (not_mem_empty _)
lemma mem_diff_shiftr_find (x : α) : x ∈ K.shiftr (K.find x + 1) \ K.shiftr (K.find x) :=
⟨K.mem_find _, mt K.shiftr.mem_iff_find_le.1 $
by simp only [find_shiftr, not_le, nat.lt_succ_self]⟩
/-- A choice of an
[exhaustion by compact sets](https://en.wikipedia.org/wiki/Exhaustion_by_compact_sets)
of a locally compact sigma compact space. -/
noncomputable def choice (X : Type*) [topological_space X] [locally_compact_space X]
[sigma_compact_space X] : compact_exhaustion X :=
begin
apply classical.choice,
let K : ℕ → {s : set X // is_compact s} :=
λ n, nat.rec_on n ⟨∅, is_compact_empty⟩
(λ n s, ⟨(exists_compact_superset s.2).some ∪ compact_covering X n,
(exists_compact_superset s.2).some_spec.1.union (is_compact_compact_covering _ _)⟩),
refine ⟨⟨λ n, K n, λ n, (K n).2, λ n, _, _⟩⟩,
{ exact subset.trans (exists_compact_superset (K n).2).some_spec.2
(interior_mono $ subset_union_left _ _) },
{ refine univ_subset_iff.1 (Union_compact_covering X ▸ _),
exact Union_subset_Union2 (λ n, ⟨n + 1, subset_union_right _ _⟩) }
end
noncomputable instance [locally_compact_space α] [sigma_compact_space α] :
inhabited (compact_exhaustion α) :=
⟨compact_exhaustion.choice α⟩
end compact_exhaustion
section clopen
/-- A set is clopen if it is both open and closed. -/
def is_clopen (s : set α) : Prop :=
is_open s ∧ is_closed s
theorem is_clopen.union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) :=
⟨is_open.union hs.1 ht.1, is_closed.union hs.2 ht.2⟩
theorem is_clopen.inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) :=
⟨is_open.inter hs.1 ht.1, is_closed.inter hs.2 ht.2⟩
@[simp] theorem is_clopen_empty : is_clopen (∅ : set α) :=
⟨is_open_empty, is_closed_empty⟩
@[simp] theorem is_clopen_univ : is_clopen (univ : set α) :=
⟨is_open_univ, is_closed_univ⟩
theorem is_clopen.compl {s : set α} (hs : is_clopen s) : is_clopen sᶜ :=
⟨hs.2.is_open_compl, is_closed_compl_iff.2 hs.1⟩
@[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen sᶜ ↔ is_clopen s :=
⟨λ h, compl_compl s ▸ is_clopen.compl h, is_clopen.compl⟩
theorem is_clopen.diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s \ t) :=
hs.inter ht.compl
lemma is_clopen_Union {β : Type*} [fintype β] {s : β → set α}
(h : ∀ i, is_clopen (s i)) : is_clopen (⋃ i, s i) :=
⟨is_open_Union (forall_and_distrib.1 h).1, is_closed_Union (forall_and_distrib.1 h).2⟩
lemma is_clopen_bUnion {β : Type*} {s : finset β} {f : β → set α} (h : ∀i ∈ s, is_clopen $ f i) :
is_clopen (⋃ i ∈ s, f i) :=
begin
refine ⟨is_open_bUnion (λ i hi, (h i hi).1), _⟩,
show is_closed (⋃ (i : β) (H : i ∈ (s : set β)), f i),
rw bUnion_eq_Union,
exact is_closed_Union (λ ⟨i, hi⟩,(h i hi).2)
end
lemma is_clopen_Inter {β : Type*} [fintype β] {s : β → set α}
(h : ∀ i, is_clopen (s i)) : is_clopen (⋂ i, s i) :=
⟨(is_open_Inter (forall_and_distrib.1 h).1), (is_closed_Inter (forall_and_distrib.1 h).2)⟩
lemma is_clopen_bInter {β : Type*} {s : finset β} {f : β → set α} (h : ∀i∈s, is_clopen (f i)) :
is_clopen (⋂i∈s, f i) :=
⟨ is_open_bInter ⟨finset_coe.fintype s⟩ (λ i hi, (h i hi).1),
by {show is_closed (⋂ (i : β) (H : i ∈ (↑s : set β)), f i), rw bInter_eq_Inter,
apply is_closed_Inter, rintro ⟨i, hi⟩, exact (h i hi).2}⟩
lemma continuous_on.preimage_clopen_of_clopen {β: Type*} [topological_space β]
{f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_clopen s)
(ht : is_clopen t) : is_clopen (s ∩ f⁻¹' t) :=
⟨continuous_on.preimage_open_of_open hf hs.1 ht.1,
continuous_on.preimage_closed_of_closed hf hs.2 ht.2⟩
/-- The intersection of a disjoint covering by two open sets of a clopen set will be clopen. -/
theorem is_clopen_inter_of_disjoint_cover_clopen {Z a b : set α} (h : is_clopen Z)
(cover : Z ⊆ a ∪ b) (ha : is_open a) (hb : is_open b) (hab : a ∩ b = ∅) : is_clopen (Z ∩ a) :=
begin
refine ⟨is_open.inter h.1 ha, _⟩,
have : is_closed (Z ∩ bᶜ) := is_closed.inter h.2 (is_closed_compl_iff.2 hb),
convert this using 1,
apply subset.antisymm,
{ exact inter_subset_inter_right Z (subset_compl_iff_disjoint.2 hab) },
{ rintros x ⟨hx₁, hx₂⟩,
exact ⟨hx₁, by simpa [not_mem_of_mem_compl hx₂] using cover hx₁⟩ }
end
@[simp] lemma is_clopen_discrete [discrete_topology α] (x : set α) : is_clopen x :=
⟨is_open_discrete _, is_closed_discrete _⟩
end clopen
section preirreducible
/-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/
def is_preirreducible (s : set α) : Prop :=
∀ (u v : set α), is_open u → is_open v →
(s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty
/-- An irreducible set `s` is one that is nonempty and
where there is no non-trivial pair of disjoint opens on `s`. -/
def is_irreducible (s : set α) : Prop :=
s.nonempty ∧ is_preirreducible s
lemma is_irreducible.nonempty {s : set α} (h : is_irreducible s) :
s.nonempty := h.1
lemma is_irreducible.is_preirreducible {s : set α} (h : is_irreducible s) :
is_preirreducible s := h.2
theorem is_preirreducible_empty : is_preirreducible (∅ : set α) :=
λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim
theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) :=
⟨singleton_nonempty x,
λ u v _ _ ⟨y, h1, h2⟩ ⟨z, h3, h4⟩, by rw mem_singleton_iff at h1 h3;
substs y z; exact ⟨x, rfl, h2, h4⟩⟩
theorem is_preirreducible.closure {s : set α} (H : is_preirreducible s) :
is_preirreducible (closure s) :=
λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩,
let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in
let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in
let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in
⟨r, subset_closure hrs, hruv⟩
lemma is_irreducible.closure {s : set α} (h : is_irreducible s) :
is_irreducible (closure s) :=
⟨h.nonempty.closure, h.is_preirreducible.closure⟩
theorem exists_preirreducible (s : set α) (H : is_preirreducible s) :
∃ t : set α, is_preirreducible t ∧ s ⊆ t ∧ ∀ u, is_preirreducible u → t ⊆ u → u = t :=
let ⟨m, hm, hsm, hmm⟩ := zorn.zorn_subset_nonempty {t : set α | is_preirreducible t}
(λ c hc hcc hcn, let ⟨t, htc⟩ := hcn in
⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩,
let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy,
⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in
or.cases_on (zorn.chain.total hcc hpc hqc)
(assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv
⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in
⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩)
(assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv
⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in
⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩),
λ x hxc, subset_sUnion_of_mem hxc⟩) s H in
⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩
/-- A maximal irreducible set that contains a given point. -/
def irreducible_component (x : α) : set α :=
classical.some (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible)
lemma irreducible_component_property (x : α) :
is_preirreducible (irreducible_component x) ∧ {x} ⊆ (irreducible_component x) ∧
∀ u, is_preirreducible u → (irreducible_component x) ⊆ u → u = (irreducible_component x) :=
classical.some_spec (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible)
theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x :=
singleton_subset_iff.1 (irreducible_component_property x).2.1
theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) :=
⟨⟨x, mem_irreducible_component⟩, (irreducible_component_property x).1⟩
theorem eq_irreducible_component {x : α} :
∀ {s : set α}, is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x :=
(irreducible_component_property x).2.2
theorem is_closed_irreducible_component {x : α} :
is_closed (irreducible_component x) :=
closure_eq_iff_is_closed.1 $ eq_irreducible_component
is_irreducible_irreducible_component.is_preirreducible.closure
subset_closure
/-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/
class preirreducible_space (α : Type u) [topological_space α] : Prop :=
(is_preirreducible_univ [] : is_preirreducible (univ : set α))
/-- An irreducible space is one that is nonempty
and where there is no non-trivial pair of disjoint opens. -/
class irreducible_space (α : Type u) [topological_space α] extends preirreducible_space α : Prop :=
(to_nonempty [] : nonempty α)
-- see Note [lower instance priority]
attribute [instance, priority 50] irreducible_space.to_nonempty
theorem nonempty_preirreducible_inter [preirreducible_space α] {s t : set α} :
is_open s → is_open t → s.nonempty → t.nonempty → (s ∩ t).nonempty :=
by simpa only [univ_inter, univ_subset_iff] using
@preirreducible_space.is_preirreducible_univ α _ _ s t
theorem is_preirreducible.image [topological_space β] {s : set α} (H : is_preirreducible s)
(f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) :=
begin
rintros u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩,
rw ← mem_preimage at hxu hyv,
rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩,
rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩,
have := H u' v' hu' hv',
rw [inter_comm s u', ← u'_eq] at this,
rw [inter_comm s v', ← v'_eq] at this,
rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨z, hzs, hzu', hzv'⟩,
refine ⟨f z, mem_image_of_mem f hzs, _, _⟩,
all_goals
{ rw ← mem_preimage,
apply mem_of_mem_inter_left,
show z ∈ _ ∩ s,
simp [*] }
end
theorem is_irreducible.image [topological_space β] {s : set α} (H : is_irreducible s)
(f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) :=
⟨nonempty_image_iff.mpr H.nonempty, H.is_preirreducible.image f hf⟩
lemma subtype.preirreducible_space {s : set α} (h : is_preirreducible s) :
preirreducible_space s :=
{ is_preirreducible_univ :=
begin
intros u v hu hv hsu hsv,
rw is_open_induced_iff at hu hv,
rcases hu with ⟨u, hu, rfl⟩,
rcases hv with ⟨v, hv, rfl⟩,
rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩,
rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩,
rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩,
exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩
end }
lemma subtype.irreducible_space {s : set α} (h : is_irreducible s) :
irreducible_space s :=
{ is_preirreducible_univ :=
(subtype.preirreducible_space h.is_preirreducible).is_preirreducible_univ,
to_nonempty := h.nonempty.to_subtype }
/-- A set `s` is irreducible if and only if
for every finite collection of open sets all of whose members intersect `s`,
`s` also intersects the intersection of the entire collection
(i.e., there is an element of `s` contained in every member of the collection). -/
lemma is_irreducible_iff_sInter {s : set α} :
is_irreducible s ↔
∀ (U : finset (set α)) (hU : ∀ u ∈ U, is_open u) (H : ∀ u ∈ U, (s ∩ u).nonempty),
(s ∩ ⋂₀ ↑U).nonempty :=
begin
split; intro h,
{ intro U, apply finset.induction_on U,
{ intros, simpa using h.nonempty },
{ intros u U hu IH hU H,
rw [finset.coe_insert, sInter_insert],
apply h.2,
{ solve_by_elim [finset.mem_insert_self] },
{ apply is_open_sInter (finset.finite_to_set U),
intros, solve_by_elim [finset.mem_insert_of_mem] },
{ solve_by_elim [finset.mem_insert_self] },
{ apply IH,
all_goals { intros, solve_by_elim [finset.mem_insert_of_mem] } } } },
{ split,
{ simpa using h ∅ _ _; intro u; simp },
intros u v hu hv hu' hv',
simpa using h {u,v} _ _,
all_goals
{ intro t,
rw [finset.mem_insert, finset.mem_singleton],
rintro (rfl|rfl); assumption } }
end
/-- A set is preirreducible if and only if
for every cover by two closed sets, it is contained in one of the two covering sets. -/
lemma is_preirreducible_iff_closed_union_closed {s : set α} :
is_preirreducible s ↔
∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ :=
begin
split,
all_goals
{ intros h t₁ t₂ ht₁ ht₂,
specialize h t₁ᶜ t₂ᶜ,
simp only [is_open_compl_iff, is_closed_compl_iff] at h,
specialize h ht₁ ht₂ },
{ contrapose!, simp only [not_subset],
rintro ⟨⟨x, hx, hx'⟩, ⟨y, hy, hy'⟩⟩,
rcases h ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ with ⟨z, hz, hz'⟩,
rw ← compl_union at hz',
exact ⟨z, hz, hz'⟩ },
{ rintro ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩,
rw ← compl_inter at h,
delta set.nonempty,
rw imp_iff_not_or at h,
contrapose! h,
split,
{ intros z hz hz', exact h z ⟨hz, hz'⟩ },
{ split; intro H; refine H _ ‹_›; assumption } }
end
/-- A set is irreducible if and only if
for every cover by a finite collection of closed sets,
it is contained in one of the members of the collection. -/
lemma is_irreducible_iff_sUnion_closed {s : set α} :
is_irreducible s ↔
∀ (Z : finset (set α)) (hZ : ∀ z ∈ Z, is_closed z) (H : s ⊆ ⋃₀ ↑Z),
∃ z ∈ Z, s ⊆ z :=
begin
rw [is_irreducible, is_preirreducible_iff_closed_union_closed],
split; intro h,
{ intro Z, apply finset.induction_on Z,
{ intros, rw [finset.coe_empty, sUnion_empty] at H,
rcases h.1 with ⟨x, hx⟩,
exfalso, tauto },
{ intros z Z hz IH hZ H,
cases h.2 z (⋃₀ ↑Z) _ _ _
with h' h',
{ exact ⟨z, finset.mem_insert_self _ _, h'⟩ },
{ rcases IH _ h' with ⟨z', hz', hsz'⟩,
{ exact ⟨z', finset.mem_insert_of_mem hz', hsz'⟩ },
{ intros, solve_by_elim [finset.mem_insert_of_mem] } },
{ solve_by_elim [finset.mem_insert_self] },
{ rw sUnion_eq_bUnion,
apply is_closed_bUnion (finset.finite_to_set Z),
{ intros, solve_by_elim [finset.mem_insert_of_mem] } },
{ simpa using H } } },
{ split,
{ by_contradiction hs,
simpa using h ∅ _ _,
{ intro z, simp },
{ simpa [set.nonempty] using hs } },
intros z₁ z₂ hz₁ hz₂ H,
have := h {z₁, z₂} _ _,
simp only [exists_prop, finset.mem_insert, finset.mem_singleton] at this,
{ rcases this with ⟨z, rfl|rfl, hz⟩; tauto },
{ intro t,
rw [finset.mem_insert, finset.mem_singleton],
rintro (rfl|rfl); assumption },
{ simpa using H } }
end
end preirreducible
|
c2c6bb3b0d1a8d6e36d2f875617b35d378c172f6 | 22e97a5d648fc451e25a06c668dc03ac7ed7bc25 | /src/ring_theory/localization.lean | 57aedeee7acdd2ed898b47678618ba028d9373dd | [
"Apache-2.0"
] | permissive | keeferrowan/mathlib | f2818da875dbc7780830d09bd4c526b0764a4e50 | aad2dfc40e8e6a7e258287a7c1580318e865817e | refs/heads/master | 1,661,736,426,952 | 1,590,438,032,000 | 1,590,438,032,000 | 266,892,663 | 0 | 0 | Apache-2.0 | 1,590,445,835,000 | 1,590,445,835,000 | null | UTF-8 | Lean | false | false | 22,893 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston
-/
import data.equiv.ring
import tactic.ring_exp
import ring_theory.ideal_operations
import group_theory.monoid_localization
/-!
# Localizations of commutative rings
We characterize the localization of a commutative ring `R` at a submonoid `M` up to
isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a
ring homomorphism `f : R →+* S` satisfying 3 properties:
1. For all `y ∈ M`, `f y` is a unit;
2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`;
3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`.
Given such a localization map `f : R →+* S`, we can define the surjection
`localization.mk'` sending `(x, y) : R × M` to `f x * (f y)⁻¹`, and
`localization.lift`, the homomorphism from `S` induced by a homomorphism from `R` which maps
elements of `M` to invertible elements of the codomain. Similarly, given commutative rings
`P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism
`g : R →+* P` such that `g(M) ⊆ T` induces a homomorphism of localizations,
`localization.map`, from `S` to `Q`.
We prove some lemmas about the `R`-algebra structure of `S`.
When `R` is an integral domain, we define `fraction_map R K` as an abbreviation for
`localization (non_zero_divisors R) K`, the natural map to `R`'s field of fractions.
We show that a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}`
is a field.
## Implementation notes
In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one
structure with an isomorphic one; one way around this is to isolate a predicate characterizing
a structure up to isomorphism, and reason about things that satisfy the predicate.
A ring localization map is defined to be a localization map of the underlying `comm_monoid` (a
`submonoid.localization_map`) which is also a ring hom. To prove most lemmas about a
`localization` `f` in this file we invoke the corresponding proof for the underlying
`comm_monoid` localization map `f.to_localization_map`, which can be found in
`group_theory.monoid_localization` and the namespace `submonoid.localization_map`.
To apply a localization map `f` as a function, we use `f.to_map`, as coercions don't work well for
this structure.
We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the
`R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure.
## Tags
localization, ring localization, commutative ring localization, characteristic predicate,
commutative ring, field of fractions
-/
variables {R : Type*} [comm_ring R] (M : submonoid R) (S : Type*) [comm_ring S]
{P : Type*} [comm_ring P]
open function
set_option old_structure_cmd true
/-- The type of ring homomorphisms satisfying the characteristic predicate: if `f : R →+* S`
satisfies this predicate, then `S` is isomorphic to the localization of `R` at `M`.
We later define an instance coercing a localization map `f` to its codomain `S` so
that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra
structure. -/
@[nolint has_inhabited_instance] structure localization
extends ring_hom R S, submonoid.localization_map M S
/-- The ring hom underlying a `localization`. -/
add_decl_doc localization.to_ring_hom
/-- The `comm_monoid` `localization_map` underlying a `comm_ring` `localization`.
See `group_theory.monoid_localization` for its definition. -/
add_decl_doc localization.to_localization_map
variables {M S}
namespace ring_hom
/-- Makes a localization map from a `comm_ring` hom satisfying the characteristic predicate. -/
def to_localization (f : R →+* S) (H1 : ∀ y : M, is_unit (f y))
(H2 : ∀ z, ∃ x : R × M, z * f x.2 = f x.1) (H3 : ∀ x y, f x = f y ↔ ∃ c : M, x * c = y * c) :
localization M S :=
{ map_units' := H1,
surj' := H2,
eq_iff_exists' := H3,
.. f }
end ring_hom
namespace localization
variables (f : localization M S)
/-- Short for `to_ring_hom`; used for applying a localization map as a function. -/
abbreviation to_map := f.to_ring_hom
lemma map_units (y : M) : is_unit (f.to_map y) := f.6 y
lemma surj (z) : ∃ x : R × M, z * f.to_map x.2 = f.to_map x.1 := f.7 z
lemma eq_iff_exists {x y} : f.to_map x = f.to_map y ↔ ∃ c : M, x * c = y * c := f.8 x y
@[ext] lemma ext {f g : localization M S}
(h : ∀ x, f.to_map x = g.to_map x) : f = g :=
begin
cases f, cases g,
simp only [] at *,
exact funext h
end
lemma ext_iff {f g : localization M S} : f = g ↔ ∀ x, f.to_map x = g.to_map x :=
⟨λ h x, h ▸ rfl, ext⟩
lemma to_map_injective : injective (@localization.to_map _ _ M S _) :=
λ _ _ h, ext $ ring_hom.ext_iff.1 h
/-- Given `a : S`, `S` a localization of `R`, `is_integer a` iff `a` is in the image of
the localization map from `R` to `S`. -/
def is_integer (a : S) : Prop := a ∈ set.range f.to_map
variables {f}
lemma is_integer_add {a b} (ha : f.is_integer a) (hb : f.is_integer b) :
f.is_integer (a + b) :=
begin
rcases ha with ⟨a', ha⟩,
rcases hb with ⟨b', hb⟩,
use a' + b',
rw [f.to_map.map_add, ha, hb]
end
lemma is_integer_mul {a b} (ha : f.is_integer a) (hb : f.is_integer b) :
f.is_integer (a * b) :=
begin
rcases ha with ⟨a', ha⟩,
rcases hb with ⟨b', hb⟩,
use a' * b',
rw [f.to_map.map_mul, ha, hb]
end
lemma is_integer_smul {a : R} {b} (hb : f.is_integer b) :
f.is_integer (f.to_map a * b) :=
begin
rcases hb with ⟨b', hb⟩,
use a * b',
rw [←hb, f.to_map.map_mul]
end
variables (f)
/-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such
that `z * f y = f x` (so this lemma is true by definition). -/
lemma sec_spec {f : localization M S} (z : S) :
z * f.to_map (f.to_localization_map.sec z).2 = f.to_map (f.to_localization_map.sec z).1 :=
classical.some_spec $ f.surj z
/-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such
that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/
lemma sec_spec' {f : localization M S} (z : S) :
f.to_map (f.to_localization_map.sec z).1 = f.to_map (f.to_localization_map.sec z).2 * z :=
by rw [mul_comm, sec_spec]
lemma map_right_cancel {x y} {c : M} (h : f.to_map (c * x) = f.to_map (c * y)) :
f.to_map x = f.to_map y :=
f.to_localization_map.map_right_cancel h
lemma map_left_cancel {x y} {c : M} (h : f.to_map (x * c) = f.to_map (y * c)) :
f.to_map x = f.to_map y :=
f.to_localization_map.map_left_cancel h
lemma eq_zero_of_fst_eq_zero {z x} {y : M}
(h : z * f.to_map y = f.to_map x) (hx : x = 0) : z = 0 :=
by rw [hx, f.to_map.map_zero] at h;
exact (is_unit.mul_left_eq_zero_iff_eq_zero (f.map_units y)).1 h
/-- Given a localization map `f : R →+* S`, the surjection sending `(x, y) : R × M` to
`f x * (f y)⁻¹`. -/
noncomputable def mk' (f : localization M S) (x : R) (y : M) : S :=
f.to_localization_map.mk' x y
@[simp] lemma mk'_sec (z : S) :
f.mk' (f.to_localization_map.sec z).1 (f.to_localization_map.sec z).2 = z :=
f.to_localization_map.mk'_sec _
lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) :
f.mk' (x₁ * x₂) (y₁ * y₂) = f.mk' x₁ y₁ * f.mk' x₂ y₂ :=
f.to_localization_map.mk'_mul _ _ _ _
lemma mk'_one (x) : f.mk' x (1 : M) = f.to_map x :=
f.to_localization_map.mk'_one _
lemma mk'_spec (x) (y : M) :
f.mk' x y * f.to_map y = f.to_map x :=
f.to_localization_map.mk'_spec _ _
lemma mk'_spec' (x) (y : M) :
f.to_map y * f.mk' x y = f.to_map x :=
f.to_localization_map.mk'_spec' _ _
theorem eq_mk'_iff_mul_eq {x} {y : M} {z} :
z = f.mk' x y ↔ z * f.to_map y = f.to_map x :=
f.to_localization_map.eq_mk'_iff_mul_eq
theorem mk'_eq_iff_eq_mul {x} {y : M} {z} :
f.mk' x y = z ↔ f.to_map x = z * f.to_map y :=
f.to_localization_map.mk'_eq_iff_eq_mul
lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} :
f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ f.to_map (x₁ * y₂) = f.to_map (x₂ * y₁) :=
f.to_localization_map.mk'_eq_iff_eq
protected lemma eq {a₁ b₁} {a₂ b₂ : M} :
f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c :=
f.to_localization_map.eq
lemma eq_iff_eq (g : localization M P) {x y} :
f.to_map x = f.to_map y ↔ g.to_map x = g.to_map y :=
f.to_localization_map.eq_iff_eq g.to_localization_map
lemma mk'_eq_iff_mk'_eq (g : localization M P) {x₁ x₂}
{y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ g.mk' x₁ y₁ = g.mk' x₂ y₂ :=
f.to_localization_map.mk'_eq_iff_mk'_eq g.to_localization_map
lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) :
f.mk' a₁ a₂ = f.mk' b₁ b₂ :=
f.to_localization_map.mk'_eq_of_eq H
@[simp] lemma mk'_self {x : R} {hx : x ∈ M} : f.mk' x ⟨x, hx⟩ = 1 :=
f.to_localization_map.mk'_self' _ hx
@[simp] lemma mk'_self' {x : M} : f.mk' x x = 1 :=
f.to_localization_map.mk'_self _
@[simp] lemma mk'_self'' {x : M} : f.mk' x.1 x = 1 :=
f.mk'_self'
lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) :
f.to_map x * f.mk' y z = f.mk' (x * y) z :=
f.to_localization_map.mul_mk'_eq_mk'_of_mul _ _ _
lemma mk'_eq_mul_mk'_one (x : R) (y : M) :
f.mk' x y = f.to_map x * f.mk' 1 y :=
(f.to_localization_map.mul_mk'_one_eq_mk' _ _).symm
@[simp] lemma mk'_mul_cancel_left (x : R) (y : M) :
f.mk' (y * x) y = f.to_map x :=
f.to_localization_map.mk'_mul_cancel_left _ _
lemma mk'_mul_cancel_right (x : R) (y : M) :
f.mk' (x * y) y = f.to_map x :=
f.to_localization_map.mk'_mul_cancel_right _ _
lemma is_unit_comp (j : S →+* P) (y : M) :
is_unit (j.comp f.to_map y) :=
f.to_localization_map.is_unit_comp j.to_monoid_hom _
/-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s
`g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/
lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : f.to_map x = f.to_map y) :
g x = g y :=
@submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _
f.to_localization_map g.to_monoid_hom hg _ _ h
lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) :
f.mk' (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = f.mk' x₁ y₁ + f.mk' x₂ y₂ :=
f.mk'_eq_iff_eq_mul.2 $ eq.symm
begin
rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, ←eq_sub_iff_add_eq, mk'_eq_iff_eq_mul,
mul_comm _ (f.to_map _), mul_sub, eq_sub_iff_add_eq, ←eq_sub_iff_add_eq', ←mul_assoc,
←f.to_map.map_mul, mul_mk'_eq_mk'_of_mul, mk'_eq_iff_eq_mul],
simp only [f.to_map.map_add, submonoid.coe_mul, f.to_map.map_mul],
ring_exp,
end
/-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s
`g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from
`S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that
`z = f x * (f y)⁻¹`. -/
noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P :=
ring_hom.mk' (@submonoid.localization_map.lift _ _ _ _ _ _ _
f.to_localization_map g.to_monoid_hom hg) $
begin
intros x y,
rw [f.to_localization_map.lift_spec, mul_comm, add_mul, ←sub_eq_iff_eq_add, eq_comm,
f.to_localization_map.lift_spec_mul, mul_comm _ (_ - _), sub_mul, eq_sub_iff_add_eq',
←eq_sub_iff_add_eq, mul_assoc, f.to_localization_map.lift_spec_mul],
show g _ * (g _ * g _) = g _ * (g _ * g _ - g _ * g _),
repeat {rw ←g.map_mul},
rw [←g.map_sub, ←g.map_mul],
apply f.eq_of_eq hg,
erw [f.to_map.map_mul, sec_spec', mul_sub, f.to_map.map_sub],
simp only [f.to_map.map_mul, sec_spec'],
ring_exp,
end
variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y))
/-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s
`g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from
`S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/
lemma lift_mk' (x y) :
f.lift hg (f.mk' x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.restrict M) hg y)⁻¹ :=
f.to_localization_map.lift_mk' _ _ _
lemma lift_mk'_spec (x v) (y : M) :
f.lift hg (f.mk' x y) = v ↔ g x = g y * v :=
f.to_localization_map.lift_mk'_spec _ _ _ _
@[simp] lemma lift_eq (x : R) :
f.lift hg (f.to_map x) = g x :=
f.to_localization_map.lift_eq _ _
lemma lift_eq_iff {x y : R × M} :
f.lift hg (f.mk' x.1 x.2) = f.lift hg (f.mk' y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) :=
f.to_localization_map.lift_eq_iff _
@[simp] lemma lift_comp : (f.lift hg).comp f.to_map = g :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_comp _
@[simp] lemma lift_of_comp (j : S →+* P) :
f.lift (f.is_unit_comp j) = j :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_of_comp j.to_monoid_hom
lemma epic_of_localization_map {j k : S →+* P}
(h : ∀ a, j.comp f.to_map a = k.comp f.to_map a) : j = k :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.epic_of_localization_map
_ _ _ _ _ _ _ f.to_localization_map j.to_monoid_hom k.to_monoid_hom h
lemma lift_unique {j : S →+* P}
(hj : ∀ x, j (f.to_map x) = g x) : f.lift hg = j :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique
_ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg j.to_monoid_hom hj
@[simp] lemma lift_id (x) : f.lift f.map_units x = x :=
f.to_localization_map.lift_id _
/-- Given two localization maps `f : R →+* S, k : R →+* P` for a submonoid `M ⊆ R`,
the hom from `P` to `S` induced by `f` is left inverse to the hom from `S` to `P`
induced by `k`. -/
@[simp] lemma lift_left_inverse {k : localization M S} (z : S) :
k.lift f.map_units (f.lift k.map_units z) = z :=
f.to_localization_map.lift_left_inverse _
lemma lift_surjective_iff :
surjective (f.lift hg) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 :=
f.to_localization_map.lift_surjective_iff hg
lemma lift_injective_iff :
injective (f.lift hg) ↔ ∀ x y, f.to_map x = f.to_map y ↔ g x = g y :=
f.to_localization_map.lift_injective_iff hg
variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q]
(k : localization T Q)
/-- Given a `comm_ring` homomorphism `g : R →+* P` where for submonoids `M ⊆ R, T ⊆ P` we have
`g(M) ⊆ T`, the induced ring homomorphism from the localization of `R` at `M` to the
localization of `P` at `T`: if `f : R →+* S` and `k : P →+* Q` are localization maps for `M`
and `T` respectively, we send `z : S` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : R × M` are
such that `z = f x * (f y)⁻¹`. -/
noncomputable def map : S →+* Q :=
@lift _ _ _ _ _ _ _ f (k.to_map.comp g) $ λ y, k.map_units ⟨g y, hy y⟩
variables {k}
lemma map_eq (x) :
f.map hy k (f.to_map x) = k.to_map (g x) :=
f.lift_eq (λ y, k.map_units ⟨g y, hy y⟩) x
@[simp] lemma map_comp :
(f.map hy k).comp f.to_map = k.to_map.comp g :=
f.lift_comp $ λ y, k.map_units ⟨g y, hy y⟩
lemma map_mk' (x) (y : M) :
f.map hy k (f.mk' x y) = k.mk' (g x) ⟨g y, hy y⟩ :=
@submonoid.localization_map.map_mk' _ _ _ _ _ _ _ f.to_localization_map
g.to_monoid_hom _ hy _ _ k.to_localization_map _ _
@[simp] lemma map_id (z : S) :
f.map (λ y, show ring_hom.id R y ∈ M, from y.2) f z = z :=
f.lift_id _
/-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition
of the induced maps equals the map of localizations induced by `l ∘ g`. -/
lemma map_comp_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W]
(j : localization U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) :
(k.map hl j).comp (f.map hy k) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j :=
ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.map_comp_map _ _ _ _ _ _ _
f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map
_ _ _ _ _ j.to_localization_map l.to_monoid_hom hl
/-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition
of the induced maps equals the map of localizations induced by `l ∘ g`. -/
lemma map_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W]
(j : localization U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) (x) :
k.map hl j (f.map hy k x) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j x :=
by rw ←f.map_comp_map hy j hl; refl
/-- Given localization maps `f : R →+* S, k : P →+* Q` for submonoids `M, T` respectively, an
isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations
`S ≃+* Q`. -/
noncomputable def ring_equiv_of_ring_equiv (k : localization T Q) (h : R ≃+* P)
(H : M.map h.to_monoid_hom = T) :
S ≃+* Q :=
(f.to_localization_map.mul_equiv_of_mul_equiv k.to_localization_map H).to_ring_equiv $
(@lift _ _ _ _ _ _ _ f (k.to_map.comp h.to_ring_hom)
(λ y, k.map_units ⟨(h y), H ▸ set.mem_image_of_mem h y.2⟩)).map_add
@[simp] lemma ring_equiv_of_ring_equiv_eq_map_apply {j : R ≃+* P}
(H : M.map j.to_monoid_hom = T) (x) :
f.ring_equiv_of_ring_equiv k j H x =
f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k x := rfl
lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) :
(f.ring_equiv_of_ring_equiv k j H).to_monoid_hom =
f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k := rfl
@[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) :
f.ring_equiv_of_ring_equiv k j H (f.to_map x) = k.to_map (j x) :=
f.to_localization_map.mul_equiv_of_mul_equiv_eq H _
lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x y) :
f.ring_equiv_of_ring_equiv k j H (f.mk' x y) =
k.mk' (j x) ⟨j y, H ▸ set.mem_image_of_mem j y.2⟩ :=
f.to_localization_map.mul_equiv_of_mul_equiv_mk' H _ _
/-!
### `algebra` section
Defines the `R`-algebra instance on a copy of `S` carrying the data of the localization map
`f` needed to induce the `R`-algebra structure. -/
variables (f)
/-- We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that
the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra
structure. -/
@[reducible, nolint unused_arguments] def codomain (f : localization M S) := S
/-- We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the
`R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. -/
instance : algebra R f.codomain := f.to_map.to_algebra
@[simp] lemma of_id (a : R) :
(algebra.of_id R f.codomain) a = f.to_map a :=
rfl
variables (f)
/-- Localization map `f` from `R` to `S` as an `R`-linear map. -/
def lin_coe : R →ₗ[R] f.codomain :=
{ to_fun := f.to_map,
add := f.to_map.map_add,
smul := f.to_map.map_mul }
variables {f}
instance coe_submodules : has_coe (ideal R) (submodule R f.codomain) :=
⟨λ I, submodule.map f.lin_coe I⟩
lemma mem_coe (I : ideal R) {x : S} :
x ∈ (I : submodule R f.codomain) ↔ ∃ y : R, y ∈ I ∧ f.to_map y = x :=
iff.rfl
end localization
variables (R)
/-- The submonoid of non-zero-divisors of a `comm_ring` `R`. -/
def non_zero_divisors : submonoid R :=
{ carrier := {x | ∀ z, z * x = 0 → z = 0},
one_mem' := λ z hz, by rwa mul_one at hz,
mul_mem' := λ x₁ x₂ hx₁ hx₂ z hz,
have z * x₁ * x₂ = 0, by rwa mul_assoc,
hx₁ z $ hx₂ (z * x₁) this }
lemma eq_zero_of_ne_zero_of_mul_eq_zero {A : Type*} [integral_domain A]
{x y : A} (hnx : x ≠ 0) (hxy : y * x = 0) :
y = 0 := or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx
lemma mem_non_zero_divisors_iff_ne_zero {A : Type*} [integral_domain A] {x : A} :
x ∈ non_zero_divisors A ↔ x ≠ 0 :=
⟨λ hm hz, zero_ne_one (hm 1 $ by rw [hz, one_mul]).symm,
λ hnx z, eq_zero_of_ne_zero_of_mul_eq_zero hnx⟩
variables (K : Type*)
/-- Localization map from an integral domain `R` to its field of fractions. -/
@[reducible] def fraction_map [comm_ring K] := localization (non_zero_divisors R) K
namespace fraction_map
open localization
variables {R K}
protected theorem injective [comm_ring K] (φ : fraction_map R K) :
injective φ.to_map :=
φ.to_map.injective_iff.2 $ λ x h,
begin
rw ←φ.to_map.map_zero at h,
cases φ.eq_iff_exists.1 h with c hc,
rw zero_mul at hc,
exact c.2 x hc
end
variables {A : Type*} [integral_domain A]
local attribute [instance] classical.dec_eq
/-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is an
integral domain. -/
def to_integral_domain [comm_ring K] (φ : fraction_map A K) : integral_domain K :=
{ eq_zero_or_eq_zero_of_mul_eq_zero :=
begin
intros z w h,
cases φ.surj z with x hx,
cases φ.surj w with y hy,
have : z * w * φ.to_map y.2 * φ.to_map x.2 = φ.to_map x.1 * φ.to_map y.1, by
rw [mul_assoc z, hy, ←hx]; ac_refl,
erw h at this,
rw [zero_mul, zero_mul, ←φ.to_map.map_mul] at this,
cases eq_zero_or_eq_zero_of_mul_eq_zero (φ.to_map.injective_iff.1
φ.injective _ this.symm) with H H,
{ exact or.inl (φ.eq_zero_of_fst_eq_zero hx H) },
{ exact or.inr (φ.eq_zero_of_fst_eq_zero hy H) },
end,
zero_ne_one := by erw [←φ.to_map.map_zero, ←φ.to_map.map_one];
exact λ h, zero_ne_one (φ.injective h),
..(infer_instance : comm_ring K) }
/-- The inverse of an element in the field of fractions of an integral domain. -/
protected noncomputable def inv [comm_ring K] (φ : fraction_map A K) (z : K) : K :=
if h : z = 0 then 0 else
φ.mk' (φ.to_localization_map.sec z).2 ⟨(φ.to_localization_map.sec z).1,
mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, h $ φ.eq_zero_of_fst_eq_zero (sec_spec z) h0⟩
protected lemma mul_inv_cancel [comm_ring K] (φ : fraction_map A K) (x : K) (hx : x ≠ 0) :
x * φ.inv x = 1 :=
show x * dite _ _ _ = 1, by rw [dif_neg hx,
←is_unit.mul_left_inj (φ.map_units ⟨(φ.to_localization_map.sec x).1,
mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, hx $ φ.eq_zero_of_fst_eq_zero (sec_spec x) h0⟩),
one_mul, mul_assoc, mk'_spec, ←eq_mk'_iff_mul_eq]; exact (φ.mk'_sec x).symm
/-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is a
field. -/
noncomputable def to_field [comm_ring K] (φ : fraction_map A K) : field K :=
{ inv := φ.inv,
mul_inv_cancel := φ.mul_inv_cancel,
inv_zero := dif_pos rfl, ..φ.to_integral_domain }
end fraction_map
|
77ae51f15bfba63cdae5042591e1dcbeee9dea36 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/topology/Top/limits.lean | 90c9f48f2a7a4c4970bd8d0d1ac1cb5b11eeba3a | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 2,719 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Scott Morrison, Mario Carneiro
-/
import topology.Top.basic
import category_theory.limits.types
import category_theory.limits.preserves
open topological_space
open category_theory
open category_theory.limits
universe u
namespace Top
variables {J : Type u} [small_category J]
def limit (F : J ⥤ Top.{u}) : cone F :=
{ X := ⟨limit (F ⋙ forget), ⨅j, (F.obj j).str.induced (limit.π (F ⋙ forget) j)⟩,
π :=
{ app := λ j, ⟨limit.π (F ⋙ forget) j, continuous_iff_le_induced.mpr (lattice.infi_le _ _)⟩,
naturality' := λ j j' f, subtype.eq ((limit.cone (F ⋙ forget)).π.naturality f) } }
def limit_is_limit (F : J ⥤ Top.{u}) : is_limit (limit F) :=
by { refine is_limit.of_faithful forget (limit.is_limit _) (λ s, ⟨_, _⟩) (λ s, rfl),
exact continuous_iff_coinduced_le.mpr (lattice.le_infi $ λ j,
coinduced_le_iff_le_induced.mp $ continuous_iff_coinduced_le.mp (s.π.app j).property) }
instance Top_has_limits : has_limits.{u} Top.{u} :=
{ has_limits_of_shape := λ J 𝒥,
{ has_limit := λ F, by exactI { cone := limit F, is_limit := limit_is_limit F } } }
instance forget_preserves_limits : preserves_limits (forget : Top.{u} ⥤ Type u) :=
{ preserves_limits_of_shape := λ J 𝒥,
{ preserves_limit := λ F,
by exactI preserves_limit_of_preserves_limit_cone
(limit.is_limit F) (limit.is_limit (F ⋙ forget)) } }
def colimit (F : J ⥤ Top.{u}) : cocone F :=
{ X := ⟨colimit (F ⋙ forget), ⨆ j, (F.obj j).str.coinduced (colimit.ι (F ⋙ forget) j)⟩,
ι :=
{ app := λ j, ⟨colimit.ι (F ⋙ forget) j, continuous_iff_coinduced_le.mpr (lattice.le_supr _ j)⟩,
naturality' := λ j j' f, subtype.eq ((colimit.cocone (F ⋙ forget)).ι.naturality f) } }
def colimit_is_colimit (F : J ⥤ Top.{u}) : is_colimit (colimit F) :=
by { refine is_colimit.of_faithful forget (colimit.is_colimit _) (λ s, ⟨_, _⟩) (λ s, rfl),
exact continuous_iff_le_induced.mpr (lattice.supr_le $ λ j,
coinduced_le_iff_le_induced.mp $ continuous_iff_coinduced_le.mp (s.ι.app j).property) }
instance Top_has_colimits : has_colimits.{u} Top.{u} :=
{ has_colimits_of_shape := λ J 𝒥,
{ has_colimit := λ F, by exactI { cocone := colimit F, is_colimit := colimit_is_colimit F } } }
instance forget_preserves_colimits : preserves_colimits (forget : Top.{u} ⥤ Type u) :=
{ preserves_colimits_of_shape := λ J 𝒥,
{ preserves_colimit := λ F,
by exactI preserves_colimit_of_preserves_colimit_cocone
(colimit.is_colimit F) (colimit.is_colimit (F ⋙ forget)) } }
end Top
|
8e576114cd1f0249eaad4db6f39a7eb9c68b67d6 | c3f2fcd060adfa2ca29f924839d2d925e8f2c685 | /tests/lean/run/alg_rw.lean | acb775d63081a6fa2fabecfc39987113f1f4cd25 | [
"Apache-2.0"
] | permissive | respu/lean | 6582d19a2f2838a28ecd2b3c6f81c32d07b5341d | 8c76419c60b63d0d9f7bc04ebb0b99812d0ec654 | refs/heads/master | 1,610,882,451,231 | 1,427,747,084,000 | 1,427,747,429,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 384 | lean | import algebra.group
open algebra
context
variable {A : Type}
variable [s : comm_monoid A]
include s
theorem one_mul_one : 1 * 1 = 1 :=
mul_one 1
end
definition one [reducible] (A : Type) [s : has_one A] : A :=
!has_one.one
context
variable {A : Type}
variable [s : comm_group A]
include s
theorem one_mul_one2 : (one A) * 1 = 1 :=
by rewrite one_mul_one
end
|
a8cec6ca6ea0a076541bc0ad97b9e47feb11c95b | 4727251e0cd73359b15b664c3170e5d754078599 | /src/order/disjointed.lean | 3f3bb366d6799fb4e54fe4367a3624340c46b5a3 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 6,090 | 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, Yaël Dillies
-/
import order.partial_sups
/-!
# Consecutive differences of sets
This file defines the way to make a sequence of elements into a sequence of disjoint elements with
the same partial sups.
For a sequence `f : ℕ → α`, this new sequence will be `f 0`, `f 1 \ f 0`, `f 2 \ (f 0 ⊔ f 1)`.
It is actually unique, as `disjointed_unique` shows.
## Main declarations
* `disjointed f`: The sequence `f 0`, `f 1 \ f 0`, `f 2 \ (f 0 ⊔ f 1)`, ....
* `partial_sups_disjointed`: `disjointed f` has the same partial sups as `f`.
* `disjoint_disjointed`: The elements of `disjointed f` are pairwise disjoint.
* `disjointed_unique`: `disjointed f` is the only pairwise disjoint sequence having the same partial
sups as `f`.
* `supr_disjointed`: `disjointed f` has the same supremum as `f`. Limiting case of
`partial_sups_disjointed`.
We also provide set notation variants of some lemmas.
## TODO
Find a useful statement of `disjointed_rec_succ`.
One could generalize `disjointed` to any locally finite bot preorder domain, in place of `ℕ`.
Related to the TODO in the module docstring of `order.partial_sups`.
-/
variables {α β : Type*}
section generalized_boolean_algebra
variables [generalized_boolean_algebra α]
/-- If `f : ℕ → α` is a sequence of elements, then `disjointed f` is the sequence formed by
subtracting each element from the nexts. This is the unique disjoint sequence whose partial sups
are the same as the original sequence. -/
def disjointed (f : ℕ → α) : ℕ → α
| 0 := f 0
| (n + 1) := f (n + 1) \ (partial_sups f n)
@[simp] lemma disjointed_zero (f : ℕ → α) : disjointed f 0 = f 0 := rfl
lemma disjointed_succ (f : ℕ → α) (n : ℕ) :
disjointed f (n + 1) = f (n + 1) \ (partial_sups f n) :=
rfl
lemma disjointed_le_id : disjointed ≤ (id : (ℕ → α) → ℕ → α) :=
begin
rintro f n,
cases n,
{ refl },
{ exact sdiff_le }
end
lemma disjointed_le (f : ℕ → α) : disjointed f ≤ f := disjointed_le_id f
lemma disjoint_disjointed (f : ℕ → α) : pairwise (disjoint on disjointed f) :=
begin
refine (symmetric.pairwise_on disjoint.symm _).2 (λ m n h, _),
cases n,
{ exact (nat.not_lt_zero _ h).elim },
exact disjoint_sdiff_self_right.mono_left ((disjointed_le f m).trans
(le_partial_sups_of_le f (nat.lt_add_one_iff.1 h))),
end
/-- An induction principle for `disjointed`. To define/prove something on `disjointed f n`, it's
enough to define/prove it for `f n` and being able to extend through diffs. -/
def disjointed_rec {f : ℕ → α} {p : α → Sort*} (hdiff : ∀ ⦃t i⦄, p t → p (t \ f i)) :
∀ ⦃n⦄, p (f n) → p (disjointed f n)
| 0 := id
| (n + 1) := λ h,
begin
suffices H : ∀ k, p (f (n + 1) \ partial_sups f k),
{ exact H n },
rintro k,
induction k with k ih,
{ exact hdiff h },
rw [partial_sups_succ, ←sdiff_sdiff_left],
exact hdiff ih,
end
@[simp] lemma disjointed_rec_zero {f : ℕ → α} {p : α → Sort*} (hdiff : ∀ ⦃t i⦄, p t → p (t \ f i))
(h₀ : p (f 0)) :
disjointed_rec hdiff h₀ = h₀ := rfl
-- TODO: Find a useful statement of `disjointed_rec_succ`.
lemma monotone.disjointed_eq {f : ℕ → α} (hf : monotone f) (n : ℕ) :
disjointed f (n + 1) = f (n + 1) \ f n :=
by rw [disjointed_succ, hf.partial_sups_eq]
@[simp] lemma partial_sups_disjointed (f : ℕ → α) :
partial_sups (disjointed f) = partial_sups f :=
begin
ext n,
induction n with k ih,
{ rw [partial_sups_zero, partial_sups_zero, disjointed_zero] },
{ rw [partial_sups_succ, partial_sups_succ, disjointed_succ, ih, sup_sdiff_self_right] }
end
/-- `disjointed f` is the unique sequence that is pairwise disjoint and has the same partial sups
as `f`. -/
lemma disjointed_unique {f d : ℕ → α} (hdisj : pairwise (disjoint on d))
(hsups : partial_sups d = partial_sups f) : d = disjointed f :=
begin
ext n,
cases n,
{ rw [←partial_sups_zero d, hsups, partial_sups_zero, disjointed_zero] },
suffices h : d n.succ = partial_sups d n.succ \ partial_sups d n,
{ rw [h, hsups, partial_sups_succ, disjointed_succ, sup_sdiff, sdiff_self, bot_sup_eq] },
rw [partial_sups_succ, sup_sdiff, sdiff_self, bot_sup_eq, eq_comm, sdiff_eq_self_iff_disjoint],
suffices h : ∀ m ≤ n, disjoint (partial_sups d m) (d n.succ),
{ exact h n le_rfl },
rintro m hm,
induction m with m ih,
{ exact hdisj _ _ (nat.succ_ne_zero _).symm },
rw [partial_sups_succ, disjoint_iff, inf_sup_right, sup_eq_bot_iff, ←disjoint_iff, ←disjoint_iff],
exact ⟨ih (nat.le_of_succ_le hm), hdisj _ _ (nat.lt_succ_of_le hm).ne⟩,
end
end generalized_boolean_algebra
section complete_boolean_algebra
variables [complete_boolean_algebra α]
lemma supr_disjointed (f : ℕ → α) : (⨆ n, disjointed f n) = (⨆ n, f n) :=
supr_eq_supr_of_partial_sups_eq_partial_sups (partial_sups_disjointed f)
lemma disjointed_eq_inf_compl (f : ℕ → α) (n : ℕ) :
disjointed f n = f n ⊓ (⨅ i < n, (f i)ᶜ) :=
begin
cases n,
{ rw [disjointed_zero, eq_comm, inf_eq_left],
simp_rw le_infi_iff,
exact λ i hi, (i.not_lt_zero hi).elim },
simp_rw [disjointed_succ, partial_sups_eq_bsupr, sdiff_eq, compl_supr],
congr,
ext i,
rw nat.lt_succ_iff,
end
end complete_boolean_algebra
/-! ### Set notation variants of lemmas -/
lemma disjointed_subset (f : ℕ → set α) (n : ℕ) : disjointed f n ⊆ f n :=
disjointed_le f n
lemma Union_disjointed {f : ℕ → set α} : (⋃ n, disjointed f n) = (⋃ n, f n) :=
supr_disjointed f
lemma disjointed_eq_inter_compl (f : ℕ → set α) (n : ℕ) :
disjointed f n = f n ∩ (⋂ i < n, (f i)ᶜ) :=
disjointed_eq_inf_compl f n
lemma preimage_find_eq_disjointed (s : ℕ → set α) (H : ∀ x, ∃ n, x ∈ s n)
[∀ x n, decidable (x ∈ s n)] (n : ℕ) :
(λ x, nat.find (H x)) ⁻¹' {n} = disjointed s n :=
by { ext x, simp [nat.find_eq_iff, disjointed_eq_inter_compl] }
|
3272f0f4430d2af93f5271acfe67f9733b7acd68 | 1437b3495ef9020d5413178aa33c0a625f15f15f | /analysis/real.lean | 728bdd6f0a73feeabcde9311a40e84bdcd5dab13 | [
"Apache-2.0"
] | permissive | jean002/mathlib | c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30 | dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd | refs/heads/master | 1,587,027,806,375 | 1,547,306,358,000 | 1,547,306,358,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,544 | 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
The real numbers ℝ.
They are constructed as the topological completion of ℚ. With the following steps:
(1) prove that ℚ forms a uniform space.
(2) subtraction and addition are uniform continuous functions in this space
(3) for multiplication and inverse this only holds on bounded subsets
(4) ℝ is defined as separated Cauchy filters over ℚ (the separation requires a quotient construction)
(5) extend the uniform continuous functions along the completion
(6) proof field properties using the principle of extension of identities
TODO
generalizations:
* topological groups & rings
* order topologies
* Archimedean fields
-/
import logic.function analysis.metric_space tactic.linarith
noncomputable theory
open classical set lattice filter topological_space
local attribute [instance] prop_decidable
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
instance : metric_space ℚ :=
metric_space.induced coe rat.cast_injective real.metric_space
theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl
instance : metric_space ℤ :=
begin
letI M := metric_space.induced coe int.cast_injective real.metric_space,
refine @metric_space.replace_uniformity _ int.uniform_space M
(le_antisymm refl_le_uniformity $ λ r ru,
mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h,
mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩),
simpa using (@int.cast_le ℝ _ _ 0).2 (int.lt_add_one_iff.1 $
(@int.cast_lt ℝ _ (abs (a - b)) 1).1 $ by simpa using h)
end
theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) :=
uniform_continuous_comap
theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) :=
uniform_embedding_comap rat.cast_injective
theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) :=
uniform_embedding_of_rat.dense_embedding $
λ x, mem_closure_iff_nhds.2 $ λ t ht,
let ⟨ε,ε0, hε⟩ := mem_nhds_iff_metric.1 ht in
let ⟨q, h⟩ := exists_rat_near x ε0 in
ne_empty_iff_exists_mem.2 ⟨_, hε (mem_ball'.2 h), q, rfl⟩
theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.embedding
theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous
theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) :=
uniform_continuous_of_metric.2 $ λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in
⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩
-- TODO(Mario): Find a way to use rat_add_continuous_lemma
theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) :=
uniform_embedding_of_rat.uniform_continuous_iff.2 $ by simp [(∘)]; exact
((uniform_continuous_fst.comp uniform_continuous_of_rat).prod_mk
(uniform_continuous_snd.comp uniform_continuous_of_rat)).comp real.uniform_continuous_add
theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) :=
uniform_continuous_of_metric.2 $ λ ε ε0, ⟨_, ε0, λ a b h,
by rw dist_comm at h; simpa [real.dist_eq] using h⟩
theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) :=
uniform_continuous_of_metric.2 $ λ ε ε0, ⟨_, ε0, λ a b h,
by rw dist_comm at h; simpa [rat.dist_eq] using h⟩
instance : uniform_add_group ℝ :=
uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg
instance : uniform_add_group ℚ :=
uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg
instance : topological_add_group ℝ := by apply_instance
instance : topological_add_group ℚ := by apply_instance
instance : orderable_topology ℚ :=
induced_orderable_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _)
lemma real.is_topological_basis_Ioo_rat :
@is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) :=
is_topological_basis_of_open_of_nhds
(by simp [is_open_Ioo] {contextual:=tt})
(assume a v hav hv,
let ⟨l, u, hl, hu, h⟩ := (mem_nhds_unbounded (no_top _) (no_bot _)).mp (mem_nhds_sets hv hav),
⟨q, hlq, hqa⟩ := exists_rat_btwn hl,
⟨p, hap, hpu⟩ := exists_rat_btwn hu in
⟨Ioo q p,
by simp; exact ⟨q, p, rat.cast_lt.1 $ lt_trans hqa hap, rfl⟩,
⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h _ (lt_trans hlq hqa') (lt_trans ha'p hpu)⟩)
instance : second_countable_topology ℝ :=
⟨⟨(⋃(a b : ℚ) (h : a < b), {Ioo a b}),
by simp [countable_Union, countable_Union_Prop],
real.is_topological_basis_Ioo_rat.2.2⟩⟩
/- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings
lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) :=
_
lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) :=
_ -/
lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) :
uniform_continuous (λp:s, p.1⁻¹) :=
uniform_continuous_of_metric.2 $ λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in
⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩
lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) :=
uniform_continuous_of_metric.2 $ λ ε ε0,
⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩
lemma real.continuous_abs : continuous (abs : ℝ → ℝ) :=
real.uniform_continuous_abs.continuous
lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) :=
uniform_continuous_of_metric.2 $ λ ε ε0,
⟨ε, ε0, λ a b h, lt_of_le_of_lt
(by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩
lemma rat.continuous_abs : continuous (abs : ℚ → ℚ) :=
rat.uniform_continuous_abs.continuous
lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (nhds r) (nhds r⁻¹) :=
by rw ← abs_pos_iff at r0; exact
tendsto_of_uniform_continuous_subtype
(real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h))
(mem_nhds_sets (real.continuous_abs _ $ is_open_lt' (abs r / 2)) (half_lt_self r0))
lemma real.continuous_inv' : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) :=
continuous_iff_tendsto.mpr $ assume ⟨r, hr⟩,
(continuous_iff_tendsto.mp continuous_subtype_val _).comp (real.tendsto_inv hr)
lemma real.continuous_inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) :
continuous (λa, (f a)⁻¹) :=
show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩),
from (continuous_subtype_mk _ hf).comp real.continuous_inv'
lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) :=
uniform_continuous_of_metric.2 $ λ ε ε0, begin
cases no_top (abs x) with y xy,
have y0 := lt_of_le_of_lt (abs_nonneg _) xy,
refine ⟨_, div_pos ε0 y0, λ a b h, _⟩,
rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)],
exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0
end
lemma real.uniform_continuous_mul (s : set (ℝ × ℝ))
{r₁ r₂ : ℝ} (r₁0 : 0 < r₁) (r₂0 : 0 < r₂)
(H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) :
uniform_continuous (λp:s, p.1.1 * p.1.2) :=
uniform_continuous_of_metric.2 $ λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 r₁0 r₂0 in
⟨δ, δ0, λ a b h,
let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩
protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) :=
continuous_iff_tendsto.2 $ λ ⟨a₁, a₂⟩,
tendsto_of_uniform_continuous_subtype
(real.uniform_continuous_mul
({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1})
(lt_of_le_of_lt (abs_nonneg _) (lt_add_one _))
(lt_of_le_of_lt (abs_nonneg _) (lt_add_one _))
(λ x, id))
(mem_nhds_sets
(is_open_prod
(real.continuous_abs _ $ is_open_gt' (abs a₁ + 1))
(real.continuous_abs _ $ is_open_gt' (abs a₂ + 1)))
⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩)
instance : topological_ring ℝ :=
{ continuous_mul := real.continuous_mul, ..real.topological_add_group }
instance : topological_semiring ℝ := by apply_instance
lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) :=
embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact
((continuous_fst.comp continuous_of_rat).prod_mk
(continuous_snd.comp continuous_of_rat)).comp real.continuous_mul
instance : topological_ring ℚ :=
{ continuous_mul := rat.continuous_mul, ..rat.topological_add_group }
theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) :=
set.ext $ λ y, by rw [mem_ball, real.dist_eq,
abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl
theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) :=
by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add,
add_sub_cancel', add_self_div_two, ← add_div,
add_assoc, add_sub_cancel'_right, add_self_div_two]
lemma real.totally_bounded_Ioo (a b : ℝ) : totally_bounded (Ioo a b) :=
totally_bounded_of_metric.2 $ λ ε ε0, begin
rcases exists_nat_gt ((b - a) / ε) with ⟨n, ba⟩,
rw [div_lt_iff' ε0, sub_lt_iff_lt_add'] at ba,
let s := (λ i:ℕ, a + ε * i) '' {i:ℕ | i < n},
refine ⟨s, finite_image _ ⟨set.fintype_lt_nat _⟩, λ x h, _⟩,
rcases h with ⟨ax, xb⟩,
let i : ℕ := ⌊(x - a) / ε⌋.to_nat,
have : (i : ℤ) = ⌊(x - a) / ε⌋ :=
int.to_nat_of_nonneg (floor_nonneg.2 $ le_of_lt (div_pos (sub_pos.2 ax) ε0)),
simp, refine ⟨_, ⟨i, _, rfl⟩, _⟩,
{ rw [← int.coe_nat_lt, this],
refine int.cast_lt.1 (lt_of_le_of_lt (floor_le _) _),
rw [int.cast_coe_nat, div_lt_iff' ε0, sub_lt_iff_lt_add'],
exact lt_trans xb ba },
{ rw [real.dist_eq, ← int.cast_coe_nat, this, abs_of_nonneg,
← sub_sub, sub_lt_iff_lt_add'],
{ have := lt_floor_add_one ((x - a) / ε),
rwa [div_lt_iff' ε0, mul_add, mul_one] at this },
{ have := floor_le ((x - a) / ε),
rwa [ge, sub_nonneg, ← le_sub_iff_add_le', ← le_div_iff' ε0] } }
end
lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) :=
by rw real.ball_eq_Ioo; apply real.totally_bounded_Ioo
lemma real.totally_bounded_Ico (a b : ℝ) : totally_bounded (Ico a b) :=
let ⟨c, ac⟩ := no_bot a in totally_bounded_subset
(by exact λ x ⟨h₁, h₂⟩, ⟨lt_of_lt_of_le ac h₁, h₂⟩)
(real.totally_bounded_Ioo c b)
lemma real.totally_bounded_Icc (a b : ℝ) : totally_bounded (Icc a b) :=
let ⟨c, bc⟩ := no_top b in totally_bounded_subset
(by exact λ x ⟨h₁, h₂⟩, ⟨h₁, lt_of_le_of_lt h₂ bc⟩)
(real.totally_bounded_Ico a c)
lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) :=
begin
have := totally_bounded_preimage uniform_embedding_of_rat (real.totally_bounded_Icc a b),
rwa (set.ext (λ q, _) : Icc _ _ = _), simp
end
-- TODO(Mario): Generalize to first-countable uniform spaces?
instance : complete_space ℝ :=
⟨λ f cf, begin
let g : ℕ → {ε:ℝ//ε>0} := λ n, ⟨n.to_pnat'⁻¹, inv_pos (nat.cast_pos.2 n.to_pnat'.pos)⟩,
choose S hS hS_dist using show ∀n:ℕ, ∃t ∈ f.sets, ∀ x y ∈ t, dist x y < g n, from
assume n, let ⟨t, tf, h⟩ := (cauchy_of_metric.1 cf).2 (g n).1 (g n).2 in ⟨t, tf, h⟩,
let F : ℕ → set ℝ := λn, ⋂i≤n, S i,
have hF : ∀n, F n ∈ f.sets := assume n, Inter_mem_sets (finite_le_nat n) (λ i _, hS i),
have hF_dist : ∀n, ∀ x y ∈ F n, dist x y < g n :=
assume n x y hx hy,
have F n ⊆ S n := bInter_subset_of_mem (le_refl n),
(hS_dist n) _ _ (this hx) (this hy),
choose G hG using assume n:ℕ, inhabited_of_mem_sets cf.1 (hF n),
have hg : ∀ ε > 0, ∃ n, ∀ j ≥ n, (g j : ℝ) < ε,
{ intros ε ε0,
cases exists_nat_gt ε⁻¹ with n hn,
refine ⟨n, λ j nj, _⟩,
have hj := lt_of_lt_of_le hn (nat.cast_le.2 nj),
have j0 := lt_trans (inv_pos ε0) hj,
have jε := (inv_lt j0 ε0).2 hj,
rwa ← pnat.to_pnat'_coe (nat.cast_pos.1 j0) at jε },
let c : cau_seq ℝ abs,
{ refine ⟨λ n, G n, λ ε ε0, _⟩,
cases hg _ ε0 with n hn,
refine ⟨n, λ j jn, _⟩,
have : F j ⊆ F n :=
bInter_subset_bInter_left (λ i h, @le_trans _ _ i n j h jn),
exact lt_trans (hF_dist n _ _ (this (hG j)) (hG n)) (hn _ $ le_refl _) },
refine ⟨cau_seq.lim c, λ s h, _⟩,
rcases mem_nhds_iff_metric.1 h with ⟨ε, ε0, hε⟩,
cases exists_forall_ge_and (hg _ $ half_pos ε0)
(cau_seq.equiv_lim c _ $ half_pos ε0) with n hn,
cases hn _ (le_refl _) with h₁ h₂,
refine sets_of_superset _ (hF n) (subset.trans _ $
subset.trans (ball_half_subset (G n) h₂) hε),
exact λ x h, lt_trans ((hF_dist n) x (G n) h (hG n)) h₁
end⟩
lemma tendsto_of_nat_at_top_at_top : tendsto (coe : ℕ → ℝ) at_top at_top :=
tendsto_infi.2 $ assume r, tendsto_principal.2 $
let ⟨n, hn⟩ := exists_nat_gt r in
mem_at_top_sets.2 ⟨n, λ m h, le_trans (le_of_lt hn) (nat.cast_le.2 h)⟩
section
lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} :=
subset.antisymm
((closure_subset_iff_subset_of_is_closed (is_closed_ge' _)).2
(image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $
λ x hx, mem_closure_iff_nhds.2 $ λ t ht,
let ⟨ε, ε0, hε⟩ := mem_nhds_iff_metric.1 ht in
let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in
ne_empty_iff_exists_mem.2 ⟨_, hε (show abs _ < _,
by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']),
p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩
/- TODO(Mario): Put these back only if needed later
lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} :=
_
lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) :
closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} :=
_-/
lemma compact_Icc {a b : ℝ} : compact (Icc a b) :=
compact_of_totally_bounded_is_closed
(real.totally_bounded_Icc a b)
(is_closed_inter (is_closed_ge' a) (is_closed_le' b))
instance : proper_space ℝ :=
{ compact_ball := λx r, by rw closed_ball_Icc; apply compact_Icc }
open real
lemma real.intermediate_value {f : ℝ → ℝ} {a b t : ℝ}
(hf : ∀ x, a ≤ x → x ≤ b → tendsto f (nhds x) (nhds (f x)))
(ha : f a ≤ t) (hb : t ≤ f b) (hab : a ≤ b) : ∃ x : ℝ, a ≤ x ∧ x ≤ b ∧ f x = t :=
let x := real.Sup {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} in
have hx₁ : ∃ y, ∀ g ∈ {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b}, g ≤ y := ⟨b, λ _ h, h.2.2⟩,
have hx₂ : ∃ y, y ∈ {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} := ⟨a, ha, le_refl _, hab⟩,
have hax : a ≤ x, from le_Sup _ hx₁ ⟨ha, le_refl _, hab⟩,
have hxb : x ≤ b, from (Sup_le _ hx₂ hx₁).2 (λ _ h, h.2.2),
⟨x, hax, hxb,
eq_of_forall_dist_le $ λ ε ε0,
let ⟨δ, hδ0, hδ⟩ := tendsto_nhds_of_metric.1 (hf _ hax hxb) ε ε0 in
(le_total t (f x)).elim
(λ h, le_of_not_gt $ λ hfε, begin
rw [dist_eq, abs_of_nonneg (sub_nonneg.2 h)] at hfε,
refine mt (Sup_le {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} hx₂ hx₁).2
(not_le_of_gt (sub_lt_self x (half_pos hδ0)))
(λ g hg, le_of_not_gt
(λ hgδ, not_lt_of_ge hg.1
(lt_trans (lt_sub.1 hfε) (sub_lt_of_sub_lt
(lt_of_le_of_lt (le_abs_self _) _))))),
rw abs_sub,
exact hδ (abs_sub_lt_iff.2 ⟨lt_of_le_of_lt (sub_nonpos.2 (le_Sup _ hx₁ hg)) hδ0,
by simp only [x] at *; linarith⟩)
end)
(λ h, le_of_not_gt $ λ hfε, begin
rw [dist_eq, abs_of_nonpos (sub_nonpos.2 h)] at hfε,
exact mt (le_Sup {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b})
(λ h : ∀ k, k ∈ {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} → k ≤ x,
not_le_of_gt ((lt_add_iff_pos_left x).2 (half_pos hδ0))
(h _ ⟨le_trans (le_sub_iff_add_le.2 (le_trans (le_abs_self _)
(le_of_lt (hδ $ by rw [dist_eq, add_sub_cancel, abs_of_nonneg (le_of_lt (half_pos hδ0))];
exact half_lt_self hδ0))))
(by linarith),
le_trans hax (le_of_lt ((lt_add_iff_pos_left _).2 (half_pos hδ0))),
le_of_not_gt (λ hδy, not_lt_of_ge hb (lt_of_le_of_lt
(show f b ≤ f b - f x - ε + t, by linarith)
(add_lt_of_neg_of_le
(sub_neg_of_lt (lt_of_le_of_lt (le_abs_self _)
(@hδ b (abs_sub_lt_iff.2 ⟨by simp only [x] at *; linarith,
by linarith⟩))))
(le_refl _))))⟩))
hx₁
end)⟩
lemma real.intermediate_value' {f : ℝ → ℝ} {a b t : ℝ}
(hf : ∀ x, a ≤ x → x ≤ b → tendsto f (nhds x) (nhds (f x)))
(ha : t ≤ f a) (hb : f b ≤ t) (hab : a ≤ b) : ∃ x : ℝ, a ≤ x ∧ x ≤ b ∧ f x = t :=
let ⟨x, hx₁, hx₂, hx₃⟩ := @real.intermediate_value
(λ x, - f x) a b (-t) (λ x hax hxb, tendsto_neg (hf x hax hxb))
(neg_le_neg ha) (neg_le_neg hb) hab in
⟨x, hx₁, hx₂, neg_inj hx₃⟩
end
|
ba32e40021d16f9043522bd7de1e86e02a005022 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/polynomial/module.lean | f0e402e31c0b7072c3490384ddeff87ee1f9292e | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 11,015 | lean | /-
Copyright (c) 2022 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import ring_theory.finite_type
/-!
# Polynomial module
In this file, we define the polynomial module for an `R`-module `M`, i.e. the `R[X]`-module `M[X]`.
This is defined as an type alias `polynomial_module R M := ℕ →₀ M`, since there might be different
module structures on `ℕ →₀ M` of interest. See the docstring of `polynomial_module` for details.
-/
universes u v
open polynomial
open_locale polynomial big_operators
variables (R M : Type*) [comm_ring R] [add_comm_group M] [module R M] (I : ideal R)
include R
/--
The `R[X]`-module `M[X]` for an `R`-module `M`.
This is isomorphic (as an `R`-module) to `M[X]` when `M` is a ring.
We require all the module instances `module S (polynomial_module R M)` to factor through `R` except
`module R[X] (polynomial_module R M)`.
In this constraint, we have the following instances for example :
- `R` acts on `polynomial_module R R[X]`
- `R[X]` acts on `polynomial_module R R[X]` as `R[Y]` acting on `R[X][Y]`
- `R` acts on `polynomial_module R[X] R[X]`
- `R[X]` acts on `polynomial_module R[X] R[X]` as `R[X]` acting on `R[X][Y]`
- `R[X][X]` acts on `polynomial_module R[X] R[X]` as `R[X][Y]` acting on itself
This is also the reason why `R` is included in the alias, or else there will be two different
instances of `module R[X] (polynomial_module R[X])`.
See https://leanprover.zulipchat.com/#narrow/stream/144837-PR-reviews/topic/.2315065.20polynomial.20modules
for the full discussion.
-/
@[derive add_comm_group, derive inhabited, nolint unused_arguments]
def polynomial_module := ℕ →₀ M
omit R
variables {M}
variables {S : Type*} [comm_semiring S] [algebra S R] [module S M] [is_scalar_tower S R M]
namespace polynomial_module
/-- This is required to have the `is_scalar_tower S R M` instance to avoid diamonds. -/
@[nolint unused_arguments]
noncomputable
instance : module S (polynomial_module R M) :=
finsupp.module ℕ M
instance : has_coe_to_fun (polynomial_module R M) (λ _, ℕ → M) :=
finsupp.has_coe_to_fun
/-- The monomial `m * x ^ i`. This is defeq to `finsupp.single_add_hom`, and is redefined here
so that it has the desired type signature. -/
noncomputable
def single (i : ℕ) : M →+ polynomial_module R M :=
finsupp.single_add_hom i
lemma single_apply (i : ℕ) (m : M) (n : ℕ) : single R i m n = ite (i = n) m 0 :=
finsupp.single_apply
/-- `polynomial_module.single` as a linear map. -/
noncomputable
def lsingle (i : ℕ) : M →ₗ[R] polynomial_module R M :=
finsupp.lsingle i
lemma lsingle_apply (i : ℕ) (m : M) (n : ℕ) : lsingle R i m n = ite (i = n) m 0 :=
finsupp.single_apply
lemma single_smul (i : ℕ) (r : R) (m : M) : single R i (r • m) = r • (single R i m) :=
(lsingle R i).map_smul r m
variable {R}
lemma induction_linear {P : polynomial_module R M → Prop} (f : polynomial_module R M)
(h0 : P 0) (hadd : ∀ f g, P f → P g → P (f + g)) (hsingle : ∀ a b, P (single R a b)) : P f :=
finsupp.induction_linear f h0 hadd hsingle
@[semireducible] noncomputable
instance polynomial_module : module R[X] (polynomial_module R M) :=
module_polynomial_of_endo (finsupp.lmap_domain _ _ nat.succ)
instance (M : Type u) [add_comm_group M] [module R M] [module S M] [is_scalar_tower S R M] :
is_scalar_tower S R (polynomial_module R M) :=
finsupp.is_scalar_tower _ _
instance is_scalar_tower' (M : Type u) [add_comm_group M] [module R M] [module S M]
[is_scalar_tower S R M] :
is_scalar_tower S R[X] (polynomial_module R M) :=
begin
haveI : is_scalar_tower R R[X] (polynomial_module R M) :=
module_polynomial_of_endo.is_scalar_tower _,
constructor,
intros x y z,
rw [← @is_scalar_tower.algebra_map_smul S R, ← @is_scalar_tower.algebra_map_smul S R,
smul_assoc],
end
@[simp]
lemma monomial_smul_single (i : ℕ) (r : R) (j : ℕ) (m : M) :
monomial i r • single R j m = single R (i + j) (r • m) :=
begin
simp only [linear_map.mul_apply, polynomial.aeval_monomial, linear_map.pow_apply,
module.algebra_map_End_apply, module_polynomial_of_endo_smul_def],
induction i generalizing r j m,
{ simp [single] },
{ rw [function.iterate_succ, function.comp_app, nat.succ_eq_add_one, add_assoc, ← i_ih],
congr' 2,
ext a,
dsimp [single],
rw [finsupp.map_domain_single, nat.succ_eq_one_add] }
end
@[simp]
lemma monomial_smul_apply (i : ℕ) (r : R) (g : polynomial_module R M) (n : ℕ) :
(monomial i r • g) n = ite (i ≤ n) (r • g (n - i)) 0 :=
begin
induction g using polynomial_module.induction_linear with p q hp hq,
{ simp only [smul_zero, finsupp.zero_apply, if_t_t] },
{ simp only [smul_add, finsupp.add_apply, hp, hq],
split_ifs, exacts [rfl, zero_add 0] },
{ rw [monomial_smul_single, single_apply, single_apply, smul_ite, smul_zero, ← ite_and],
congr,
rw eq_iff_iff,
split,
{ rintro rfl, simp },
{ rintro ⟨e, rfl⟩, rw [add_comm, tsub_add_cancel_of_le e] } }
end
@[simp]
lemma smul_single_apply (i : ℕ) (f : R[X]) (m : M) (n : ℕ) :
(f • single R i m) n = ite (i ≤ n) (f.coeff (n - i) • m) 0 :=
begin
induction f using polynomial.induction_on' with p q hp hq,
{ rw [add_smul, finsupp.add_apply, hp, hq, coeff_add, add_smul],
split_ifs, exacts [rfl, zero_add 0] },
{ rw [monomial_smul_single, single_apply, coeff_monomial, ite_smul, zero_smul],
by_cases h : i ≤ n,
{ simp_rw [eq_tsub_iff_add_eq_of_le h, if_pos h] },
{ rw [if_neg h, ite_eq_right_iff], intro e, exfalso, linarith } }
end
lemma smul_apply (f : R[X]) (g : polynomial_module R M) (n : ℕ) :
(f • g) n = ∑ x in finset.nat.antidiagonal n, f.coeff x.1 • g x.2 :=
begin
induction f using polynomial.induction_on' with p q hp hq,
{ rw [add_smul, finsupp.add_apply, hp, hq, ← finset.sum_add_distrib],
congr',
ext,
rw [coeff_add, add_smul] },
{ rw [finset.nat.sum_antidiagonal_eq_sum_range_succ (λ i j, (monomial f_n f_a).coeff i • g j),
monomial_smul_apply],
dsimp [monomial],
simp_rw [finsupp.single_smul, finsupp.single_apply],
rw finset.sum_ite_eq,
simp [nat.lt_succ_iff] }
end
/-- `polynomial_module R R` is isomorphic to `R[X]` as an `R[X]` module. -/
noncomputable
def equiv_polynomial_self : polynomial_module R R ≃ₗ[R[X]] R[X] :=
{ map_smul' := λ r x, begin
induction r using polynomial.induction_on' with _ _ _ _ n p,
{ simp only [add_smul, map_add, ring_equiv.to_fun_eq_coe, *] at * },
{ ext i,
dsimp,
rw [monomial_smul_apply, ← polynomial.C_mul_X_pow_eq_monomial, mul_assoc,
polynomial.coeff_C_mul, polynomial.coeff_X_pow_mul', mul_ite, mul_zero],
simp }
end,
..(polynomial.to_finsupp_iso R).symm }
/-- `polynomial_module R S` is isomorphic to `S[X]` as an `R` module. -/
noncomputable
def equiv_polynomial {S : Type*} [comm_ring S] [algebra R S] :
polynomial_module R S ≃ₗ[R] S[X] :=
{ map_smul' := λ r x, rfl, ..(polynomial.to_finsupp_iso S).symm }
variables (R' : Type*) {M' : Type*} [comm_ring R'] [add_comm_group M'] [module R' M']
variables [algebra R R'] [module R M'] [is_scalar_tower R R' M']
/-- The image of a polynomial under a linear map. -/
noncomputable
def map (f : M →ₗ[R] M') : polynomial_module R M →ₗ[R] polynomial_module R' M' :=
finsupp.map_range.linear_map f
@[simp]
lemma map_single (f : M →ₗ[R] M') (i : ℕ) (m : M) :
map R' f (single R i m) = single R' i (f m) :=
finsupp.map_range_single
lemma map_smul (f : M →ₗ[R] M') (p : R[X]) (q : polynomial_module R M) :
map R' f (p • q) = p.map (algebra_map R R') • map R' f q :=
begin
apply induction_linear q,
{ rw [smul_zero, map_zero, smul_zero] },
{ intros f g e₁ e₂, rw [smul_add, map_add, e₁, e₂, map_add, smul_add] },
intros i m,
apply polynomial.induction_on' p,
{ intros p q e₁ e₂, rw [add_smul, map_add, e₁, e₂, polynomial.map_add, add_smul] },
{ intros j s,
rw [monomial_smul_single, map_single, polynomial.map_monomial, map_single,
monomial_smul_single, f.map_smul, algebra_map_smul] }
end
/-- Evaulate a polynomial `p : polynomial_module R M` at `r : R`. -/
@[simps (lemmas_only)]
def eval (r : R) : polynomial_module R M →ₗ[R] M :=
{ to_fun := λ p, p.sum (λ i m, r ^ i • m),
map_add' := λ x y, finsupp.sum_add_index' (λ _, smul_zero _) (λ _ _ _, smul_add _ _ _),
map_smul' := λ s m, begin
refine (finsupp.sum_smul_index' _).trans _,
{ exact λ i, smul_zero _ },
{ simp_rw [← smul_comm s, ← finsupp.smul_sum], refl }
end }
@[simp]
lemma eval_single (r : R) (i : ℕ) (m : M) : eval r (single R i m) = r ^ i • m :=
finsupp.sum_single_index (smul_zero _)
@[simp]
lemma eval_lsingle (r : R) (i : ℕ) (m : M) : eval r (lsingle R i m) = r ^ i • m :=
eval_single r i m
lemma eval_smul (p : R[X]) (q : polynomial_module R M) (r : R) :
eval r (p • q) = p.eval r • eval r q :=
begin
apply induction_linear q,
{ rw [smul_zero, map_zero, smul_zero] },
{ intros f g e₁ e₂, rw [smul_add, map_add, e₁, e₂, map_add, smul_add] },
intros i m,
apply polynomial.induction_on' p,
{ intros p q e₁ e₂, rw [add_smul, map_add, polynomial.eval_add, e₁, e₂, add_smul] },
{ intros j s,
rw [monomial_smul_single, eval_single, polynomial.eval_monomial, eval_single,
smul_comm, ← smul_smul, pow_add, mul_smul] }
end
@[simp]
lemma eval_map (f : M →ₗ[R] M') (q : polynomial_module R M) (r : R) :
eval (algebra_map R R' r) (map R' f q) = f (eval r q) :=
begin
apply induction_linear q,
{ simp_rw map_zero },
{ intros f g e₁ e₂, simp_rw [map_add, e₁, e₂] },
{ intros i m,
rw [map_single, eval_single, eval_single, f.map_smul, ← map_pow, algebra_map_smul] }
end
@[simp]
lemma eval_map' (f : M →ₗ[R] M) (q : polynomial_module R M) (r : R) :
eval r (map R f q) = f (eval r q) :=
eval_map R f q r
/-- `comp p q` is the composition of `p : R[X]` and `q : M[X]` as `q(p(x))`. -/
@[simps] noncomputable
def comp (p : R[X]) : polynomial_module R M →ₗ[R] polynomial_module R M :=
((eval p).restrict_scalars R).comp (map R[X] (lsingle R 0))
lemma comp_single (p : R[X]) (i : ℕ) (m : M) : comp p (single R i m) = p ^ i • single R 0 m :=
begin
rw comp_apply,
erw [map_single, eval_single],
refl
end
lemma comp_eval (p : R[X]) (q : polynomial_module R M) (r : R) :
eval r (comp p q) = eval (p.eval r) q :=
begin
rw ← linear_map.comp_apply,
apply induction_linear q,
{ rw [map_zero, map_zero] },
{ intros _ _ e₁ e₂, rw [map_add, map_add, e₁, e₂] },
{ intros i m,
rw [linear_map.comp_apply, comp_single, eval_single, eval_smul, eval_single, pow_zero,
one_smul, polynomial.eval_pow] }
end
lemma comp_smul (p p' : R[X]) (q : polynomial_module R M) :
comp p (p' • q) = p'.comp p • comp p q :=
begin
rw [comp_apply, map_smul, eval_smul, polynomial.comp, polynomial.eval_map, comp_apply],
refl
end
end polynomial_module
|
24e5ff7c7a5682858a0e1ff646591ee833bac1c0 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/category_theory/monad/default.lean | 78b9c222ec50d4f2ac3910ca48b706d8c9d85efd | [
"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 | 68 | lean | import
category_theory.monad.limits
category_theory.monad.types
|
bea4d015013496f5f5d11bd66d276bb507d534b0 | 271e26e338b0c14544a889c31c30b39c989f2e0f | /tests/lean/run/unif_issue.lean | bc86d76718220f0c9609606494f320c41e9b047f | [
"Apache-2.0"
] | permissive | dgorokho/lean4 | 805f99b0b60c545b64ac34ab8237a8504f89d7d4 | e949a052bad59b1c7b54a82d24d516a656487d8a | refs/heads/master | 1,607,061,363,851 | 1,578,006,086,000 | 1,578,006,086,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 750 | lean | import Init.Lean
open Lean
#eval toString $
Unhygienic.run $
do a ← `(Nat.one);
let rhs_0 : _ := fun (a : Lean.Syntax) (b : Lean.Syntax) => pure Syntax.missing;
let rhs_1 : _ := fun (_a : _) => pure Lean.Syntax.missing;
let discr_2 : _ := a;
ite (Lean.Syntax.isOfKind discr_2 (Lean.mkNameStr (Lean.mkNameStr (Lean.mkNameStr (Lean.mkNameStr Lean.Name.anonymous "Lean") "Parser") "Term") "add"))
(let discr_3 : _ := Lean.Syntax.getArg discr_2 0;
let discr_4 : _ := Lean.Syntax.getArg discr_2 1;
let discr_5 : _ := Lean.Syntax.getArg discr_2 2;
rhs_0 discr_3 discr_5)
(let discr_7 : _ := a;
rhs_1 Unit.unit)
#check (pure 0 : Id Nat)
#check (let rhs := fun a => pure a; rhs 0 : Id Nat)
|
abcbf77658e33906097f19e676bbade12e8d9bf3 | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/algebra/group_power.lean | f24b9cd18d518586a5e9ba321b369e1d057c6261 | [
"Apache-2.0"
] | permissive | eric-wieser/mathlib | 42842584f584359bbe1fc8b88b3ff937c8acd72d | d0df6b81cd0920ad569158c06a3fd5abb9e63301 | refs/heads/master | 1,669,546,404,255 | 1,595,254,668,000 | 1,595,254,668,000 | 281,173,504 | 0 | 0 | Apache-2.0 | 1,595,263,582,000 | 1,595,263,581,000 | null | UTF-8 | Lean | false | false | 37,009 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis
-/
import algebra.opposites
import data.list.basic
import data.int.cast
import data.equiv.basic
import deprecated.ring
/-!
# Power operations on monoids and groups
The power operation on monoids and groups.
We separate this from group, because it depends on `ℕ`,
which in turn depends on other parts of algebra.
## Notation
The class `has_pow α β` provides the notation `a^b` for powers.
We define instances of `has_pow M ℕ`, for monoids `M`, and `has_pow G ℤ` for groups `G`.
We also define infix operators `•ℕ` and `•ℤ` for scalar multiplication by a natural and an integer
numbers, respectively.
## Implementation details
We adopt the convention that `0^0 = 1`.
-/
universes u v w x y z u₁ u₂
variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z}
{R : Type u₁} {S : Type u₂}
/-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/
def monoid.pow [has_mul M] [has_one M] (a : M) : ℕ → M
| 0 := 1
| (n+1) := a * monoid.pow n
/-- The scalar multiplication in an additive monoid.
`n •ℕ a = a+a+...+a` n times. -/
def nsmul [has_add A] [has_zero A] (n : ℕ) (a : A) : A :=
@monoid.pow (multiplicative A) _ { one := (0 : A) } a n
infix ` •ℕ `:70 := nsmul
@[priority 5] instance monoid.has_pow [monoid M] : has_pow M ℕ := ⟨monoid.pow⟩
/-!
### Commutativity
First we prove some facts about `semiconj_by` and `commute`. They do not require any theory about
`pow` and/or `nsmul` and will be useful later in this file.
-/
namespace semiconj_by
variables [monoid M]
@[simp] lemma pow_right {a x y : M} (h : semiconj_by a x y) (n : ℕ) : semiconj_by a (x^n) (y^n) :=
nat.rec_on n (one_right a) $ λ n ihn, h.mul_right ihn
end semiconj_by
namespace commute
variables [monoid M] {a b : M}
@[simp] theorem pow_right (h : commute a b) (n : ℕ) : commute a (b ^ n) := h.pow_right n
@[simp] theorem pow_left (h : commute a b) (n : ℕ) : commute (a ^ n) b := (h.symm.pow_right n).symm
@[simp] theorem pow_pow (h : commute a b) (m n : ℕ) : commute (a ^ m) (b ^ n) :=
(h.pow_left m).pow_right n
@[simp] theorem self_pow (a : M) (n : ℕ) : commute a (a ^ n) := (commute.refl a).pow_right n
@[simp] theorem pow_self (a : M) (n : ℕ) : commute (a ^ n) a := (commute.refl a).pow_left n
@[simp] theorem pow_pow_self (a : M) (m n : ℕ) : commute (a ^ m) (a ^ n) :=
(commute.refl a).pow_pow m n
end commute
/-!
### (Additive) monoid
-/
section monoid
variables [monoid M] [monoid N] [add_monoid A] [add_monoid B]
@[simp] theorem pow_zero (a : M) : a^0 = 1 := rfl
@[simp] theorem zero_nsmul (a : A) : 0 •ℕ a = 0 := rfl
theorem pow_succ (a : M) (n : ℕ) : a^(n+1) = a * a^n := rfl
theorem succ_nsmul (a : A) (n : ℕ) : (n+1) •ℕ a = a + n •ℕ a := rfl
@[simp] theorem pow_one (a : M) : a^1 = a := mul_one _
@[simp] theorem one_nsmul (a : A) : 1 •ℕ a = a := add_zero _
@[simp] lemma pow_ite (P : Prop) [decidable P] (a : M) (b c : ℕ) :
a ^ (if P then b else c) = if P then a ^ b else a ^ c :=
by split_ifs; refl
@[simp] lemma ite_pow (P : Prop) [decidable P] (a b : M) (c : ℕ) :
(if P then a else b) ^ c = if P then a ^ c else b ^ c :=
by split_ifs; refl
@[simp] lemma pow_boole (P : Prop) [decidable P] (a : M) :
a ^ (if P then 1 else 0) = if P then a else 1 :=
by simp
theorem pow_mul_comm' (a : M) (n : ℕ) : a^n * a = a * a^n := commute.pow_self a n
theorem nsmul_add_comm' : ∀ (a : A) (n : ℕ), n •ℕ a + a = a + n •ℕ a :=
@pow_mul_comm' (multiplicative A) _
theorem pow_succ' (a : M) (n : ℕ) : a^(n+1) = a^n * a :=
by rw [pow_succ, pow_mul_comm']
theorem succ_nsmul' (a : A) (n : ℕ) : (n+1) •ℕ a = n •ℕ a + a :=
@pow_succ' (multiplicative A) _ _ _
theorem pow_two (a : M) : a^2 = a * a :=
show a*(a*1)=a*a, by rw mul_one
theorem two_nsmul (a : A) : 2 •ℕ a = a + a :=
@pow_two (multiplicative A) _ a
theorem pow_add (a : M) (m n : ℕ) : a^(m + n) = a^m * a^n :=
by induction n with n ih; [rw [add_zero, pow_zero, mul_one],
rw [pow_succ', ← mul_assoc, ← ih, ← pow_succ', add_assoc]]
theorem add_nsmul : ∀ (a : A) (m n : ℕ), (m + n) •ℕ a = m •ℕ a + n •ℕ a :=
@pow_add (multiplicative A) _
@[simp] theorem one_pow (n : ℕ) : (1 : M)^n = 1 :=
by induction n with n ih; [refl, rw [pow_succ, ih, one_mul]]
@[simp] theorem nsmul_zero (n : ℕ) : n •ℕ (0 : A) = 0 :=
by induction n with n ih; [refl, rw [succ_nsmul, ih, zero_add]]
theorem pow_mul (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n :=
by induction n with n ih; [rw mul_zero, rw [nat.mul_succ, pow_add, pow_succ', ih]]; refl
theorem mul_nsmul' : ∀ (a : A) (m n : ℕ), m * n •ℕ a = n •ℕ (m •ℕ a) :=
@pow_mul (multiplicative A) _
theorem pow_mul' (a : M) (m n : ℕ) : a^(m * n) = (a^n)^m :=
by rw [mul_comm, pow_mul]
theorem mul_nsmul (a : A) (m n : ℕ) : m * n •ℕ a = m •ℕ (n •ℕ a) :=
@pow_mul' (multiplicative A) _ a m n
@[simp] theorem nsmul_one [has_one A] : ∀ n : ℕ, n •ℕ (1 : A) = n :=
add_monoid_hom.eq_nat_cast
⟨λ n, n •ℕ (1 : A), zero_nsmul _, λ _ _, add_nsmul _ _ _⟩
(one_nsmul _)
theorem pow_bit0 (a : M) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _
theorem bit0_nsmul (a : A) (n : ℕ) : bit0 n •ℕ a = n •ℕ a + n •ℕ a := add_nsmul _ _ _
theorem pow_bit1 (a : M) (n : ℕ) : a ^ bit1 n = a^n * a^n * a :=
by rw [bit1, pow_succ', pow_bit0]
theorem bit1_nsmul : ∀ (a : A) (n : ℕ), bit1 n •ℕ a = n •ℕ a + n •ℕ a + a :=
@pow_bit1 (multiplicative A) _
theorem pow_mul_comm (a : M) (m n : ℕ) : a^m * a^n = a^n * a^m :=
commute.pow_pow_self a m n
theorem nsmul_add_comm : ∀ (a : A) (m n : ℕ), m •ℕ a + n •ℕ a = n •ℕ a + m •ℕ a :=
@pow_mul_comm (multiplicative A) _
@[simp, priority 500]
theorem list.prod_repeat (a : M) (n : ℕ) : (list.repeat a n).prod = a ^ n :=
by induction n with n ih; [refl, rw [list.repeat_succ, list.prod_cons, ih]]; refl
@[simp, priority 500]
theorem list.sum_repeat : ∀ (a : A) (n : ℕ), (list.repeat a n).sum = n •ℕ a :=
@list.prod_repeat (multiplicative A) _
theorem monoid_hom.map_pow (f : M →* N) (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n
| 0 := f.map_one
| (n+1) := by rw [pow_succ, pow_succ, f.map_mul, monoid_hom.map_pow]
theorem add_monoid_hom.map_nsmul (f : A →+ B) (a : A) (n : ℕ) : f (n •ℕ a) = n •ℕ f a :=
f.to_multiplicative.map_pow a n
theorem is_monoid_hom.map_pow (f : M → N) [is_monoid_hom f] (a : M) :
∀(n : ℕ), f (a ^ n) = (f a) ^ n :=
(monoid_hom.of f).map_pow a
theorem is_add_monoid_hom.map_nsmul (f : A → B) [is_add_monoid_hom f] (a : A) (n : ℕ) :
f (n •ℕ a) = n •ℕ f a :=
(add_monoid_hom.of f).map_nsmul a n
@[simp, norm_cast] lemma units.coe_pow (u : units M) (n : ℕ) : ((u ^ n : units M) : M) = u ^ n :=
(units.coe_hom M).map_pow u n
lemma commute.mul_pow {a b : M} (h : commute a b) (n : ℕ) : (a * b) ^ n = a ^ n * b ^ n :=
nat.rec_on n (by simp) $ λ n ihn,
by simp only [pow_succ, ihn, ← mul_assoc, (h.pow_left n).right_comm]
theorem neg_pow [ring R] (a : R) (n : ℕ) : (- a) ^ n = (-1) ^ n * a ^ n :=
(neg_one_mul a) ▸ (commute.neg_one_left a).mul_pow n
end monoid
@[simp] theorem nat.pow_eq_pow (p q : ℕ) :
@has_pow.pow _ _ monoid.has_pow p q = p ^ q :=
by induction q with q ih; [refl, rw [nat.pow_succ, pow_succ', ih]]
theorem nat.nsmul_eq_mul (m n : ℕ) : m •ℕ n = m * n :=
by induction m with m ih; [rw [zero_nsmul, zero_mul],
rw [succ_nsmul', ih, nat.succ_mul]]
/-!
### Commutative (additive) monoid
-/
section comm_monoid
variables [comm_monoid M] [add_comm_monoid A]
theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n = a^n * b^n :=
(commute.all a b).mul_pow n
theorem nsmul_add : ∀ (a b : A) (n : ℕ), n •ℕ (a + b) = n •ℕ a + n •ℕ b :=
@mul_pow (multiplicative A) _
instance pow.is_monoid_hom (n : ℕ) : is_monoid_hom ((^ n) : M → M) :=
{ map_mul := λ _ _, mul_pow _ _ _, map_one := one_pow _ }
instance nsmul.is_add_monoid_hom (n : ℕ) : is_add_monoid_hom (nsmul n : A → A) :=
{ map_add := λ _ _, nsmul_add _ _ _, map_zero := nsmul_zero _ }
end comm_monoid
section group
variables [group G] [group H] [add_group A] [add_group B]
section nat
@[simp] theorem inv_pow (a : G) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ :=
by induction n with n ih; [exact one_inv.symm,
rw [pow_succ', pow_succ, ih, mul_inv_rev]]
@[simp] theorem neg_nsmul : ∀ (a : A) (n : ℕ), n •ℕ (-a) = -(n •ℕ a) :=
@inv_pow (multiplicative A) _
theorem pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ :=
have h1 : m - n + n = m, from nat.sub_add_cancel h,
have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1],
eq_mul_inv_of_mul_eq h2
theorem nsmul_sub : ∀ (a : A) {m n : ℕ}, n ≤ m → (m - n) •ℕ a = m •ℕ a - n •ℕ a :=
@pow_sub (multiplicative A) _
theorem pow_inv_comm (a : G) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m :=
(commute.refl a).inv_left.pow_pow m n
theorem nsmul_neg_comm : ∀ (a : A) (m n : ℕ), m •ℕ (-a) + n •ℕ a = n •ℕ a + m •ℕ (-a) :=
@pow_inv_comm (multiplicative A) _
end nat
open int
/--
The power operation in a group. This extends `monoid.pow` to negative integers
with the definition `a^(-n) = (a^n)⁻¹`.
-/
def gpow (a : G) : ℤ → G
| (of_nat n) := a^n
| -[1+n] := (a^(nat.succ n))⁻¹
/--
The scalar multiplication by integers on an additive group.
This extends `nsmul` to negative integers
with the definition `(-n) •ℤ a = -(n •ℕ a)`.
-/
def gsmul (n : ℤ) (a : A) : A :=
@gpow (multiplicative A) _ a n
@[priority 10] instance group.has_pow : has_pow G ℤ := ⟨gpow⟩
infix ` •ℤ `:70 := gsmul
@[simp] theorem gpow_coe_nat (a : G) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl
@[simp] theorem gsmul_coe_nat (a : A) (n : ℕ) : n •ℤ a = n •ℕ a := rfl
theorem gpow_of_nat (a : G) (n : ℕ) : a ^ of_nat n = a ^ n := rfl
theorem gsmul_of_nat (a : A) (n : ℕ) : of_nat n •ℤ a = n •ℕ a := rfl
@[simp] theorem gpow_neg_succ_of_nat (a : G) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl
@[simp] theorem gsmul_neg_succ_of_nat (a : A) (n : ℕ) : -[1+n] •ℤ a = - (n.succ •ℕ a) := rfl
local attribute [ematch] le_of_lt
open nat
@[simp] theorem gpow_zero (a : G) : a ^ (0:ℤ) = 1 := rfl
@[simp] theorem zero_gsmul (a : A) : (0:ℤ) •ℤ a = 0 := rfl
@[simp] theorem gpow_one (a : G) : a ^ (1:ℤ) = a := pow_one a
@[simp] theorem one_gsmul (a : A) : (1:ℤ) •ℤ a = a := add_zero _
@[simp] theorem one_gpow : ∀ (n : ℤ), (1 : G) ^ n = 1
| (n : ℕ) := one_pow _
| -[1+ n] := show _⁻¹=(1:G), by rw [_root_.one_pow, one_inv]
@[simp] theorem gsmul_zero : ∀ (n : ℤ), n •ℤ (0 : A) = 0 :=
@one_gpow (multiplicative A) _
@[simp] theorem gpow_neg (a : G) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹
| (n+1:ℕ) := rfl
| 0 := one_inv.symm
| -[1+ n] := (inv_inv _).symm
lemma mul_gpow_neg_one (a b : G) : (a*b)^(-(1:ℤ)) = b^(-(1:ℤ))*a^(-(1:ℤ)) :=
by simp only [mul_inv_rev, gpow_one, gpow_neg]
@[simp] theorem neg_gsmul : ∀ (a : A) (n : ℤ), -n •ℤ a = -(n •ℤ a) :=
@gpow_neg (multiplicative A) _
theorem gpow_neg_one (x : G) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x
theorem neg_one_gsmul (x : A) : (-1:ℤ) •ℤ x = -x := congr_arg has_neg.neg $ one_nsmul x
theorem gsmul_one [has_one A] (n : ℤ) : n •ℤ (1 : A) = n :=
by cases n; simp
theorem inv_gpow (a : G) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹
| (n : ℕ) := inv_pow a n
| -[1+ n] := congr_arg has_inv.inv $ inv_pow a (n+1)
theorem gsmul_neg (a : A) (n : ℤ) : gsmul n (- a) = - gsmul n a :=
@inv_gpow (multiplicative A) _ a n
lemma gpow_add_one (a : G) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a
| (of_nat n) := by simp [← int.coe_nat_succ, pow_succ']
| -[1+0] := by simp [int.neg_succ_of_nat_eq]
| -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, gpow_neg, neg_add, neg_add_cancel_right, gpow_neg,
← int.coe_nat_succ, gpow_coe_nat, gpow_coe_nat, _root_.pow_succ _ (n + 1), mul_inv_rev,
inv_mul_cancel_right]
theorem add_one_gsmul : ∀ (a : A) (i : ℤ), (i + 1) •ℤ a = i •ℤ a + a :=
@gpow_add_one (multiplicative A) _
lemma gpow_sub_one (a : G) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ :=
calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : (mul_inv_cancel_right _ _).symm
... = a^n * a⁻¹ : by rw [← gpow_add_one, sub_add_cancel]
lemma gpow_add (a : G) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n :=
begin
induction n using int.induction_on with n ihn n ihn,
case hz : { simp },
{ simp only [← add_assoc, gpow_add_one, ihn, mul_assoc] },
{ rw [gpow_sub_one, ← mul_assoc, ← ihn, ← gpow_sub_one, add_sub_assoc] }
end
lemma mul_self_gpow (b : G) (m : ℤ) : b*b^m = b^(m+1) :=
by { conv_lhs {congr, rw ← gpow_one b }, rw [← gpow_add, add_comm] }
lemma mul_gpow_self (b : G) (m : ℤ) : b^m*b = b^(m+1) :=
by { conv_lhs {congr, skip, rw ← gpow_one b }, rw [← gpow_add, add_comm] }
theorem add_gsmul : ∀ (a : A) (i j : ℤ), (i + j) •ℤ a = i •ℤ a + j •ℤ a :=
@gpow_add (multiplicative A) _
lemma gpow_sub (a : G) (m n : ℤ) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ :=
by rw [sub_eq_add_neg, gpow_add, gpow_neg]
lemma sub_gsmul (m n : ℤ) (a : A) : (m - n) •ℤ a = m •ℤ a - n •ℤ a :=
@gpow_sub (multiplicative A) _ _ _ _
theorem gpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i :=
by rw [gpow_add, gpow_one]
theorem one_add_gsmul : ∀ (a : A) (i : ℤ), (1 + i) •ℤ a = a + i •ℤ a :=
@gpow_one_add (multiplicative A) _
theorem gpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i :=
by rw [← gpow_add, ← gpow_add, add_comm]
theorem gsmul_add_comm : ∀ (a : A) (i j), i •ℤ a + j •ℤ a = j •ℤ a + i •ℤ a :=
@gpow_mul_comm (multiplicative A) _
theorem gpow_mul (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ m) ^ n :=
int.induction_on n (by simp) (λ n ihn, by simp [mul_add, gpow_add, ihn])
(λ n ihn, by simp only [mul_sub, gpow_sub, ihn, mul_one, gpow_one])
theorem gsmul_mul' : ∀ (a : A) (m n : ℤ), m * n •ℤ a = n •ℤ (m •ℤ a) :=
@gpow_mul (multiplicative A) _
theorem gpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m :=
by rw [mul_comm, gpow_mul]
theorem gsmul_mul (a : A) (m n : ℤ) : m * n •ℤ a = m •ℤ (n •ℤ a) :=
by rw [mul_comm, gsmul_mul']
theorem gpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _
theorem bit0_gsmul (a : A) (n : ℤ) : bit0 n •ℤ a = n •ℤ a + n •ℤ a := gpow_add _ _ _
theorem gpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a :=
by rw [bit1, gpow_add]; simp [gpow_bit0]
theorem bit1_gsmul : ∀ (a : A) (n : ℤ), bit1 n •ℤ a = n •ℤ a + n •ℤ a + a :=
@gpow_bit1 (multiplicative A) _
theorem monoid_hom.map_gpow (f : G →* H) (a : G) (n : ℤ) : f (a ^ n) = f a ^ n :=
by cases n; [exact f.map_pow _ _, exact (f.map_inv _).trans (congr_arg _ $ f.map_pow _ _)]
theorem add_monoid_hom.map_gsmul (f : A →+ B) (a : A) (n : ℤ) : f (n •ℤ a) = n •ℤ f a :=
f.to_multiplicative.map_gpow a n
@[simp, norm_cast] lemma units.coe_gpow (u : units G) (n : ℤ) : ((u ^ n : units G) : G) = u ^ n :=
(units.coe_hom G).map_gpow u n
theorem commute.mul_gpow {a b : G} (h : commute a b) : ∀ n : ℤ, (a * b) ^ n = a ^ n * b ^ n
| (n : ℕ) := h.mul_pow n
| -[1+n] := by simp [h.mul_pow, (h.pow_pow n.succ n.succ).inv_inv.symm.eq]
end group
section comm_group
variables [comm_group G] [add_comm_group A]
theorem mul_gpow (a b : G) (n : ℤ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_gpow n
theorem gsmul_add : ∀ (a b : A) (n : ℤ), n •ℤ (a + b) = n •ℤ a + n •ℤ b :=
@mul_gpow (multiplicative A) _
theorem gsmul_sub (a b : A) (n : ℤ) : gsmul n (a - b) = gsmul n a - gsmul n b :=
by simp only [gsmul_add, gsmul_neg, sub_eq_add_neg]
instance gpow.is_group_hom (n : ℤ) : is_group_hom ((^ n) : G → G) :=
{ map_mul := λ _ _, mul_gpow _ _ n }
instance gsmul.is_add_group_hom (n : ℤ) : is_add_group_hom (gsmul n : A → A) :=
{ map_add := λ _ _, gsmul_add _ _ n }
end comm_group
@[simp] lemma with_bot.coe_nsmul [add_monoid A] (a : A) (n : ℕ) :
((nsmul n a : A) : with_bot A) = nsmul n a :=
add_monoid_hom.map_nsmul ⟨(coe : A → with_bot A), with_bot.coe_zero, with_bot.coe_add⟩ a n
theorem nsmul_eq_mul' [semiring R] (a : R) (n : ℕ) : n •ℕ a = a * n :=
by induction n with n ih; [rw [zero_nsmul, nat.cast_zero, mul_zero],
rw [succ_nsmul', ih, nat.cast_succ, mul_add, mul_one]]
@[simp] theorem nsmul_eq_mul [semiring R] (n : ℕ) (a : R) : n •ℕ a = n * a :=
by rw [nsmul_eq_mul', (n.cast_commute a).eq]
theorem mul_nsmul_left [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = a * (n •ℕ b) :=
by rw [nsmul_eq_mul', nsmul_eq_mul', mul_assoc]
theorem mul_nsmul_assoc [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = n •ℕ a * b :=
by rw [nsmul_eq_mul, nsmul_eq_mul, mul_assoc]
lemma zero_pow [semiring R] : ∀ {n : ℕ}, 0 < n → (0 : R) ^ n = 0
| (n+1) _ := zero_mul _
@[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m :=
by induction m with m ih; [exact nat.cast_one, rw [nat.pow_succ, pow_succ', nat.cast_mul, ih]]
@[simp, norm_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m :=
by induction m with m ih; [exact int.coe_nat_one, rw [nat.pow_succ, pow_succ', int.coe_nat_mul, ih]]
theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k :=
by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, nat.pow_succ, ih]]
namespace ring_hom
variables [semiring R] [semiring S]
@[simp] lemma map_pow (f : R →+* S) (a) :
∀ n : ℕ, f (a ^ n) = (f a) ^ n :=
f.to_monoid_hom.map_pow a
end ring_hom
lemma is_semiring_hom.map_pow [semiring R] [semiring S] (f : R → S) [is_semiring_hom f] (a) :
∀ n : ℕ, f (a ^ n) = (f a) ^ n :=
is_monoid_hom.map_pow f a
theorem neg_one_pow_eq_or [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1
| 0 := or.inl rfl
| (n+1) := (neg_one_pow_eq_or n).swap.imp
(λ h, by rw [pow_succ, h, neg_one_mul, neg_neg])
(λ h, by rw [pow_succ, h, mul_one])
lemma pow_dvd_pow [comm_semiring R] (a : R) {m n : ℕ} (h : m ≤ n) :
a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_sub_cancel' h]⟩
theorem pow_dvd_pow_of_dvd [comm_semiring R] {a b : R} (h : a ∣ b) : ∀ n : ℕ, a ^ n ∣ b ^ n
| 0 := dvd_refl _
| (n+1) := mul_dvd_mul h (pow_dvd_pow_of_dvd n)
lemma pow_two_sub_pow_two {R : Type*} [comm_ring R] (a b : R) :
a ^ 2 - b ^ 2 = (a + b) * (a - b) :=
by simp only [pow_two, mul_sub, add_mul, sub_sub, add_sub, mul_comm, sub_add_cancel]
lemma eq_or_eq_neg_of_pow_two_eq_pow_two [integral_domain R] (a b : R) (h : a ^ 2 = b ^ 2) :
a = b ∨ a = -b :=
by rwa [← add_eq_zero_iff_eq_neg, ← sub_eq_zero, or_comm, ← mul_eq_zero,
← pow_two_sub_pow_two a b, sub_eq_zero]
-- The next four lemmas allow us to replace multiplication by a numeral with a `gsmul` expression.
-- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`.
lemma bit0_mul [ring R] {n r : R} : bit0 n * r = gsmul 2 (n * r) :=
by { dsimp [bit0], rw [add_mul, add_gsmul, one_gsmul], }
lemma mul_bit0 [ring R] {n r : R} : r * bit0 n = gsmul 2 (r * n) :=
by { dsimp [bit0], rw [mul_add, add_gsmul, one_gsmul], }
lemma bit1_mul [ring R] {n r : R} : bit1 n * r = gsmul 2 (n * r) + r :=
by { dsimp [bit1], rw [add_mul, bit0_mul, one_mul], }
lemma mul_bit1 [ring R] {n r : R} : r * bit1 n = gsmul 2 (r * n) + r :=
by { dsimp [bit1], rw [mul_add, mul_bit0, mul_one], }
@[simp] theorem gsmul_eq_mul [ring R] (a : R) : ∀ n, n •ℤ a = n * a
| (n : ℕ) := nsmul_eq_mul _ _
| -[1+ n] := show -(_ •ℕ _)=-_*_, by rw [neg_mul_eq_neg_mul_symm, nsmul_eq_mul, nat.cast_succ]
theorem gsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n •ℤ a = a * n :=
by rw [gsmul_eq_mul, (n.cast_commute a).eq]
theorem mul_gsmul_left [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) :=
by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc]
theorem mul_gsmul_assoc [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b :=
by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc]
@[simp]
lemma gsmul_int_int (a b : ℤ) : a •ℤ b = a * b := by simp [gsmul_eq_mul]
lemma gsmul_int_one (n : ℤ) : n •ℤ 1 = n := by simp
@[simp, norm_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m :=
by induction m with m ih; [exact int.cast_one,
rw [pow_succ, pow_succ, int.cast_mul, ih]]
lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = (-1) ^ (n % 2) :=
by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two]
theorem sq_sub_sq [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) :=
by rw [pow_two, pow_two, mul_self_sub_mul_self]
theorem pow_eq_zero [domain R] {x : R} {n : ℕ} (H : x^n = 0) : x = 0 :=
begin
induction n with n ih,
{ rw pow_zero at H,
rw [← mul_one x, H, mul_zero] },
exact or.cases_on (mul_eq_zero.1 H) id ih
end
@[field_simps] theorem pow_ne_zero [domain R] {a : R} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 :=
mt pow_eq_zero h
theorem nsmul_nonneg [ordered_add_comm_monoid R] {a : R} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n •ℕ a
| 0 := le_refl _
| (n+1) := add_nonneg H (nsmul_nonneg n)
lemma pow_abs [decidable_linear_ordered_comm_ring R] (a : R) (n : ℕ) : (abs a)^n = abs (a^n) :=
by induction n with n ih; [exact (abs_one).symm,
rw [pow_succ, pow_succ, ih, abs_mul]]
lemma abs_neg_one_pow [decidable_linear_ordered_comm_ring R] (n : ℕ) : abs ((-1 : R)^n) = 1 :=
by rw [←pow_abs, abs_neg, abs_one, one_pow]
section add_monoid
variable [ordered_add_comm_monoid A]
theorem nsmul_le_nsmul {a : A} {n m : ℕ} (ha : 0 ≤ a) (h : n ≤ m) : n •ℕ a ≤ m •ℕ a :=
let ⟨k, hk⟩ := nat.le.dest h in
calc n •ℕ a = n •ℕ a + 0 : (add_zero _).symm
... ≤ n •ℕ a + k •ℕ a : add_le_add_left (nsmul_nonneg ha _) _
... = m •ℕ a : by rw [← hk, add_nsmul]
lemma nsmul_le_nsmul_of_le_right {a b : A} (hab : a ≤ b) : ∀ i : ℕ, i •ℕ a ≤ i •ℕ b
| 0 := by simp
| (k+1) := add_le_add hab (nsmul_le_nsmul_of_le_right _)
end add_monoid
namespace canonically_ordered_semiring
variable [canonically_ordered_comm_semiring R]
theorem pow_pos {a : R} (H : 0 < a) : ∀ n : ℕ, 0 < a ^ n
| 0 := canonically_ordered_semiring.zero_lt_one
| (n+1) := canonically_ordered_semiring.mul_pos.2 ⟨H, pow_pos n⟩
lemma pow_le_pow_of_le_left {a b : R} (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i
| 0 := by simp
| (k+1) := canonically_ordered_semiring.mul_le_mul hab (pow_le_pow_of_le_left k)
theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n :=
by simpa only [one_pow] using pow_le_pow_of_le_left H n
theorem pow_le_one {a : R} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1:=
by simpa only [one_pow] using pow_le_pow_of_le_left H n
end canonically_ordered_semiring
section linear_ordered_semiring
variable [linear_ordered_semiring R]
theorem pow_pos {a : R} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n
| 0 := zero_lt_one
| (n+1) := mul_pos H (pow_pos _)
theorem pow_nonneg {a : R} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n
| 0 := zero_le_one
| (n+1) := mul_nonneg H (pow_nonneg _)
theorem pow_lt_pow_of_lt_left {x y : R} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) :
x ^ n < y ^ n :=
begin
cases lt_or_eq_of_le Hxpos,
{ rw ←nat.sub_add_cancel Hnpos,
induction (n - 1), { simpa only [pow_one] },
rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one],
apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) },
{ rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),}
end
theorem pow_left_inj {x y : R} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n)
(Hxyn : x ^ n = y ^ n) : x = y :=
begin
rcases lt_trichotomy x y with hxy | rfl | hyx,
{ exact absurd Hxyn (ne_of_lt (pow_lt_pow_of_lt_left hxy Hxpos Hnpos)) },
{ refl },
{ exact absurd Hxyn (ne_of_gt (pow_lt_pow_of_lt_left hyx Hypos Hnpos)) },
end
theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n
| 0 := le_refl _
| (n+1) := by simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n)
zero_le_one (le_trans zero_le_one H)
/-- Bernoulli's inequality. This version works for semirings but requires
an additional hypothesis `0 ≤ a * a`. -/
theorem one_add_mul_le_pow' {a : R} (Hsqr : 0 ≤ a * a) (H : 0 ≤ 1 + a) :
∀ (n : ℕ), 1 + n •ℕ a ≤ (1 + a) ^ n
| 0 := le_of_eq $ add_zero _
| (n+1) :=
calc 1 + (n + 1) •ℕ a ≤ (1 + a) * (1 + n •ℕ a) :
by simpa [succ_nsmul, mul_add, add_mul, mul_nsmul_left, add_comm, add_left_comm]
using nsmul_nonneg Hsqr n
... ≤ (1 + a)^(n+1) : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) H
theorem pow_le_pow {a : R} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m :=
let ⟨k, hk⟩ := nat.le.dest h in
calc a ^ n = a ^ n * 1 : (mul_one _).symm
... ≤ a ^ n * a ^ k : mul_le_mul_of_nonneg_left
(one_le_pow_of_one_le ha _)
(pow_nonneg (le_trans zero_le_one ha) _)
... = a ^ m : by rw [←hk, pow_add]
lemma pow_lt_pow {a : R} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m :=
begin
have h' : 1 ≤ a := le_of_lt h,
have h'' : 0 < a := lt_trans zero_lt_one h,
cases m, cases h2, rw [pow_succ, ←one_mul (a ^ n)],
exact mul_lt_mul h (pow_le_pow h' (nat.le_of_lt_succ h2)) (pow_pos h'' _) (le_of_lt h'')
end
lemma pow_le_pow_of_le_left {a b : R} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i
| 0 := by simp
| (k+1) := mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab)
lemma lt_of_pow_lt_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b :=
lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h
private lemma pow_lt_pow_of_lt_one_aux {a : R} (h : 0 < a) (ha : a < 1) (i : ℕ) :
∀ k : ℕ, a ^ (i + k + 1) < a ^ i
| 0 :=
begin
simp only [add_zero],
rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one
end
| (k+1) :=
begin
rw ←one_mul (a^i),
apply mul_lt_mul ha _ _ zero_le_one,
{ apply le_of_lt, apply pow_lt_pow_of_lt_one_aux },
{ show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h }
end
private lemma pow_le_pow_of_le_one_aux {a : R} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) :
∀ k : ℕ, a ^ (i + k) ≤ a ^ i
| 0 := by simp
| (k+1) := by rw [←add_assoc, ←one_mul (a^i)];
exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one
lemma pow_lt_pow_of_lt_one {a : R} (h : 0 < a) (ha : a < 1)
{i j : ℕ} (hij : i < j) : a ^ j < a ^ i :=
let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in
by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _
lemma pow_le_pow_of_le_one {a : R} (h : 0 ≤ a) (ha : a ≤ 1)
{i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i :=
let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in
by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _
lemma pow_le_one {x : R} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1
| 0 h0 h1 := le_refl (1 : R)
| (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1)
end linear_ordered_semiring
theorem pow_two_nonneg [linear_ordered_ring R] (a : R) : 0 ≤ a ^ 2 :=
by { rw pow_two, exact mul_self_nonneg _ }
theorem pow_two_pos_of_ne_zero [linear_ordered_ring R] (a : R) (h : a ≠ 0) : 0 < a ^ 2 :=
lt_of_le_of_ne (pow_two_nonneg a) (pow_ne_zero 2 h).symm
/-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/
theorem one_add_mul_le_pow [linear_ordered_ring R] {a : R} (H : -2 ≤ a) :
∀ (n : ℕ), 1 + n •ℕ a ≤ (1 + a) ^ n
| 0 := le_of_eq $ add_zero _
| 1 := by simp
| (n+2) :=
have H' : 0 ≤ 2 + a,
from neg_le_iff_add_nonneg.1 H,
have 0 ≤ n •ℕ (a * a * (2 + a)) + a * a,
from add_nonneg (nsmul_nonneg (mul_nonneg (mul_self_nonneg a) H') n)
(mul_self_nonneg a),
calc 1 + (n + 2) •ℕ a ≤ 1 + (n + 2) •ℕ a + (n •ℕ (a * a * (2 + a)) + a * a) :
(le_add_iff_nonneg_right _).2 this
... = (1 + a) * (1 + a) * (1 + n •ℕ a) :
by { simp only [add_mul, mul_add, mul_two, mul_one, one_mul, succ_nsmul, nsmul_add,
mul_nsmul_assoc, (mul_nsmul_left _ _ _).symm],
ac_refl }
... ≤ (1 + a) * (1 + a) * (1 + a)^n :
mul_le_mul_of_nonneg_left (one_add_mul_le_pow n) (mul_self_nonneg (1 + a))
... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc]
/-- Bernoulli's inequality reformulated to estimate `a^n`. -/
theorem one_add_sub_mul_le_pow [linear_ordered_ring R]
{a : R} (H : -1 ≤ a) (n : ℕ) : 1 + n •ℕ (a - 1) ≤ a ^ n :=
have -2 ≤ a - 1, by { rw [bit0, neg_add], exact sub_le_sub_right H 1 },
by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n
namespace int
lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 :=
(units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl)
lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) :=
by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one]
@[simp] lemma nat_abs_pow_two (x : ℤ) : (x.nat_abs ^ 2 : ℤ) = x ^ 2 :=
by rw [pow_two, int.nat_abs_mul_self', pow_two]
end int
@[simp] lemma neg_square {α} [ring α] (z : α) : (-z)^2 = z^2 :=
by simp [pow, monoid.pow]
lemma of_add_nsmul [add_monoid A] (x : A) (n : ℕ) :
multiplicative.of_add (n •ℕ x) = (multiplicative.of_add x)^n := rfl
lemma of_add_gsmul [add_group A] (x : A) (n : ℤ) :
multiplicative.of_add (n •ℤ x) = (multiplicative.of_add x)^n := rfl
variables (M G A)
/-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image
of `multiplicative.of_add 1`. -/
def powers_hom [monoid M] : M ≃ (multiplicative ℕ →* M) :=
{ to_fun := λ x, ⟨λ n, x ^ n.to_add, pow_zero x, λ m n, pow_add x m n⟩,
inv_fun := λ f, f (multiplicative.of_add 1),
left_inv := pow_one,
right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_pow, ← of_add_nsmul] } }
/-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image
of `multiplicative.of_add 1`. -/
def gpowers_hom [group G] : G ≃ (multiplicative ℤ →* G) :=
{ to_fun := λ x, ⟨λ n, x ^ n.to_add, gpow_zero x, λ m n, gpow_add x m n⟩,
inv_fun := λ f, f (multiplicative.of_add 1),
left_inv := gpow_one,
right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_gpow, ← of_add_gsmul ] } }
/-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/
def multiples_hom [add_monoid A] : A ≃ (ℕ →+ A) :=
{ to_fun := λ x, ⟨λ n, n •ℕ x, zero_nsmul x, λ m n, add_nsmul _ _ _⟩,
inv_fun := λ f, f 1,
left_inv := one_nsmul,
right_inv := λ f, add_monoid_hom.ext_nat $ one_nsmul (f 1) }
/-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/
def gmultiples_hom [add_group A] : A ≃ (ℤ →+ A) :=
{ to_fun := λ x, ⟨λ n, n •ℤ x, zero_gsmul x, λ m n, add_gsmul _ _ _⟩,
inv_fun := λ f, f 1,
left_inv := one_gsmul,
right_inv := λ f, add_monoid_hom.ext_int $ one_gsmul (f 1) }
variables {M G A}
@[simp] lemma powers_hom_apply [monoid M] (x : M) (n : multiplicative ℕ) :
powers_hom M x n = x ^ n.to_add := rfl
@[simp] lemma powers_hom_symm_apply [monoid M] (f : multiplicative ℕ →* M) :
(powers_hom M).symm f = f (multiplicative.of_add 1) := rfl
lemma mnat_monoid_hom_eq [monoid M] (f : multiplicative ℕ →* M) (n : multiplicative ℕ) :
f n = (f (multiplicative.of_add 1)) ^ n.to_add :=
by rw [← powers_hom_symm_apply, ← powers_hom_apply, equiv.apply_symm_apply]
lemma mnat_monoid_hom_ext [monoid M] ⦃f g : multiplicative ℕ →* M⦄
(h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g :=
monoid_hom.ext $ λ n, by rw [mnat_monoid_hom_eq f, mnat_monoid_hom_eq g, h]
/-!
### Commutativity (again)
Facts about `semiconj_by` and `commute` that require `gpow` or `gsmul`, or the fact that integer
multiplication equals semiring multiplication.
-/
namespace semiconj_by
section
variables [semiring R] {a x y : R}
@[simp] lemma cast_nat_mul_right (h : semiconj_by a x y) (n : ℕ) : semiconj_by a ((n : R) * x) (n * y) :=
semiconj_by.mul_right (nat.commute_cast _ _) h
@[simp] lemma cast_nat_mul_left (h : semiconj_by a x y) (n : ℕ) : semiconj_by ((n : R) * a) x y :=
semiconj_by.mul_left (nat.cast_commute _ _) h
@[simp] lemma cast_nat_mul_cast_nat_mul (h : semiconj_by a x y) (m n : ℕ) :
semiconj_by ((m : R) * a) (n * x) (n * y) :=
(h.cast_nat_mul_left m).cast_nat_mul_right n
end
variables [monoid M] [group G] [ring R]
@[simp] lemma units_gpow_right {a : M} {x y : units M} (h : semiconj_by a x y) :
∀ m : ℤ, semiconj_by a (↑(x^m)) (↑(y^m))
| (n : ℕ) := by simp only [gpow_coe_nat, units.coe_pow, h, pow_right]
| -[1+n] := by simp only [gpow_neg_succ_of_nat, units.coe_pow, units_inv_right, h, pow_right]
@[simp] lemma gpow_right {a x y : G} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (x^m) (y^m)
| (n : ℕ) := h.pow_right n
| -[1+n] := (h.pow_right n.succ).inv_right
variables {a b x y x' y' : R}
@[simp] lemma cast_int_mul_right (h : semiconj_by a x y) (m : ℤ) :
semiconj_by a ((m : ℤ) * x) (m * y) :=
semiconj_by.mul_right (int.commute_cast _ _) h
@[simp] lemma cast_int_mul_left (h : semiconj_by a x y) (m : ℤ) : semiconj_by ((m : R) * a) x y :=
semiconj_by.mul_left (int.cast_commute _ _) h
@[simp] lemma cast_int_mul_cast_int_mul (h : semiconj_by a x y) (m n : ℤ) :
semiconj_by ((m : R) * a) (n * x) (n * y) :=
(h.cast_int_mul_left m).cast_int_mul_right n
end semiconj_by
namespace commute
section
variables [semiring R] {a b : R}
@[simp] theorem cast_nat_mul_right (h : commute a b) (n : ℕ) : commute a ((n : R) * b) :=
h.cast_nat_mul_right n
@[simp] theorem cast_nat_mul_left (h : commute a b) (n : ℕ) : commute ((n : R) * a) b :=
h.cast_nat_mul_left n
@[simp] theorem cast_nat_mul_cast_nat_mul (h : commute a b) (m n : ℕ) :
commute ((m : R) * a) (n * b) :=
h.cast_nat_mul_cast_nat_mul m n
@[simp] theorem self_cast_nat_mul (n : ℕ) : commute a (n * a) :=
(commute.refl a).cast_nat_mul_right n
@[simp] theorem cast_nat_mul_self (n : ℕ) : commute ((n : R) * a) a :=
(commute.refl a).cast_nat_mul_left n
@[simp] theorem self_cast_nat_mul_cast_nat_mul (m n : ℕ) : commute ((m : R) * a) (n * a) :=
(commute.refl a).cast_nat_mul_cast_nat_mul m n
end
variables [monoid M] [group G] [ring R]
@[simp] lemma units_gpow_right {a : M} {u : units M} (h : commute a u) (m : ℤ) :
commute a (↑(u^m)) :=
h.units_gpow_right m
@[simp] lemma units_gpow_left {u : units M} {a : M} (h : commute ↑u a) (m : ℤ) :
commute (↑(u^m)) a :=
(h.symm.units_gpow_right m).symm
section
variables {a b : G}
@[simp] lemma gpow_right (h : commute a b) (m : ℤ) : commute a (b^m) :=
h.gpow_right m
@[simp] lemma gpow_left (h : commute a b) (m : ℤ) : commute (a^m) b :=
(h.symm.gpow_right m).symm
lemma gpow_gpow (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) := (h.gpow_left m).gpow_right n
variables (a) (m n : ℕ)
@[simp] theorem self_gpow : commute a (a ^ n) := (commute.refl a).gpow_right n
@[simp] theorem gpow_self : commute (a ^ n) a := (commute.refl a).gpow_left n
@[simp] theorem gpow_gpow_self : commute (a ^ m) (a ^ n) := (commute.refl a).gpow_gpow m n
end
variables {a b : R}
@[simp] lemma cast_int_mul_right (h : commute a b) (m : ℤ) : commute a (m * b) :=
h.cast_int_mul_right m
@[simp] lemma cast_int_mul_left (h : commute a b) (m : ℤ) : commute ((m : R) * a) b :=
h.cast_int_mul_left m
lemma cast_int_mul_cast_int_mul (h : commute a b) (m n : ℤ) : commute ((m : R) * a) (n * b) :=
h.cast_int_mul_cast_int_mul m n
variables (a) (m n : ℤ)
@[simp] theorem self_cast_int_mul : commute a (n * a) := (commute.refl a).cast_int_mul_right n
@[simp] theorem cast_int_mul_self : commute ((n : R) * a) a := (commute.refl a).cast_int_mul_left n
theorem self_cast_int_mul_cast_int_mul : commute ((m : R) * a) (n * a) :=
(commute.refl a).cast_int_mul_cast_int_mul m n
end commute
namespace units
variables [monoid M]
lemma conj_pow (u : units M) (x : M) (n : ℕ) : (↑u * x * ↑(u⁻¹))^n = u * x^n * ↑(u⁻¹) :=
(divp_eq_iff_mul_eq.2 ((u.mk_semiconj_by x).pow_right n).eq.symm).symm
lemma conj_pow' (u : units M) (x : M) (n : ℕ) : (↑(u⁻¹) * x * u)^n = ↑(u⁻¹) * x^n * u:=
(u⁻¹).conj_pow x n
open opposite
/-- Moving to the opposite monoid commutes with taking powers. -/
@[simp] lemma op_pow (x : M) (n : ℕ) : op (x ^ n) = (op x) ^ n :=
begin
induction n with n h,
{ simp },
{ rw [pow_succ', op_mul, h, pow_succ] }
end
@[simp] lemma unop_pow (x : Mᵒᵖ) (n : ℕ) : unop (x ^ n) = (unop x) ^ n :=
begin
induction n with n h,
{ simp },
{ rw [pow_succ', unop_mul, h, pow_succ] }
end
end units
|
cdb0f0e56bee803c642f04b4494bf600932a55d8 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/ring_theory/henselian.lean | 38d366b1512370bb22e7fd1f0c3ebd9b2c381055 | [
"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 | 11,759 | lean | /-
Copyright (c) 2021 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import data.polynomial.taylor
import ring_theory.ideal.local_ring
import linear_algebra.adic_completion
/-!
# Henselian rings
In this file we set up the basic theory of Henselian (local) rings.
A ring `R` is *Henselian* at an ideal `I` if the following conditions hold:
* `I` is contained in the Jacobson radical of `R`
* for every polynomial `f` over `R`, with a *simple* root `a₀` over the quotient ring `R/I`,
there exists a lift `a : R` of `a₀` that is a root of `f`.
(Here, saying that a root `b` of a polynomial `g` is *simple* means that `g.derivative.eval b` is a
unit. Warning: if `R/I` is not a field then it is not enough to assume that `g` has a factorization
into monic linear factors in which `X - b` shows up only once; for example `1` is not a simple root
of `X^2-1` over `ℤ/4ℤ`.)
A local ring `R` is *Henselian* if it is Henselian at its maximal ideal.
In this case the first condition is automatic, and in the second condition we may ask for
`f.derivative.eval a ≠ 0`, since the quotient ring `R/I` is a field in this case.
## Main declarations
* `henselian_ring`: a typeclass on commutative rings,
asserting that the ring is Henselian at the ideal `I`.
* `henselian_local_ring`: a typeclass on commutative rings,
asserting that the ring is local Henselian.
* `field.henselian`: fields are Henselian local rings
* `henselian.tfae`: equivalent ways of expressing the Henselian property for local rings
* `is_adic_complete.henselian`:
a ring `R` with ideal `I` that is `I`-adically complete is Henselian at `I`
## References
https://stacks.math.columbia.edu/tag/04GE
## Todo
After a good API for etale ring homomorphisms has been developed,
we can give more equivalent characterization os Henselian rings.
In particular, this can give a proof that factorizations into coprime polynomials can be lifted
from the residue field to the Henselian ring.
The following gist contains some code sketches in that direction.
https://gist.github.com/jcommelin/47d94e4af092641017a97f7f02bf9598
-/
noncomputable theory
universes u v
open_locale big_operators polynomial
open local_ring polynomial function
lemma is_local_ring_hom_of_le_jacobson_bot {R : Type*} [comm_ring R]
(I : ideal R) (h : I ≤ ideal.jacobson ⊥) :
is_local_ring_hom (ideal.quotient.mk I) :=
begin
constructor,
intros a h,
have : is_unit (ideal.quotient.mk (ideal.jacobson ⊥) a),
{ rw [is_unit_iff_exists_inv] at *,
obtain ⟨b, hb⟩ := h,
obtain ⟨b, rfl⟩ := ideal.quotient.mk_surjective b,
use ideal.quotient.mk _ b,
rw [←(ideal.quotient.mk _).map_one, ←(ideal.quotient.mk _).map_mul, ideal.quotient.eq] at ⊢ hb,
exact h hb },
obtain ⟨⟨x, y, h1, h2⟩, rfl : x = _⟩ := this,
obtain ⟨y, rfl⟩ := ideal.quotient.mk_surjective y,
rw [← (ideal.quotient.mk _).map_mul, ← (ideal.quotient.mk _).map_one, ideal.quotient.eq,
ideal.mem_jacobson_bot] at h1 h2,
specialize h1 1,
simp at h1,
exact h1.1,
end
/-- A ring `R` is *Henselian* at an ideal `I` if the following condition holds:
for every polynomial `f` over `R`, with a *simple* root `a₀` over the quotient ring `R/I`,
there exists a lift `a : R` of `a₀` that is a root of `f`.
(Here, saying that a root `b` of a polynomial `g` is *simple* means that `g.derivative.eval b` is a
unit. Warning: if `R/I` is not a field then it is not enough to assume that `g` has a factorization
into monic linear factors in which `X - b` shows up only once; for example `1` is not a simple root
of `X^2-1` over `ℤ/4ℤ`.) -/
class henselian_ring (R : Type*) [comm_ring R] (I : ideal R) : Prop :=
(jac : I ≤ ideal.jacobson ⊥)
(is_henselian : ∀ (f : R[X]) (hf : f.monic) (a₀ : R) (h₁ : f.eval a₀ ∈ I)
(h₂ : is_unit (ideal.quotient.mk I (f.derivative.eval a₀))),
∃ a : R, f.is_root a ∧ (a - a₀ ∈ I))
/-- A local ring `R` is *Henselian* if the following condition holds:
for every polynomial `f` over `R`, with a *simple* root `a₀` over the residue field,
there exists a lift `a : R` of `a₀` that is a root of `f`.
(Recall that a root `b` of a polynomial `g` is *simple* if it is not a double root, so if
`g.derivative.eval b ≠ 0`.)
In other words, `R` is local Henselian if it is Henselian at the ideal `I`,
in the sense of `henselian_ring`. -/
class henselian_local_ring (R : Type*) [comm_ring R] extends local_ring R : Prop :=
(is_henselian : ∀ (f : R[X]) (hf : f.monic) (a₀ : R) (h₁ : f.eval a₀ ∈ maximal_ideal R)
(h₂ : is_unit (f.derivative.eval a₀)),
∃ a : R, f.is_root a ∧ (a - a₀ ∈ maximal_ideal R))
@[priority 100] -- see Note [lower instance priority]
instance field.henselian (K : Type*) [field K] : henselian_local_ring K :=
{ is_henselian := λ f hf a₀ h₁ h₂,
begin
refine ⟨a₀, _, _⟩;
rwa [(maximal_ideal K).eq_bot_of_prime, ideal.mem_bot] at *,
rw sub_self,
end }
lemma henselian_local_ring.tfae (R : Type u) [comm_ring R] [local_ring R] :
tfae [
henselian_local_ring R,
∀ (f : R[X]) (hf : f.monic) (a₀ : residue_field R) (h₁ : aeval a₀ f = 0)
(h₂ : aeval a₀ f.derivative ≠ 0),
∃ a : R, f.is_root a ∧ (residue R a = a₀),
∀ {K : Type u} [field K], by exactI ∀ (φ : R →+* K) (hφ : surjective φ)
(f : R[X]) (hf : f.monic) (a₀ : K) (h₁ : f.eval₂ φ a₀ = 0)
(h₂ : f.derivative.eval₂ φ a₀ ≠ 0),
∃ a : R, f.is_root a ∧ (φ a = a₀)] :=
begin
tfae_have _3_2 : 3 → 2, { intro H, exact H (residue R) ideal.quotient.mk_surjective, },
tfae_have _2_1 : 2 → 1,
{ intros H, constructor, intros f hf a₀ h₁ h₂,
specialize H f hf (residue R a₀),
have aux := flip mem_nonunits_iff.mp h₂,
simp only [aeval_def, ring_hom.algebra_map_to_algebra, eval₂_at_apply,
← ideal.quotient.eq_zero_iff_mem, ← local_ring.mem_maximal_ideal] at H h₁ aux,
obtain ⟨a, ha₁, ha₂⟩ := H h₁ aux,
refine ⟨a, ha₁, _⟩,
rw ← ideal.quotient.eq_zero_iff_mem,
rwa [← sub_eq_zero, ← ring_hom.map_sub] at ha₂, },
tfae_have _1_3 : 1 → 3,
{ introsI hR K _K φ hφ f hf a₀ h₁ h₂,
obtain ⟨a₀, rfl⟩ := hφ a₀,
have H := henselian_local_ring.is_henselian f hf a₀,
simp only [← ker_eq_maximal_ideal φ hφ, eval₂_at_apply, φ.mem_ker] at H h₁ h₂,
obtain ⟨a, ha₁, ha₂⟩ := H h₁ _,
{ refine ⟨a, ha₁, _⟩, rwa [φ.map_sub, sub_eq_zero] at ha₂, },
{ contrapose! h₂,
rwa [← mem_nonunits_iff, ← local_ring.mem_maximal_ideal,
← local_ring.ker_eq_maximal_ideal φ hφ, φ.mem_ker] at h₂, } },
tfae_finish,
end
instance (R : Type*) [comm_ring R] [hR : henselian_local_ring R] :
henselian_ring R (maximal_ideal R) :=
{ jac := by { rw [ideal.jacobson, le_Inf_iff], rintro I ⟨-, hI⟩, exact (eq_maximal_ideal hI).ge },
is_henselian :=
begin
intros f hf a₀ h₁ h₂,
refine henselian_local_ring.is_henselian f hf a₀ h₁ _,
contrapose! h₂,
rw [← mem_nonunits_iff, ← local_ring.mem_maximal_ideal, ← ideal.quotient.eq_zero_iff_mem] at h₂,
rw h₂,
exact not_is_unit_zero
end }
/-- A ring `R` that is `I`-adically complete is Henselian at `I`. -/
@[priority 100] -- see Note [lower instance priority]
instance is_adic_complete.henselian_ring
(R : Type*) [comm_ring R] (I : ideal R) [is_adic_complete I R] :
henselian_ring R I :=
{ jac := is_adic_complete.le_jacobson_bot _,
is_henselian :=
begin
intros f hf a₀ h₁ h₂,
classical,
let f' := f.derivative,
-- we define a sequence `c n` by starting at `a₀` and then continually
-- applying the function sending `b` to `b - f(b)/f'(b)` (Newton's method).
-- Note that `f'.eval b` is a unit, because `b` has the same residue as `a₀` modulo `I`.
let c : ℕ → R := λ n, nat.rec_on n a₀ (λ _ b, b - f.eval b * ring.inverse (f'.eval b)),
have hc : ∀ n, c (n+1) = c n - f.eval (c n) * ring.inverse (f'.eval (c n)),
{ intro n, dsimp only [c, nat.rec_add_one], refl, },
-- we now spend some time determining properties of the sequence `c : ℕ → R`
-- `hc_mod`: for every `n`, we have `c n ≡ a₀ [SMOD I]`
-- `hf'c` : for every `n`, `f'.eval (c n)` is a unit
-- `hfcI` : for every `n`, `f.eval (c n)` is contained in `I ^ (n+1)`
have hc_mod : ∀ n, c n ≡ a₀ [SMOD I],
{ intro n, induction n with n ih, { refl },
rw [nat.succ_eq_add_one, hc, sub_eq_add_neg, ← add_zero a₀],
refine ih.add _,
rw [smodeq.zero, ideal.neg_mem_iff],
refine I.mul_mem_right _ _,
rw [← smodeq.zero] at h₁ ⊢,
exact (ih.eval f).trans h₁, },
have hf'c : ∀ n, is_unit (f'.eval (c n)),
{ intro n,
haveI := is_local_ring_hom_of_le_jacobson_bot I (is_adic_complete.le_jacobson_bot I),
apply is_unit_of_map_unit (ideal.quotient.mk I),
convert h₂ using 1,
exact smodeq.def.mp ((hc_mod n).eval _), },
have hfcI : ∀ n, f.eval (c n) ∈ I ^ (n+1),
{ intro n,
induction n with n ih, { simpa only [pow_one] },
simp only [nat.succ_eq_add_one],
rw [← taylor_eval_sub (c n), hc],
simp only [sub_eq_add_neg, add_neg_cancel_comm],
rw [eval_eq_sum, sum_over_range' _ _ _ (lt_add_of_pos_right _ zero_lt_two),
← finset.sum_range_add_sum_Ico _ (nat.le_add_left _ _)],
swap, { intro i, rw zero_mul },
refine ideal.add_mem _ _ _,
{ simp only [finset.sum_range_succ, taylor_coeff_one, mul_one, pow_one, taylor_coeff_zero,
mul_neg, finset.sum_singleton, finset.range_one, pow_zero],
rw [mul_left_comm, ring.mul_inverse_cancel _ (hf'c n), mul_one, add_neg_self],
exact ideal.zero_mem _ },
{ refine submodule.sum_mem _ _, simp only [finset.mem_Ico],
rintro i ⟨h2i, hi⟩,
have aux : n + 2 ≤ i * (n + 1), { transitivity 2 * (n + 1); nlinarith only [h2i], },
refine ideal.mul_mem_left _ _ (ideal.pow_le_pow aux _),
rw [pow_mul'],
refine ideal.pow_mem_pow ((ideal.neg_mem_iff _).2 $ ideal.mul_mem_right _ _ ih) _, } },
-- we are now in the position to show that `c : ℕ → R` is a Cauchy sequence
have aux : ∀ m n, m ≤ n → c m ≡ c n [SMOD (I ^ m • ⊤ : ideal R)],
{ intros m n hmn,
rw [← ideal.one_eq_top, ideal.smul_eq_mul, mul_one],
obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le hmn, clear hmn,
induction k with k ih, { rw add_zero, },
rw [nat.succ_eq_add_one, ← add_assoc, hc, ← add_zero (c m), sub_eq_add_neg],
refine ih.add _, symmetry,
rw [smodeq.zero, ideal.neg_mem_iff],
refine ideal.mul_mem_right _ _ (ideal.pow_le_pow _ (hfcI _)),
rw [add_assoc], exact le_self_add },
-- hence the sequence converges to some limit point `a`, which is the `a` we are looking for
obtain ⟨a, ha⟩ := is_precomplete.prec' c aux,
refine ⟨a, _, _⟩,
{ show f.is_root a,
suffices : ∀ n, f.eval a ≡ 0 [SMOD (I ^ n • ⊤ : ideal R)], { from is_Hausdorff.haus' _ this },
intro n, specialize ha n,
rw [← ideal.one_eq_top, ideal.smul_eq_mul, mul_one] at ha ⊢,
refine (ha.symm.eval f).trans _,
rw [smodeq.zero],
exact ideal.pow_le_pow le_self_add (hfcI _), },
{ show a - a₀ ∈ I,
specialize ha 1,
rw [hc, pow_one, ← ideal.one_eq_top, ideal.smul_eq_mul, mul_one, sub_eq_add_neg] at ha,
rw [← smodeq.sub_mem, ← add_zero a₀],
refine ha.symm.trans (smodeq.rfl.add _),
rw [smodeq.zero, ideal.neg_mem_iff],
exact ideal.mul_mem_right _ _ h₁, }
end }
|
fb6ecaaf861c5c20c901e58c00074fd3bc74b533 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/limits/constructions/binary_products.lean | 1320170cf887ef945de07ced5cc0eb9d9dd766e0 | [
"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 | 10,066 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Andrew Yang
-/
import category_theory.limits.shapes.terminal
import category_theory.limits.shapes.pullbacks
import category_theory.limits.shapes.binary_products
import category_theory.limits.preserves.shapes.pullbacks
import category_theory.limits.preserves.shapes.terminal
/-!
# Constructing binary product from pullbacks and terminal object.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
The product is the pullback over the terminal objects. In particular, if a category
has pullbacks and a terminal object, then it has binary products.
We also provide the dual.
-/
universes v v' u u'
open category_theory category_theory.category category_theory.limits
variables {C : Type u} [category.{v} C] {D : Type u'} [category.{v'} D] (F : C ⥤ D)
/-- If a span is the pullback span over the terminal object, then it is a binary product. -/
def is_binary_product_of_is_terminal_is_pullback (F : discrete walking_pair ⥤ C) (c : cone F)
{X : C} (hX : is_terminal X)
(f : F.obj ⟨walking_pair.left⟩ ⟶ X) (g : F.obj ⟨walking_pair.right⟩ ⟶ X)
(hc : is_limit (pullback_cone.mk (c.π.app ⟨walking_pair.left⟩) (c.π.app ⟨walking_pair.right⟩ : _)
$ hX.hom_ext (_ ≫ f) (_ ≫ g))) : is_limit c :=
{ lift := λ s, hc.lift
(pullback_cone.mk (s.π.app ⟨walking_pair.left⟩) (s.π.app ⟨walking_pair.right⟩)
(hX.hom_ext _ _)),
fac' := λ s j, discrete.cases_on j
(λ j, walking_pair.cases_on j (hc.fac _ walking_cospan.left) (hc.fac _ walking_cospan.right)),
uniq' := λ s m J,
begin
let c' := pullback_cone.mk
(m ≫ c.π.app ⟨walking_pair.left⟩) (m ≫ c.π.app ⟨walking_pair.right⟩ : _)
(hX.hom_ext (_ ≫ f) (_ ≫ g)),
rw [←J, ←J],
apply hc.hom_ext,
rintro (_|(_|_)); simp only [pullback_cone.mk_π_app_one, pullback_cone.mk_π_app],
exacts [(category.assoc _ _ _).symm.trans (hc.fac_assoc c' walking_cospan.left f).symm,
(hc.fac c' walking_cospan.left).symm, (hc.fac c' walking_cospan.right).symm]
end }
/-- The pullback over the terminal object is the product -/
def is_product_of_is_terminal_is_pullback {W X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (h : W ⟶ X)
(k : W ⟶ Y) (H₁ : is_terminal Z)
(H₂ : is_limit (pullback_cone.mk _ _ (show h ≫ f = k ≫ g, from H₁.hom_ext _ _))) :
is_limit (binary_fan.mk h k) :=
begin
apply is_binary_product_of_is_terminal_is_pullback _ _ H₁,
exact H₂
end
/-- The product is the pullback over the terminal object. -/
def is_pullback_of_is_terminal_is_product {W X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (h : W ⟶ X)
(k : W ⟶ Y) (H₁ : is_terminal Z)
(H₂ : is_limit (binary_fan.mk h k)) :
is_limit (pullback_cone.mk _ _ (show h ≫ f = k ≫ g, from H₁.hom_ext _ _)) :=
begin
apply pullback_cone.is_limit_aux',
intro s,
use H₂.lift (binary_fan.mk s.fst s.snd),
use H₂.fac (binary_fan.mk s.fst s.snd) ⟨walking_pair.left⟩,
use H₂.fac (binary_fan.mk s.fst s.snd) ⟨walking_pair.right⟩,
intros m h₁ h₂,
apply H₂.hom_ext,
rintro ⟨⟨⟩⟩,
{ exact h₁.trans (H₂.fac (binary_fan.mk s.fst s.snd) ⟨walking_pair.left⟩).symm },
{ exact h₂.trans (H₂.fac (binary_fan.mk s.fst s.snd) ⟨walking_pair.right⟩).symm }
end
/-- Any category with pullbacks and a terminal object has a limit cone for each walking pair. -/
noncomputable def limit_cone_of_terminal_and_pullbacks [has_terminal C] [has_pullbacks C]
(F : discrete walking_pair ⥤ C) : limit_cone F :=
{ cone :=
{ X := pullback (terminal.from (F.obj ⟨walking_pair.left⟩))
(terminal.from (F.obj ⟨walking_pair.right⟩)),
π := discrete.nat_trans (λ x, discrete.cases_on x
(λ x, walking_pair.cases_on x pullback.fst pullback.snd)) },
is_limit := is_binary_product_of_is_terminal_is_pullback
F _ terminal_is_terminal _ _ (pullback_is_pullback _ _) }
variable (C)
/-- Any category with pullbacks and terminal object has binary products. -/
-- This is not an instance, as it is not always how one wants to construct binary products!
lemma has_binary_products_of_has_terminal_and_pullbacks
[has_terminal C] [has_pullbacks C] :
has_binary_products C :=
{ has_limit := λ F, has_limit.mk (limit_cone_of_terminal_and_pullbacks F) }
variable {C}
/-- A functor that preserves terminal objects and pullbacks preserves binary products. -/
noncomputable
def preserves_binary_products_of_preserves_terminal_and_pullbacks
[has_terminal C] [has_pullbacks C]
[preserves_limits_of_shape (discrete.{0} pempty) F]
[preserves_limits_of_shape walking_cospan F] :
preserves_limits_of_shape (discrete walking_pair) F :=
⟨λ K, preserves_limit_of_preserves_limit_cone (limit_cone_of_terminal_and_pullbacks K).2
begin
apply is_binary_product_of_is_terminal_is_pullback _ _
(is_limit_of_has_terminal_of_preserves_limit F),
apply is_limit_of_has_pullback_of_preserves_limit,
end⟩
/-- In a category with a terminal object and pullbacks,
a product of objects `X` and `Y` is isomorphic to a pullback. -/
noncomputable
def prod_iso_pullback [has_terminal C] [has_pullbacks C] (X Y : C) [has_binary_product X Y] :
X ⨯ Y ≅ pullback (terminal.from X) (terminal.from Y) :=
limit.iso_limit_cone (limit_cone_of_terminal_and_pullbacks _)
/-- If a cospan is the pushout cospan under the initial object, then it is a binary coproduct. -/
def is_binary_coproduct_of_is_initial_is_pushout (F : discrete walking_pair ⥤ C) (c : cocone F)
{X : C} (hX : is_initial X)
(f : X ⟶ F.obj ⟨walking_pair.left⟩) (g : X ⟶ F.obj ⟨walking_pair.right⟩)
(hc : is_colimit (pushout_cocone.mk (c.ι.app ⟨walking_pair.left⟩)
(c.ι.app ⟨walking_pair.right⟩ : _) $ hX.hom_ext (f ≫ _) (g ≫ _))) : is_colimit c :=
{ desc := λ s, hc.desc
(pushout_cocone.mk (s.ι.app ⟨walking_pair.left⟩) (s.ι.app ⟨walking_pair.right⟩)
(hX.hom_ext _ _)),
fac' := λ s j, discrete.cases_on j
(λ j, walking_pair.cases_on j (hc.fac _ walking_span.left) (hc.fac _ walking_span.right)),
uniq' := λ s m J,
begin
let c' := pushout_cocone.mk
(c.ι.app ⟨walking_pair.left⟩ ≫ m) (c.ι.app ⟨walking_pair.right⟩ ≫ m)
(hX.hom_ext (f ≫ _) (g ≫ _)),
rw [←J, ←J],
apply hc.hom_ext,
rintro (_|(_|_));
simp only [pushout_cocone.mk_ι_app_zero, pushout_cocone.mk_ι_app, category.assoc],
congr' 1,
exacts [(hc.fac c' walking_span.left).symm,
(hc.fac c' walking_span.left).symm, (hc.fac c' walking_span.right).symm]
end }
/-- The pushout under the initial object is the coproduct -/
def is_coproduct_of_is_initial_is_pushout {W X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (h : W ⟶ X)
(k : W ⟶ Y) (H₁ : is_initial W)
(H₂ : is_colimit (pushout_cocone.mk _ _ (show h ≫ f = k ≫ g, from H₁.hom_ext _ _))) :
is_colimit (binary_cofan.mk f g) :=
begin
apply is_binary_coproduct_of_is_initial_is_pushout _ _ H₁,
exact H₂
end
/-- The coproduct is the pushout under the initial object. -/
def is_pushout_of_is_initial_is_coproduct {W X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (h : W ⟶ X)
(k : W ⟶ Y) (H₁ : is_initial W)
(H₂ : is_colimit (binary_cofan.mk f g)) :
is_colimit (pushout_cocone.mk _ _ (show h ≫ f = k ≫ g, from H₁.hom_ext _ _)) :=
begin
apply pushout_cocone.is_colimit_aux',
intro s,
use H₂.desc (binary_cofan.mk s.inl s.inr),
use H₂.fac (binary_cofan.mk s.inl s.inr) ⟨walking_pair.left⟩,
use H₂.fac (binary_cofan.mk s.inl s.inr) ⟨walking_pair.right⟩,
intros m h₁ h₂,
apply H₂.hom_ext,
rintro ⟨⟨⟩⟩,
{ exact h₁.trans (H₂.fac (binary_cofan.mk s.inl s.inr) ⟨walking_pair.left⟩).symm },
{ exact h₂.trans (H₂.fac (binary_cofan.mk s.inl s.inr) ⟨walking_pair.right⟩).symm }
end
/-- Any category with pushouts and an initial object has a colimit cocone for each walking pair. -/
noncomputable def colimit_cocone_of_initial_and_pushouts [has_initial C] [has_pushouts C]
(F : discrete walking_pair ⥤ C) : colimit_cocone F :=
{ cocone :=
{ X := pushout (initial.to (F.obj ⟨walking_pair.left⟩))
(initial.to (F.obj ⟨walking_pair.right⟩)),
ι := discrete.nat_trans (λ x, discrete.cases_on x
(λ x, walking_pair.cases_on x pushout.inl pushout.inr)) },
is_colimit := is_binary_coproduct_of_is_initial_is_pushout
F _ initial_is_initial _ _ (pushout_is_pushout _ _) }
variable (C)
/-- Any category with pushouts and initial object has binary coproducts. -/
-- This is not an instance, as it is not always how one wants to construct binary coproducts!
lemma has_binary_coproducts_of_has_initial_and_pushouts
[has_initial C] [has_pushouts C] :
has_binary_coproducts C :=
{ has_colimit := λ F, has_colimit.mk (colimit_cocone_of_initial_and_pushouts F) }
variable {C}
/-- A functor that preserves initial objects and pushouts preserves binary coproducts. -/
noncomputable
def preserves_binary_coproducts_of_preserves_initial_and_pushouts
[has_initial C] [has_pushouts C]
[preserves_colimits_of_shape (discrete.{0} pempty) F]
[preserves_colimits_of_shape walking_span F] :
preserves_colimits_of_shape (discrete walking_pair) F :=
⟨λ K, preserves_colimit_of_preserves_colimit_cocone (colimit_cocone_of_initial_and_pushouts K).2
begin
apply is_binary_coproduct_of_is_initial_is_pushout _ _
(is_colimit_of_has_initial_of_preserves_colimit F),
apply is_colimit_of_has_pushout_of_preserves_colimit,
end⟩
/-- In a category with an initial object and pushouts,
a coproduct of objects `X` and `Y` is isomorphic to a pushout. -/
noncomputable
def coprod_iso_pushout [has_initial C] [has_pushouts C] (X Y : C) [has_binary_coproduct X Y] :
X ⨿ Y ≅ pushout (initial.to X) (initial.to Y) :=
colimit.iso_colimit_cocone (colimit_cocone_of_initial_and_pushouts _)
|
6dbc710108cf1dedece918aa5856974bb760f5a6 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/partialVariable.lean | b7f77fface5d41454c7099cbf97b9f907d84d359 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 11 | lean | variable :
|
d29743aa51579099912d4562ce34182f7f2c2d9f | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/set_theory/ordinal_notation.lean | d157cdd795915dafe0c8427acc4fc0e9327fb9db | [
"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 | 35,924 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import set_theory.ordinal_arithmetic
/-!
# Ordinal notations
constructive ordinal arithmetic for ordinals `< ε₀`.
-/
open ordinal
open_locale ordinal -- get notation for `ω`
/-- Recursive definition of an ordinal notation. `zero` denotes the
ordinal 0, and `oadd e n a` is intended to refer to `ω^e * n + a`.
For this to be valid Cantor normal form, we must have the exponents
decrease to the right, but we can't state this condition until we've
defined `repr`, so it is a separate definition `NF`. -/
@[derive decidable_eq]
inductive onote : Type
| zero : onote
| oadd : onote → ℕ+ → onote → onote
namespace onote
/-- Notation for 0 -/
instance : has_zero onote := ⟨zero⟩
@[simp] theorem zero_def : zero = 0 := rfl
instance : inhabited onote := ⟨0⟩
/-- Notation for 1 -/
instance : has_one onote := ⟨oadd 0 1 0⟩
/-- Notation for ω -/
def omega : onote := oadd 1 1 0
/-- The ordinal denoted by a notation -/
@[simp] noncomputable def repr : onote → ordinal.{0}
| 0 := 0
| (oadd e n a) := ω ^ repr e * n + repr a
/-- Auxiliary definition to print an ordinal notation -/
def to_string_aux1 (e : onote) (n : ℕ) (s : string) : string :=
if e = 0 then _root_.to_string n else
(if e = 1 then "ω" else "ω^(" ++ s ++ ")") ++
if n = 1 then "" else "*" ++ _root_.to_string n
/-- Print an ordinal notation -/
def to_string : onote → string
| zero := "0"
| (oadd e n 0) := to_string_aux1 e n (to_string e)
| (oadd e n a) := to_string_aux1 e n (to_string e) ++ " + " ++ to_string a
/-- Print an ordinal notation -/
def repr' : onote → string
| zero := "0"
| (oadd e n a) := "(oadd " ++ repr' e ++ " " ++ _root_.to_string (n:ℕ) ++ " " ++ repr' a ++ ")"
instance : has_to_string onote := ⟨to_string⟩
instance : has_repr onote := ⟨repr'⟩
instance : preorder onote :=
{ le := λ x y, repr x ≤ repr y,
lt := λ x y, repr x < repr y,
le_refl := λ a, @le_refl ordinal _ _,
le_trans := λ a b c, @le_trans ordinal _ _ _ _,
lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ordinal _ _ _ }
theorem lt_def {x y : onote} : x < y ↔ repr x < repr y := iff.rfl
theorem le_def {x y : onote} : x ≤ y ↔ repr x ≤ repr y := iff.rfl
/-- Convert a `nat` into an ordinal -/
@[simp] def of_nat : ℕ → onote
| 0 := 0
| (nat.succ n) := oadd 0 n.succ_pnat 0
@[simp] theorem of_nat_one : of_nat 1 = 1 := rfl
@[simp] theorem repr_of_nat (n : ℕ) : repr (of_nat n) = n :=
by cases n; simp
@[simp] theorem repr_one : repr 1 = 1 :=
by simpa using repr_of_nat 1
theorem omega_le_oadd (e n a) : ω ^ repr e ≤ repr (oadd e n a) :=
begin
unfold repr,
refine le_trans _ (le_add_right _ _),
simpa using (mul_le_mul_iff_left $ power_pos (repr e) omega_pos).2 (nat_cast_le.2 n.2)
end
theorem oadd_pos (e n a) : 0 < oadd e n a :=
@lt_of_lt_of_le _ _ _ _ _ (power_pos _ omega_pos)
(omega_le_oadd _ _ _)
/-- Compare ordinal notations -/
def cmp : onote → onote → ordering
| 0 0 := ordering.eq
| _ 0 := ordering.gt
| 0 _ := ordering.lt
| o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) :=
(cmp e₁ e₂).or_else $ (_root_.cmp (n₁:ℕ) n₂).or_else (cmp a₁ a₂)
theorem eq_of_cmp_eq : ∀ {o₁ o₂}, cmp o₁ o₂ = ordering.eq → o₁ = o₂
| 0 0 h := rfl
| (oadd e n a) 0 h := by injection h
| 0 (oadd e n a) h := by injection h
| o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) h := begin
revert h, simp [cmp],
cases h₁ : cmp e₁ e₂; intro h; try {cases h},
have := eq_of_cmp_eq h₁, subst e₂,
revert h, cases h₂ : _root_.cmp (n₁:ℕ) n₂; intro h; try {cases h},
have := eq_of_cmp_eq h, subst a₂,
rw [_root_.cmp, cmp_using_eq_eq] at h₂,
have := subtype.eq (eq_of_incomp h₂), subst n₂, simp
end
theorem zero_lt_one : (0 : onote) < 1 :=
by rw [lt_def, repr, repr_one]; exact zero_lt_one
/-- `NF_below o b` says that `o` is a normal form ordinal notation
satisfying `repr o < ω ^ b`. -/
inductive NF_below : onote → ordinal.{0} → Prop
| zero {b} : NF_below 0 b
| oadd' {e n a eb b} : NF_below e eb →
NF_below a (repr e) → repr e < b → NF_below (oadd e n a) b
/-- A normal form ordinal notation has the form
ω ^ a₁ * n₁ + ω ^ a₂ * n₂ + ... ω ^ aₖ * nₖ
where `a₁ > a₂ > ... > aₖ` and all the `aᵢ` are
also in normal form.
We will essentially only be interested in normal form
ordinal notations, but to avoid complicating the algorithms
we define everything over general ordinal notations and
only prove correctness with normal form as an invariant. -/
@[class, pp_nodot] def NF (o : onote) := Exists (NF_below o)
instance NF.zero : NF 0 := ⟨0, NF_below.zero⟩
theorem NF_below.oadd {e n a b} : NF e →
NF_below a (repr e) → repr e < b → NF_below (oadd e n a) b
| ⟨eb, h⟩ := NF_below.oadd' h
theorem NF_below.fst {e n a b} (h : NF_below (oadd e n a) b) : NF e :=
by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact ⟨_, h₁⟩
theorem NF.fst {e n a} : NF (oadd e n a) → NF e
| ⟨b, h⟩ := h.fst
theorem NF_below.snd {e n a b} (h : NF_below (oadd e n a) b) : NF_below a (repr e) :=
by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact h₂
theorem NF.snd' {e n a} : NF (oadd e n a) → NF_below a (repr e)
| ⟨b, h⟩ := h.snd
theorem NF.snd {e n a} (h : NF (oadd e n a)) : NF a :=
⟨_, h.snd'⟩
theorem NF.oadd {e a} (h₁ : NF e) (n)
(h₂ : NF_below a (repr e)) : NF (oadd e n a) :=
⟨_, NF_below.oadd h₁ h₂ (ordinal.lt_succ_self _)⟩
instance NF.oadd_zero (e n) [h : NF e] : NF (oadd e n 0) :=
h.oadd _ NF_below.zero
theorem NF_below.lt {e n a b} (h : NF_below (oadd e n a) b) : repr e < b :=
by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact h₃
theorem NF_below_zero : ∀ {o}, NF_below o 0 ↔ o = 0
| 0 := ⟨λ _, rfl, λ _, NF_below.zero⟩
| (oadd e n a) := ⟨λ h, (not_le_of_lt h.lt).elim (zero_le _),
λ e, e.symm ▸ NF_below.zero⟩
theorem NF.zero_of_zero {e n a} (h : NF (oadd e n a)) (e0 : e = 0) : a = 0 :=
by simpa [e0, NF_below_zero] using h.snd'
theorem NF_below.repr_lt {o b} (h : NF_below o b) : repr o < ω ^ b :=
begin
induction h with _ e n a eb b h₁ h₂ h₃ _ IH,
{ exact power_pos _ omega_pos },
{ rw repr,
refine lt_of_lt_of_le ((ordinal.add_lt_add_iff_left _).2 IH) _,
rw ← mul_succ,
refine le_trans (mul_le_mul_left _ $ ordinal.succ_le.2 $ nat_lt_omega _) _,
rw ← power_succ,
exact power_le_power_right omega_pos (ordinal.succ_le.2 h₃) }
end
theorem NF_below.mono {o b₁ b₂} (bb : b₁ ≤ b₂) (h : NF_below o b₁) : NF_below o b₂ :=
begin
induction h with _ e n a eb b h₁ h₂ h₃ _ IH; constructor,
exacts [h₁, h₂, lt_of_lt_of_le h₃ bb]
end
theorem NF.below_of_lt {e n a b} (H : repr e < b) : NF (oadd e n a) → NF_below (oadd e n a) b
| ⟨b', h⟩ := by cases h with _ _ _ _ eb _ h₁ h₂ h₃;
exact NF_below.oadd' h₁ h₂ H
theorem NF.below_of_lt' : ∀ {o b}, repr o < ω ^ b → NF o → NF_below o b
| 0 b H _ := NF_below.zero
| (oadd e n a) b H h := h.below_of_lt $ (power_lt_power_iff_right one_lt_omega).1 $
(lt_of_le_of_lt (omega_le_oadd _ _ _) H)
theorem NF_below_of_nat : ∀ n, NF_below (of_nat n) 1
| 0 := NF_below.zero
| (nat.succ n) := NF_below.oadd NF.zero NF_below.zero ordinal.zero_lt_one
instance NF_of_nat (n) : NF (of_nat n) := ⟨_, NF_below_of_nat n⟩
instance NF_one : NF 1 := by rw ← of_nat_one; apply_instance
theorem oadd_lt_oadd_1 {e₁ n₁ o₁ e₂ n₂ o₂} (h₁ : NF (oadd e₁ n₁ o₁)) (h : e₁ < e₂) :
oadd e₁ n₁ o₁ < oadd e₂ n₂ o₂ :=
@lt_of_lt_of_le _ _ _ _ _ ((h₁.below_of_lt h).repr_lt) (omega_le_oadd _ _ _)
theorem oadd_lt_oadd_2 {e o₁ o₂ : onote} {n₁ n₂ : ℕ+}
(h₁ : NF (oadd e n₁ o₁)) (h : (n₁:ℕ) < n₂) : oadd e n₁ o₁ < oadd e n₂ o₂ :=
begin
simp [lt_def],
refine lt_of_lt_of_le ((ordinal.add_lt_add_iff_left _).2 h₁.snd'.repr_lt)
(le_trans _ (le_add_right _ _)),
rwa [← mul_succ, mul_le_mul_iff_left (power_pos _ omega_pos),
ordinal.succ_le, nat_cast_lt]
end
theorem oadd_lt_oadd_3 {e n a₁ a₂} (h : a₁ < a₂) :
oadd e n a₁ < oadd e n a₂ :=
begin
rw lt_def, unfold repr,
exact (ordinal.add_lt_add_iff_left _).2 h
end
theorem cmp_compares : ∀ (a b : onote) [NF a] [NF b], (cmp a b).compares a b
| 0 0 h₁ h₂ := rfl
| (oadd e n a) 0 h₁ h₂ := oadd_pos _ _ _
| 0 (oadd e n a) h₁ h₂ := oadd_pos _ _ _
| o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) h₁ h₂ := begin
rw cmp,
have IHe := @cmp_compares _ _ h₁.fst h₂.fst,
cases cmp e₁ e₂,
case ordering.lt { exact oadd_lt_oadd_1 h₁ IHe },
case ordering.gt { exact oadd_lt_oadd_1 h₂ IHe },
change e₁ = e₂ at IHe, subst IHe,
unfold _root_.cmp, cases nh : cmp_using (<) (n₁:ℕ) n₂,
case ordering.lt {
rw cmp_using_eq_lt at nh, exact oadd_lt_oadd_2 h₁ nh },
case ordering.gt {
rw cmp_using_eq_gt at nh, exact oadd_lt_oadd_2 h₂ nh },
rw cmp_using_eq_eq at nh,
have := subtype.eq (eq_of_incomp nh), subst n₂,
have IHa := @cmp_compares _ _ h₁.snd h₂.snd,
cases cmp a₁ a₂,
case ordering.lt { exact oadd_lt_oadd_3 IHa },
case ordering.gt { exact oadd_lt_oadd_3 IHa },
change a₁ = a₂ at IHa, subst IHa, exact rfl
end
theorem repr_inj {a b} [NF a] [NF b] : repr a = repr b ↔ a = b :=
⟨match cmp a b, cmp_compares a b with
| ordering.lt, (h : repr a < repr b), e := (ne_of_lt h e).elim
| ordering.gt, (h : repr a > repr b), e := (ne_of_gt h e).elim
| ordering.eq, h, e := h
end, congr_arg _⟩
theorem NF.of_dvd_omega_power {b e n a} (h : NF (oadd e n a)) (d : ω ^ b ∣ repr (oadd e n a)) :
b ≤ repr e ∧ ω ^ b ∣ repr a :=
begin
have := mt repr_inj.1 (λ h, by injection h : oadd e n a ≠ 0),
have L := le_of_not_lt (λ l, not_le_of_lt (h.below_of_lt l).repr_lt (le_of_dvd this d)),
simp at d,
exact ⟨L, (dvd_add_iff $ dvd_mul_of_dvd_left (power_dvd_power _ L) _).1 d⟩
end
theorem NF.of_dvd_omega {e n a} (h : NF (oadd e n a)) :
ω ∣ repr (oadd e n a) → repr e ≠ 0 ∧ ω ∣ repr a :=
by rw [← power_one ω, ← one_le_iff_ne_zero]; exact h.of_dvd_omega_power
/-- `top_below b o` asserts that the largest exponent in `o`, if
it exists, is less than `b`. This is an auxiliary definition
for decidability of `NF`. -/
def top_below (b) : onote → Prop
| 0 := true
| (oadd e n a) := cmp e b = ordering.lt
instance decidable_top_below : decidable_rel top_below :=
by intros b o; cases o; delta top_below; apply_instance
theorem NF_below_iff_top_below {b} [NF b] : ∀ {o},
NF_below o (repr b) ↔ NF o ∧ top_below b o
| 0 := ⟨λ h, ⟨⟨_, h⟩, trivial⟩, λ _, NF_below.zero⟩
| (oadd e n a) :=
⟨λ h, ⟨⟨_, h⟩, (@cmp_compares _ b h.fst _).eq_lt.2 h.lt⟩,
λ ⟨h₁, h₂⟩, h₁.below_of_lt $ (@cmp_compares _ b h₁.fst _).eq_lt.1 h₂⟩
instance decidable_NF : decidable_pred NF
| 0 := is_true NF.zero
| (oadd e n a) := begin
have := decidable_NF e,
have := decidable_NF a, resetI,
apply decidable_of_iff (NF e ∧ NF a ∧ top_below e a),
abstract {
rw ← and_congr_right (λ h, @NF_below_iff_top_below _ h _),
exact ⟨λ ⟨h₁, h₂⟩, NF.oadd h₁ n h₂, λ h, ⟨h.fst, h.snd'⟩⟩ },
end
/-- Addition of ordinal notations (correct only for normal input) -/
def add : onote → onote → onote
| 0 o := o
| (oadd e n a) o := match add a o with
| 0 := oadd e n 0
| o'@(oadd e' n' a') := match cmp e e' with
| ordering.lt := o'
| ordering.eq := oadd e (n + n') a'
| ordering.gt := oadd e n o'
end
end
instance : has_add onote := ⟨add⟩
@[simp] theorem zero_add (o : onote) : 0 + o = o := rfl
theorem oadd_add (e n a o) : oadd e n a + o = add._match_1 e n (a + o) := rfl
/-- Subtraction of ordinal notations (correct only for normal input) -/
def sub : onote → onote → onote
| 0 o := 0
| o 0 := o
| o₁@(oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) := match cmp e₁ e₂ with
| ordering.lt := 0
| ordering.gt := o₁
| ordering.eq := match (n₁:ℕ) - n₂ with
| 0 := if n₁ = n₂ then sub a₁ a₂ else 0
| (nat.succ k) := oadd e₁ k.succ_pnat a₁
end
end
instance : has_sub onote := ⟨sub⟩
theorem add_NF_below {b} : ∀ {o₁ o₂}, NF_below o₁ b → NF_below o₂ b → NF_below (o₁ + o₂) b
| 0 o h₁ h₂ := h₂
| (oadd e n a) o h₁ h₂ := begin
have h' := add_NF_below (h₁.snd.mono $ le_of_lt h₁.lt) h₂,
simp [oadd_add], cases a + o with e' n' a',
{ exact NF_below.oadd h₁.fst NF_below.zero h₁.lt },
simp [add], have := @cmp_compares _ _ h₁.fst h'.fst,
cases cmp e e'; simp [add],
{ exact h' },
{ simp at this, subst e',
exact NF_below.oadd h'.fst h'.snd h'.lt },
{ exact NF_below.oadd h₁.fst (NF.below_of_lt this ⟨_, h'⟩) h₁.lt }
end
instance add_NF (o₁ o₂) : ∀ [NF o₁] [NF o₂], NF (o₁ + o₂)
| ⟨b₁, h₁⟩ ⟨b₂, h₂⟩ := (b₁.le_total b₂).elim
(λ h, ⟨b₂, add_NF_below (h₁.mono h) h₂⟩)
(λ h, ⟨b₁, add_NF_below h₁ (h₂.mono h)⟩)
@[simp] theorem repr_add : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ + o₂) = repr o₁ + repr o₂
| 0 o h₁ h₂ := by simp
| (oadd e n a) o h₁ h₂ := begin
haveI := h₁.snd, have h' := repr_add a o,
conv at h' in (_+o) {simp [(+)]},
have nf := onote.add_NF a o,
conv at nf in (_+o) {simp [(+)]},
conv in (_+o) {simp [(+), add]},
cases add a o with e' n' a'; simp [add, h'.symm, add_assoc],
have := h₁.fst, haveI := nf.fst, have ee := cmp_compares e e',
cases cmp e e'; simp [add],
{ rw [← add_assoc, @add_absorp _ (repr e') (ω ^ repr e' * (n':ℕ))],
{ have := (h₁.below_of_lt ee).repr_lt, unfold repr at this,
exact lt_of_le_of_lt (le_add_right _ _) this },
{ simpa using (mul_le_mul_iff_left $
power_pos (repr e') omega_pos).2 (nat_cast_le.2 n'.pos) } },
{ change e = e' at ee, substI e',
rw [← add_assoc, ← ordinal.mul_add, ← nat.cast_add] }
end
theorem sub_NF_below : ∀ {o₁ o₂ b}, NF_below o₁ b → NF o₂ → NF_below (o₁ - o₂) b
| 0 o b h₁ h₂ := by cases o; exact NF_below.zero
| (oadd e n a) 0 b h₁ h₂ := h₁
| (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) b h₁ h₂ := begin
have h' := sub_NF_below h₁.snd h₂.snd,
simp [has_sub.sub, sub] at h' ⊢,
have := @cmp_compares _ _ h₁.fst h₂.fst,
cases cmp e₁ e₂; simp [sub],
{ apply NF_below.zero },
{ simp at this, subst e₂,
cases mn : (n₁:ℕ) - n₂; simp [sub],
{ by_cases en : n₁ = n₂; simp [en],
{ exact h'.mono (le_of_lt h₁.lt) },
{ exact NF_below.zero } },
{ exact NF_below.oadd h₁.fst h₁.snd h₁.lt } },
{ exact h₁ }
end
instance sub_NF (o₁ o₂) : ∀ [NF o₁] [NF o₂], NF (o₁ - o₂)
| ⟨b₁, h₁⟩ h₂ := ⟨b₁, sub_NF_below h₁ h₂⟩
@[simp] theorem repr_sub : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ - o₂) = repr o₁ - repr o₂
| 0 o h₁ h₂ := by cases o; exact (ordinal.zero_sub _).symm
| (oadd e n a) 0 h₁ h₂ := (ordinal.sub_zero _).symm
| (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) h₁ h₂ := begin
haveI := h₁.snd, haveI := h₂.snd, have h' := repr_sub a₁ a₂,
conv at h' in (a₁-a₂) {simp [has_sub.sub]},
have nf := onote.sub_NF a₁ a₂,
conv at nf in (a₁-a₂) {simp [has_sub.sub]},
conv in (_-oadd _ _ _) {simp [has_sub.sub, sub]},
have ee := @cmp_compares _ _ h₁.fst h₂.fst,
cases cmp e₁ e₂,
{ rw [sub_eq_zero_iff_le.2], {refl},
exact le_of_lt (oadd_lt_oadd_1 h₁ ee) },
{ change e₁ = e₂ at ee, substI e₂, unfold sub._match_1,
cases mn : (n₁:ℕ) - n₂; dsimp only [sub._match_2],
{ by_cases en : n₁ = n₂,
{ simp [en], rwa [add_sub_add_cancel] },
{ simp [en, -repr],
exact (sub_eq_zero_iff_le.2 $ le_of_lt $ oadd_lt_oadd_2 h₁ $
lt_of_le_of_ne (nat.sub_eq_zero_iff_le.1 mn) (mt pnat.eq en)).symm } },
{ simp [nat.succ_pnat, -nat.cast_succ],
rw [(nat.sub_eq_iff_eq_add $ le_of_lt $ nat.lt_of_sub_eq_succ mn).1 mn,
add_comm, nat.cast_add, ordinal.mul_add, add_assoc, add_sub_add_cancel],
refine (ordinal.sub_eq_of_add_eq $ add_absorp h₂.snd'.repr_lt $
le_trans _ (le_add_right _ _)).symm,
simpa using mul_le_mul_left _ (nat_cast_le.2 $ nat.succ_pos _) } },
{ exact (ordinal.sub_eq_of_add_eq $ add_absorp (h₂.below_of_lt ee).repr_lt $
omega_le_oadd _ _ _).symm }
end
/-- Multiplication of ordinal notations (correct only for normal input) -/
def mul : onote → onote → onote
| 0 _ := 0
| _ 0 := 0
| o₁@(oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) :=
if e₂ = 0 then oadd e₁ (n₁ * n₂) a₁ else
oadd (e₁ + e₂) n₂ (mul o₁ a₂)
instance : has_mul onote := ⟨mul⟩
@[simp] theorem zero_mul (o : onote) : 0 * o = 0 := by cases o; refl
@[simp] theorem mul_zero (o : onote) : o * 0 = 0 := by cases o; refl
theorem oadd_mul (e₁ n₁ a₁ e₂ n₂ a₂) : oadd e₁ n₁ a₁ * oadd e₂ n₂ a₂ =
if e₂ = 0 then oadd e₁ (n₁ * n₂) a₁ else
oadd (e₁ + e₂) n₂ (oadd e₁ n₁ a₁ * a₂) := rfl
theorem oadd_mul_NF_below {e₁ n₁ a₁ b₁} (h₁ : NF_below (oadd e₁ n₁ a₁) b₁) :
∀ {o₂ b₂}, NF_below o₂ b₂ → NF_below (oadd e₁ n₁ a₁ * o₂) (repr e₁ + b₂)
| 0 b₂ h₂ := NF_below.zero
| (oadd e₂ n₂ a₂) b₂ h₂ := begin
have IH := oadd_mul_NF_below h₂.snd,
by_cases e0 : e₂ = 0; simp [e0, oadd_mul],
{ apply NF_below.oadd h₁.fst h₁.snd,
simpa using (add_lt_add_iff_left (repr e₁)).2
(lt_of_le_of_lt (ordinal.zero_le _) h₂.lt) },
{ haveI := h₁.fst, haveI := h₂.fst,
apply NF_below.oadd, apply_instance,
{ rwa repr_add },
{ rw [repr_add, ordinal.add_lt_add_iff_left], exact h₂.lt } }
end
instance mul_NF : ∀ o₁ o₂ [NF o₁] [NF o₂], NF (o₁ * o₂)
| 0 o h₁ h₂ := by cases o; exact NF.zero
| (oadd e n a) o ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ :=
⟨_, oadd_mul_NF_below hb₁ hb₂⟩
@[simp] theorem repr_mul : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ * o₂) = repr o₁ * repr o₂
| 0 o h₁ h₂ := by cases o; exact (ordinal.zero_mul _).symm
| (oadd e₁ n₁ a₁) 0 h₁ h₂ := (ordinal.mul_zero _).symm
| (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) h₁ h₂ := begin
have IH : repr (mul _ _) = _ := @repr_mul _ _ h₁ h₂.snd,
conv {to_lhs, simp [(*)]},
have ao : repr a₁ + ω ^ repr e₁ * (n₁:ℕ) = ω ^ repr e₁ * (n₁:ℕ),
{ apply add_absorp h₁.snd'.repr_lt,
simpa using (mul_le_mul_iff_left $ power_pos _ omega_pos).2
(nat_cast_le.2 n₁.2) },
by_cases e0 : e₂ = 0; simp [e0, mul],
{ cases nat.exists_eq_succ_of_ne_zero n₂.ne_zero with x xe,
simp [h₂.zero_of_zero e0, xe, -nat.cast_succ],
rw [← nat_cast_succ x, add_mul_succ _ ao, mul_assoc] },
{ haveI := h₁.fst, haveI := h₂.fst,
simp [IH, repr_add, power_add, ordinal.mul_add],
rw ← mul_assoc, congr' 2,
have := mt repr_inj.1 e0,
rw [add_mul_limit ao (power_is_limit_left omega_is_limit this),
mul_assoc, mul_omega_dvd (nat_cast_pos.2 n₁.pos) (nat_lt_omega _)],
simpa using power_dvd_power ω (one_le_iff_ne_zero.2 this) },
end
/-- Calculate division and remainder of `o` mod ω.
`split' o = (a, n)` means `o = ω * a + n`. -/
def split' : onote → onote × ℕ
| 0 := (0, 0)
| (oadd e n a) := if e = 0 then (0, n) else
let (a', m) := split' a in (oadd (e - 1) n a', m)
/-- Calculate division and remainder of `o` mod ω.
`split o = (a, n)` means `o = a + n`, where `ω ∣ a`. -/
def split : onote → onote × ℕ
| 0 := (0, 0)
| (oadd e n a) := if e = 0 then (0, n) else
let (a', m) := split a in (oadd e n a', m)
/-- `scale x o` is the ordinal notation for `ω ^ x * o`. -/
def scale (x : onote) : onote → onote
| 0 := 0
| (oadd e n a) := oadd (x + e) n (scale a)
/-- `mul_nat o n` is the ordinal notation for `o * n`. -/
def mul_nat : onote → ℕ → onote
| 0 m := 0
| _ 0 := 0
| (oadd e n a) (m+1) := oadd e (n * m.succ_pnat) a
/-- Auxiliary definition to compute the ordinal notation for the ordinal
exponentiation in `power` -/
def power_aux (e a0 a : onote) : ℕ → ℕ → onote
| _ 0 := 0
| 0 (m+1) := oadd e m.succ_pnat 0
| (k+1) m := scale (e + mul_nat a0 k) a + power_aux k m
/-- `power o₁ o₂` calculates the ordinal notation for
the ordinal exponential `o₁ ^ o₂`. -/
def power (o₁ o₂ : onote) : onote :=
match split o₁ with
| (0, 0) := if o₂ = 0 then 1 else 0
| (0, 1) := 1
| (0, m+1) := let (b', k) := split' o₂ in
oadd b' (@has_pow.pow ℕ+ _ _ m.succ_pnat k) 0
| (a@(oadd a0 _ _), m) := match split o₂ with
| (b, 0) := oadd (a0 * b) 1 0
| (b, k+1) := let eb := a0*b in
scale (eb + mul_nat a0 k) a + power_aux eb a0 (mul_nat a m) k m
end
end
instance : has_pow onote onote := ⟨power⟩
theorem power_def (o₁ o₂ : onote) : o₁ ^ o₂ = power._match_1 o₂ (split o₁) := rfl
theorem split_eq_scale_split' : ∀ {o o' m} [NF o], split' o = (o', m) → split o = (scale 1 o', m)
| 0 o' m h p := by injection p; substs o' m; refl
| (oadd e n a) o' m h p := begin
by_cases e0 : e = 0; simp [e0, split, split'] at p ⊢,
{ rcases p with ⟨rfl, rfl⟩, exact ⟨rfl, rfl⟩ },
{ revert p, cases h' : split' a with a' m',
haveI := h.fst, haveI := h.snd,
simp [split_eq_scale_split' h', split, split'],
have : 1 + (e - 1) = e,
{ refine repr_inj.1 _, simp,
have := mt repr_inj.1 e0,
exact add_sub_cancel_of_le (one_le_iff_ne_zero.2 this) },
intros, substs o' m, simp [scale, this] }
end
theorem NF_repr_split' : ∀ {o o' m} [NF o], split' o = (o', m) → NF o' ∧ repr o = ω * repr o' + m
| 0 o' m h p := by injection p; substs o' m; simp [NF.zero]
| (oadd e n a) o' m h p := begin
by_cases e0 : e = 0; simp [e0, split, split'] at p ⊢,
{ rcases p with ⟨rfl, rfl⟩,
simp [h.zero_of_zero e0, NF.zero] },
{ revert p, cases h' : split' a with a' m',
haveI := h.fst, haveI := h.snd,
cases NF_repr_split' h' with IH₁ IH₂,
simp [IH₂, split'],
intros, substs o' m,
have : ω ^ repr e = ω ^ (1 : ordinal.{0}) * ω ^ (repr e - 1),
{ have := mt repr_inj.1 e0,
rw [← power_add, add_sub_cancel_of_le (one_le_iff_ne_zero.2 this)] },
refine ⟨NF.oadd (by apply_instance) _ _, _⟩,
{ simp at this ⊢,
refine IH₁.below_of_lt' ((mul_lt_mul_iff_left omega_pos).1 $
lt_of_le_of_lt (le_add_right _ m') _),
rw [← this, ← IH₂], exact h.snd'.repr_lt },
{ rw this, simp [ordinal.mul_add, mul_assoc, add_assoc] } }
end
theorem scale_eq_mul (x) [NF x] : ∀ o [NF o], scale x o = oadd x 1 0 * o
| 0 h := rfl
| (oadd e n a) h := begin
simp [(*)], simp [mul, scale],
haveI := h.snd,
by_cases e0 : e = 0,
{ rw scale_eq_mul, simp [e0, h.zero_of_zero, show x + 0 = x, from repr_inj.1 (by simp)] },
{ simp [e0, scale_eq_mul, (*)] }
end
instance NF_scale (x) [NF x] (o) [NF o] : NF (scale x o) :=
by rw scale_eq_mul; apply_instance
@[simp] theorem repr_scale (x) [NF x] (o) [NF o] : repr (scale x o) = ω ^ repr x * repr o :=
by simp [scale_eq_mul]
theorem NF_repr_split {o o' m} [NF o] (h : split o = (o', m)) : NF o' ∧ repr o = repr o' + m :=
begin
cases e : split' o with a n,
cases NF_repr_split' e with s₁ s₂, resetI,
rw split_eq_scale_split' e at h,
injection h, substs o' n,
simp [repr_scale, s₂.symm],
apply_instance
end
theorem split_dvd {o o' m} [NF o] (h : split o = (o', m)) : ω ∣ repr o' :=
begin
cases e : split' o with a n,
rw split_eq_scale_split' e at h,
injection h, subst o',
cases NF_repr_split' e, resetI, simp
end
theorem split_add_lt {o e n a m} [NF o] (h : split o = (oadd e n a, m)) : repr a + m < ω ^ repr e :=
begin
cases NF_repr_split h with h₁ h₂,
cases h₁.of_dvd_omega (split_dvd h) with e0 d,
have := h₁.fst, have := h₁.snd,
refine add_lt_omega_power h₁.snd'.repr_lt (lt_of_lt_of_le (nat_lt_omega _) _),
simpa using power_le_power_right omega_pos (one_le_iff_ne_zero.2 e0),
end
@[simp] theorem mul_nat_eq_mul (n o) : mul_nat o n = o * of_nat n :=
by cases o; cases n; refl
instance NF_mul_nat (o) [NF o] (n) : NF (mul_nat o n) :=
by simp; apply_instance
instance NF_power_aux (e a0 a) [NF e] [NF a0] [NF a] : ∀ k m, NF (power_aux e a0 a k m)
| k 0 := by cases k; exact NF.zero
| 0 (m+1) := NF.oadd_zero _ _
| (k+1) (m+1) := by haveI := NF_power_aux k;
simp [power_aux, nat.succ_ne_zero]; apply_instance
instance NF_power (o₁ o₂) [NF o₁] [NF o₂] : NF (o₁ ^ o₂) :=
begin
cases e₁ : split o₁ with a m,
have na := (NF_repr_split e₁).1,
cases e₂ : split' o₂ with b' k,
haveI := (NF_repr_split' e₂).1,
casesI a with a0 n a',
{ cases m with m,
{ by_cases o₂ = 0; simp [pow, power, e₁, h]; apply_instance },
{ by_cases m = 0; simp [pow, power, e₁, e₂, h]; apply_instance } },
{ simp [pow, power, e₁, e₂, split_eq_scale_split' e₂],
have := na.fst,
cases k with k; simp [succ_eq_add_one, power]; resetI; apply_instance }
end
theorem scale_power_aux (e a0 a : onote) [NF e] [NF a0] [NF a] :
∀ k m, repr (power_aux e a0 a k m) = ω ^ repr e * repr (power_aux 0 a0 a k m)
| 0 m := by cases m; simp [power_aux]
| (k+1) m := by by_cases m = 0; simp [h, power_aux,
ordinal.mul_add, power_add, mul_assoc, scale_power_aux]
theorem repr_power_aux₁ {e a} [Ne : NF e] [Na : NF a] {a' : ordinal}
(e0 : repr e ≠ 0) (h : a' < ω ^ repr e) (aa : repr a = a') (n : ℕ+) :
(ω ^ repr e * (n:ℕ) + a') ^ ω = (ω ^ repr e) ^ ω :=
begin
subst aa,
have No := Ne.oadd n (Na.below_of_lt' h),
have := omega_le_oadd e n a, unfold repr at this,
refine le_antisymm _ (power_le_power_left _ this),
apply (power_le_of_limit
(ne_of_gt $ lt_of_lt_of_le (power_pos _ omega_pos) this) omega_is_limit).2,
intros b l,
have := (No.below_of_lt (lt_succ_self _)).repr_lt, unfold repr at this,
apply le_trans (power_le_power_left b $ le_of_lt this),
rw [← power_mul, ← power_mul],
apply power_le_power_right omega_pos,
cases le_or_lt ω (repr e) with h h,
{ apply le_trans (mul_le_mul_left _ $ le_of_lt $ lt_succ_self _),
rw [succ, add_mul_succ _ (one_add_of_omega_le h), ← succ,
succ_le, mul_lt_mul_iff_left (pos_iff_ne_zero.2 e0)],
exact omega_is_limit.2 _ l },
{ refine le_trans (le_of_lt $ mul_lt_omega (omega_is_limit.2 _ h) l) _,
simpa using mul_le_mul_right ω (one_le_iff_ne_zero.2 e0) }
end
section
local infixr ^ := @pow ordinal.{0} ordinal ordinal.has_pow
theorem repr_power_aux₂ {a0 a'} [N0 : NF a0] [Na' : NF a'] (m : ℕ)
(d : ω ∣ repr a')
(e0 : repr a0 ≠ 0) (h : repr a' + m < ω ^ repr a0) (n : ℕ+) (k : ℕ) :
let R := repr (power_aux 0 a0 (oadd a0 n a' * of_nat m) k m) in
(k ≠ 0 → R < (ω ^ repr a0) ^ succ k) ∧
(ω ^ repr a0) ^ k * (ω ^ repr a0 * (n:ℕ) + repr a') + R =
(ω ^ repr a0 * (n:ℕ) + repr a' + m) ^ succ k :=
begin
intro,
haveI No : NF (oadd a0 n a') :=
N0.oadd n (Na'.below_of_lt' $ lt_of_le_of_lt (le_add_right _ _) h),
induction k with k IH, {cases m; simp [power_aux, R]},
rename R R', let R := repr (power_aux 0 a0 (oadd a0 n a' * of_nat m) k m),
let ω0 := ω ^ repr a0, let α' := ω0 * n + repr a',
change (k ≠ 0 → R < ω0 ^ succ k) ∧ ω0 ^ k * α' + R = (α' + m) ^ succ k at IH,
have RR : R' = ω0 ^ k * (α' * m) + R,
{ by_cases m = 0; simp [h, R', power_aux, R, power_mul],
{ cases k; simp [power_aux] }, { refl } },
have α0 : 0 < α', {simpa [α', lt_def, repr] using oadd_pos a0 n a'},
have ω00 : 0 < ω0 ^ k := power_pos _ (power_pos _ omega_pos),
have Rl : R < ω ^ (repr a0 * succ ↑k),
{ by_cases k0 : k = 0,
{ simp [k0],
refine lt_of_lt_of_le _ (power_le_power_right omega_pos (one_le_iff_ne_zero.2 e0)),
cases m with m; simp [k0, R, power_aux, omega_pos],
rw [← nat.cast_succ], apply nat_lt_omega },
{ rw power_mul, exact IH.1 k0 } },
refine ⟨λ_, _, _⟩,
{ rw [RR, ← power_mul _ _ (succ k.succ)],
have e0 := pos_iff_ne_zero.2 e0,
have rr0 := lt_of_lt_of_le e0 (le_add_left _ _),
apply add_lt_omega_power,
{ simp [power_mul, ω0, power_add, mul_assoc],
rw [mul_lt_mul_iff_left ω00, ← ordinal.power_add],
have := (No.below_of_lt _).repr_lt, unfold repr at this,
refine mul_lt_omega_power rr0 this (nat_lt_omega _),
simpa using (add_lt_add_iff_left (repr a0)).2 e0 },
{ refine lt_of_lt_of_le Rl (power_le_power_right omega_pos $
mul_le_mul_left _ $ succ_le_succ.2 $ nat_cast_le.2 $ le_of_lt k.lt_succ_self) } },
refine calc
ω0 ^ k.succ * α' + R'
= ω0 ^ succ k * α' + (ω0 ^ k * α' * m + R) : by rw [nat_cast_succ, RR, ← mul_assoc]
... = (ω0 ^ k * α' + R) * α' + (ω0 ^ k * α' + R) * m : _
... = (α' + m) ^ succ k.succ : by rw [← ordinal.mul_add, ← nat_cast_succ, power_succ, IH.2],
congr' 1,
{ have αd : ω ∣ α' := dvd_add (dvd_mul_of_dvd_left
(by simpa using power_dvd_power ω (one_le_iff_ne_zero.2 e0)) _) d,
rw [ordinal.mul_add (ω0 ^ k), add_assoc, ← mul_assoc, ← power_succ,
add_mul_limit _ (is_limit_iff_omega_dvd.2 ⟨ne_of_gt α0, αd⟩), mul_assoc,
@mul_omega_dvd n (nat_cast_pos.2 n.pos) (nat_lt_omega _) _ αd],
apply @add_absorp _ (repr a0 * succ k),
{ refine add_lt_omega_power _ Rl,
rw [power_mul, power_succ, mul_lt_mul_iff_left ω00],
exact No.snd'.repr_lt },
{ have := mul_le_mul_left (ω0 ^ succ k) (one_le_iff_pos.2 $ nat_cast_pos.2 n.pos),
rw power_mul, simpa [-power_succ] } },
{ cases m,
{ have : R = 0, {cases k; simp [R, power_aux]}, simp [this] },
{ rw [← nat_cast_succ, add_mul_succ],
apply add_absorp Rl,
rw [power_mul, power_succ],
apply ordinal.mul_le_mul_left,
simpa [α', repr] using omega_le_oadd a0 n a' } }
end
end
theorem repr_power (o₁ o₂) [NF o₁] [NF o₂] : repr (o₁ ^ o₂) = repr o₁ ^ repr o₂ :=
begin
cases e₁ : split o₁ with a m,
cases NF_repr_split e₁ with N₁ r₁,
cases a with a0 n a',
{ cases m with m,
{ by_cases o₂ = 0; simp [power_def, power, e₁, h, r₁],
have := mt repr_inj.1 h, rw zero_power this },
{ cases e₂ : split' o₂ with b' k,
cases NF_repr_split' e₂ with _ r₂,
by_cases m = 0; simp [power_def, power, e₁, h, r₁, e₂, r₂, -nat.cast_succ],
rw [power_add, power_mul, power_omega _ (nat_lt_omega _)],
simpa using nat_cast_lt.2 (nat.succ_lt_succ $ nat.pos_iff_ne_zero.2 h) } },
{ haveI := N₁.fst, haveI := N₁.snd,
cases N₁.of_dvd_omega (split_dvd e₁) with a00 ad,
have al := split_add_lt e₁,
have aa : repr (a' + of_nat m) = repr a' + m, {simp},
cases e₂ : split' o₂ with b' k,
cases NF_repr_split' e₂ with _ r₂,
simp [power_def, power, e₁, r₁, split_eq_scale_split' e₂],
cases k with k; resetI,
{ simp [power, r₂, power_mul, repr_power_aux₁ a00 al aa, add_assoc] },
{ simp [succ_eq_add_one, power, r₂, power_add, power_mul, mul_assoc, add_assoc],
rw [repr_power_aux₁ a00 al aa, scale_power_aux], simp [power_mul],
rw [← ordinal.mul_add, ← add_assoc (ω ^ repr a0 * (n:ℕ))], congr' 1,
rw [← power_succ],
exact (repr_power_aux₂ _ ad a00 al _ _).2 } }
end
end onote
/-- The type of normal ordinal notations. (It would have been
nicer to define this right in the inductive type, but `NF o`
requires `repr` which requires `onote`, so all these things
would have to be defined at once, which messes up the VM
representation.) -/
def nonote := {o : onote // o.NF}
instance : decidable_eq nonote := by unfold nonote; apply_instance
namespace nonote
open onote
instance NF (o : nonote) : NF o.1 := o.2
/-- Construct a `nonote` from an ordinal notation
(and infer normality) -/
def mk (o : onote) [h : NF o] : nonote := ⟨o, h⟩
/-- The ordinal represented by an ordinal notation.
(This function is noncomputable because ordinal
arithmetic is noncomputable. In computational applications
`nonote` can be used exclusively without reference
to `ordinal`, but this function allows for correctness
results to be stated.) -/
noncomputable def repr (o : nonote) : ordinal := o.1.repr
instance : has_to_string nonote := ⟨λ x, x.1.to_string⟩
instance : has_repr nonote := ⟨λ x, x.1.repr'⟩
instance : preorder nonote :=
{ le := λ x y, repr x ≤ repr y,
lt := λ x y, repr x < repr y,
le_refl := λ a, @le_refl ordinal _ _,
le_trans := λ a b c, @le_trans ordinal _ _ _ _,
lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ordinal _ _ _ }
instance : has_zero nonote := ⟨⟨0, NF.zero⟩⟩
instance : inhabited nonote := ⟨0⟩
/-- Convert a natural number to an ordinal notation -/
def of_nat (n : ℕ) : nonote := ⟨of_nat n, _, NF_below_of_nat _⟩
/-- Compare ordinal notations -/
def cmp (a b : nonote) : ordering :=
cmp a.1 b.1
theorem cmp_compares : ∀ a b : nonote, (cmp a b).compares a b
| ⟨a, ha⟩ ⟨b, hb⟩ := begin
resetI,
dsimp [cmp], have := onote.cmp_compares a b,
cases onote.cmp a b; try {exact this},
exact subtype.mk_eq_mk.2 this
end
instance : linear_order nonote :=
{ le_antisymm := λ a b, match cmp a b, cmp_compares a b with
| ordering.lt, h, h₁, h₂ := (not_lt_of_le h₂).elim h
| ordering.eq, h, h₁, h₂ := h
| ordering.gt, h, h₁, h₂ := (not_lt_of_le h₁).elim h
end,
le_total := λ a b, match cmp a b, cmp_compares a b with
| ordering.lt, h := or.inl (le_of_lt h)
| ordering.eq, h := or.inl (le_of_eq h)
| ordering.gt, h := or.inr (le_of_lt h)
end,
..nonote.preorder }
instance decidable_lt : @decidable_rel nonote (<)
| a b := decidable_of_iff _ (cmp_compares a b).eq_lt
instance : decidable_linear_order nonote :=
{ decidable_le := λ a b, decidable_of_iff _ not_lt,
decidable_lt := nonote.decidable_lt,
..nonote.linear_order }
/-- Asserts that `repr a < ω ^ repr b`. Used in `nonote.rec_on` -/
def below (a b : nonote) : Prop := NF_below a.1 (repr b)
/-- The `oadd` pseudo-constructor for `nonote` -/
def oadd (e : nonote) (n : ℕ+) (a : nonote) (h : below a e) : nonote := ⟨_, NF.oadd e.2 n h⟩
/-- This is a recursor-like theorem for `nonote` suggesting an
inductive definition, which can't actually be defined this
way due to conflicting dependencies. -/
@[elab_as_eliminator] def rec_on {C : nonote → Sort*} (o : nonote)
(H0 : C 0)
(H1 : ∀ e n a h, C e → C a → C (oadd e n a h)) : C o :=
begin
cases o with o h, induction o with e n a IHe IHa,
{ exact H0 },
{ exact H1 ⟨e, h.fst⟩ n ⟨a, h.snd⟩ h.snd' (IHe _) (IHa _) }
end
/-- Addition of ordinal notations -/
instance : has_add nonote := ⟨λ x y, mk (x.1 + y.1)⟩
theorem repr_add (a b) : repr (a + b) = repr a + repr b :=
onote.repr_add a.1 b.1
/-- Subtraction of ordinal notations -/
instance : has_sub nonote := ⟨λ x y, mk (x.1 - y.1)⟩
theorem repr_sub (a b) : repr (a - b) = repr a - repr b :=
onote.repr_sub a.1 b.1
/-- Multiplication of ordinal notations -/
instance : has_mul nonote := ⟨λ x y, mk (x.1 * y.1)⟩
theorem repr_mul (a b) : repr (a * b) = repr a * repr b :=
onote.repr_mul a.1 b.1
/-- Exponentiation of ordinal notations -/
def power (x y : nonote) := mk (x.1.power y.1)
theorem repr_power (a b) : repr (power a b) = (repr a).power (repr b) :=
onote.repr_power a.1 b.1
end nonote
|
2f2e75a63979f698cf12bef21576c2725c83afdc | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/pi/basic.lean | f5f844e1027c91faed1c2a2d22c6cdc5f65632c0 | [
"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,184 | 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
import data.sum.basic
/-!
# Categories of indexed families of objects.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
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)] {A : Type u₁} [category.{u₁} A]
/--
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) }
/--
Similar to `pi`, but all functors come from the same category `A`
-/
@[simps]
def pi' (f : Π i, A ⥤ C i) : A ⥤ Π i, C i :=
{ obj := λ a i, (f i).obj a,
map := λ a₁ a₂ h i, (f i).map h, }
section eq_to_hom
@[simp] lemma eq_to_hom_proj {x x' : Π i, C i} (h : x = x') (i : I) :
(eq_to_hom h : x ⟶ x') i = eq_to_hom (function.funext_iff.mp h i) := by { subst h, refl, }
end eq_to_hom
-- One could add some natural isomorphisms showing
-- how `functor.pi` commutes with `pi.eval` and `pi.comap`.
@[simp] lemma pi'_eval (f : Π i, A ⥤ C i) (i : I) : (pi' f) ⋙ (pi.eval C i) = f i :=
begin
apply functor.ext; intros,
{ simp, }, { refl, }
end
/-- Two functors to a product category are equal iff they agree on every coordinate. -/
lemma pi_ext (f f' : A ⥤ Π i, C i) (h : ∀ i, f ⋙ (pi.eval C i) = f' ⋙ (pi.eval C i)) :
f = f' :=
begin
apply functor.ext, swap,
{ intro X, ext i, specialize h i,
have := congr_obj h X, simpa, },
{ intros x y p, ext i, specialize h i,
have := congr_hom h p, simpa, }
end
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
|
2b05612577a41804614a0f87ee7e0b4a433f6a90 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/eq10.lean | 1c48b3756e2f6955d1bd9077638f7908e24f4304 | [
"Apache-2.0"
] | permissive | soonhokong/lean | cb8aa01055ffe2af0fb99a16b4cda8463b882cd1 | 38607e3eb57f57f77c0ac114ad169e9e4262e24f | refs/heads/master | 1,611,187,284,081 | 1,450,766,737,000 | 1,476,122,547,000 | 11,513,992 | 2 | 0 | null | 1,401,763,102,000 | 1,374,182,235,000 | C++ | UTF-8 | Lean | false | false | 1,372 | lean | inductive formula :=
| eqf : nat → nat → formula
| andf : formula → formula → formula
| impf : formula → formula → formula
| notf : formula → formula
| orf : formula → formula → formula
| allf : (nat → formula) → formula
namespace formula
definition implies (a b : Prop) : Prop := a → b
definition denote : formula → Prop
| denote (eqf n1 n2) := n1 = n2
| denote (andf f1 f2) := denote f1 ∧ denote f2
| denote (impf f1 f2) := implies (denote f1) (denote f2)
| denote (orf f1 f2) := denote f1 ∨ denote f2
| denote (notf f) := ¬ denote f
| denote (allf f) := ∀ n : nat, denote (f n)
theorem denote_eqf (n1 n2 : nat) : denote (eqf n1 n2) = (n1 = n2) :=
rfl
theorem denote_andf (f1 f2 : formula) : denote (andf f1 f2) = (denote f1 ∧ denote f2) :=
rfl
theorem denote_impf (f1 f2 : formula) : denote (impf f1 f2) = (denote f1 → denote f2) :=
rfl
theorem denote_orf (f1 f2 : formula) : denote (orf f1 f2) = (denote f1 ∨ denote f2) :=
rfl
theorem denote_notf (f : formula) : denote (notf f) = ¬ denote f :=
rfl
theorem denote_allf (f : nat → formula) : denote (allf f) = (∀ n, denote (f n)) :=
rfl
example : denote (allf (λ n₁, allf (λ n₂, impf (eqf n₁ n₂) (eqf n₂ n₁)))) =
(∀ n₁ n₂ : nat, n₁ = n₂ → n₂ = n₁) :=
rfl
end formula
|
2d46be3456701ea4d38d9b33087446c59762bd8b | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/algebra/category/CommRing/colimits.lean | 0f1d2d6a00b64c2ae223dc58b20d9afaddeec8bb | [
"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 | 13,305 | 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.CommRing.basic
import category_theory.limits.limits
/-!
# 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 `Mon` by constructing the
free monoid on the disjoint union of all the monoids in the diagram,
then taking the quotient by the monoid laws within each monoid,
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
{ rw cocone.naturality_concrete, },
-- zero
{ erw ring_hom.map_zero ((s.ι).app r) },
-- one
{ erw ring_hom.map_one ((s.ι).app r) },
-- neg
{ rw ring_hom.map_neg ((s.ι).app r_j) },
-- add
{ rw ring_hom.map_add ((s.ι).app r_j) },
-- mul
{ rw ring_hom.map_mul ((s.ι).app r_j) },
-- 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. -/
@[simps]
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 only [desc_morphism, quot_zero],
erw ring_hom.map_zero m,
refl, },
{ simp only [desc_morphism, quot_one],
erw ring_hom.map_one m,
refl, },
{ simp only [desc_morphism, quot_neg],
erw ring_hom.map_neg m,
rw [x_ih],
refl, },
{ simp only [desc_morphism, quot_add],
erw ring_hom.map_add m,
rw [x_ih_a, x_ih_a_1],
refl, },
{ simp only [desc_morphism, quot_mul],
erw ring_hom.map_mul m,
rw [x_ih_a, x_ih_a_1],
refl, },
refl
end }.
instance has_colimits_CommRing : has_colimits.{v} CommRing.{v} :=
{ has_colimits_of_shape := λ J 𝒥,
{ has_colimit := λ F, by exactI
{ cocone := colimit_cocone F,
is_colimit := colimit_is_colimit F } } }
end CommRing.colimits
|
0fecfdf06fec0e075f23f814b8d4723de4b04077 | da23b545e1653cafd4ab88b3a42b9115a0b1355f | /test/terminal_goal.lean | 78762466af9dc0bc636841b615dccf34f7c8d54c | [] | no_license | minchaowu/lean-tidy | 137f5058896e0e81dae84bf8d02b74101d21677a | 2d4c52d66cf07c59f8746e405ba861b4fa0e3835 | refs/heads/master | 1,585,283,406,120 | 1,535,094,033,000 | 1,535,094,033,000 | 145,945,792 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,478 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import tidy.recover
import tidy.fsplit
structure C :=
( w : Type )
( x : list w )
( y : Type )
( z : prod w y )
def test_terminal_goal : C :=
begin
fsplit,
success_if_fail { terminal_goal },
exact ℕ,
terminal_goal,
exact [],
success_if_fail { terminal_goal },
exact bool,
terminal_goal,
exact (0, tt)
end
-- verifying that terminal_goal correctly considers all propositional goals as terminal?
structure foo :=
(x : ℕ)
(p : x = 0)
open tactic
lemma bar : ∃ F : foo, F = ⟨ 0, by refl ⟩ :=
begin
split,
swap,
split,
terminal_goal,
swap,
success_if_fail { terminal_goal },
exact 0,
refl,
refl,
end
structure D :=
( w : ℕ → Type )
( x : list (w 0) )
def test_terminal_goal' : D :=
begin
split,
swap,
success_if_fail { terminal_goal },
intros,
success_if_fail { terminal_goal },
exact ℕ,
exact []
end
def f : unit → Type := λ _, ℕ
def test_terminal_goal'' : Σ x : unit, f x :=
begin
split,
terminal_goal,
swap,
terminal_goal,
exact (),
dsimp [f],
exact 0
end
def test_subsingleton_goal : 0 = 0 :=
begin
subsingleton_goal,
refl
end
def test_subsingleton_goal' : list ℕ :=
begin
success_if_fail { subsingleton_goal },
exact []
end |
a75d8130f33513d1c93f916e9d4b6796f9875327 | 367134ba5a65885e863bdc4507601606690974c1 | /src/analysis/normed_space/enorm.lean | 32db241a8cd3f594c44cd5e455e7fac97e270204 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 7,706 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury G. Kudryashov
-/
import analysis.normed_space.basic
/-!
# Extended norm
In this file we define a structure `enorm 𝕜 V` representing an extended norm (i.e., a norm that can
take the value `∞`) on a vector space `V` over a normed field `𝕜`. We do not use `class` for
an `enorm` because the same space can have more than one extended norm. For example, the space of
measurable functions `f : α → ℝ` has a family of `L_p` extended norms.
We prove some basic inequalities, then define
* `emetric_space` structure on `V` corresponding to `e : enorm 𝕜 V`;
* the subspace of vectors with finite norm, called `e.finite_subspace`;
* a `normed_space` structure on this space.
The last definition is an instance because the type involves `e`.
## Implementation notes
We do not define extended normed groups. They can be added to the chain once someone will need them.
## Tags
normed space, extended norm
-/
local attribute [instance, priority 1001] classical.prop_decidable
open_locale ennreal
/-- Extended norm on a vector space. As in the case of normed spaces, we require only
`∥c • x∥ ≤ ∥c∥ * ∥x∥` in the definition, then prove an equality in `map_smul`. -/
structure enorm (𝕜 : Type*) (V : Type*) [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] :=
(to_fun : V → ℝ≥0∞)
(eq_zero' : ∀ x, to_fun x = 0 → x = 0)
(map_add_le' : ∀ x y : V, to_fun (x + y) ≤ to_fun x + to_fun y)
(map_smul_le' : ∀ (c : 𝕜) (x : V), to_fun (c • x) ≤ nnnorm c * to_fun x)
namespace enorm
variables {𝕜 : Type*} {V : Type*} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V]
(e : enorm 𝕜 V)
instance : has_coe_to_fun (enorm 𝕜 V) := ⟨_, enorm.to_fun⟩
lemma injective_coe_fn : function.injective (λ (e : enorm 𝕜 V) (x : V), e x) :=
λ e₁ e₂ h, by cases e₁; cases e₂; congr; exact h
@[ext] lemma ext {e₁ e₂ : enorm 𝕜 V} (h : ∀ x, e₁ x = e₂ x) : e₁ = e₂ :=
injective_coe_fn $ funext h
lemma ext_iff {e₁ e₂ : enorm 𝕜 V} : e₁ = e₂ ↔ ∀ x, e₁ x = e₂ x :=
⟨λ h x, h ▸ rfl, ext⟩
@[simp, norm_cast] lemma coe_inj {e₁ e₂ : enorm 𝕜 V} : ⇑e₁ = e₂ ↔ e₁ = e₂ :=
injective_coe_fn.eq_iff
@[simp] lemma map_smul (c : 𝕜) (x : V) : e (c • x) = nnnorm c * e x :=
le_antisymm (e.map_smul_le' c x) $
begin
by_cases hc : c = 0, { simp [hc] },
calc (nnnorm c : ℝ≥0∞) * e x = nnnorm c * e (c⁻¹ • c • x) : by rw [inv_smul_smul' hc]
... ≤ nnnorm c * (nnnorm (c⁻¹) * e (c • x)) : _
... = e (c • x) : _,
{ exact ennreal.mul_le_mul (le_refl _) (e.map_smul_le' _ _) },
{ rw [← mul_assoc, normed_field.nnnorm_inv, ennreal.coe_inv,
ennreal.mul_inv_cancel _ ennreal.coe_ne_top, one_mul]; simp [hc] }
end
@[simp] lemma map_zero : e 0 = 0 :=
by { rw [← zero_smul 𝕜 (0:V), e.map_smul], norm_num }
@[simp] lemma eq_zero_iff {x : V} : e x = 0 ↔ x = 0 :=
⟨e.eq_zero' x, λ h, h.symm ▸ e.map_zero⟩
@[simp] lemma map_neg (x : V) : e (-x) = e x :=
calc e (-x) = nnnorm (-1:𝕜) * e x : by rw [← map_smul, neg_one_smul]
... = e x : by simp
lemma map_sub_rev (x y : V) : e (x - y) = e (y - x) :=
by rw [← neg_sub, e.map_neg]
lemma map_add_le (x y : V) : e (x + y) ≤ e x + e y := e.map_add_le' x y
lemma map_sub_le (x y : V) : e (x - y) ≤ e x + e y :=
calc e (x - y) = e (x + -y) : by rw sub_eq_add_neg
... ≤ e x + e (-y) : e.map_add_le x (-y)
... = e x + e y : by rw [e.map_neg]
instance : partial_order (enorm 𝕜 V) :=
{ le := λ e₁ e₂, ∀ x, e₁ x ≤ e₂ x,
le_refl := λ e x, le_refl _,
le_trans := λ e₁ e₂ e₃ h₁₂ h₂₃ x, le_trans (h₁₂ x) (h₂₃ x),
le_antisymm := λ e₁ e₂ h₁₂ h₂₁, ext $ λ x, le_antisymm (h₁₂ x) (h₂₁ x) }
/-- The `enorm` sending each non-zero vector to infinity. -/
noncomputable instance : has_top (enorm 𝕜 V) :=
⟨{ to_fun := λ x, if x = 0 then 0 else ⊤,
eq_zero' := λ x, by { split_ifs; simp [*] },
map_add_le' := λ x y,
begin
split_ifs with hxy hx hy hy hx hy hy; try { simp [*] },
simpa [hx, hy] using hxy
end,
map_smul_le' := λ c x,
begin
split_ifs with hcx hx hx; simp only [smul_eq_zero, not_or_distrib] at hcx,
{ simp only [mul_zero, le_refl] },
{ have : c = 0, by tauto,
simp [this] },
{ tauto },
{ simp [hcx.1] }
end }⟩
noncomputable instance : inhabited (enorm 𝕜 V) := ⟨⊤⟩
lemma top_map {x : V} (hx : x ≠ 0) : (⊤ : enorm 𝕜 V) x = ⊤ := if_neg hx
noncomputable instance : semilattice_sup_top (enorm 𝕜 V) :=
{ le := (≤),
lt := (<),
top := ⊤,
le_top := λ e x, if h : x = 0 then by simp [h] else by simp [top_map h],
sup := λ e₁ e₂,
{ to_fun := λ x, max (e₁ x) (e₂ x),
eq_zero' := λ x h, e₁.eq_zero_iff.1 (ennreal.max_eq_zero_iff.1 h).1,
map_add_le' := λ x y, max_le
(le_trans (e₁.map_add_le _ _) $ add_le_add (le_max_left _ _) (le_max_left _ _))
(le_trans (e₂.map_add_le _ _) $ add_le_add (le_max_right _ _) (le_max_right _ _)),
map_smul_le' := λ c x, le_of_eq $ by simp only [map_smul, ennreal.mul_max] },
le_sup_left := λ e₁ e₂ x, le_max_left _ _,
le_sup_right := λ e₁ e₂ x, le_max_right _ _,
sup_le := λ e₁ e₂ e₃ h₁ h₂ x, max_le (h₁ x) (h₂ x),
.. enorm.partial_order }
@[simp, norm_cast] lemma coe_max (e₁ e₂ : enorm 𝕜 V) : ⇑(e₁ ⊔ e₂) = λ x, max (e₁ x) (e₂ x) := rfl
@[norm_cast]
lemma max_map (e₁ e₂ : enorm 𝕜 V) (x : V) : (e₁ ⊔ e₂) x = max (e₁ x) (e₂ x) := rfl
/-- Structure of an `emetric_space` defined by an extended norm. -/
def emetric_space : emetric_space V :=
{ edist := λ x y, e (x - y),
edist_self := λ x, by simp,
eq_of_edist_eq_zero := λ x y, by simp [sub_eq_zero],
edist_comm := e.map_sub_rev,
edist_triangle := λ x y z,
calc e (x - z) = e ((x - y) + (y - z)) : by rw [sub_add_sub_cancel]
... ≤ e (x - y) + e (y - z) : e.map_add_le (x - y) (y - z) }
/-- The subspace of vectors with finite enorm. -/
def finite_subspace : subspace 𝕜 V :=
{ carrier := {x | e x < ⊤},
zero_mem' := by simp,
add_mem' := λ x y hx hy, lt_of_le_of_lt (e.map_add_le x y) (ennreal.add_lt_top.2 ⟨hx, hy⟩),
smul_mem' := λ c x hx,
calc e (c • x) = nnnorm c * e x : e.map_smul c x
... < ⊤ : ennreal.mul_lt_top ennreal.coe_lt_top hx }
/-- Metric space structure on `e.finite_subspace`. We use `emetric_space.to_metric_space_of_dist`
to ensure that this definition agrees with `e.emetric_space`. -/
instance : metric_space e.finite_subspace :=
begin
letI := e.emetric_space,
refine emetric_space.to_metric_space_of_dist _ (λ x y, _) (λ x y, rfl),
change e (x - y) ≠ ⊤,
rw [← ennreal.lt_top_iff_ne_top],
exact lt_of_le_of_lt (e.map_sub_le x y) (ennreal.add_lt_top.2 ⟨x.2, y.2⟩)
end
lemma finite_dist_eq (x y : e.finite_subspace) : dist x y = (e (x - y)).to_real := rfl
lemma finite_edist_eq (x y : e.finite_subspace) : edist x y = e (x - y) := rfl
/-- Normed group instance on `e.finite_subspace`. -/
instance : normed_group e.finite_subspace :=
{ norm := λ x, (e x).to_real,
dist_eq := λ x y, rfl }
lemma finite_norm_eq (x : e.finite_subspace) : ∥x∥ = (e x).to_real := rfl
/-- Normed space instance on `e.finite_subspace`. -/
instance : normed_space 𝕜 e.finite_subspace :=
{ norm_smul_le := λ c x, le_of_eq $ by simp [finite_norm_eq, ennreal.to_real_mul] }
end enorm
|
fc5bea4bb71f685c09b15991cb0e25f0083c57a7 | aa101d73b1a3173c7ec56de02b96baa8ca64c42e | /src/solutions/07_first_negations.lean | 04a55965bbd8465fdf65992af3ba0dcd13f39815 | [
"Apache-2.0"
] | permissive | gihanmarasingha/tutorials | b554d4d53866c493c4341dc13e914b01444e95a6 | 56617114ef0f9f7b808476faffd11e22e4380918 | refs/heads/master | 1,671,141,758,153 | 1,599,173,318,000 | 1,599,173,318,000 | 282,405,870 | 0 | 0 | Apache-2.0 | 1,595,666,751,000 | 1,595,666,750,000 | null | UTF-8 | Lean | false | false | 8,366 | lean | import tuto_lib
import data.int.parity
/-
Negations, proof by contradiction and contraposition.
This file introduces the logical rules and tactics related to negation:
exfalso, by_contradiction, contrapose, by_cases and push_neg.
There is a special statement denoted by `false` which, by definition,
has no proof.
So `false` implies everything. Indeed `false → P` means any proof of
`false` could be turned into a proof of P.
This fact is known by its latin name
"ex falso quod libet" (from false follows whatever you want).
Hence Lean's tactic to invoke this is called `exfalso`.
-/
example : false → 0 = 1 :=
begin
intro h,
exfalso,
exact h,
end
/-
The preceding example suggests that this definition of `false` isn't very useful.
But actually it allows us to define the negation of a statement P as
"P implies false" that we can read as "if P were true, we would get
a contradiction". Lean denotes this by `¬ P`.
One can prove that (¬ P) ↔ (P ↔ false). But in practice we directly
use the definition of `¬ P`.
-/
example {x : ℝ} : ¬ x < x :=
begin
intro hyp,
rw lt_iff_le_and_ne at hyp,
cases hyp with hyp_inf hyp_non,
clear hyp_inf, -- we won't use that one, so let's discard it
change x = x → false at hyp_non, -- Lean doesn't need this psychological line
apply hyp_non,
refl,
end
open int
-- 0045
example (n : ℤ) (h_pair : even n) (h_non_pair : ¬ even n) : 0 = 1 :=
begin
-- sorry
exfalso,
exact h_non_pair h_pair,
-- sorry
end
-- 0046
example (P Q : Prop) (h₁ : P ∨ Q) (h₂ : ¬ (P ∧ Q)) : ¬ P ↔ Q :=
begin
-- sorry
split,
{ intro hnP,
cases h₁ with hP hQ,
{ exfalso,
exact hnP hP, },
{ exact hQ }, },
{ intros hQ hP,
exact h₂ ⟨hP, hQ⟩ },
-- sorry
end
/-
The definition of negation easily implies that, for every statement P,
P → ¬ ¬ P
The excluded middle axiom, which asserts P ∨ ¬ P allows us to
prove the converse implication.
Together those two implications form the principle of double negation elimination.
not_not {P : Prop} : (¬ ¬ P) ↔ P
The implication `¬ ¬ P → P` is the basis for proofs by contradiction:
in order to prove P, it suffices to prove ¬¬ P, ie `¬ P → false`.
Of course there is no need to keep explaining all this. The tactic
`by_contradiction Hyp` will transform any goal P into `false` and
add Hyp : ¬ P to the local context.
Let's return to a proof from the 5th file: uniqueness of limits for a sequence.
This cannot be proved without using some version of the excluded middle
axiom. We used it secretely in
eq_of_abs_sub_le_all (x y : ℝ) : (∀ ε > 0, |x - y| ≤ ε) → x = y
(we'll prove a variation on this lemma below).
-/
example (u : ℕ → ℝ) (l l' : ℝ) : seq_limit u l → seq_limit u l' → l = l' :=
begin
intros hl hl',
by_contradiction H,
change l ≠ l' at H, -- Lean does not need this line
have ineg : |l-l'| > 0,
exact abs_pos_of_ne_zero (sub_ne_zero_of_ne H),
cases hl ( |l-l'|/4 ) (by linarith) with N hN,
cases hl' ( |l-l'|/4 ) (by linarith) with N' hN',
let N₀ := max N N', -- this is a new tactic, whose effect should be clear
specialize hN N₀ (le_max_left _ _),
specialize hN' N₀ (le_max_right _ _),
have clef : |l-l'| < |l-l'|,
calc
|l - l'| = |(l-u N₀) + (u N₀ -l')| : by ring
... ≤ |l - u N₀| + |u N₀ - l'| : by apply abs_add
... = |u N₀ - l| + |u N₀ - l'| : by rw abs_sub
... < |l-l'| : by linarith,
linarith, -- linarith can also find simple numerical contradictions
end
/-
Another incarnation of the excluded middle axiom is the principle of
contraposition: in order to prove P ⇒ Q, it suffices to prove
non Q ⇒ non P.
-/
-- Using a proof by contradiction, let's prove the contraposition principle
-- 0047
example (P Q : Prop) (h : ¬ Q → ¬ P) : P → Q :=
begin
-- sorry
intro hP,
by_contradiction hnQ,
exact h hnQ hP,
-- sorry
end
/-
Again Lean doesn't need to be explain this principle. We can use the
`contrapose` tactic.
-/
example (P Q : Prop) (h : ¬ Q → ¬ P) : P → Q :=
begin
contrapose,
exact h,
end
/-
In the next exercise, we'll use
odd n : ∃ k, n = 2*k + 1
not_even_iff_odd : ¬ even n ↔ odd n,
-/
-- 0048
example (n : ℤ) : even (n^2) ↔ even n :=
begin
-- sorry
split,
{ contrapose,
rw not_even_iff_odd,
rw not_even_iff_odd,
rintro ⟨k, rfl⟩,
use 2*k*(k+1),
ring },
{ rintro ⟨k, rfl⟩,
use 2*k^2,
ring },
-- sorry
end
/-
As a last step on our law of the excluded middle tour, let's notice that, especially
in pure logic exercises, it can sometimes be useful to use the
excluded middle axiom in its original form:
classical.em : ∀ P, P ∨ ¬ P
Instead of applying this lemma and then using the `cases` tactic, we
have the shortcut
by_cases h : P,
combining both steps to create two proof branches: one assuming
h : P, and the other assuming h : ¬ P
For instance, let's prove a reformulation of this implication relation,
which is sometimes used as a definition in other logical foundations,
especially those based on truth tables (hence very strongly using
excluded middle from the very beginning).
-/
variables (P Q : Prop)
example : (P → Q) ↔ (¬ P ∨ Q) :=
begin
split,
{ intro h,
by_cases hP : P,
{ right,
exact h hP },
{ left,
exact hP } },
{ intros h hP,
cases h with hnP hQ,
{ exfalso,
exact hnP hP },
{ exact hQ } },
end
-- 0049
example : ¬ (P ∧ Q) ↔ ¬ P ∨ ¬ Q :=
begin
-- sorry
split,
{ intro h,
by_cases hP : P,
{ right,
intro hQ,
exact h ⟨hP, hQ⟩ },
{ left,
exact hP } },
{ rintros h ⟨hP, hQ⟩,
cases h with hnP hnQ,
{ exact hnP hP },
{ exact hnQ hQ } },
-- sorry
end
/-
It is crucial to understand negation of quantifiers.
Let's do it by hand for a little while.
In the first exercise, only the definition of negation is needed.
-/
-- 0050
example (n : ℤ) : ¬ (∃ k, n = 2*k) ↔ ∀ k, n ≠ 2*k :=
begin
-- sorry
split,
{ intros hyp k hk,
exact hyp ⟨k, hk⟩ },
{ rintros hyp ⟨k, rfl⟩,
exact hyp k rfl },
-- sorry
end
/-
Contrary to negation of the existential quantifier, negation of the
universal quantifier requires excluded middle for the first implication.
In order to prove this, we can use either
* a double proof by contradiction
* a contraposition, not_not : (¬ ¬ P) ↔ P) and a proof by contradiction.
-/
def even_fun (f : ℝ → ℝ) := ∀ x, f (-x) = f x
-- 0051
example (f : ℝ → ℝ) : ¬ even_fun f ↔ ∃ x, f (-x) ≠ f x :=
begin
-- sorry
split,
{ contrapose,
intro h,
rw not_not,
intro x,
by_contradiction H,
apply h,
use x,
/- Alternative version
intro h,
by_contradiction H,
apply h,
intro x,
by_contradiction H',
apply H,
use x, -/ },
{ rintros ⟨x, hx⟩ h',
exact hx (h' x) },
-- sorry
end
/-
Of course we can't keep repeating the above proofs, especially the second one.
So we use the `push_neg` tactic.
-/
example : ¬ even_fun (λ x, 2*x) :=
begin
unfold even_fun, -- Here unfolding is important because push_neg won't do it.
push_neg,
use 42,
linarith,
end
-- 0052
example (f : ℝ → ℝ) : ¬ even_fun f ↔ ∃ x, f (-x) ≠ f x :=
begin
-- sorry
unfold even_fun,
push_neg,
-- sorry
end
def bounded_above (f : ℝ → ℝ) := ∃ M, ∀ x, f x ≤ M
example : ¬ bounded_above (λ x, x) :=
begin
unfold bounded_above,
push_neg,
intro M,
use M + 1,
linarith,
end
-- Let's contrapose
-- 0053
example (x : ℝ) : (∀ ε > 0, x ≤ ε) → x ≤ 0 :=
begin
-- sorry
contrapose,
push_neg,
intro h,
use x/2,
split ; linarith,
-- sorry
end
/-
The "contrapose, push_neg" combo is so common that we can abreviate it to
`contrapose!`
Let's use this trick, together with:
eq_or_lt_of_le : a ≤ b → a = b ∨ a < b
-/
-- 0054
example (f : ℝ → ℝ) : (∀ x y, x < y → f x < f y) ↔ (∀ x y, (x ≤ y ↔ f x ≤ f y)) :=
begin
-- sorry
split,
{ intros hf x y,
split,
{ intros hxy,
cases eq_or_lt_of_le hxy with hxy hxy,
{ rw hxy },
{ linarith [hf x y hxy]} },
{ contrapose!,
apply hf } },
{ intros hf x y,
contrapose!,
intro h,
rwa hf, }
-- sorry
end
|
0f643d227df10feb57a030afa451fd7e06c3f77c | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch4/ex0402.lean | 2301580634266afbc899d5dbb2997d2b9c62d9d4 | [] | no_license | Ailrun/Theorem_Proving_in_Lean | ae6a23f3c54d62d401314d6a771e8ff8b4132db2 | 2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68 | refs/heads/master | 1,609,838,270,467 | 1,586,846,743,000 | 1,586,846,743,000 | 240,967,761 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 227 | lean | open nat
example : ∃ x : ℕ, x > 0 :=
⟨1, zero_lt_succ 0⟩
example (x : ℕ) (h : x > 0) : ∃ y, y < x :=
⟨0, h⟩
example (x y z : ℕ) (hxy : x < y) (hyz : y < z) : ∃ w, x < w ∧ w < z :=
⟨y, hxy, hyz⟩
|
e5c436f9df2785ad3a8d7cd40c3a956a55098003 | fecda8e6b848337561d6467a1e30cf23176d6ad0 | /src/data/list/perm.lean | aa2c7ecceb3fe0af0fdb255c8dee4088df294673 | [
"Apache-2.0"
] | permissive | spolu/mathlib | bacf18c3d2a561d00ecdc9413187729dd1f705ed | 480c92cdfe1cf3c2d083abded87e82162e8814f4 | refs/heads/master | 1,671,684,094,325 | 1,600,736,045,000 | 1,600,736,045,000 | 297,564,749 | 1 | 0 | null | 1,600,758,368,000 | 1,600,758,367,000 | null | UTF-8 | Lean | false | false | 43,893 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro
-/
import data.list.bag_inter
import data.list.erase_dup
import data.list.zip
import logic.relation
import data.nat.fact
/-!
# List permutations
-/
namespace list
universe variables uu vv
variables {α : Type uu} {β : Type vv}
/-- `perm l₁ l₂` or `l₁ ~ l₂` asserts that `l₁` and `l₂` are permutations
of each other. This is defined by induction using pairwise swaps. -/
inductive perm : list α → list α → Prop
| nil : perm [] []
| cons : Π (x : α) {l₁ l₂ : list α}, perm l₁ l₂ → perm (x::l₁) (x::l₂)
| swap : Π (x y : α) (l : list α), perm (y::x::l) (x::y::l)
| trans : Π {l₁ l₂ l₃ : list α}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃
open perm (swap)
infix ~ := perm
@[refl] protected theorem perm.refl : ∀ (l : list α), l ~ l
| [] := perm.nil
| (x::xs) := (perm.refl xs).cons x
@[symm] protected theorem perm.symm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₂ ~ l₁ :=
perm.rec_on p
perm.nil
(λ x l₁ l₂ p₁ r₁, r₁.cons x)
(λ x y l, swap y x l)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₂.trans r₁)
theorem perm_comm {l₁ l₂ : list α} : l₁ ~ l₂ ↔ l₂ ~ l₁ := ⟨perm.symm, perm.symm⟩
theorem perm.swap'
(x y : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : y::x::l₁ ~ x::y::l₂ :=
(swap _ _ _).trans ((p.cons _).cons _)
attribute [trans] perm.trans
theorem perm.eqv (α) : equivalence (@perm α) :=
mk_equivalence (@perm α) (@perm.refl α) (@perm.symm α) (@perm.trans α)
instance is_setoid (α) : setoid (list α) :=
setoid.mk (@perm α) (perm.eqv α)
theorem perm.subset {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ ⊆ l₂ :=
λ a, perm.rec_on p
(λ h, h)
(λ x l₁ l₂ p₁ r₁ i, or.elim i
(λ ax, by simp [ax])
(λ al₁, or.inr (r₁ al₁)))
(λ x y l ayxl, or.elim ayxl
(λ ay, by simp [ay])
(λ axl, or.elim axl
(λ ax, by simp [ax])
(λ al, or.inr (or.inr al))))
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁))
theorem perm.mem_iff {a : α} {l₁ l₂ : list α} (h : l₁ ~ l₂) : a ∈ l₁ ↔ a ∈ l₂ :=
iff.intro (λ m, h.subset m) (λ m, h.symm.subset m)
theorem perm.append_right {l₁ l₂ : list α} (t₁ : list α) (p : l₁ ~ l₂) : l₁++t₁ ~ l₂++t₁ :=
perm.rec_on p
(perm.refl ([] ++ t₁))
(λ x l₁ l₂ p₁ r₁, r₁.cons x)
(λ x y l, swap x y _)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₁.trans r₂)
theorem perm.append_left {t₁ t₂ : list α} : ∀ (l : list α), t₁ ~ t₂ → l++t₁ ~ l++t₂
| [] p := p
| (x::xs) p := (perm.append_left xs p).cons x
theorem perm.append {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁++t₁ ~ l₂++t₂ :=
(p₁.append_right t₁).trans (p₂.append_left l₂)
theorem perm.append_cons (a : α) {h₁ h₂ t₁ t₂ : list α}
(p₁ : h₁ ~ h₂) (p₂ : t₁ ~ t₂) : h₁ ++ a::t₁ ~ h₂ ++ a::t₂ :=
p₁.append (p₂.cons a)
@[simp] theorem perm_middle {a : α} : ∀ {l₁ l₂ : list α}, l₁++a::l₂ ~ a::(l₁++l₂)
| [] l₂ := perm.refl _
| (b::l₁) l₂ := ((@perm_middle l₁ l₂).cons _).trans (swap a b _)
@[simp] theorem perm_append_singleton (a : α) (l : list α) : l ++ [a] ~ a::l :=
perm_middle.trans $ by rw [append_nil]
theorem perm_append_comm : ∀ {l₁ l₂ : list α}, (l₁++l₂) ~ (l₂++l₁)
| [] l₂ := by simp
| (a::t) l₂ := (perm_append_comm.cons _).trans perm_middle.symm
theorem concat_perm (l : list α) (a : α) : concat l a ~ a :: l :=
by simp
theorem perm.length_eq {l₁ l₂ : list α} (p : l₁ ~ l₂) : length l₁ = length l₂ :=
perm.rec_on p
rfl
(λ x l₁ l₂ p r, by simp[r])
(λ x y l, by simp)
(λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂)
theorem perm.eq_nil {l : list α} (p : l ~ []) : l = [] :=
eq_nil_of_length_eq_zero p.length_eq
theorem perm.nil_eq {l : list α} (p : [] ~ l) : [] = l :=
p.symm.eq_nil.symm
theorem perm_nil {l₁ : list α} : l₁ ~ [] ↔ l₁ = [] :=
⟨λ p, p.eq_nil, λ e, e ▸ perm.refl _⟩
theorem not_perm_nil_cons (x : α) (l : list α) : ¬ [] ~ x::l
| p := by injection p.symm.eq_nil
@[simp] theorem reverse_perm : ∀ (l : list α), reverse l ~ l
| [] := perm.nil
| (a::l) := by { rw reverse_cons,
exact (perm_append_singleton _ _).trans ((reverse_perm l).cons a) }
theorem perm_cons_append_cons {l l₁ l₂ : list α} (a : α) (p : l ~ l₁++l₂) :
a::l ~ l₁++(a::l₂) :=
(p.cons a).trans perm_middle.symm
@[simp] theorem perm_repeat {a : α} {n : ℕ} {l : list α} : l ~ repeat a n ↔ l = repeat a n :=
⟨λ p, (eq_repeat.2
⟨p.length_eq.trans $ length_repeat _ _,
λ b m, eq_of_mem_repeat $ p.subset m⟩),
λ h, h ▸ perm.refl _⟩
@[simp] theorem repeat_perm {a : α} {n : ℕ} {l : list α} : repeat a n ~ l ↔ repeat a n = l :=
(perm_comm.trans perm_repeat).trans eq_comm
@[simp] theorem perm_singleton {a : α} {l : list α} : l ~ [a] ↔ l = [a] :=
@perm_repeat α a 1 l
@[simp] theorem singleton_perm {a : α} {l : list α} : [a] ~ l ↔ [a] = l :=
@repeat_perm α a 1 l
theorem perm.eq_singleton {a : α} {l : list α} (p : l ~ [a]) : l = [a] :=
perm_singleton.1 p
theorem perm.singleton_eq {a : α} {l : list α} (p : [a] ~ l) : [a] = l :=
p.symm.eq_singleton.symm
theorem singleton_perm_singleton {a b : α} : [a] ~ [b] ↔ a = b :=
by simp
theorem perm_cons_erase [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) :
l ~ a :: l.erase a :=
let ⟨l₁, l₂, _, e₁, e₂⟩ := exists_erase_eq h in
e₂.symm ▸ e₁.symm ▸ perm_middle
@[elab_as_eliminator] theorem perm_induction_on
{P : list α → list α → Prop} {l₁ l₂ : list α} (p : l₁ ~ l₂)
(h₁ : P [] [])
(h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂))
(h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂))
(h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) :
P l₁ l₂ :=
have P_refl : ∀ l, P l l, from
assume l,
list.rec_on l h₁ (λ x xs ih, h₂ x xs xs (perm.refl xs) ih),
perm.rec_on p h₁ h₂ (λ x y l, h₃ x y l l (perm.refl l) (P_refl l)) h₄
@[congr] theorem perm.filter_map (f : α → option β) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
filter_map f l₁ ~ filter_map f l₂ :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂,
{ simp },
{ simp only [filter_map], cases f x with a; simp [filter_map, IH, perm.cons] },
{ simp only [filter_map], cases f x with a; cases f y with b; simp [filter_map, swap] },
{ exact IH₁.trans IH₂ }
end
@[congr] theorem perm.map (f : α → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
map f l₁ ~ map f l₂ :=
filter_map_eq_map f ▸ p.filter_map _
theorem perm.pmap {p : α → Prop} (f : Π a, p a → β)
{l₁ l₂ : list α} (p : l₁ ~ l₂) {H₁ H₂} : pmap f l₁ H₁ ~ pmap f l₂ H₂ :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂,
{ simp },
{ simp [IH, perm.cons] },
{ simp [swap] },
{ refine IH₁.trans IH₂,
exact λ a m, H₂ a (p₂.subset m) }
end
theorem perm.filter (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} (s : l₁ ~ l₂) : filter p l₁ ~ filter p l₂ :=
by rw ← filter_map_eq_filter; apply s.filter_map _
theorem exists_perm_sublist {l₁ l₂ l₂' : list α}
(s : l₁ <+ l₂) (p : l₂ ~ l₂') : ∃ l₁' ~ l₁, l₁' <+ l₂' :=
begin
induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂ generalizing l₁ s,
{ exact ⟨[], eq_nil_of_sublist_nil s ▸ perm.refl _, nil_sublist _⟩ },
{ cases s with _ _ _ s l₁ _ _ s,
{ exact let ⟨l₁', p', s'⟩ := IH s in ⟨l₁', p', s'.cons _ _ _⟩ },
{ exact let ⟨l₁', p', s'⟩ := IH s in ⟨x::l₁', p'.cons x, s'.cons2 _ _ _⟩ } },
{ cases s with _ _ _ s l₁ _ _ s; cases s with _ _ _ s l₁ _ _ s,
{ exact ⟨l₁, perm.refl _, (s.cons _ _ _).cons _ _ _⟩ },
{ exact ⟨x::l₁, perm.refl _, (s.cons _ _ _).cons2 _ _ _⟩ },
{ exact ⟨y::l₁, perm.refl _, (s.cons2 _ _ _).cons _ _ _⟩ },
{ exact ⟨x::y::l₁, perm.swap _ _ _, (s.cons2 _ _ _).cons2 _ _ _⟩ } },
{ exact let ⟨m₁, pm, sm⟩ := IH₁ s, ⟨r₁, pr, sr⟩ := IH₂ sm in
⟨r₁, pr.trans pm, sr⟩ }
end
theorem perm.sizeof_eq_sizeof [has_sizeof α] {l₁ l₂ : list α} (h : l₁ ~ l₂) :
l₁.sizeof = l₂.sizeof :=
begin
induction h with hd l₁ l₂ h₁₂ h_sz₁₂ a b l l₁ l₂ l₃ h₁₂ h₂₃ h_sz₁₂ h_sz₂₃,
{ refl },
{ simp only [list.sizeof, h_sz₁₂] },
{ simp only [list.sizeof, add_left_comm] },
{ simp only [h_sz₁₂, h_sz₂₃] }
end
section rel
open relator
variables {γ : Type*} {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
local infixr ` ∘r ` : 80 := relation.comp
lemma perm_comp_perm : (perm ∘r perm : list α → list α → Prop) = perm :=
begin
funext a c, apply propext,
split,
{ exact assume ⟨b, hab, hba⟩, perm.trans hab hba },
{ exact assume h, ⟨a, perm.refl a, h⟩ }
end
lemma perm_comp_forall₂ {l u v} (hlu : perm l u) (huv : forall₂ r u v) : (forall₂ r ∘r perm) l v :=
begin
induction hlu generalizing v,
case perm.nil { cases huv, exact ⟨[], forall₂.nil, perm.nil⟩ },
case perm.cons : a l u hlu ih {
cases huv with _ b _ v hab huv',
rcases ih huv' with ⟨l₂, h₁₂, h₂₃⟩,
exact ⟨b::l₂, forall₂.cons hab h₁₂, h₂₃.cons _⟩
},
case perm.swap : a₁ a₂ l₁ l₂ h₂₃ {
cases h₂₃ with _ b₁ _ l₂ h₁ hr_₂₃,
cases hr_₂₃ with _ b₂ _ l₂ h₂ h₁₂,
exact ⟨b₂::b₁::l₂, forall₂.cons h₂ (forall₂.cons h₁ h₁₂), perm.swap _ _ _⟩
},
case perm.trans : la₁ la₂ la₃ _ _ ih₁ ih₂ {
rcases ih₂ huv with ⟨lb₂, hab₂, h₂₃⟩,
rcases ih₁ hab₂ with ⟨lb₁, hab₁, h₁₂⟩,
exact ⟨lb₁, hab₁, perm.trans h₁₂ h₂₃⟩
}
end
lemma forall₂_comp_perm_eq_perm_comp_forall₂ : forall₂ r ∘r perm = perm ∘r forall₂ r :=
begin
funext l₁ l₃, apply propext,
split,
{ assume h, rcases h with ⟨l₂, h₁₂, h₂₃⟩,
have : forall₂ (flip r) l₂ l₁, from h₁₂.flip ,
rcases perm_comp_forall₂ h₂₃.symm this with ⟨l', h₁, h₂⟩,
exact ⟨l', h₂.symm, h₁.flip⟩ },
{ exact assume ⟨l₂, h₁₂, h₂₃⟩, perm_comp_forall₂ h₁₂ h₂₃ }
end
lemma rel_perm_imp (hr : right_unique r) : (forall₂ r ⇒ forall₂ r ⇒ implies) perm perm :=
assume a b h₁ c d h₂ h,
have (flip (forall₂ r) ∘r (perm ∘r forall₂ r)) b d, from ⟨a, h₁, c, h, h₂⟩,
have ((flip (forall₂ r) ∘r forall₂ r) ∘r perm) b d,
by rwa [← forall₂_comp_perm_eq_perm_comp_forall₂, ← relation.comp_assoc] at this,
let ⟨b', ⟨c', hbc, hcb⟩, hbd⟩ := this in
have b' = b, from right_unique_forall₂ @hr hcb hbc,
this ▸ hbd
lemma rel_perm (hr : bi_unique r) : (forall₂ r ⇒ forall₂ r ⇒ (↔)) perm perm :=
assume a b hab c d hcd, iff.intro
(rel_perm_imp hr.2 hab hcd)
(rel_perm_imp (assume a b c, left_unique_flip hr.1) hab.flip hcd.flip)
end rel
section subperm
/-- `subperm l₁ l₂`, denoted `l₁ <+~ l₂`, means that `l₁` is a sublist of
a permutation of `l₂`. This is an analogue of `l₁ ⊆ l₂` which respects
multiplicities of elements, and is used for the `≤` relation on multisets. -/
def subperm (l₁ l₂ : list α) : Prop := ∃ l ~ l₁, l <+ l₂
infix ` <+~ `:50 := subperm
theorem nil_subperm {l : list α} : [] <+~ l :=
⟨[], perm.nil, by simp⟩
theorem perm.subperm_left {l l₁ l₂ : list α} (p : l₁ ~ l₂) : l <+~ l₁ ↔ l <+~ l₂ :=
suffices ∀ {l₁ l₂ : list α}, l₁ ~ l₂ → l <+~ l₁ → l <+~ l₂,
from ⟨this p, this p.symm⟩,
λ l₁ l₂ p ⟨u, pu, su⟩,
let ⟨v, pv, sv⟩ := exists_perm_sublist su p in
⟨v, pv.trans pu, sv⟩
theorem perm.subperm_right {l₁ l₂ l : list α} (p : l₁ ~ l₂) : l₁ <+~ l ↔ l₂ <+~ l :=
⟨λ ⟨u, pu, su⟩, ⟨u, pu.trans p, su⟩,
λ ⟨u, pu, su⟩, ⟨u, pu.trans p.symm, su⟩⟩
theorem sublist.subperm {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁ <+~ l₂ :=
⟨l₁, perm.refl _, s⟩
theorem perm.subperm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ <+~ l₂ :=
⟨l₂, p.symm, sublist.refl _⟩
@[refl] theorem subperm.refl (l : list α) : l <+~ l := (perm.refl _).subperm
@[trans] theorem subperm.trans {l₁ l₂ l₃ : list α} : l₁ <+~ l₂ → l₂ <+~ l₃ → l₁ <+~ l₃
| s ⟨l₂', p₂, s₂⟩ :=
let ⟨l₁', p₁, s₁⟩ := p₂.subperm_left.2 s in ⟨l₁', p₁, s₁.trans s₂⟩
theorem subperm.length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ ≤ length l₂
| ⟨l, p, s⟩ := p.length_eq ▸ length_le_of_sublist s
theorem subperm.perm_of_length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₂ ≤ length l₁ → l₁ ~ l₂
| ⟨l, p, s⟩ h :=
suffices l = l₂, from this ▸ p.symm,
eq_of_sublist_of_length_le s $ p.symm.length_eq ▸ h
theorem subperm.antisymm {l₁ l₂ : list α} (h₁ : l₁ <+~ l₂) (h₂ : l₂ <+~ l₁) : l₁ ~ l₂ :=
h₁.perm_of_length_le h₂.length_le
theorem subperm.subset {l₁ l₂ : list α} : l₁ <+~ l₂ → l₁ ⊆ l₂
| ⟨l, p, s⟩ := subset.trans p.symm.subset s.subset
end subperm
theorem sublist.exists_perm_append : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → ∃ l, l₂ ~ l₁ ++ l
| ._ ._ sublist.slnil := ⟨nil, perm.refl _⟩
| ._ ._ (sublist.cons l₁ l₂ a s) :=
let ⟨l, p⟩ := sublist.exists_perm_append s in
⟨a::l, (p.cons a).trans perm_middle.symm⟩
| ._ ._ (sublist.cons2 l₁ l₂ a s) :=
let ⟨l, p⟩ := sublist.exists_perm_append s in
⟨l, p.cons a⟩
theorem perm.countp_eq (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} (s : l₁ ~ l₂) : countp p l₁ = countp p l₂ :=
by rw [countp_eq_length_filter, countp_eq_length_filter];
exact (s.filter _).length_eq
theorem subperm.countp_le (p : α → Prop) [decidable_pred p]
{l₁ l₂ : list α} : l₁ <+~ l₂ → countp p l₁ ≤ countp p l₂
| ⟨l, p', s⟩ := p'.countp_eq p ▸ countp_le_of_sublist s
theorem perm.count_eq [decidable_eq α] {l₁ l₂ : list α}
(p : l₁ ~ l₂) (a) : count a l₁ = count a l₂ :=
p.countp_eq _
theorem subperm.count_le [decidable_eq α] {l₁ l₂ : list α}
(s : l₁ <+~ l₂) (a) : count a l₁ ≤ count a l₂ :=
s.countp_le _
theorem perm.foldl_eq' {f : β → α → β} {l₁ l₂ : list α} (p : l₁ ~ l₂) :
(∀ (x ∈ l₁) (y ∈ l₁) z, f (f z x) y = f (f z y) x) → ∀ b, foldl f b l₁ = foldl f b l₂ :=
perm_induction_on p
(λ H b, rfl)
(λ x t₁ t₂ p r H b, r (λ x hx y hy, H _ (or.inr hx) _ (or.inr hy)) _)
(λ x y t₁ t₂ p r H b,
begin
simp only [foldl],
rw [H x (or.inr $ or.inl rfl) y (or.inl rfl)],
exact r (λ x hx y hy, H _ (or.inr $ or.inr hx) _ (or.inr $ or.inr hy)) _
end)
(λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ H b, eq.trans (r₁ H b)
(r₂ (λ x hx y hy, H _ (p₁.symm.subset hx) _ (p₁.symm.subset hy)) b))
theorem perm.foldl_eq {f : β → α → β} {l₁ l₂ : list α} (rcomm : right_commutative f) (p : l₁ ~ l₂) :
∀ b, foldl f b l₁ = foldl f b l₂ :=
p.foldl_eq' $ λ x hx y hy z, rcomm z x y
theorem perm.foldr_eq {f : α → β → β} {l₁ l₂ : list α} (lcomm : left_commutative f) (p : l₁ ~ l₂) :
∀ b, foldr f b l₁ = foldr f b l₂ :=
perm_induction_on p
(λ b, rfl)
(λ x t₁ t₂ p r b, by simp; rw [r b])
(λ x y t₁ t₂ p r b, by simp; rw [lcomm, r b])
(λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a))
lemma perm.rec_heq {β : list α → Sort*} {f : Πa l, β l → β (a::l)} {b : β []} {l l' : list α}
(hl : perm l l')
(f_congr : ∀{a l l' b b'}, perm l l' → b == b' → f a l b == f a l' b')
(f_swap : ∀{a a' l b}, f a (a'::l) (f a' l b) == f a' (a::l) (f a l b)) :
@list.rec α β b f l == @list.rec α β b f l' :=
begin
induction hl,
case list.perm.nil { refl },
case list.perm.cons : a l l' h ih { exact f_congr h ih },
case list.perm.swap : a a' l { exact f_swap },
case list.perm.trans : l₁ l₂ l₃ h₁ h₂ ih₁ ih₂ { exact heq.trans ih₁ ih₂ }
end
section
variables {op : α → α → α} [is_associative α op] [is_commutative α op]
local notation a * b := op a b
local notation l <*> a := foldl op a l
lemma perm.fold_op_eq {l₁ l₂ : list α} {a : α} (h : l₁ ~ l₂) : l₁ <*> a = l₂ <*> a :=
h.foldl_eq (right_comm _ is_commutative.comm is_associative.assoc) _
end
section comm_monoid
/-- If elements of a list commute with each other, then their product does not
depend on the order of elements-/
@[to_additive]
lemma perm.prod_eq' [monoid α] {l₁ l₂ : list α} (h : l₁ ~ l₂)
(hc : l₁.pairwise (λ x y, x * y = y * x)) :
l₁.prod = l₂.prod :=
h.foldl_eq' (forall_of_forall_of_pairwise (λ x y h z, (h z).symm) (λ x hx z, rfl) $
hc.imp $ λ x y h z, by simp only [mul_assoc, h]) _
variable [comm_monoid α]
@[to_additive]
lemma perm.prod_eq {l₁ l₂ : list α} (h : perm l₁ l₂) : prod l₁ = prod l₂ :=
h.fold_op_eq
@[to_additive]
lemma prod_reverse (l : list α) : prod l.reverse = prod l :=
(reverse_perm l).prod_eq
end comm_monoid
theorem perm_inv_core {a : α} {l₁ l₂ r₁ r₂ : list α} : l₁++a::r₁ ~ l₂++a::r₂ → l₁++r₁ ~ l₂++r₂ :=
begin
generalize e₁ : l₁++a::r₁ = s₁, generalize e₂ : l₂++a::r₂ = s₂,
intro p, revert l₁ l₂ r₁ r₂ e₁ e₂,
refine perm_induction_on p _ (λ x t₁ t₂ p IH, _) (λ x y t₁ t₂ p IH, _)
(λ t₁ t₂ t₃ p₁ p₂ IH₁ IH₂, _); intros l₁ l₂ r₁ r₂ e₁ e₂,
{ apply (not_mem_nil a).elim, rw ← e₁, simp },
{ cases l₁ with y l₁; cases l₂ with z l₂;
dsimp at e₁ e₂; injections; subst x,
{ substs t₁ t₂, exact p },
{ substs z t₁ t₂, exact p.trans perm_middle },
{ substs y t₁ t₂, exact perm_middle.symm.trans p },
{ substs z t₁ t₂, exact (IH rfl rfl).cons y } },
{ rcases l₁ with _|⟨y, _|⟨z, l₁⟩⟩; rcases l₂ with _|⟨u, _|⟨v, l₂⟩⟩;
dsimp at e₁ e₂; injections; substs x y,
{ substs r₁ r₂, exact p.cons a },
{ substs r₁ r₂, exact p.cons u },
{ substs r₁ v t₂, exact (p.trans perm_middle).cons u },
{ substs r₁ r₂, exact p.cons y },
{ substs r₁ r₂ y u, exact p.cons a },
{ substs r₁ u v t₂, exact ((p.trans perm_middle).cons y).trans (swap _ _ _) },
{ substs r₂ z t₁, exact (perm_middle.symm.trans p).cons y },
{ substs r₂ y z t₁, exact (swap _ _ _).trans ((perm_middle.symm.trans p).cons u) },
{ substs u v t₁ t₂, exact (IH rfl rfl).swap' _ _ } },
{ substs t₁ t₃,
have : a ∈ t₂ := p₁.subset (by simp),
rcases mem_split this with ⟨l₂, r₂, e₂⟩,
subst t₂, exact (IH₁ rfl rfl).trans (IH₂ rfl rfl) }
end
theorem perm.cons_inv {a : α} {l₁ l₂ : list α} : a::l₁ ~ a::l₂ → l₁ ~ l₂ :=
@perm_inv_core _ _ [] [] _ _
@[simp] theorem perm_cons (a : α) {l₁ l₂ : list α} : a::l₁ ~ a::l₂ ↔ l₁ ~ l₂ :=
⟨perm.cons_inv, perm.cons a⟩
theorem perm_append_left_iff {l₁ l₂ : list α} : ∀ l, l++l₁ ~ l++l₂ ↔ l₁ ~ l₂
| [] := iff.rfl
| (a::l) := (perm_cons a).trans (perm_append_left_iff l)
theorem perm_append_right_iff {l₁ l₂ : list α} (l) : l₁++l ~ l₂++l ↔ l₁ ~ l₂ :=
⟨λ p, (perm_append_left_iff _).1 $ perm_append_comm.trans $ p.trans perm_append_comm,
perm.append_right _⟩
theorem perm_option_to_list {o₁ o₂ : option α} : o₁.to_list ~ o₂.to_list ↔ o₁ = o₂ :=
begin
refine ⟨λ p, _, λ e, e ▸ perm.refl _⟩,
cases o₁ with a; cases o₂ with b, {refl},
{ cases p.length_eq },
{ cases p.length_eq },
{ exact option.mem_to_list.1 (p.symm.subset $ by simp) }
end
theorem subperm_cons (a : α) {l₁ l₂ : list α} : a::l₁ <+~ a::l₂ ↔ l₁ <+~ l₂ :=
⟨λ ⟨l, p, s⟩, begin
cases s with _ _ _ s' u _ _ s',
{ exact (p.subperm_left.2 $ (sublist_cons _ _).subperm).trans s'.subperm },
{ exact ⟨u, p.cons_inv, s'⟩ }
end, λ ⟨l, p, s⟩, ⟨a::l, p.cons a, s.cons2 _ _ _⟩⟩
theorem cons_subperm_of_mem {a : α} {l₁ l₂ : list α} (d₁ : nodup l₁) (h₁ : a ∉ l₁) (h₂ : a ∈ l₂)
(s : l₁ <+~ l₂) : a :: l₁ <+~ l₂ :=
begin
rcases s with ⟨l, p, s⟩,
induction s generalizing l₁,
case list.sublist.slnil { cases h₂ },
case list.sublist.cons : r₁ r₂ b s' ih {
simp at h₂,
cases h₂ with e m,
{ subst b, exact ⟨a::r₁, p.cons a, s'.cons2 _ _ _⟩ },
{ rcases ih m d₁ h₁ p with ⟨t, p', s'⟩, exact ⟨t, p', s'.cons _ _ _⟩ } },
case list.sublist.cons2 : r₁ r₂ b s' ih {
have bm : b ∈ l₁ := (p.subset $ mem_cons_self _ _),
have am : a ∈ r₂ := h₂.resolve_left (λ e, h₁ $ e.symm ▸ bm),
rcases mem_split bm with ⟨t₁, t₂, rfl⟩,
have st : t₁ ++ t₂ <+ t₁ ++ b :: t₂ := by simp,
rcases ih am (nodup_of_sublist st d₁)
(mt (λ x, st.subset x) h₁)
(perm.cons_inv $ p.trans perm_middle) with ⟨t, p', s'⟩,
exact ⟨b::t, (p'.cons b).trans $ (swap _ _ _).trans (perm_middle.symm.cons a), s'.cons2 _ _ _⟩ }
end
theorem subperm_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+~ l++l₂ ↔ l₁ <+~ l₂
| [] := iff.rfl
| (a::l) := (subperm_cons a).trans (subperm_append_left l)
theorem subperm_append_right {l₁ l₂ : list α} (l) : l₁++l <+~ l₂++l ↔ l₁ <+~ l₂ :=
(perm_append_comm.subperm_left.trans perm_append_comm.subperm_right).trans (subperm_append_left l)
theorem subperm.exists_of_length_lt {l₁ l₂ : list α} :
l₁ <+~ l₂ → length l₁ < length l₂ → ∃ a, a :: l₁ <+~ l₂
| ⟨l, p, s⟩ h :=
suffices length l < length l₂ → ∃ (a : α), a :: l <+~ l₂, from
(this $ p.symm.length_eq ▸ h).imp (λ a, (p.cons a).subperm_right.1),
begin
clear subperm.exists_of_length_lt p h l₁, rename l₂ u,
induction s with l₁ l₂ a s IH _ _ b s IH; intro h,
{ cases h },
{ cases lt_or_eq_of_le (nat.le_of_lt_succ h : length l₁ ≤ length l₂) with h h,
{ exact (IH h).imp (λ a s, s.trans (sublist_cons _ _).subperm) },
{ exact ⟨a, eq_of_sublist_of_length_eq s h ▸ subperm.refl _⟩ } },
{ exact (IH $ nat.lt_of_succ_lt_succ h).imp
(λ a s, (swap _ _ _).subperm_right.1 $ (subperm_cons _).2 s) }
end
theorem subperm_of_subset_nodup
{l₁ l₂ : list α} (d : nodup l₁) (H : l₁ ⊆ l₂) : l₁ <+~ l₂ :=
begin
induction d with a l₁' h d IH,
{ exact ⟨nil, perm.nil, nil_sublist _⟩ },
{ cases forall_mem_cons.1 H with H₁ H₂,
simp at h,
exact cons_subperm_of_mem d h H₁ (IH H₂) }
end
theorem perm_ext {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) :
l₁ ~ l₂ ↔ ∀a, a ∈ l₁ ↔ a ∈ l₂ :=
⟨λ p a, p.mem_iff, λ H, subperm.antisymm
(subperm_of_subset_nodup d₁ (λ a, (H a).1))
(subperm_of_subset_nodup d₂ (λ a, (H a).2))⟩
theorem nodup.sublist_ext {l₁ l₂ l : list α} (d : nodup l)
(s₁ : l₁ <+ l) (s₂ : l₂ <+ l) : l₁ ~ l₂ ↔ l₁ = l₂ :=
⟨λ h, begin
induction s₂ with l₂ l a s₂ IH l₂ l a s₂ IH generalizing l₁,
{ exact h.eq_nil },
{ simp at d,
cases s₁ with _ _ _ s₁ l₁ _ _ s₁,
{ exact IH d.2 s₁ h },
{ apply d.1.elim,
exact subperm.subset ⟨_, h.symm, s₂⟩ (mem_cons_self _ _) } },
{ simp at d,
cases s₁ with _ _ _ s₁ l₁ _ _ s₁,
{ apply d.1.elim,
exact subperm.subset ⟨_, h, s₁⟩ (mem_cons_self _ _) },
{ rw IH d.2 s₁ h.cons_inv } }
end, λ h, by rw h⟩
section
variable [decidable_eq α]
-- attribute [congr]
theorem perm.erase (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) :
l₁.erase a ~ l₂.erase a :=
if h₁ : a ∈ l₁ then
have h₂ : a ∈ l₂, from p.subset h₁,
perm.cons_inv $ (perm_cons_erase h₁).symm.trans $ p.trans (perm_cons_erase h₂)
else
have h₂ : a ∉ l₂, from mt p.mem_iff.2 h₁,
by rw [erase_of_not_mem h₁, erase_of_not_mem h₂]; exact p
theorem subperm_cons_erase (a : α) (l : list α) : l <+~ a :: l.erase a :=
begin
by_cases h : a ∈ l,
{ exact (perm_cons_erase h).subperm },
{ rw [erase_of_not_mem h],
exact (sublist_cons _ _).subperm }
end
theorem erase_subperm (a : α) (l : list α) : l.erase a <+~ l :=
(erase_sublist _ _).subperm
theorem subperm.erase {l₁ l₂ : list α} (a : α) (h : l₁ <+~ l₂) : l₁.erase a <+~ l₂.erase a :=
let ⟨l, hp, hs⟩ := h in ⟨l.erase a, hp.erase _, hs.erase _⟩
theorem perm.diff_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.diff t ~ l₂.diff t :=
by induction t generalizing l₁ l₂ h; simp [*, perm.erase]
theorem perm.diff_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l.diff t₁ = l.diff t₂ :=
by induction h generalizing l; simp [*, perm.erase, erase_comm]
<|> exact (ih_1 _).trans (ih_2 _)
theorem perm.diff {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) :
l₁.diff t₁ ~ l₂.diff t₂ :=
ht.diff_left l₂ ▸ hl.diff_right _
theorem subperm.diff_right {l₁ l₂ : list α} (h : l₁ <+~ l₂) (t : list α) :
l₁.diff t <+~ l₂.diff t :=
by induction t generalizing l₁ l₂ h; simp [*, subperm.erase]
theorem erase_cons_subperm_cons_erase (a b : α) (l : list α) :
(a :: l).erase b <+~ a :: l.erase b :=
begin
by_cases h : a = b,
{ subst b,
rw [erase_cons_head],
apply subperm_cons_erase },
{ rw [erase_cons_tail _ h] }
end
theorem subperm_cons_diff {a : α} : ∀ {l₁ l₂ : list α}, (a :: l₁).diff l₂ <+~ a :: l₁.diff l₂
| l₁ [] := ⟨a::l₁, by simp⟩
| l₁ (b::l₂) :=
begin
simp only [diff_cons],
refine ((erase_cons_subperm_cons_erase a b l₁).diff_right l₂).trans _,
apply subperm_cons_diff
end
theorem subset_cons_diff {a : α} {l₁ l₂ : list α} : (a :: l₁).diff l₂ ⊆ a :: l₁.diff l₂ :=
subperm_cons_diff.subset
theorem perm.bag_inter_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) :
l₁.bag_inter t ~ l₂.bag_inter t :=
begin
induction h with x _ _ _ _ x y _ _ _ _ _ _ ih_1 ih_2 generalizing t, {simp},
{ by_cases x ∈ t; simp [*, perm.cons] },
{ by_cases x = y, {simp [h]},
by_cases xt : x ∈ t; by_cases yt : y ∈ t,
{ simp [xt, yt, mem_erase_of_ne h, mem_erase_of_ne (ne.symm h), erase_comm, swap] },
{ simp [xt, yt, mt mem_of_mem_erase, perm.cons] },
{ simp [xt, yt, mt mem_of_mem_erase, perm.cons] },
{ simp [xt, yt] } },
{ exact (ih_1 _).trans (ih_2 _) }
end
theorem perm.bag_inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) :
l.bag_inter t₁ = l.bag_inter t₂ :=
begin
induction l with a l IH generalizing t₁ t₂ p, {simp},
by_cases a ∈ t₁,
{ simp [h, p.subset h, IH (p.erase _)] },
{ simp [h, mt p.mem_iff.2 h, IH p] }
end
theorem perm.bag_inter {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) :
l₁.bag_inter t₁ ~ l₂.bag_inter t₂ :=
ht.bag_inter_left l₂ ▸ hl.bag_inter_right _
theorem cons_perm_iff_perm_erase {a : α} {l₁ l₂ : list α} : a::l₁ ~ l₂ ↔ a ∈ l₂ ∧ l₁ ~ l₂.erase a :=
⟨λ h, have a ∈ l₂, from h.subset (mem_cons_self a l₁),
⟨this, (h.trans $ perm_cons_erase this).cons_inv⟩,
λ ⟨m, h⟩, (h.cons a).trans (perm_cons_erase m).symm⟩
theorem perm_iff_count {l₁ l₂ : list α} : l₁ ~ l₂ ↔ ∀ a, count a l₁ = count a l₂ :=
⟨perm.count_eq, λ H, begin
induction l₁ with a l₁ IH generalizing l₂,
{ cases l₂ with b l₂, {refl},
specialize H b, simp at H, contradiction },
{ have : a ∈ l₂ := count_pos.1 (by rw ← H; simp; apply nat.succ_pos),
refine ((IH $ λ b, _).cons a).trans (perm_cons_erase this).symm,
specialize H b,
rw (perm_cons_erase this).count_eq at H,
by_cases b = a; simp [h] at H ⊢; assumption }
end⟩
instance decidable_perm : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂)
| [] [] := is_true $ perm.refl _
| [] (b::l₂) := is_false $ λ h, by have := h.nil_eq; contradiction
| (a::l₁) l₂ := by haveI := decidable_perm l₁ (l₂.erase a);
exact decidable_of_iff' _ cons_perm_iff_perm_erase
-- @[congr]
theorem perm.erase_dup {l₁ l₂ : list α} (p : l₁ ~ l₂) :
erase_dup l₁ ~ erase_dup l₂ :=
perm_iff_count.2 $ λ a,
if h : a ∈ l₁
then by simp [nodup_erase_dup, h, p.subset h]
else by simp [h, mt p.mem_iff.2 h]
-- attribute [congr]
theorem perm.insert (a : α)
{l₁ l₂ : list α} (p : l₁ ~ l₂) : insert a l₁ ~ insert a l₂ :=
if h : a ∈ l₁
then by simpa [h, p.subset h] using p
else by simpa [h, mt p.mem_iff.2 h] using p.cons a
theorem perm_insert_swap (x y : α) (l : list α) :
insert x (insert y l) ~ insert y (insert x l) :=
begin
by_cases xl : x ∈ l; by_cases yl : y ∈ l; simp [xl, yl],
by_cases xy : x = y, { simp [xy] },
simp [not_mem_cons_of_ne_of_not_mem xy xl,
not_mem_cons_of_ne_of_not_mem (ne.symm xy) yl],
constructor
end
theorem perm_insert_nth {α} (x : α) (l : list α) {n} (h : n ≤ l.length) :
insert_nth n x l ~ x :: l :=
begin
induction l generalizing n,
{ cases n, refl, cases h },
cases n,
{ simp [insert_nth] },
{ simp only [insert_nth, modify_nth_tail],
transitivity,
{ apply perm.cons, apply l_ih,
apply nat.le_of_succ_le_succ h },
{ apply perm.swap } }
end
theorem perm.union_right {l₁ l₂ : list α} (t₁ : list α) (h : l₁ ~ l₂) : l₁ ∪ t₁ ~ l₂ ∪ t₁ :=
begin
induction h with a _ _ _ ih _ _ _ _ _ _ _ _ ih_1 ih_2; try {simp},
{ exact ih.insert a },
{ apply perm_insert_swap },
{ exact ih_1.trans ih_2 }
end
theorem perm.union_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l ∪ t₁ ~ l ∪ t₂ :=
by induction l; simp [*, perm.insert]
-- @[congr]
theorem perm.union {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∪ t₁ ~ l₂ ∪ t₂ :=
(p₁.union_right t₁).trans (p₂.union_left l₂)
theorem perm.inter_right {l₁ l₂ : list α} (t₁ : list α) : l₁ ~ l₂ → l₁ ∩ t₁ ~ l₂ ∩ t₁ :=
perm.filter _
theorem perm.inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l ∩ t₁ = l ∩ t₂ :=
by { dsimp [(∩), list.inter], congr, funext a, rw [p.mem_iff] }
-- @[congr]
theorem perm.inter {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∩ t₁ ~ l₂ ∩ t₂ :=
p₂.inter_left l₂ ▸ p₁.inter_right t₁
end
theorem perm.pairwise_iff {R : α → α → Prop} (S : symmetric R) :
∀ {l₁ l₂ : list α} (p : l₁ ~ l₂), pairwise R l₁ ↔ pairwise R l₂ :=
suffices ∀ {l₁ l₂}, l₁ ~ l₂ → pairwise R l₁ → pairwise R l₂, from λ l₁ l₂ p, ⟨this p, this p.symm⟩,
λ l₁ l₂ p d, begin
induction d with a l₁ h d IH generalizing l₂,
{ rw ← p.nil_eq, constructor },
{ have : a ∈ l₂ := p.subset (mem_cons_self _ _),
rcases mem_split this with ⟨s₂, t₂, rfl⟩,
have p' := (p.trans perm_middle).cons_inv,
refine (pairwise_middle S).2 (pairwise_cons.2 ⟨λ b m, _, IH _ p'⟩),
exact h _ (p'.symm.subset m) }
end
theorem perm.nodup_iff {l₁ l₂ : list α} : l₁ ~ l₂ → (nodup l₁ ↔ nodup l₂) :=
perm.pairwise_iff $ @ne.symm α
theorem perm.bind_right {l₁ l₂ : list α} (f : α → list β) (p : l₁ ~ l₂) :
l₁.bind f ~ l₂.bind f :=
begin
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ simp, exact IH.append_left _ },
{ simp, rw [← append_assoc, ← append_assoc], exact perm_append_comm.append_right _ },
{ exact IH₁.trans IH₂ }
end
theorem perm.bind_left (l : list α) {f g : α → list β} (h : ∀ a, f a ~ g a) :
l.bind f ~ l.bind g :=
by induction l with a l IH; simp; exact (h a).append IH
theorem perm.product_right {l₁ l₂ : list α} (t₁ : list β) (p : l₁ ~ l₂) :
product l₁ t₁ ~ product l₂ t₁ :=
p.bind_right _
theorem perm.product_left (l : list α) {t₁ t₂ : list β} (p : t₁ ~ t₂) :
product l t₁ ~ product l t₂ :=
perm.bind_left _ $ λ a, p.map _
@[congr] theorem perm.product {l₁ l₂ : list α} {t₁ t₂ : list β}
(p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : product l₁ t₁ ~ product l₂ t₂ :=
(p₁.product_right t₁).trans (p₂.product_left l₂)
theorem sublists_cons_perm_append (a : α) (l : list α) :
sublists (a :: l) ~ sublists l ++ map (cons a) (sublists l) :=
begin
simp only [sublists, sublists_aux_cons_cons, cons_append, perm_cons],
refine (perm.cons _ _).trans perm_middle.symm,
induction sublists_aux l cons with b l IH; simp,
exact (IH.cons _).trans perm_middle.symm
end
theorem sublists_perm_sublists' : ∀ l : list α, sublists l ~ sublists' l
| [] := perm.refl _
| (a::l) := let IH := sublists_perm_sublists' l in
by rw sublists'_cons; exact
(sublists_cons_perm_append _ _).trans (IH.append (IH.map _))
theorem revzip_sublists (l : list α) :
∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists → l₁ ++ l₂ ~ l :=
begin
rw revzip,
apply list.reverse_rec_on l,
{ intros l₁ l₂ h, simp at h, simp [h] },
{ intros l a IH l₁ l₂ h,
rw [sublists_concat, reverse_append, zip_append, ← map_reverse,
zip_map_right, zip_map_left] at h; [skip, {simp}],
simp only [prod.mk.inj_iff, mem_map, mem_append, prod.map_mk, prod.exists] at h,
rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩,
{ rw ← append_assoc,
exact (IH _ _ h).append_right _ },
{ rw append_assoc,
apply (perm_append_comm.append_left _).trans,
rw ← append_assoc,
exact (IH _ _ h).append_right _ } }
end
theorem revzip_sublists' (l : list α) :
∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists' → l₁ ++ l₂ ~ l :=
begin
rw revzip,
induction l with a l IH; intros l₁ l₂ h,
{ simp at h, simp [h] },
{ rw [sublists'_cons, reverse_append, zip_append, ← map_reverse,
zip_map_right, zip_map_left] at h; [simp at h, simp],
rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩,
{ exact perm_middle.trans ((IH _ _ h).cons _) },
{ exact (IH _ _ h).cons _ } }
end
theorem perm_lookmap (f : α → option α) {l₁ l₂ : list α}
(H : pairwise (λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d) l₁)
(p : l₁ ~ l₂) : lookmap f l₁ ~ lookmap f l₂ :=
begin
let F := λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d,
change pairwise F l₁ at H,
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ cases h : f a,
{ simp [h], exact IH (pairwise_cons.1 H).2 },
{ simp [lookmap_cons_some _ _ h, p] } },
{ cases h₁ : f a with c; cases h₂ : f b with d,
{ simp [h₁, h₂], apply swap },
{ simp [h₁, lookmap_cons_some _ _ h₂], apply swap },
{ simp [lookmap_cons_some _ _ h₁, h₂], apply swap },
{ simp [lookmap_cons_some _ _ h₁, lookmap_cons_some _ _ h₂],
rcases (pairwise_cons.1 H).1 _ (or.inl rfl) _ h₂ _ h₁ with ⟨rfl, rfl⟩,
refl } },
{ refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)),
exact λ a b h c h₁ d h₂, (h d h₂ c h₁).imp eq.symm eq.symm }
end
theorem perm.erasep (f : α → Prop) [decidable_pred f] {l₁ l₂ : list α}
(H : pairwise (λ a b, f a → f b → false) l₁)
(p : l₁ ~ l₂) : erasep f l₁ ~ erasep f l₂ :=
begin
let F := λ a b, f a → f b → false,
change pairwise F l₁ at H,
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ by_cases h : f a,
{ simp [h, p] },
{ simp [h], exact IH (pairwise_cons.1 H).2 } },
{ by_cases h₁ : f a; by_cases h₂ : f b; simp [h₁, h₂],
{ cases (pairwise_cons.1 H).1 _ (or.inl rfl) h₂ h₁ },
{ apply swap } },
{ refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)),
exact λ a b h h₁ h₂, h h₂ h₁ }
end
/- enumerating permutations -/
section permutations
theorem permutations_aux2_fst (t : α) (ts : list α) (r : list β) : ∀ (ys : list α) (f : list α → β),
(permutations_aux2 t ts r ys f).1 = ys ++ ts
| [] f := rfl
| (y::ys) f := match _, permutations_aux2_fst ys _ : ∀ o : list α × list β, o.1 = ys ++ ts →
(permutations_aux2._match_1 t y f o).1 = y :: ys ++ ts with
| ⟨_, zs⟩, rfl := rfl
end
@[simp] theorem permutations_aux2_snd_nil (t : α) (ts : list α) (r : list β) (f : list α → β) :
(permutations_aux2 t ts r [] f).2 = r := rfl
@[simp] theorem permutations_aux2_snd_cons (t : α) (ts : list α) (r : list β) (y : α) (ys : list α)
(f : list α → β) :
(permutations_aux2 t ts r (y::ys) f).2 = f (t :: y :: ys ++ ts) ::
(permutations_aux2 t ts r ys (λx : list α, f (y::x))).2 :=
match _, permutations_aux2_fst t ts r _ _ : ∀ o : list α × list β, o.1 = ys ++ ts →
(permutations_aux2._match_1 t y f o).2 = f (t :: y :: ys ++ ts) :: o.2 with
| ⟨_, zs⟩, rfl := rfl
end
theorem permutations_aux2_append (t : α) (ts : list α) (r : list β) (ys : list α) (f : list α → β) :
(permutations_aux2 t ts nil ys f).2 ++ r = (permutations_aux2 t ts r ys f).2 :=
by induction ys generalizing f; simp *
theorem mem_permutations_aux2 {t : α} {ts : list α} {ys : list α} {l l' : list α} :
l' ∈ (permutations_aux2 t ts [] ys (append l)).2 ↔
∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l' = l ++ l₁ ++ t :: l₂ ++ ts :=
begin
induction ys with y ys ih generalizing l,
{ simp {contextual := tt} },
{ rw [permutations_aux2_snd_cons, show (λ (x : list α), l ++ y :: x) = append (l ++ [y]),
by funext; simp, mem_cons_iff, ih], split; intro h,
{ rcases h with e | ⟨l₁, l₂, l0, ye, _⟩,
{ subst l', exact ⟨[], y::ys, by simp⟩ },
{ substs l' ys, exact ⟨y::l₁, l₂, l0, by simp⟩ } },
{ rcases h with ⟨_ | ⟨y', l₁⟩, l₂, l0, ye, rfl⟩,
{ simp [ye] },
{ simp at ye, rcases ye with ⟨rfl, rfl⟩,
exact or.inr ⟨l₁, l₂, l0, by simp⟩ } } }
end
theorem mem_permutations_aux2' {t : α} {ts : list α} {ys : list α} {l : list α} :
l ∈ (permutations_aux2 t ts [] ys id).2 ↔
∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l = l₁ ++ t :: l₂ ++ ts :=
by rw [show @id (list α) = append nil, by funext; refl]; apply mem_permutations_aux2
theorem length_permutations_aux2 (t : α) (ts : list α) (ys : list α) (f : list α → β) :
length (permutations_aux2 t ts [] ys f).2 = length ys :=
by induction ys generalizing f; simp *
theorem foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) :
foldr (λy r, (permutations_aux2 t ts r y id).2) r L =
L.bind (λ y, (permutations_aux2 t ts [] y id).2) ++ r :=
by induction L with l L ih; [refl, {simp [ih], rw ← permutations_aux2_append}]
theorem mem_foldr_permutations_aux2 {t : α} {ts : list α} {r L : list (list α)} {l' : list α} :
l' ∈ foldr (λy r, (permutations_aux2 t ts r y id).2) r L ↔ l' ∈ r ∨
∃ l₁ l₂, l₁ ++ l₂ ∈ L ∧ l₂ ≠ [] ∧ l' = l₁ ++ t :: l₂ ++ ts :=
have (∃ (a : list α), a ∈ L ∧
∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ a = l₁ ++ l₂ ∧ l' = l₁ ++ t :: (l₂ ++ ts)) ↔
∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ l₁ ++ l₂ ∈ L ∧ l' = l₁ ++ t :: (l₂ ++ ts),
from ⟨λ ⟨a, aL, l₁, l₂, l0, e, h⟩, ⟨l₁, l₂, l0, e ▸ aL, h⟩,
λ ⟨l₁, l₂, l0, aL, h⟩, ⟨_, aL, l₁, l₂, l0, rfl, h⟩⟩,
by rw foldr_permutations_aux2; simp [mem_permutations_aux2', this,
or.comm, or.left_comm, or.assoc, and.comm, and.left_comm, and.assoc]
theorem length_foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) :
length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = sum (map length L) + length r :=
by simp [foldr_permutations_aux2, (∘), length_permutations_aux2]
theorem length_foldr_permutations_aux2' (t : α) (ts : list α) (r L : list (list α))
(n) (H : ∀ l ∈ L, length l = n) :
length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = n * length L + length r :=
begin
rw [length_foldr_permutations_aux2, (_ : sum (map length L) = n * length L)],
induction L with l L ih, {simp},
have sum_map : sum (map length L) = n * length L :=
ih (λ l m, H l (mem_cons_of_mem _ m)),
have length_l : length l = n := H _ (mem_cons_self _ _),
simp [sum_map, length_l, mul_add, add_comm]
end
theorem perm_of_mem_permutations_aux :
∀ {ts is l : list α}, l ∈ permutations_aux ts is → l ~ ts ++ is :=
begin
refine permutations_aux.rec (by simp) _,
introv IH1 IH2 m,
rw [permutations_aux_cons, permutations, mem_foldr_permutations_aux2] at m,
rcases m with m | ⟨l₁, l₂, m, _, e⟩,
{ exact (IH1 m).trans perm_middle },
{ subst e,
have p : l₁ ++ l₂ ~ is,
{ simp [permutations] at m,
cases m with e m, {simp [e]},
exact is.append_nil ▸ IH2 m },
exact ((perm_middle.trans (p.cons _)).append_right _).trans (perm_append_comm.cons _) }
end
theorem perm_of_mem_permutations {l₁ l₂ : list α}
(h : l₁ ∈ permutations l₂) : l₁ ~ l₂ :=
(eq_or_mem_of_mem_cons h).elim (λ e, e ▸ perm.refl _)
(λ m, append_nil l₂ ▸ perm_of_mem_permutations_aux m)
theorem length_permutations_aux : ∀ ts is : list α,
length (permutations_aux ts is) + is.length.fact = (length ts + length is).fact :=
begin
refine permutations_aux.rec (by simp) _,
intros t ts is IH1 IH2,
have IH2 : length (permutations_aux is nil) + 1 = is.length.fact,
{ simpa using IH2 },
simp [-add_comm, nat.fact, nat.add_succ, mul_comm] at IH1,
rw [permutations_aux_cons,
length_foldr_permutations_aux2' _ _ _ _ _
(λ l m, (perm_of_mem_permutations m).length_eq),
permutations, length, length, IH2,
nat.succ_add, nat.fact_succ, mul_comm (nat.succ _), ← IH1,
add_comm (_*_), add_assoc, nat.mul_succ, mul_comm]
end
theorem length_permutations (l : list α) : length (permutations l) = (length l).fact :=
length_permutations_aux l []
theorem mem_permutations_of_perm_lemma {is l : list α}
(H : l ~ [] ++ is → (∃ ts' ~ [], l = ts' ++ is) ∨ l ∈ permutations_aux is [])
: l ~ is → l ∈ permutations is :=
by simpa [permutations, perm_nil] using H
theorem mem_permutations_aux_of_perm :
∀ {ts is l : list α}, l ~ is ++ ts → (∃ is' ~ is, l = is' ++ ts) ∨ l ∈ permutations_aux ts is :=
begin
refine permutations_aux.rec (by simp) _,
intros t ts is IH1 IH2 l p,
rw [permutations_aux_cons, mem_foldr_permutations_aux2],
rcases IH1 (p.trans perm_middle) with ⟨is', p', e⟩ | m,
{ clear p, subst e,
rcases mem_split (p'.symm.subset (mem_cons_self _ _)) with ⟨l₁, l₂, e⟩,
subst is',
have p := (perm_middle.symm.trans p').cons_inv,
cases l₂ with a l₂',
{ exact or.inl ⟨l₁, by simpa using p⟩ },
{ exact or.inr (or.inr ⟨l₁, a::l₂',
mem_permutations_of_perm_lemma IH2 p, by simp⟩) } },
{ exact or.inr (or.inl m) }
end
@[simp] theorem mem_permutations (s t : list α) : s ∈ permutations t ↔ s ~ t :=
⟨perm_of_mem_permutations, mem_permutations_of_perm_lemma mem_permutations_aux_of_perm⟩
end permutations
end list
|
a0c1c241efbbb627ba9712e52a095ecfea2b9d92 | cdd15b3bb33b8e58e7dc799c73d41f131dea7dc1 | /towers.lean | 03ba38a24f30a566482bc7e01687d39ccc0a813a | [] | no_license | marcusklaas/tower-of-hanoi | 0018a9ef39b94b2848b356067ac6c4298b4953ce | 9b03acb4ea02b584079147f2f2574f9399d3c662 | refs/heads/master | 1,633,710,072,558 | 1,544,799,004,000 | 1,544,799,004,000 | 115,736,638 | 2 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 11,276 | lean |
import data.vector
variables {n : ℕ} {α : Type}
inductive column
| left : column
| middle : column
| right : column
-- TODO: apparently arrays could be very natural in this situation
-- okay so we encode valid states as fixed length sequences
def validstate (n : ℕ) := vector column n
lemma update_preserve_length {a : α} (l : list α) :
∀ i, list.length l = list.length (list.update_nth l i a) :=
begin
induction l; intro i; cases i; simp [list.update_nth, list.length]; rw l_ih i
end
def vector.update_nth : vector α n → fin n → α → vector α n
| v i a := ⟨ list.update_nth v.val i.val a, by { rw ←(update_preserve_length v.val), exact v.property } ⟩
def zero_fin (n : ℕ) : fin (nat.succ n) := ⟨0, dec_trivial⟩
lemma update_nth_helper (v : vector α n) (i : fin n) (a b : α)
: vector.cons b (vector.update_nth v i a) = vector.update_nth (vector.cons b v) (fin.succ i) a :=
begin
cases v,
cases i,
refl
end
lemma vector_nth_helper (v : vector α n) (i : fin n) (a : α)
: vector.nth (vector.cons a v) (fin.succ i) = vector.nth v i :=
begin
cases i,
cases v,
cases n,
cases i_is_lt,
refl
end
def movestone (s : validstate n) (i : fin n) (dest : column)
(valid_move: ∀j, j > i → vector.nth s j ≠ dest ∧ vector.nth s j ≠ vector.nth s i) : validstate n :=
vector.update_nth s i dest
/-- `refl_trans r`: relexive and transitive closure of `r` -/
inductive refl_trans {α : Sort*} (r : α → α → Prop) (a : α) : α → Prop
| refl {} : refl_trans a
| tail {b c} : refl_trans b → r b c → refl_trans c
def one_step : validstate n → validstate n → Prop
| s1 s2 := ∃ (i : fin n) (dest : column) pf, s2 = movestone s1 i dest pf
def multi_step : validstate n → validstate n → Prop := refl_trans one_step
lemma vector.eq_iff {n} {a b : vector α n} : a = b ↔ a.1 = b.1 :=
begin
cases a; cases b,
split,
{ intro h, exact congr_arg subtype.val h },
{ apply vector.eq }
end
lemma update_with_self (l : list α) (i : ℕ) (h : i < list.length l) :
l = list.update_nth l i (list.nth_le l i h) :=
begin
induction l generalizing i,
cases h,
cases i; simp [list.update_nth],
apply l_ih
end
lemma conseq_updates (l : list α) (a b : α) (i : ℕ) :
list.update_nth (list.update_nth l i a) i b = list.update_nth l i b :=
begin
induction l generalizing i,
refl,
cases i; simp [list.update_nth],
apply l_ih
end
lemma update_reversibility (i : fin n) (a : column) (s1 s2 : validstate n) (h : s1 = vector.update_nth s2 i a) :
s2 = vector.update_nth s1 i (vector.nth s2 i) :=
begin
apply vector.eq,
change s2.val = list.update_nth s1.val (i.val) (vector.nth s2 i),
cases s2,
cases s1,
cases i,
induction s1_val generalizing i_val s2_val n,
{
rw [←s1_property] at i_is_lt,
cases i_is_lt,
},
{
have yolo := (iff.elim_left vector.eq_iff) h,
simp [vector.update_nth] at yolo,
simp [vector.nth, yolo, conseq_updates],
exact update_with_self _ _ _
}
end
lemma fin_pred (j : fin (nat.succ n)) (k : fin n) (h : j > fin.succ k)
: ∃ (i : fin n), fin.succ i = j ∧ i > k :=
begin
cases j,
cases j_val,
cases h,
cases k,
exact ⟨ ⟨ j_val, nat.lt_of_succ_lt_succ j_is_lt ⟩, ⟨ rfl, nat.lt_of_succ_lt_succ h ⟩ ⟩
end
-- this h₃ we can actually construct from the arguments, but oh well
lemma list_jth_after_update_i (l : list α) (i j : ℕ) (a : α) (h₁ : j < list.length l) (h₃ : j < list.length (list.update_nth l i a)) (h₂ : i < j) :
list.nth_le (list.update_nth l i a) j h₃ = list.nth_le l j h₁ :=
begin
induction l generalizing i j,
cases h₁,
cases i; cases j,
cases h₂,
simp [list.update_nth],
cases h₂,
exact l_ih _ _ _ _ (nat.lt_of_succ_lt_succ h₂)
end
lemma jth_after_update_i (i j : fin n) (a : column) (s : validstate n) (h : i < j) :
vector.nth (vector.update_nth s i a) j = vector.nth s j :=
begin
cases s,
exact list_jth_after_update_i _ _ _ _ _ _ h
end
lemma ith_after_update_i (i : fin n) (a : column) (s : validstate n)
: vector.nth (vector.update_nth s i a) i = a :=
begin
cases i,
cases s,
induction s_val generalizing n i_val,
{
rw ←s_property at i_is_lt,
cases i_is_lt,
},
{
cases n,
cases i_is_lt,
cases i_val,
refl,
apply s_val_ih _ (nat.lt_of_succ_lt_succ i_is_lt) (nat.add_right_cancel s_property)
}
end
lemma one_step_symm {s1 s2 : validstate n} (h: one_step s1 s2) : one_step s2 s1 :=
begin
cases h,
cases h_h,
cases h_h_h,
cases n,
{
cases h_w,
cases h_w_is_lt,
},
rw movestone at h_h_h_h,
apply exists.intro h_w,
apply exists.intro (vector.nth s1 h_w),
apply exists.intro _,
exact update_reversibility _ _ _ _ h_h_h_h,
intros j hj,
rw [h_h_h_h, jth_after_update_i _ _ _ _ hj, ith_after_update_i],
exact and.swap (h_h_h_w j hj)
end
lemma multi_step_transitive {a b c : validstate n} (hab : multi_step a b) (hbc : multi_step b c) : multi_step a c :=
begin
induction hbc,
assumption,
exact hbc_ih.tail hbc_a_1
end
lemma multi_step_symmetric {a b : validstate n} (hab : multi_step a b) : multi_step b a :=
begin
induction hab,
exact refl_trans.refl,
exact multi_step_transitive (refl_trans.tail refl_trans.refl (one_step_symm hab_a_1)) hab_ih
end
-- picks an unused column
def third_column : column → column → column
| column.left column.right := column.middle
| column.right column.left := column.middle
| column.left _ := column.right
| column.right _ := column.left
| column.middle column.left := column.right
| column.middle _ := column.left
lemma third_column_unused : ∀ c1 c2, third_column c1 c2 ≠ c1 ∧ third_column c1 c2 ≠ c2 :=
begin
intros c1 c2,
cases c1;
cases c2;
simp [third_column],
end
lemma equiv_cons (s1 s2 : validstate n) (a : column) (h : multi_step s1 s2)
: multi_step (vector.cons a s1) (vector.cons a s2) :=
begin
induction h,
exact refl_trans.refl,
apply refl_trans.tail h_ih,
cases h_a_1,
cases h_a_1_h,
cases h_a_1_h_h,
rw one_step,
apply exists.intro (fin.succ h_a_1_w),
apply exists.intro h_a_1_h_w,
apply exists.intro _,
{
rw h_a_1_h_h_h,
apply update_nth_helper
},
{
-- repackage IH pf
intros j h2,
cases fin_pred j h_a_1_w h2,
rw [vector_nth_helper, ←h.left, vector_nth_helper],
exact (h_a_1_h_h_w w h.right)
}
end
lemma nth_of_list_repeat (a : α) (i n : ℕ) (h : i < list.length (list.repeat a n))
: list.nth_le (list.repeat a n) i h = a :=
begin
induction i generalizing n;
{
cases n,
cases h,
simp *,
}
end
lemma nth_of_repeat (i : fin n) (a : α)
: vector.nth (vector.repeat a n) i = a :=
begin
cases i,
cases n,
cases i_is_lt,
cases i_val,
refl,
simp [vector.repeat, vector.nth],
have i_lt_n := nat.lt_of_succ_lt_succ i_is_lt,
have len_repeat_n : n = list.length (list.repeat a n) := by simp *,
rw len_repeat_n at i_lt_n,
exact nth_of_list_repeat a i_val n i_lt_n
end
lemma zeroth_of_cons (a : α) (v : vector α n)
: vector.nth (vector.cons a v) ⟨0, dec_trivial⟩ = a :=
begin
cases v,
refl
end
lemma all_states_equiv (s1 s2 : validstate n) : multi_step s1 s2 :=
begin
induction n,
{
have s1_eq_s2 : s1 = s2 := begin
cases s1,
cases s2,
cases s1_val,
{
cases s2_val,
refl,
cases s2_property,
},
cases s1_property,
end,
rw s1_eq_s2,
exact refl_trans.refl
},
{
-- IDEA:
-- s1 : [x0, x1, ..., x(n-1)],
-- s2 : [y0, y1, ..., y(n-1)],
-- let z = third_column x0 y0
-- by induction hypothesis:
-- [x1, ..., x(n-1)] ~ [z, ..., z]
-- [y1, ..., y(n-1)] ~ [z, ..., z]
-- then by prefix lemma,
-- s1 ~ [x0, z, ..., z]
-- s2 ~ [y0, z, ..., z]
-- and we can go from [x0, z, ..., z] to [y0, z, ..., z] in one step
-- since ~ (multi_step) is an equivalence (trans, symm), s1 ~ s2
cases s1,
cases s1_val,
cases s1_property,
cases s2,
cases s2_val,
cases s2_property,
-- z = third_column s1_val_hd s2_val_hd
-- s1 ~ [x0, z, ..., z]
have proppp1 : list.length s1_val_tl = n_n := begin
cases s1_property,
refl
end,
-- FIXME: this is a mess lol
have s1_equiv_s10zzz : multi_step ⟨s1_val_hd :: s1_val_tl, s1_property⟩ (vector.cons s1_val_hd (vector.repeat (third_column s1_val_hd s2_val_hd) n_n)) :=
begin
have yolo : (vector.cons s1_val_hd ⟨s1_val_tl, proppp1⟩) = ⟨s1_val_hd :: s1_val_tl, s1_property⟩ := rfl,
rw ←yolo,
apply equiv_cons,
apply n_ih,
end,
-- s2 ~ [y0, z, ..., z]
have proppp2 : list.length s2_val_tl = n_n := begin
cases s2_property,
refl
end,
have s2_equiv_s20zzz : multi_step ⟨s2_val_hd :: s2_val_tl, s2_property⟩ (vector.cons s2_val_hd (vector.repeat (third_column s1_val_hd s2_val_hd) n_n)) :=
begin
have yolo : (vector.cons s2_val_hd ⟨s2_val_tl, proppp2⟩) = ⟨s2_val_hd :: s2_val_tl, s2_property⟩ := rfl,
rw ←yolo,
apply equiv_cons,
apply n_ih,
end,
have small_step : one_step (vector.cons s1_val_hd (vector.repeat (third_column s1_val_hd s2_val_hd) n_n))
(vector.cons s2_val_hd (vector.repeat (third_column s1_val_hd s2_val_hd) n_n)) :=
begin
apply exists.intro (zero_fin n_n),
{
apply exists.intro s2_val_hd,
apply exists.intro,
refl,
intros j h,
cases j,
cases j_val,
cases h,
apply and.intro,
{
rw ←fin.succ,
{
rw [vector_nth_helper, nth_of_repeat],
exact (third_column_unused _ _).right
},
exact nat.lt_of_succ_lt_succ j_is_lt
},
{
rw ←fin.succ,
{
rw [vector_nth_helper, zero_fin, nth_of_repeat, zeroth_of_cons],
exact (third_column_unused _ _).left
},
exact nat.lt_of_succ_lt_succ j_is_lt
}
}
end,
exact multi_step_transitive (refl_trans.tail s1_equiv_s10zzz small_step) (multi_step_symmetric s2_equiv_s20zzz)
}
end
theorem towers_hanoi_solvable : ∀ n : ℕ, multi_step (vector.repeat column.left n) (vector.repeat column.right n) :=
λ n, all_states_equiv (vector.repeat column.left n) (vector.repeat column.right n)
|
6f7c91869a4b16477a39365b0f37bd6c8aabebf0 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/fintype/card.lean | 90fba901adb0cd94db695e9ca829305f50bbaaec | [
"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 | 16,159 | 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 algebra.big_operators.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
@[to_additive]
lemma prod_bool [comm_monoid α] (f : bool → α) : ∏ b, f b = f tt * f ff := by simp
lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = ∑ a : α, 1 :=
finset.card_eq_sum_ones _
section
open finset
variables {ι : Type*} [decidable_eq ι] [fintype ι]
@[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]
/-- If a product of a `finset` of a subsingleton type has a given
value, so do the terms in that product. -/
@[to_additive "If a sum of a `finset` of a subsingleton type has a given
value, so do the terms in that sum."]
lemma eq_of_subsingleton_of_prod_eq {ι : Type*} [subsingleton ι] {s : finset ι}
{f : ι → M} {b : M} (h : ∏ i in s, f i = b) : ∀ i ∈ s, f i = b :=
finset.eq_of_card_le_one_of_prod_eq (finset.card_le_one_of_subsingleton s) h
end
end fintype
open finset
@[to_additive]
theorem fin.prod_univ_def [comm_monoid β] {n : ℕ} (f : fin n → β) :
∏ i, f i = ((list.fin_range n).map f).prod :=
by simp [fin.univ_def, finset.fin_range]
@[to_additive]
theorem fin.prod_of_fn [comm_monoid β] {n : ℕ} (f : fin n → β) :
(list.of_fn f).prod = ∏ i, f i :=
by rw [list.of_fn_eq_map, fin.prod_univ_def]
/-- A product of a function `f : fin 0 → β` is `1` because `fin 0` is empty -/
@[simp, to_additive "A sum of a function `f : fin 0 → β` is `0` because `fin 0` is empty"]
theorem fin.prod_univ_zero [comm_monoid β] (f : fin 0 → β) : ∏ i, f i = 1 := rfl
/-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the product of `f x`, for some `x : fin (n + 1)` times the remaining product -/
theorem fin.prod_univ_succ_above [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) (x : fin (n + 1)) :
∏ i, f i = f x * ∏ i : fin n, f (x.succ_above i) :=
begin
rw [fin.univ_succ_above, finset.prod_insert, finset.prod_image],
{ intros x _ y _ hxy, exact fin.succ_above_right_inj.mp hxy },
{ simp [fin.succ_above_ne] }
end
/-- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the sum of `f x`, for some `x : fin (n + 1)` plus the remaining product -/
theorem fin.sum_univ_succ_above [add_comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) (x : fin (n + 1)) :
∑ i, f i = f x + ∑ i : fin n, f (x.succ_above i) :=
by apply @fin.prod_univ_succ_above (multiplicative β)
attribute [to_additive] fin.prod_univ_succ_above
/-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the product of `f 0` plus the remaining product -/
theorem fin.prod_univ_succ [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) :
∏ i, f i = f 0 * ∏ i : fin n, f i.succ :=
fin.prod_univ_succ_above f 0
/-- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the sum of `f 0` plus the remaining product -/
theorem fin.sum_univ_succ [add_comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) :
∑ i, f i = f 0 + ∑ i : fin n, f i.succ :=
fin.sum_univ_succ_above f 0
attribute [to_additive] fin.prod_univ_succ
/-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the product of `f (fin.last n)` plus the remaining product -/
theorem fin.prod_univ_cast_succ [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) :
∏ i, f i = (∏ i : fin n, f i.cast_succ) * f (fin.last n) :=
by simpa [mul_comm] using fin.prod_univ_succ_above f (fin.last n)
/-- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)`
is the sum of `f (fin.last n)` plus the remaining sum -/
theorem fin.sum_univ_cast_succ [add_comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) :
∑ i, f i = ∑ 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 β) = ∑ 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 finset.card_pi [decidable_eq α] {δ : α → Type*}
(s : finset α) (t : Π a, finset (δ a)) :
(s.pi t).card = ∏ a in s, card (t a) :=
multiset.card_pi _ _
@[simp] lemma fintype.card_pi_finset [decidable_eq α] [fintype α]
{δ : α → Type*} (t : Π a, finset (δ a)) :
(fintype.pi_finset t).card = ∏ a, card (t a) :=
by simp [fintype.pi_finset, card_map]
@[simp] lemma fintype.card_pi {β : α → Type*} [decidable_eq α] [fintype α]
[f : Π a, fintype (β a)] : fintype.card (Π a, β a) = ∏ a, fintype.card (β a) :=
fintype.card_pi_finset _
-- FIXME ouch, this should be in the main file.
@[simp] lemma fintype.card_fun [decidable_eq α] [fintype α] [fintype β] :
fintype.card (α → β) = fintype.card β ^ fintype.card α :=
by rw [fintype.card_pi, finset.prod_const]; 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 α _} → β) :
∏ x in univ.attach, f x = ∏ x, f ⟨x, (mem_univ _)⟩ :=
prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩)
/-- 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) → β) :
∏ x in univ.pi t, f x = ∏ x in fintype.pi_finset t, 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 → β} :
∏ a, ∑ b in t a, f a b = ∑ p in fintype.pi_finset t, ∏ 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) :
∑ 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) :
∑ 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
@[to_additive]
lemma equiv.prod_comp [fintype α] [fintype β] [comm_monoid γ] (e : α ≃ β) (f : β → γ) :
∏ i, f (e i) = ∏ i, f i :=
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
/-- 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 : ℕ) :
∏ i : fin n, f i = ∏ i in range n, f i :=
calc (∏ i : fin n, f i) = ∏ i : {x // x ∈ range n}, f i :
((equiv.fin_equiv_subtype n).trans
(equiv.subtype_congr_right (λ _, mem_range.symm))).prod_comp (f ∘ coe)
... = ∏ i in range n, f i : by rw [← attach_eq_univ, prod_attach]
@[to_additive]
lemma finset.prod_fin_eq_prod_range [comm_monoid β] {n : ℕ} (c : fin n → β) :
∏ i, c i = ∏ i in finset.range n, if h : i < n then c ⟨i, h⟩ else 1 :=
begin
rw [← fin.prod_univ_eq_prod_range, finset.prod_congr rfl],
rintros ⟨i, hi⟩ _,
simp only [fin.coe_eq_val, hi, dif_pos]
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, attach_eq_univ],
substI p,
congr
end
@[to_additive] lemma finset.prod_fiberwise [decidable_eq β] [fintype β] [comm_monoid γ]
(s : finset α) (f : α → β) (g : α → γ) :
∏ b : β, ∏ a in s.filter (λ a, f a = b), g a = ∏ a in s, g a :=
finset.prod_fiberwise_of_maps_to (λ x _, mem_univ _) _
@[to_additive]
lemma fintype.prod_fiberwise [fintype α] [decidable_eq β] [fintype β] [comm_monoid γ]
(f : α → β) (g : α → γ) :
(∏ b : β, ∏ a : {a // f a = b}, g (a : α)) = ∏ a, g a :=
begin
rw [← (equiv.sigma_preimage_equiv f).prod_comp, ← univ_sigma_univ, prod_sigma],
refl
end
lemma fintype.prod_dite [fintype α] {p : α → Prop} [decidable_pred p]
[comm_monoid β] (f : Π (a : α) (ha : p a), β) (g : Π (a : α) (ha : ¬p a), β) :
(∏ a, dite (p a) (f a) (g a)) = (∏ a : {a // p a}, f a a.2) * (∏ a : {a // ¬p a}, g a a.2) :=
begin
simp only [prod_dite, attach_eq_univ],
congr' 1,
{ convert (equiv.subtype_congr_right _).prod_comp (λ x : {x // p x}, f x x.2),
simp },
{ convert (equiv.subtype_congr_right _).prod_comp (λ x : {x // ¬p x}, g x x.2),
simp }
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_iff, 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 = ∏ j in finset.univ.filter (λ (j : fin n), j.val < i), f j :=
begin
have A : ∀ (j : fin n), ¬ ((j : ℕ) < 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 : ℕ) < i.succ) = ((j : ℕ) < i),
{ assume j,
have : (j : ℕ) < 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.
-- Use `multiplicative` instead.
lemma sum_take_of_fn [add_comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) :
((of_fn f).take i).sum = ∑ j in finset.univ.filter (λ (j : fin n), j.val < i), f j :=
@prod_take_of_fn (multiplicative α) _ n f i
attribute [to_additive] prod_take_of_fn
@[to_additive]
lemma prod_of_fn [comm_monoid α] {n : ℕ} {f : fin n → α} :
(of_fn f).prod = ∏ i, f i :=
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 : ℕ) < n := λ j, j.is_lt,
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.is_lt
| [] := 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
|
8d75d5ee488995059fbcd409a1ab9cc4820f3e94 | bb31430994044506fa42fd667e2d556327e18dfe | /src/category_theory/category/basic.lean | 02f3ac93913f65ad1a54910e4257089b3c8e6014 | [
"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 | 11,052 | 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, Reid Barton
-/
import combinatorics.quiver.basic
/-!
# Categories
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Defines a category, as a type class parametrised by the type of objects.
## Notations
Introduces notations
* `X ⟶ Y` for the morphism spaces (type as `\hom`),
* `𝟙 X` for the identity morphism on `X` (type as `\b1`),
* `f ≫ g` for composition in the 'arrows' convention (type as `\gg`).
Users may like to add `f ⊚ g` for composition in the standard convention, using
```lean
local notation f ` ⊚ `:80 g:80 := category.comp g f -- type as \oo
```
-/
/--
The typeclass `category C` describes morphisms associated to objects of type `C : Type u`.
The universe levels of the objects and morphisms are independent, and will often need to be
specified explicitly, as `category.{v} C`.
Typically any concrete example will either be a `small_category`, where `v = u`,
which can be introduced as
```
universes u
variables {C : Type u} [small_category C]
```
or a `large_category`, where `u = v+1`, which can be introduced as
```
universes u
variables {C : Type (u+1)} [large_category C]
```
In order for the library to handle these cases uniformly,
we generally work with the unconstrained `category.{v u}`,
for which objects live in `Type u` and morphisms live in `Type v`.
Because the universe parameter `u` for the objects can be inferred from `C`
when we write `category C`, while the universe parameter `v` for the morphisms
can not be automatically inferred, through the category theory library
we introduce universe parameters with morphism levels listed first,
as in
```
universes v u
```
or
```
universes v₁ v₂ u₁ u₂
```
when multiple independent universes are needed.
This has the effect that we can simply write `category.{v} C`
(that is, only specifying a single parameter) while `u` will be inferred.
Often, however, it's not even necessary to include the `.{v}`.
(Although it was in earlier versions of Lean.)
If it is omitted a "free" universe will be used.
-/
library_note "category_theory universes"
universes v u
namespace category_theory
/-- A preliminary structure on the way to defining a category,
containing the data, but none of the axioms. -/
class category_struct (obj : Type u)
extends quiver.{v+1} obj : Type (max u (v+1)) :=
(id : Π X : obj, hom X X)
(comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z))
notation `𝟙` := category_struct.id -- type as \b1
infixr ` ≫ `:80 := category_struct.comp -- type as \gg
/--
The typeclass `category C` describes morphisms associated to objects of type `C`.
The universe levels of the objects and morphisms are unconstrained, and will often need to be
specified explicitly, as `category.{v} C`. (See also `large_category` and `small_category`.)
See <https://stacks.math.columbia.edu/tag/0014>.
-/
class category (obj : Type u)
extends category_struct.{v} obj : Type (max u (v+1)) :=
(id_comp' : ∀ {X Y : obj} (f : hom X Y), 𝟙 X ≫ f = f . obviously)
(comp_id' : ∀ {X Y : obj} (f : hom X Y), f ≫ 𝟙 Y = f . obviously)
(assoc' : ∀ {W X Y Z : obj} (f : hom W X) (g : hom X Y) (h : hom Y Z),
(f ≫ g) ≫ h = f ≫ (g ≫ h) . obviously)
-- `restate_axiom` is a command that creates a lemma from a structure field,
-- discarding any auto_param wrappers from the type.
-- (It removes a backtick from the name, if it finds one, and otherwise adds "_lemma".)
restate_axiom category.id_comp'
restate_axiom category.comp_id'
restate_axiom category.assoc'
attribute [simp] category.id_comp category.comp_id category.assoc
attribute [trans] category_struct.comp
/--
A `large_category` has objects in one universe level higher than the universe level of
the morphisms. It is useful for examples such as the category of types, or the category
of groups, etc.
-/
abbreviation large_category (C : Type (u+1)) : Type (u+1) := category.{u} C
/--
A `small_category` has objects and morphisms in the same universe level.
-/
abbreviation small_category (C : Type u) : Type (u+1) := category.{u} C
section
variables {C : Type u} [category.{v} C] {X Y Z : C}
initialize_simps_projections category (to_category_struct_to_quiver_hom → hom,
to_category_struct_comp → comp, to_category_struct_id → id, -to_category_struct)
/-- postcompose an equation between morphisms by another morphism -/
lemma eq_whisker {f g : X ⟶ Y} (w : f = g) (h : Y ⟶ Z) : f ≫ h = g ≫ h :=
by rw w
/-- precompose an equation between morphisms by another morphism -/
lemma whisker_eq (f : X ⟶ Y) {g h : Y ⟶ Z} (w : g = h) : f ≫ g = f ≫ h :=
by rw w
infixr ` =≫ `:80 := eq_whisker
infixr ` ≫= `:80 := whisker_eq
lemma eq_of_comp_left_eq {f g : X ⟶ Y} (w : ∀ {Z : C} (h : Y ⟶ Z), f ≫ h = g ≫ h) : f = g :=
by { convert w (𝟙 Y), tidy }
lemma eq_of_comp_right_eq {f g : Y ⟶ Z} (w : ∀ {X : C} (h : X ⟶ Y), h ≫ f = h ≫ g) : f = g :=
by { convert w (𝟙 Y), tidy }
lemma eq_of_comp_left_eq' (f g : X ⟶ Y)
(w : (λ {Z : C} (h : Y ⟶ Z), f ≫ h) = (λ {Z : C} (h : Y ⟶ Z), g ≫ h)) : f = g :=
eq_of_comp_left_eq (λ Z h, by convert congr_fun (congr_fun w Z) h)
lemma eq_of_comp_right_eq' (f g : Y ⟶ Z)
(w : (λ {X : C} (h : X ⟶ Y), h ≫ f) = (λ {X : C} (h : X ⟶ Y), h ≫ g)) : f = g :=
eq_of_comp_right_eq (λ X h, by convert congr_fun (congr_fun w X) h)
lemma id_of_comp_left_id (f : X ⟶ X) (w : ∀ {Y : C} (g : X ⟶ Y), f ≫ g = g) : f = 𝟙 X :=
by { convert w (𝟙 X), tidy }
lemma id_of_comp_right_id (f : X ⟶ X) (w : ∀ {Y : C} (g : Y ⟶ X), g ≫ f = g) : f = 𝟙 X :=
by { convert w (𝟙 X), tidy }
lemma comp_ite {P : Prop} [decidable P]
{X Y Z : C} (f : X ⟶ Y) (g g' : (Y ⟶ Z)) :
(f ≫ if P then g else g') = (if P then f ≫ g else f ≫ g') :=
by { split_ifs; refl }
lemma ite_comp {P : Prop} [decidable P]
{X Y Z : C} (f f' : (X ⟶ Y)) (g : Y ⟶ Z) :
(if P then f else f') ≫ g = (if P then f ≫ g else f' ≫ g) :=
by { split_ifs; refl }
lemma comp_dite {P : Prop} [decidable P]
{X Y Z : C} (f : X ⟶ Y) (g : P → (Y ⟶ Z)) (g' : ¬P → (Y ⟶ Z)) :
(f ≫ if h : P then g h else g' h) = (if h : P then f ≫ g h else f ≫ g' h) :=
by { split_ifs; refl }
lemma dite_comp {P : Prop} [decidable P]
{X Y Z : C} (f : P → (X ⟶ Y)) (f' : ¬P → (X ⟶ Y)) (g : Y ⟶ Z) :
(if h : P then f h else f' h) ≫ g = (if h : P then f h ≫ g else f' h ≫ g) :=
by { split_ifs; refl }
/--
A morphism `f` is an epimorphism if it can be "cancelled" when precomposed:
`f ≫ g = f ≫ h` implies `g = h`.
See <https://stacks.math.columbia.edu/tag/003B>.
-/
class epi (f : X ⟶ Y) : Prop :=
(left_cancellation : Π {Z : C} (g h : Y ⟶ Z) (w : f ≫ g = f ≫ h), g = h)
/--
A morphism `f` is a monomorphism if it can be "cancelled" when postcomposed:
`g ≫ f = h ≫ f` implies `g = h`.
See <https://stacks.math.columbia.edu/tag/003B>.
-/
class mono (f : X ⟶ Y) : Prop :=
(right_cancellation : Π {Z : C} (g h : Z ⟶ X) (w : g ≫ f = h ≫ f), g = h)
instance (X : C) : epi (𝟙 X) :=
⟨λ Z g h w, by simpa using w⟩
instance (X : C) : mono (𝟙 X) :=
⟨λ Z g h w, by simpa using w⟩
lemma cancel_epi (f : X ⟶ Y) [epi f] {g h : Y ⟶ Z} : (f ≫ g = f ≫ h) ↔ g = h :=
⟨λ p, epi.left_cancellation g h p, congr_arg _⟩
lemma cancel_mono (f : X ⟶ Y) [mono f] {g h : Z ⟶ X} : (g ≫ f = h ≫ f) ↔ g = h :=
⟨λ p, mono.right_cancellation g h p, congr_arg _⟩
lemma cancel_epi_id (f : X ⟶ Y) [epi f] {h : Y ⟶ Y} : (f ≫ h = f) ↔ h = 𝟙 Y :=
by { convert cancel_epi f, simp, }
lemma cancel_mono_id (f : X ⟶ Y) [mono f] {g : X ⟶ X} : (g ≫ f = f) ↔ g = 𝟙 X :=
by { convert cancel_mono f, simp, }
lemma epi_comp {X Y Z : C} (f : X ⟶ Y) [epi f] (g : Y ⟶ Z) [epi g] : epi (f ≫ g) :=
begin
split, intros Z a b w,
apply (cancel_epi g).1,
apply (cancel_epi f).1,
simpa using w,
end
lemma mono_comp {X Y Z : C} (f : X ⟶ Y) [mono f] (g : Y ⟶ Z) [mono g] : mono (f ≫ g) :=
begin
split, intros Z a b w,
apply (cancel_mono f).1,
apply (cancel_mono g).1,
simpa using w,
end
lemma mono_of_mono {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [mono (f ≫ g)] : mono f :=
begin
split, intros Z a b w,
replace w := congr_arg (λ k, k ≫ g) w,
dsimp at w,
rw [category.assoc, category.assoc] at w,
exact (cancel_mono _).1 w,
end
lemma mono_of_mono_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [mono h] (w : f ≫ g = h) :
mono f :=
by { substI h, exact mono_of_mono f g, }
lemma epi_of_epi {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [epi (f ≫ g)] : epi g :=
begin
split, intros Z a b w,
replace w := congr_arg (λ k, f ≫ k) w,
dsimp at w,
rw [←category.assoc, ←category.assoc] at w,
exact (cancel_epi _).1 w,
end
lemma epi_of_epi_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [epi h] (w : f ≫ g = h) :
epi g :=
by substI h; exact epi_of_epi f g
end
section
variable (C : Type u)
variable [category.{v} C]
universe u'
instance ulift_category : category.{v} (ulift.{u'} C) :=
{ hom := λ X Y, (X.down ⟶ Y.down),
id := λ X, 𝟙 X.down,
comp := λ _ _ _ f g, f ≫ g }
-- We verify that this previous instance can lift small categories to large categories.
example (D : Type u) [small_category D] : large_category (ulift.{u+1} D) := by apply_instance
end
end category_theory
/--
Many proofs in the category theory library use the `dsimp, simp` pattern,
which typically isn't necessary elsewhere.
One would usually hope that the same effect could be achieved simply with `simp`.
The essential issue is that composition of morphisms involves dependent types.
When you have a chain of morphisms being composed, say `f : X ⟶ Y` and `g : Y ⟶ Z`,
then `simp` can operate succesfully on the morphisms
(e.g. if `f` is the identity it can strip that off).
However if we have an equality of objects, say `Y = Y'`,
then `simp` can't operate because it would break the typing of the composition operations.
We rarely have interesting equalities of objects
(because that would be "evil" --- anything interesting should be expressed as an isomorphism
and tracked explicitly),
except of course that we have plenty of definitional equalities of objects.
`dsimp` can apply these safely, even inside a composition.
After `dsimp` has cleared up the object level, `simp` can resume work on the morphism level ---
but without the `dsimp` step, because `simp` looks at expressions syntactically,
the relevant lemmas might not fire.
There's no bound on how many times you potentially could have to switch back and forth,
if the `simp` introduced new objects we again need to `dsimp`.
In practice this does occur, but only rarely, because `simp` tends to shorten chains of compositions
(i.e. not introduce new objects at all).
-/
library_note "dsimp, simp"
|
cf0c4c52a7f4f2fc77cb6fa9f8730ed6ddaf4902 | a4673261e60b025e2c8c825dfa4ab9108246c32e | /tests/lean/rewrite.lean | 574f7577ae58d367da56c2a71d95382c706a40d1 | [
"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 | 1,392 | lean | axiom appendNil {α} (as : List α) : as ++ [] = as
axiom appendAssoc {α} (as bs cs : List α) : (as ++ bs) ++ cs = as ++ (bs ++ cs)
axiom reverseEq {α} (as : List α) : as.reverse.reverse = as
theorem ex1 {α} (as bs : List α) : as.reverse.reverse ++ [] ++ [] ++ bs ++ bs = as ++ (bs ++ bs) := by
rw [appendNil, appendNil, reverseEq];
traceState;
rw ←appendAssoc;
exact rfl
theorem ex2 {α} (as bs : List α) : as.reverse.reverse ++ [] ++ [] ++ bs ++ bs = as ++ (bs ++ bs) := by
rewrite [reverseEq, reverseEq]; -- Error on second reverseEq
done
axiom zeroAdd (x : Nat) : 0 + x = x
theorem ex2 (x y z) (h₁ : 0 + x = y) (h₂ : 0 + y = z) : x = z := by
rewrite zeroAdd at h₁ h₂;
traceState;
subst x;
subst y;
exact rfl
theorem ex3 (x y z) (h₁ : 0 + x = y) (h₂ : 0 + y = z) : x = z := by
rewrite zeroAdd at *;
subst x;
subst y;
exact rfl
theorem ex4 (x y z) (h₁ : 0 + x = y) (h₂ : 0 + y = z) : x = z := by
rewrite appendAssoc at *; -- Error
done
theorem ex5 (m n k : Nat) (h : 0 + n = m) (h : k = m) : k = n := by
rw zeroAdd at *;
traceState; -- `h` is still a name for `h : k = m`
refine Eq.trans h ?hole;
apply Eq.symm;
assumption
theorem ex6 (p q r : Prop) (h₁ : q → r) (h₂ : p ↔ q) (h₃ : p) : r := by
rw ←h₂ at h₁;
exact h₁ h₃
theorem ex7 (p q r : Prop) (h₁ : q → r) (h₂ : p ↔ q) (h₃ : p) : r := by
rw h₂ at h₃;
exact h₁ h₃
|
dfc4ed39ef26ec439afd4a1f2bdf262753be4c32 | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/set_theory/cardinal.lean | 354f5478f9e670ac4a3925ae0ff0d526418f6f34 | [
"Apache-2.0"
] | permissive | troyjlee/mathlib | e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5 | 45e7eb8447555247246e3fe91c87066506c14875 | refs/heads/master | 1,689,248,035,046 | 1,629,470,528,000 | 1,629,470,528,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 55,120 | 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, Floris van Doorn
-/
import data.set.countable
import set_theory.schroeder_bernstein
import data.fintype.card
import data.nat.enat
/-!
# Cardinal Numbers
We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity.
## Main definitions
* `cardinal` the type of cardinal numbers (in a given universe).
* `cardinal.mk α` or `#α` is the cardinality of `α`. The notation `#` lives in the locale
`cardinal`.
* There is an instance that `cardinal` forms a `canonically_ordered_comm_semiring`.
* Addition `c₁ + c₂` is defined by `cardinal.add_def α β : #α + #β = #(α ⊕ β)`.
* Multiplication `c₁ * c₂` is defined by `cardinal.mul_def : #α * #β = #(α * β)`.
* The order `c₁ ≤ c₂` is defined by `cardinal.le_def α β : #α ≤ #β ↔ nonempty (α ↪ β)`.
* Exponentiation `c₁ ^ c₂` is defined by `cardinal.power_def α β : #α ^ #β = #(β → α)`.
* `cardinal.omega` the cardinality of `ℕ`. This definition is universe polymorphic:
`cardinal.omega.{u} : cardinal.{u}`
(contrast with `ℕ : Type`, which lives in a specific universe).
In some cases the universe level has to be given explicitly.
* `cardinal.min (I : nonempty ι) (c : ι → cardinal)` is the minimal cardinal in the range of `c`.
* `cardinal.succ c` is the successor cardinal, the smallest cardinal larger than `c`.
* `cardinal.sum` is the sum of a collection of cardinals.
* `cardinal.sup` is the supremum of a collection of cardinals.
* `cardinal.powerlt c₁ c₂` or `c₁ ^< c₂` is defined as `sup_{γ < β} α^γ`.
## Main Statements
* Cantor's theorem: `cardinal.cantor c : c < 2 ^ c`.
* König's theorem: `cardinal.sum_lt_prod`
## Implementation notes
* There is a type of cardinal numbers in every universe level:
`cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`.
The operation `cardinal.lift` lifts cardinal numbers to a higher level.
* Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file
`set_theory/cardinal_ordinal.lean`.
* There is an instance `has_pow cardinal`, but this will only fire if Lean already knows that both
the base and the exponent live in the same universe. As a workaround, you can add
```
local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow
```
to a file. This notation will work even if Lean doesn't know yet that the base and the exponent
live in the same universe (but no exponents in other types can be used).
## References
* <https://en.wikipedia.org/wiki/Cardinal_number>
## Tags
cardinal number, cardinal arithmetic, cardinal exponentiation, omega,
Cantor's theorem, König's theorem, Konig's theorem
-/
open function set
open_locale classical
universes u v w x
variables {α β : Type u}
/-- The equivalence relation on types given by equivalence (bijective correspondence) of types.
Quotienting by this equivalence relation gives the cardinal numbers.
-/
instance cardinal.is_equivalent : setoid (Type u) :=
{ r := λα β, nonempty (α ≃ β),
iseqv := ⟨λα,
⟨equiv.refl α⟩,
λα β ⟨e⟩, ⟨e.symm⟩,
λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ }
/-- `cardinal.{u}` is the type of cardinal numbers in `Type u`,
defined as the quotient of `Type u` by existence of an equivalence
(a bijection with explicit inverse). -/
def cardinal : Type (u + 1) := quotient cardinal.is_equivalent
namespace cardinal
/-- The cardinal number of a type -/
def mk : Type u → cardinal := quotient.mk
localized "notation `#` := cardinal.mk" in cardinal
protected lemma eq : mk α = mk β ↔ nonempty (α ≃ β) := quotient.eq
@[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl
@[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _
/-- We define the order on cardinal numbers by `mk α ≤ mk β` if and only if
there exists an embedding (injective function) from α to β. -/
instance : has_le cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $
assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩
theorem le_def (α β : Type u) : mk α ≤ mk β ↔ nonempty (α ↪ β) :=
iff.rfl
theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β :=
⟨⟨f, hf⟩⟩
theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α :=
⟨embedding.of_surjective f hf⟩
theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} :
c ≤ mk α ↔ ∃ p : set α, mk p = c :=
⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩,
⟨set.range f, eq.symm $ quot.sound ⟨equiv.of_injective f hf⟩⟩,
λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩
theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) :=
by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl }
protected lemma eq_congr : α ≃ β → # α = # β :=
λ h, quot.sound ⟨h⟩
noncomputable instance : linear_order cardinal.{u} :=
{ le := (≤),
le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩,
le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩,
le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂),
le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total,
decidable_le := classical.dec_rel _ }
-- short-circuit type class inference
noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance
instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩
instance : inhabited cardinal.{u} := ⟨0⟩
@[simp]
lemma eq_zero_of_is_empty {α : Type u} [is_empty α] : mk α = 0 :=
quotient.sound ⟨equiv.equiv_pempty α⟩
lemma eq_zero_iff_is_empty {α : Type u} : mk α = 0 ↔ is_empty α :=
⟨λ e, let ⟨h⟩ := quotient.exact e in
equiv.equiv_empty_equiv α $ h.trans equiv.empty_equiv_pempty.symm,
@eq_zero_of_is_empty _⟩
theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α :=
(not_iff_not.2 eq_zero_iff_is_empty).trans not_is_empty_iff
instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩
instance : nontrivial cardinal.{u} :=
⟨⟨1, 0, ne_zero_iff_nonempty.2 ⟨punit.star⟩⟩⟩
theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α :=
⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩,
λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩
theorem one_lt_iff_nontrivial {α : Type u} : 1 < mk α ↔ nontrivial α :=
by { rw [← not_iff_not, not_nontrivial_iff_subsingleton, ← le_one_iff_subsingleton], simp }
instance : has_add cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩
@[simp] theorem add_def (α β : Type u) : mk α + mk β = mk (α ⊕ β) := rfl
instance : has_mul cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩
@[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl
private theorem add_comm (a b : cardinal.{u}) : a + b = b + a :=
quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩
private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a :=
quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩
private theorem zero_add (a : cardinal.{u}) : 0 + a = a :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.empty_sum pempty α⟩
private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩
private theorem one_mul (a : cardinal.{u}) : 1 * a = a :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩
private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c :=
quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩
protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {a b : cardinal.{u}} :
a * b = 0 → a = 0 ∨ b = 0 :=
begin
refine quotient.induction_on b _,
refine quotient.induction_on a _,
intros a b h,
contrapose h,
simp_rw [not_or_distrib, ← ne.def] at h,
have := @prod.nonempty a b (ne_zero_iff_nonempty.mp h.1) (ne_zero_iff_nonempty.mp h.2),
exact ne_zero_iff_nonempty.mpr this
end
instance : comm_semiring cardinal.{u} :=
{ zero := 0,
one := 1,
add := (+),
mul := (*),
zero_add := zero_add,
add_zero := assume a, by rw [add_comm a 0, zero_add a],
add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.sum_assoc α β γ⟩,
add_comm := add_comm,
zero_mul := zero_mul,
mul_zero := assume a, by rw [mul_comm a 0, zero_mul a],
one_mul := one_mul,
mul_one := assume a, by rw [mul_comm a 1, one_mul a],
mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.prod_assoc α β γ⟩,
mul_comm := mul_comm,
left_distrib := left_distrib,
right_distrib := assume a b c,
by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] }
/-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/
protected def power (a b : cardinal.{u}) : cardinal.{u} :=
quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩
instance : has_pow cardinal cardinal := ⟨cardinal.power⟩
local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow
@[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl
@[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.pempty_arrow_equiv_punit α⟩
@[simp] theorem power_one {a : cardinal} : a ^ 1 = a :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.punit_arrow_equiv α⟩
@[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.arrow_punit_equiv_punit α⟩
@[simp] theorem prop_eq_two : mk (ulift Prop) = 2 :=
quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩
@[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 :=
quotient.induction_on a $ assume α heq,
(ne_zero_iff_nonempty.1 heq).elim $ assume a,
by { haveI : nonempty α := ⟨a⟩, exact quotient.sound ⟨equiv.equiv_pempty _⟩ }
theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 :=
quotient.induction_on₂ a b $ λ α β h,
let ⟨a⟩ := ne_zero_iff_nonempty.1 h in
ne_zero_iff_nonempty.2 ⟨λ _, a⟩
theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c :=
quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩
theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c :=
quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩
theorem power_mul {a b c : cardinal} : a ^ (b * c) = (a ^ b) ^ c :=
by rw [_root_.mul_comm b c];
from (quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.curry γ β α⟩)
@[simp] lemma pow_cast_right (κ : cardinal.{u}) :
∀ n : ℕ, (κ ^ (↑n : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow κ n
| 0 := by simp
| (_+1) := by rw [nat.cast_succ, power_add, power_one, _root_.mul_comm, pow_succ, pow_cast_right]
section order_properties
open sum
protected theorem zero_le : ∀(a : cardinal), 0 ≤ a :=
by rintro ⟨α⟩; exact ⟨embedding.of_is_empty⟩
protected theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.sum_map e₂⟩
protected theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c :=
cardinal.add_le_add (le_refl _)
protected theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c :=
⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩,
have (α ⊕ ((range f)ᶜ : set β)) ≃ β, from
(equiv.sum_congr (equiv.of_injective f hf) (equiv.refl _)).trans $
(equiv.set.sum_compl (range f)),
⟨⟦↥(range f)ᶜ⟧, quotient.sound ⟨this.symm⟩⟩,
λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ cardinal.add_le_add_left _ (cardinal.zero_le _)⟩
instance : order_bot cardinal.{u} :=
{ bot := 0, bot_le := cardinal.zero_le, ..cardinal.linear_order }
instance : canonically_ordered_comm_semiring cardinal.{u} :=
{ add_le_add_left := λ a b h c, cardinal.add_le_add_left _ h,
lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (cardinal.add_le_add_left _),
le_iff_exists_add := @cardinal.le_iff_exists_add,
eq_zero_or_eq_zero_of_mul_eq_zero := @cardinal.eq_zero_or_eq_zero_of_mul_eq_zero,
..cardinal.order_bot,
..cardinal.comm_semiring, ..cardinal.linear_order }
noncomputable instance : canonically_linear_ordered_add_monoid cardinal.{u} :=
{ .. (infer_instance : canonically_ordered_add_monoid cardinal.{u}),
.. cardinal.linear_order }
@[simp] theorem zero_lt_one : (0 : cardinal) < 1 :=
lt_of_le_of_ne (zero_le _) zero_ne_one
lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 :=
by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le }
theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact
let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in
⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩
theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 :=
begin
by_cases ha : a = 0,
simp [ha, zero_power_le],
exact le_trans (power_le_power_left ha h) (le_max_left _ _)
end
theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c :=
quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩
end order_properties
/-- **Cantor's theorem** -/
theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a :=
by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨
⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩,
λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $
λ s t h, by funext a; injection congr_fun (hf h) a⟩
instance : no_top_order cardinal.{u} :=
{ no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order }
/-- The minimum cardinal in a family of cardinals (the existence
of which is provided by `injective_min`). -/
noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal :=
f $ classical.some $
@embedding.min_injective _ (λ i, (f i).out) I
theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i :=
⟨_, rfl⟩
theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i :=
by rw [← mk_out (min I f), ← mk_out (f i)]; exact
let ⟨g⟩ := classical.some_spec
(@embedding.min_injective _ (λ i, (f i).out) I) in
⟨g i⟩
theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i :=
⟨λ h i, le_trans h (min_le _ _),
λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩
protected theorem wf : @well_founded cardinal.{u} (<) :=
⟨λ a, classical.by_contradiction $ λ h,
let ι := {c :cardinal // ¬ acc (<) c},
f : ι → cardinal := subtype.val,
⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in
hc (acc.intro _ (λ j ⟨_, h'⟩,
classical.by_contradiction $ λ hj, h' $
by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩
instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩
instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩
/-- The successor cardinal - the smallest cardinal greater than
`c`. This is not the same as `c + 1` except in the case of finite `c`. -/
noncomputable def succ (c : cardinal) : cardinal :=
@min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val
theorem lt_succ_self (c : cardinal) : c < succ c :=
by cases min_eq _ _ with s e; rw [succ, e]; exact s.2
theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b :=
⟨lt_of_lt_of_le (lt_succ_self _), λ h,
by exact min_le _ (subtype.mk b h)⟩
theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b :=
by rw [← not_le, succ_le, not_lt]
theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c :=
begin
refine quot.induction_on c (λ α, _) (lt_succ_self c),
refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _),
cases h.left with f,
have : ¬ surjective f := λ hn,
ne_of_lt h (quotient.sound ⟨equiv.of_bijective f ⟨f.injective, hn⟩⟩),
cases not_forall.1 this with b nex,
refine ⟨⟨sum.rec (by exact f) _, _⟩⟩,
{ exact λ _, b },
{ intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩,
{ rw f.injective h },
{ exact nex.elim ⟨_, h⟩ },
{ exact nex.elim ⟨_, h.symm⟩ },
{ refl } }
end
lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 :=
by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le }
/-- The indexed sum of cardinals is the cardinality of the
indexed disjoint union, i.e. sigma type. -/
def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out
theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f :=
by rw ← quotient.out_eq (f i); exact
⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩
@[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) :=
quot.sound ⟨equiv.sigma_congr_right $ λ i,
classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩
theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a :=
quotient.induction_on a $ λ α, by simp; exact
quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩
theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g :=
⟨(embedding.refl _).sigma_map $ λ i, classical.choice $
by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩
/-- The indexed supremum of cardinals is the smallest cardinal above
everything in the family. -/
noncomputable def sup {ι} (f : ι → cardinal) : cardinal :=
@min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1)
theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f :=
by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i
theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a :=
⟨λ h i, le_trans (le_sup _ _) h,
λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩
theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g :=
sup_le.2 $ λ i, le_trans (H i) (le_sup _ _)
theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f :=
sup_le.2 $ le_sum _
theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f :=
by rw ← sum_const; exact sum_le_sum _ _ (le_sup _)
theorem sup_eq_zero {ι} {f : ι → cardinal} [is_empty ι] : sup f = 0 :=
by { rw [← nonpos_iff_eq_zero, sup_le], exact is_empty_elim }
/-- The indexed product of cardinals is the cardinality of the Pi type
(dependent product). -/
def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out)
@[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) :=
quot.sound ⟨equiv.Pi_congr_right $ λ i,
classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩
theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι :=
quotient.induction_on a $ by simp
theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g :=
⟨embedding.Pi_congr_right $ λ i, classical.choice $
by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩
theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 :=
begin
suffices : nonempty (Π i, (f i).out) ↔ ∀ i, nonempty (f i).out,
{ simpa [← ne_zero_iff_nonempty, prod] },
exact classical.nonempty_pi
end
theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 :=
not_iff_not.1 $ by simpa using prod_ne_zero f
/-- The universe lift operation on cardinals. You can specify the universes explicitly with
`lift.{u v} : cardinal.{u} → cardinal.{max u v}` -/
def lift (c : cardinal.{u}) : cardinal.{max u v} :=
quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩,
quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩
theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl
theorem lift_umax : lift.{u (max u v)} = lift.{u v} :=
funext $ λ a, quot.induction_on a $ λ α,
quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩
theorem lift_id' (a : cardinal) : lift a = a :=
quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩
@[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u}
@[simp] theorem lift_lift (a : cardinal) :
lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a :=
quot.induction_on a $ λ α,
quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩
theorem lift_mk_le {α : Type u} {β : Type v} :
lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) :=
⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩,
λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩
/-- A variant of `lift_mk_le` with universes specialized as `w = max u v`.
This is sometimes necessary to avoid universe unification issues. -/
theorem lift_mk_le' {α : Type u} {β : Type v} :
lift.{u v} (mk α) ≤ lift.{v u} (mk β) ↔ nonempty (α ↪ β) :=
⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩,
λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩
theorem lift_mk_eq {α : Type u} {β : Type v} :
lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) :=
quotient.eq.trans
⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩,
λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩
@[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b :=
quotient.induction_on₂ a b $ λ α β,
by rw ← lift_umax; exact lift_mk_le
@[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b :=
by simp [le_antisymm_iff]
@[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b :=
by simp [lt_iff_le_not_le, -not_le]
@[simp] theorem lift_zero : lift 0 = 0 :=
quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩
@[simp] theorem lift_one : lift 1 = 1 :=
quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩
@[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a :=
by simp [bit0]
@[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) :=
le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $
let ⟨i, e⟩ := min_eq I (lift ∘ f) in
by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $
by have := min_le (lift ∘ f) j; rwa e at this)
theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} :
b ≤ lift a → ∃ a', lift a' = b :=
quotient.induction_on₂ a b $ λ α β,
by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact
λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2
⟨embedding.equiv_of_surjective
(embedding.cod_restrict _ f set.mem_range_self)
$ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩
theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} :
b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a :=
⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩,
λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩
theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} :
b < lift a ↔ ∃ a', lift a' = b ∧ a' < a :=
⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in
⟨a', e, lift_lt.1 $ e.symm ▸ h⟩,
λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩
@[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) :=
le_antisymm
(le_of_not_gt $ λ h, begin
rcases lt_lift_iff.1 h with ⟨b, e, h⟩,
rw [lt_succ, ← lift_le, e] at h,
exact not_lt_of_le h (lt_succ_self _)
end)
(succ_le.2 $ lift_lt.2 $ lt_succ_self _)
@[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} :
lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b :=
calc lift.{u (max v w)} a = lift.{v (max u w)} b
↔ lift.{(max u v) w} (lift.{u v} a)
= lift.{(max u v) w} (lift.{v u} b) : by simp
... ↔ lift.{u v} a = lift.{v u} b : lift_inj
theorem mk_prod {α : Type u} {β : Type v} :
mk (α × β) = lift.{u v} (mk α) * lift.{v u} (mk β) :=
quotient.sound ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩
theorem sum_const_eq_lift_mul (ι : Type u) (a : cardinal.{v}) :
sum (λ _:ι, a) = lift.{u v} (mk ι) * lift.{v u} a :=
begin
apply quotient.induction_on a,
intro α,
simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id],
convert mk_prod using 1,
exact quotient.sound ⟨equiv.sigma_equiv_prod ι α⟩,
end
protected lemma le_sup_iff {ι : Type v} {f : ι → cardinal.{max v w}} {c : cardinal} :
(c ≤ sup f) ↔ (∀ b, (∀ i, f i ≤ b) → c ≤ b) :=
⟨λ h b hb, le_trans h (sup_le.mpr hb), λ h, h _ $ λ i, le_sup f i⟩
/-- The lift of a supremum is the supremum of the lifts. -/
lemma lift_sup {ι : Type v} (f : ι → cardinal.{max v w}) :
lift.{(max v w) u} (sup.{v w} f) =
sup.{v (max u w)} (λ i : ι, lift.{(max v w) u} (f i)) :=
begin
apply le_antisymm,
{ rw [cardinal.le_sup_iff], intros c hc, by_contra h,
obtain ⟨d, rfl⟩ := cardinal.lift_down (not_le.mp h).le,
simp only [lift_le, sup_le] at h hc,
exact h hc },
{ simp only [cardinal.sup_le, lift_le, le_sup, implies_true_iff] }
end
/-- To prove that the lift of a supremum is bounded by some cardinal `t`,
it suffices to show that the lift of each cardinal is bounded by `t`. -/
lemma lift_sup_le {ι : Type v} (f : ι → cardinal.{max v w})
(t : cardinal.{max u v w}) (w : ∀ i, lift.{_ u} (f i) ≤ t) :
lift.{(max v w) u} (sup f) ≤ t :=
by { rw lift_sup, exact sup_le.mpr w, }
@[simp] lemma lift_sup_le_iff {ι : Type v} (f : ι → cardinal.{max v w}) (t : cardinal.{max u v w}) :
lift.{(max v w) u} (sup f) ≤ t ↔ ∀ i, lift.{_ u} (f i) ≤ t :=
⟨λ h i, (lift_le.mpr (le_sup f i)).trans h,
λ h, lift_sup_le f t h⟩
universes v' w'
/--
To prove an inequality between the lifts to a common universe of two different supremums,
it suffices to show that the lift of each cardinal from the smaller supremum
if bounded by the lift of some cardinal from the larger supremum.
-/
lemma lift_sup_le_lift_sup
{ι : Type v} {ι' : Type v'} (f : ι → cardinal.{max v w}) (f' : ι' → cardinal.{max v' w'})
(g : ι → ι') (h : ∀ i, lift.{_ (max v' w')} (f i) ≤ lift.{_ (max v w)} (f' (g i))) :
lift.{_ (max v' w')} (sup f) ≤ lift.{_ (max v w)} (sup f') :=
begin
apply lift_sup_le.{(max v' w')} f,
intro i,
apply le_trans (h i),
simp only [lift_le],
apply le_sup,
end
/-- A variant of `lift_sup_le_lift_sup` with universes specialized via `w = v` and `w' = v'`.
This is sometimes necessary to avoid universe unification issues. -/
lemma lift_sup_le_lift_sup'
{ι : Type v} {ι' : Type v'} (f : ι → cardinal.{v}) (f' : ι' → cardinal.{v'})
(g : ι → ι') (h : ∀ i, lift.{_ v'} (f i) ≤ lift.{_ v} (f' (g i))) :
lift.{_ v'} (sup.{v v} f) ≤ lift.{_ v} (sup.{v' v'} f') :=
lift_sup_le_lift_sup f f' g h
/-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/
def omega : cardinal.{u} := lift (mk ℕ)
lemma mk_nat : mk nat = omega := (lift_id _).symm
theorem omega_ne_zero : omega ≠ 0 :=
ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩
theorem omega_pos : 0 < omega :=
pos_iff_ne_zero.2 omega_ne_zero
@[simp] theorem lift_omega : lift omega = omega := lift_lift _
/- properties about the cast from nat -/
@[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n
| 0 := quotient.sound ⟨equiv.equiv_pempty _⟩
| (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact
quotient.sound (fintype.card_eq.1 $ by simp)
@[simp] theorem lift_nat_cast (n : ℕ) : lift n = n :=
by induction n; simp *
lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{u v} a = n ↔ a = n :=
by rw [← lift_nat_cast.{u v} n, lift_inj]
lemma nat_eq_lift_eq_iff {n : ℕ} {a : cardinal.{u}} :
(n : cardinal) = lift.{u v} a ↔ (n : cardinal) = a :=
by rw [← lift_nat_cast.{u v} n, lift_inj]
theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp
theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α :=
by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}];
exact fintype.card_eq.1 (by simp)
theorem card_le_of_finset {α} (s : finset α) :
(s.card : cardinal) ≤ cardinal.mk α :=
begin
rw (_ : (s.card : cardinal) = cardinal.mk s),
{ exact ⟨function.embedding.subtype _⟩ },
rw [cardinal.fintype_card, fintype.card_coe]
end
@[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n :=
by induction n; simp [pow_succ', -_root_.add_comm, power_add, *]
@[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n :=
by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact
⟨λ ⟨⟨f, hf⟩⟩, by simpa only [fintype.card_fin] using fintype.card_le_of_injective f hf,
λ h, ⟨(fin.cast_le h).to_embedding⟩⟩
@[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n :=
by simp [lt_iff_le_not_le, -not_le]
@[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n :=
by simp [le_antisymm_iff]
@[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n :=
le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _)
@[simp] theorem succ_zero : succ 0 = 1 :=
by norm_cast
theorem card_le_of {α : Type u} {n : ℕ} (H : ∀ s : finset α, s.card ≤ n) :
# α ≤ n :=
begin
refine lt_succ.1 (lt_of_not_ge $ λ hn, _),
rw [← cardinal.nat_succ, ← cardinal.lift_mk_fin n.succ] at hn,
cases hn with f,
refine not_lt_of_le (H $ finset.univ.map f) _,
rw [finset.card_map, ← fintype.card, fintype.card_ulift, fintype.card_fin],
exact n.lt_succ_self
end
theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a :=
by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb;
exact lt_of_lt_of_le (cantor _) (power_le_power_right hb)
theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c :=
by rw [← succ_zero, succ_le]
theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 :=
by rw [one_le_iff_pos, pos_iff_ne_zero]
theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega :=
succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact
⟨⟨coe, λ a b, fin.ext⟩⟩
@[simp] theorem one_lt_omega : 1 < omega :=
by simpa using nat_lt_omega 1
theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n :=
⟨λ h, begin
rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩,
rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩,
suffices : finite S,
{ cases this, resetI,
existsi fintype.card S,
rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] },
by_contra nf,
have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a :=
λ n IH,
let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in
not_forall.1 (λ h, nf
⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩),
let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)),
refine not_le_of_lt h' ⟨⟨F, _⟩⟩,
suffices : ∀ (n : ℕ) (m < n), F m ≠ F n,
{ refine λ m n, not_imp_not.1 (λ ne, _),
rcases lt_trichotomy m n with h|h|h,
{ exact this n m h },
{ contradiction },
{ exact (this m n h).symm } },
intros n m h,
have := classical.some_spec (P n (λ y _, F y)),
rw [← show F n = classical.some (P n (λ y _, F y)),
from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this,
exact λ e, this ⟨m, h, e⟩,
end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩
theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c :=
⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h,
λ h, le_of_not_lt $ λ hn, begin
rcases lt_omega.1 hn with ⟨n, rfl⟩,
exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1)))
end⟩
theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) :=
lt_omega.trans ⟨λ ⟨n, e⟩, begin
rw [← lift_mk_fin n] at e,
cases quotient.exact e with f,
exact ⟨fintype.of_equiv _ f.symm⟩
end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩
theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S :=
lt_omega_iff_fintype
instance can_lift_cardinal_nat : can_lift cardinal ℕ :=
⟨ coe, λ x, x < omega, λ x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩
theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega
end
lemma add_lt_omega_iff {a b : cardinal} : a + b < omega ↔ a < omega ∧ b < omega :=
⟨λ h, ⟨lt_of_le_of_lt (self_le_add_right _ _) h, lt_of_le_of_lt (self_le_add_left _ _) h⟩,
λ⟨h1, h2⟩, add_lt_omega h1 h2⟩
theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega
end
lemma mul_lt_omega_iff {a b : cardinal} : a * b < omega ↔ a = 0 ∨ b = 0 ∨ a < omega ∧ b < omega :=
begin
split,
{ intro h, by_cases ha : a = 0, { left, exact ha },
right, by_cases hb : b = 0, { left, exact hb },
right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split,
{ rw [← mul_one a],
refine lt_of_le_of_lt (mul_le_mul' (le_refl a) hb) h },
{ rw [← _root_.one_mul b],
refine lt_of_le_of_lt (mul_le_mul' ha (le_refl b)) h }},
rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, _root_.zero_mul, mul_zero]
end
lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) :
a * b < omega ↔ a < omega ∧ b < omega :=
by simp [mul_lt_omega_iff, ha, hb]
theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega
end
lemma eq_one_iff_unique {α : Type*} :
mk α = 1 ↔ subsingleton α ∧ nonempty α :=
calc mk α = 1 ↔ mk α ≤ 1 ∧ ¬mk α < 1 : eq_iff_le_not_lt
... ↔ subsingleton α ∧ nonempty α :
begin
apply and_congr le_one_iff_subsingleton,
push_neg,
rw [one_le_iff_ne_zero, ne_zero_iff_nonempty]
end
theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α :=
by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_fintype]
lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega :=
⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩,
λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩
lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega :=
begin
rw [countable_iff_exists_injective], split,
rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩,
rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩
end
/-- This function sends finite cardinals to the corresponding natural, and infinite cardinals
to 0. -/
noncomputable def to_nat : zero_hom cardinal ℕ :=
⟨λ c, if h : c < omega.{v} then classical.some (lt_omega.1 h) else 0,
begin
have h : 0 < omega := nat_lt_omega 0,
rw [dif_pos h, ← cardinal.nat_cast_inj, ← classical.some_spec (lt_omega.1 h), nat.cast_zero],
end⟩
lemma to_nat_apply_of_lt_omega {c : cardinal} (h : c < omega) :
c.to_nat = classical.some (lt_omega.1 h) :=
dif_pos h
@[simp]
lemma to_nat_apply_of_omega_le {c : cardinal} (h : omega ≤ c) :
c.to_nat = 0 :=
dif_neg (not_lt_of_le h)
@[simp]
lemma cast_to_nat_of_lt_omega {c : cardinal} (h : c < omega) :
↑c.to_nat = c :=
by rw [to_nat_apply_of_lt_omega h, ← classical.some_spec (lt_omega.1 h)]
@[simp]
lemma to_nat_cast (n : ℕ) : cardinal.to_nat n = n :=
begin
rw [to_nat_apply_of_lt_omega (nat_lt_omega n), ← nat_cast_inj],
exact (classical.some_spec (lt_omega.1 (nat_lt_omega n))).symm,
end
/-- `to_nat` has a right-inverse: coercion. -/
lemma to_nat_right_inverse : function.right_inverse (coe : ℕ → cardinal) to_nat := to_nat_cast
lemma to_nat_surjective : surjective to_nat := to_nat_right_inverse.surjective
@[simp]
lemma mk_to_nat_of_infinite [h : infinite α] : (mk α).to_nat = 0 :=
dif_neg (not_lt_of_le (infinite_iff.1 h))
@[simp]
lemma mk_to_nat_eq_card [fintype α] : (mk α).to_nat = fintype.card α :=
by simp [fintype_card]
@[simp]
lemma zero_to_nat : cardinal.to_nat 0 = 0 :=
by rw [← to_nat_cast 0, nat.cast_zero]
@[simp]
lemma one_to_nat : cardinal.to_nat 1 = 1 :=
by rw [← to_nat_cast 1, nat.cast_one]
/-- This function sends finite cardinals to the corresponding natural, and infinite cardinals
to `⊤`. -/
noncomputable def to_enat : cardinal →+ enat :=
{ to_fun := λ c, if c < omega.{v} then c.to_nat else ⊤,
map_zero' := by simp [if_pos (lt_trans zero_lt_one one_lt_omega)],
map_add' := λ x y, begin
by_cases hx : x < omega,
{ obtain ⟨x0, rfl⟩ := lt_omega.1 hx,
by_cases hy : y < omega,
{ obtain ⟨y0, rfl⟩ := lt_omega.1 hy,
simp only [add_lt_omega hx hy, hx, hy, to_nat_cast, if_true],
rw [← nat.cast_add, to_nat_cast, enat.coe_add] },
{ rw [if_neg hy, if_neg, enat.add_top],
contrapose! hy,
apply lt_of_le_of_lt le_add_self hy } },
{ rw [if_neg hx, if_neg, enat.top_add],
contrapose! hx,
apply lt_of_le_of_lt le_self_add hx },
end }
@[simp]
lemma to_enat_apply_of_lt_omega {c : cardinal} (h : c < omega) :
c.to_enat = c.to_nat :=
if_pos h
@[simp]
lemma to_enat_apply_of_omega_le {c : cardinal} (h : omega ≤ c) :
c.to_enat = ⊤ :=
if_neg (not_lt_of_le h)
@[simp]
lemma to_enat_cast (n : ℕ) : cardinal.to_enat n = n :=
by rw [to_enat_apply_of_lt_omega (nat_lt_omega n), to_nat_cast]
@[simp]
lemma mk_to_enat_of_infinite [h : infinite α] : (mk α).to_enat = ⊤ :=
to_enat_apply_of_omega_le (infinite_iff.1 h)
lemma to_enat_surjective : surjective to_enat :=
begin
intro x,
exact enat.cases_on x ⟨omega, to_enat_apply_of_omega_le (le_refl omega)⟩
(λ n, ⟨n, to_enat_cast n⟩),
end
@[simp]
lemma mk_to_enat_eq_coe_card [fintype α] : (mk α).to_enat = fintype.card α :=
by simp [fintype_card]
lemma mk_int : mk ℤ = omega :=
denumerable_iff.mp ⟨by apply_instance⟩
lemma mk_pnat : mk ℕ+ = omega :=
denumerable_iff.mp ⟨by apply_instance⟩
lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y :=
begin
split,
{ rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h },
{ rintro ⟨x, y, h⟩, by_contra h',
rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h',
apply h, exactI subsingleton.elim _ _ }
end
lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y :=
begin
rw [two_le_iff],
split,
{ rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩),
rw [←h'] at h, exact ⟨z, h⟩ },
{ rintro ⟨y, h⟩, exact ⟨x, y, h⟩ }
end
/-- **König's theorem** -/
theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g :=
lt_of_not_ge $ λ ⟨F⟩, begin
have : inhabited (Π (i : ι), (g i).out),
{ refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩,
rw mk_out,
exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI,
let G := inv_fun F,
have sG : surjective G := inv_fun_surjective F.2,
choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b,
{ assume i,
simp only [- not_exists, not_exists.symm, not_forall.symm],
refine λ h, not_le_of_lt (H i) _,
rw [← mk_out (f i), ← mk_out (g i)],
exact ⟨embedding.of_surjective _ h⟩ },
exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _))
end
@[simp] theorem mk_empty : mk empty = 0 :=
fintype_card empty
@[simp] theorem mk_pempty : mk pempty = 0 :=
fintype_card pempty
@[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 :=
by { haveI : is_empty p := ⟨h⟩, exact quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty _⟩ }
theorem mk_unit : mk unit = 1 :=
(fintype_card unit).trans nat.cast_one
@[simp] theorem mk_punit : mk punit = 1 :=
(fintype_card punit).trans nat.cast_one
@[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 :=
quotient.sound ⟨equiv.set.singleton x⟩
@[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 :=
quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩
@[simp] theorem mk_bool : mk bool = 2 :=
quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩
@[simp] theorem mk_Prop : mk Prop = 2 :=
(quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool
@[simp] theorem mk_set {α : Type u} : mk (set α) = 2 ^ mk α :=
begin
rw [← prop_eq_two, cardinal.power_def (ulift Prop) α, cardinal.eq],
exact ⟨equiv.arrow_congr (equiv.refl _) equiv.ulift.symm⟩,
end
@[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 :=
quotient.sound ⟨equiv.option_equiv_sum_punit α⟩
theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) :=
calc mk (list α)
= mk (Σ n, vector α n) : quotient.sound ⟨(equiv.sigma_preimage_equiv list.length).symm⟩
... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n,
⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩
... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n,
equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩
... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) :
by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk]
theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α :=
mk_le_of_surjective quot.exists_rep
theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α :=
mk_quot_le
theorem mk_subtype_le {α : Type u} (p : α → Prop) : mk (subtype p) ≤ mk α :=
⟨embedding.subtype p⟩
theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) :
mk (subtype p) ≤ mk (subtype q) :=
⟨embedding.subtype_map (embedding.refl α) h⟩
@[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 :=
quotient.sound ⟨equiv.set.pempty α⟩
lemma mk_emptyc_iff {α : Type u} {s : set α} : mk s = 0 ↔ s = ∅ :=
begin
split,
{ intro h,
have h2 : cardinal.mk s = cardinal.mk pempty, by simp [h],
refine set.eq_empty_iff_forall_not_mem.mpr (λ _ hx, _),
rcases cardinal.eq.mp h2 with ⟨f, _⟩,
cases f ⟨_, hx⟩ },
{ intro, convert mk_emptyc _ }
end
theorem mk_univ {α : Type u} : mk (@univ α) = mk α :=
quotient.sound ⟨equiv.set.univ α⟩
theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s :=
mk_le_of_surjective surjective_onto_image
theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} :
lift.{v u} (mk (f '' s)) ≤ lift.{u v} (mk s) :=
lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩
theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α :=
mk_le_of_surjective surjective_onto_range
theorem mk_range_le_lift {α : Type u} {β : Type v} {f : α → β} :
lift.{v u} (mk (range f)) ≤ lift.{u v} (mk α) :=
lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_range⟩
lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α :=
quotient.sound ⟨(equiv.of_injective f h).symm⟩
lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) :
lift.{v u} (mk (range f)) = lift.{u v} (mk α) :=
begin
have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.of_injective f hf).symm⟩,
simp only [lift_umax.{u v}, lift_umax.{v u}] at this,
exact this
end
lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) :
lift.{v (max u w)} (# (range f)) = lift.{u (max v w)} (# α) :=
lift_mk_eq.mpr ⟨(equiv.of_injective f hf).symm⟩
theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) :
mk (f '' s) = mk s :=
quotient.sound ⟨(equiv.set.image f s hf).symm⟩
theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) :=
calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f)
... = sum (λ i, mk (f i)) : (sum_mk _).symm
theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) :
mk (⋃ i, f i) = sum (λ i, mk (f i)) :=
calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩
... = sum (λi, mk (f i)) : (sum_mk _).symm
lemma mk_Union_le {α ι : Type u} (f : ι → set α) :
mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) :=
le_trans mk_Union_le_sum_mk (sum_le_sup _)
lemma mk_sUnion_le {α : Type u} (A : set (set α)) :
mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) :=
by { rw [sUnion_eq_Union], apply mk_Union_le }
lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) :
mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) :=
by { rw [bUnion_eq_Union], apply mk_Union_le }
@[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk s :=
by rw [fintype_card, nat_cast_inj, fintype.card_coe]
lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega :=
by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ }
theorem mk_eq_nat_iff_finset {α} {s : set α} {n : ℕ} :
mk s = n ↔ ∃ t : finset α, (t : set α) = s ∧ t.card = n :=
begin
split,
{ intro h,
have : # s < omega, by { rw h, exact nat_lt_omega n },
refine ⟨(lt_omega_iff_finite.1 this).to_finset, finite.coe_to_finset _, nat_cast_inj.1 _⟩,
rwa [finset_card, finite.coe_sort_to_finset] },
{ rintro ⟨t, rfl, rfl⟩,
exact finset_card.symm }
end
theorem mk_union_add_mk_inter {α : Type u} {S T : set α} :
mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T :=
quot.sound ⟨equiv.set.union_sum_inter S T⟩
/-- The cardinality of a union is at most the sum of the cardinalities
of the two sets. -/
lemma mk_union_le {α : Type u} (S T : set α) : mk (S ∪ T : set α) ≤ mk S + mk T :=
@mk_union_add_mk_inter α S T ▸ self_le_add_right (mk (S ∪ T : set α)) (mk (S ∩ T : set α))
theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) :
mk (S ∪ T : set α) = mk S + mk T :=
quot.sound ⟨equiv.set.union H⟩
lemma mk_sum_compl {α} (s : set α) : #s + #(sᶜ : set α) = #α :=
quotient.sound ⟨equiv.set.sum_compl s⟩
lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t :=
⟨set.embedding_of_subset s t h⟩
lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} :=
⟨embedding_of_subset _ _ h⟩
lemma mk_set_le (s : set α) : mk s ≤ mk α :=
mk_subtype_le s
lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) :
lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩
lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α)
(h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩
lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) :
mk (f '' s) = mk s :=
quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩
lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) :
mk {a : α // p (e a)} = mk {b : β // p b} :=
quotient.sound ⟨equiv.subtype_equiv_of_subtype e⟩
lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } :=
quotient.sound ⟨equiv.set.sep s t⟩
lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β)
(h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) :=
begin
rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2),
apply subtype.coind_injective, exact h.comp subtype.val_injective
end
lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β)
(h : s ⊆ range f) : lift.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) :=
begin
rw lift_mk_le.{v u 0},
refine ⟨⟨_, _⟩⟩,
{ rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ },
rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp,
rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩,
rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩,
simp, intro hxx', rw hxx'
end
lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β)
(h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) :=
le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2)
lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) :
mk (f ⁻¹' s) ≤ mk s :=
by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_subset_range (f : α → β) (s : set β)
(h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) :=
by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β)
(h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s :=
by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] }
lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α}
{t : set β} (h : t ⊆ f '' s) :
lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1,
rw [mk_sep], refl }
lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) :
mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1,
rw [mk_sep], refl }
theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} :
c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c :=
begin
rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype],
apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective
end
/-- The function α^{<β}, defined to be sup_{γ < β} α^γ.
We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a
higher universe -/
noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} :=
sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s)
infix ` ^< `:80 := powerlt
theorem powerlt_aux {c c' : cardinal} (h : c < c') :
∃(s : {s : set c'.out // mk s < c'}), mk s = c :=
begin
cases out_embedding.mp (le_of_lt h) with f,
have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 },
exact ⟨⟨range f, by convert h⟩, this⟩
end
lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ :=
by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s }
lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ :=
begin
rw [powerlt, sup_le],
split,
{ intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s },
intros h s, exact h _ s.2
end
lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c :=
by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h }
lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ :=
begin
apply le_antisymm,
{ rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] },
{ apply le_powerlt, apply lt_succ_self }
end
lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) :=
by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] }
lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 :=
begin
apply le_antisymm,
{ rw [powerlt_le], intros c hc, apply zero_power_le },
convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero]
end
lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 :=
begin
convert sup_eq_zero,
exact subtype.is_empty_of_false (λ x, (zero_le _).not_lt),
end
end cardinal
lemma equiv.cardinal_eq {α β} : α ≃ β → cardinal.mk α = cardinal.mk β :=
cardinal.eq_congr
|
f2b826ae100872aa255eed2b2f9157f88e56d0e3 | 8c9f90127b78cbeb5bb17fd6b5db1db2ffa3cbc4 | /assesment1.lean | 9a14fef01438cd2050466fbda6b33aa95c7f4043 | [] | no_license | picrin/lean | 420f4d08bb3796b911d56d0938e4410e1da0e072 | 3d10c509c79704aa3a88ebfb24d08b30ce1137cc | refs/heads/master | 1,611,166,610,726 | 1,536,671,438,000 | 1,536,671,438,000 | 60,029,899 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,481 | lean | open classical
variables p q r : Prop
lemma andFalseElimRight : ¬(p ∧ q) → p → ¬q :=
assume (LHS : ¬(p ∧ q)) (Hp: p),
(λ (Hq: q), LHS (and.intro Hp Hq))
lemma andFalseElimLeft : ¬(p ∧ q) → (q → ¬p) :=
assume (LHS : ¬(p ∧ q)) (Hq: q),
(λ (Hp: p), LHS (and.intro Hp Hq))
lemma andFalseIntroLeft : ¬p → ¬(p ∧ q) :=
assume (LHS : ¬p),
(λ Hnpq: (p ∧ q), LHS (and.elim_left Hnpq))
lemma andFalseIntroRight : ¬p → ¬(q ∧ p) :=
assume (LHS : ¬p),
(λ Hnpq: (q ∧ p), LHS (and.elim_right Hnpq))
lemma deMorganAndLeft : ¬(p ∧ q) → (¬p ∨ ¬q) :=
assume LHS : ¬(p ∧ q),
-- The claim easily follows from excluded middle on p
or.elim (em p) -- (p ∨ ¬p)
-- if p, we have to first show that ¬q, and then introduce desired disjunction (¬p ∨ ¬q)
(λ Hp: p, or.intro_right (¬p) (andFalseElimRight p q LHS Hp))
-- if ¬p, we can simply introduce desired disjunction (¬p ∨ ¬q)
(λ Hp: (¬p), or.intro_left (¬q) Hp)
lemma deMorganAndRight : (¬p ∨ ¬q) → ¬(p ∧ q) :=
assume LHS : (¬p ∨ ¬q),
or.elim LHS (andFalseIntroLeft p q) (andFalseIntroRight q p)
check (assume (Hnp : (¬p)), deMorganAndRight p (¬q) (or.intro_left (¬¬q) Hnp))
check λ (Hp : p), or.intro_left q (Hp : p)
theorem deMorganAnd : ¬(p ∧ q) ↔ (¬p ∨ ¬q) :=
iff.intro (deMorganAndLeft p q) (deMorganAndRight p q)
theorem deMorganOrRight : (¬p ∧ ¬q) → ¬(p ∨ q) :=
λ (LHS : (¬p) ∧ (¬q)),
λ (Hporq : p ∨ q),
or.elim Hporq
(λ (Hp : p), (and.elim_left LHS) Hp)
(λ (Hq : q), (and.elim_right LHS) Hq)
theorem doubleNeg : ¬¬p → p :=
λ (H : ¬¬p),
or.elim (em p)
(assume Hp : p, Hp)
(assume Hnp : ¬p, absurd Hnp H)
theorem contraposition (Hpq : p → q) (Hnq : ¬q) : ¬p :=
not.intro
(assume Hp : p,
show false, from not.elim Hnq (Hpq Hp))
theorem contrapositionRev : (¬q → ¬p) → (p → q) :=
λ (LHS : (¬q → ¬p)),
λ (Hp : p),
(doubleNeg q (λ (Hq : ¬q), LHS Hq Hp))
theorem doubleNegRev : p → ¬¬p :=
λ (Hp : p), or.elim (em ¬p)
(assume Hnp : ¬p, absurd Hp Hnp)
(assume Hnnp : ¬¬p, Hnnp)
lemma deMorganAndRightNot : (¬p ∨ q) → ¬(p ∧ ¬q) :=
assume LHS : (¬p ∨ q),
or.elim LHS
(assume (Hnp : (¬p)), deMorganAndRight p (¬q) (or.intro_left (¬¬q) Hnp))
(assume (Hq : q), deMorganAndRight p (¬q) (or.intro_right (¬p) (doubleNegRev q Hq)))
theorem deMorganContra : ¬(¬p ∧ ¬q) → ¬¬(p ∨ q) :=
λ (LHS: ¬(¬p ∧ ¬q)), doubleNegRev (p ∨ q) (or.elim ((deMorganAndLeft ¬p ¬q) LHS)
(λ (H1: ¬¬p), or.intro_left q (doubleNeg p H1))
(λ (H2: ¬¬q), or.intro_right p (doubleNeg q H2)))
theorem deMorganOrLeft : ¬(p ∨ q) → (¬p ∧ ¬q) :=
contrapositionRev (¬(p ∨ q)) (¬p ∧ ¬q) (deMorganContra p q)
theorem equiTrans {p q r : Prop} : (p ↔ q) → (q ↔ r) → (p ↔ r) :=
assume eq1 : (p ↔ q),
assume eq2 : (q ↔ r),
iff.intro
(assume Hp: p, (iff.elim_left eq2) ((iff.elim_left eq1) Hp))
(assume Hr: r, (iff.elim_right eq1) ((iff.elim_right eq2) Hr))
theorem distributivity : p ∧ (q ∨ r) → (p ∧ q) ∨ (p ∧ r) :=
λ (LHS : p ∧ (q ∨ r)),
or.elim (and.elim_right LHS)
(λ (Hq : q),
or.intro_left
(p ∧ r)
(and.intro (and.elim_left LHS) Hq))
(λ (Hr : r),
or.intro_right
(p ∧ q)
(and.intro (and.elim_left LHS) Hr))
lemma s1 {p q r : Prop} : ¬(p ∨ (q ∧ ¬r)) ∧ q ↔ (¬p ∧ ¬(q ∧ ¬r)) ∧ q :=
iff.intro
(assume (LHS : ¬(p ∨ (q ∧ ¬r)) ∧ q),
and.intro
(deMorganOrLeft p (q ∧ ¬r)
(and.elim_left LHS))
(and.elim_right LHS))
(assume (LHS : (¬p ∧ ¬(q ∧ ¬r)) ∧ q),
and.intro
(deMorganOrRight p (q ∧ ¬r)
(and.elim_left LHS))
(and.elim_right LHS))
lemma doubleNegOr : (q ∨ r) → (q ∨ ¬¬r) :=
assume (LHS : (q ∨ r)), or.elim LHS
(λ (Hq : q), or.intro_left (¬¬r) Hq)
(λ (Hr : r), or.intro_right q (doubleNegRev r Hr))
lemma doubleNegOrRev : (q ∨ ¬¬r) → (q ∨ r) :=
assume (LHS : (q ∨ ¬¬r)), or.elim LHS
(λ (Hq : q), or.intro_left (r) Hq)
(λ (Hr : ¬¬r), or.intro_right q (doubleNeg r Hr))
lemma s2 {p q r : Prop} : (¬p ∧ ¬(q ∧ ¬r)) ∧ q ↔ (¬p ∧ (¬q ∨ r)) ∧ q :=
iff.intro
(assume (LHS : (¬p ∧ ¬(q ∧ ¬r)) ∧ q),
and.intro
(and.intro
(and.elim_left (and.elim_left LHS))
(doubleNegOrRev (¬q) r (deMorganAndLeft q (¬r) (and.elim_right (and.elim_left LHS)))))
(and.elim_right LHS))
(assume (LHS2 : (¬p ∧ (¬q ∨ r)) ∧ q),
and.intro
((and.intro
((and.elim_left (and.elim_left LHS2)) : (¬p))
((deMorganAndRightNot (q) (r) ((and.elim_right (and.elim_left (LHS2 : (¬p ∧ (¬q ∨ r)) ∧ q))) : (¬q ∨ r))) : (¬(q ∧ ¬r)))) : (¬p ∧ ¬(q ∧ ¬r)))
((and.elim_right (LHS2 : (¬p ∧ (¬q ∨ r)) ∧ q)) : q))
lemma s3 {p q r : Prop} : (¬p ∧ (¬q ∨ r)) ∧ q ↔ ((¬p ∧ ¬q) ∨ (¬p ∧ r)) ∧ q := sorry
lemma s4 {p q r : Prop} : ((¬p ∧ ¬q) ∨ (¬p ∧ r)) ∧ q ↔ ((¬p ∨ (¬p ∧ r)) ∧ (¬q ∨ (¬p ∧ r))) ∧ q := sorry
lemma s5 {p q r : Prop} : ((¬p ∨ (¬p ∧ r)) ∧ (¬q ∨ (¬p ∧ r))) ∧ q ↔ (((¬p ∨ ¬p) ∧ (¬p ∨ r)) ∧ (¬q ∨ (¬p ∧ r))) ∧ q := sorry
lemma s6 {p q r : Prop} : (((¬p ∨ ¬p) ∧ (¬p ∨ r)) ∧ (¬q ∨ (¬p ∧ r))) ∧ q ↔ ((¬p ∨ r) ∧ (¬q ∨ ¬p) ∧ (¬q ∨ r)) ∧ q := sorry
lemma s7 {p q r : Prop} : ((¬p ∨ r) ∧ (¬q ∨ ¬p) ∧ (¬q ∨ r)) ∧ q ↔ (¬p ∨ r) ∧ (¬q ∨ r) ∧ (¬q ∨ ¬p) ∧ q := sorry
lemma s8 {p q r : Prop} : (¬p ∨ r) ∧ (¬q ∨ r) ∧ (¬q ∨ ¬p) ∧ q ↔ (¬(p ∨ q) ∨ r) ∧ ((¬q ∧ q) ∨ (¬p ∧ q)) := sorry
lemma s9 {p q r : Prop} : (¬(p ∨ q) ∨ r) ∧ ((¬q ∧ q) ∨ (¬p ∧ q)) ↔ (¬(p ∨ q) ∨ r) ∧ (¬p ∧ q) := sorry
lemma s11 {p q r : Prop} : (¬(p ∨ q) ∨ r) ∧ (¬p ∧ q) ↔ (r ∧ (¬p ∧ q)) ∨ (¬(p ∨ q) ∧ (¬p ∧ q)) := sorry
lemma s12 {p q r : Prop} : (r ∧ (¬p ∧ q)) ∨ (¬(p ∨ q) ∧ (¬p ∧ q)) ↔ (r ∧ (¬p ∧ q)) ∨ (¬p ∧ ¬q ∧ ¬p ∧ q) := sorry
lemma s13 {p q r : Prop} : (r ∧ (¬p ∧ q)) ∨ (¬p ∧ ¬q ∧ ¬p ∧ q) ↔ ((¬p ∧ ¬q) ∨ (¬p ∧ r)) ∧ q := sorry
lemma s14 {p q r : Prop} : ((¬p ∧ ¬q) ∨ (¬p ∧ r)) ∧ q ↔ ((¬p ∨ (¬p ∧ r)) ∧ (¬q ∨ (¬p ∧ r))) ∧ q := sorry
lemma s15 {p q r : Prop} : ((¬p ∨ (¬p ∧ r)) ∧ (¬q ∨ (¬p ∧ r))) ∧ q ↔ ((¬p ∧ q) ∧ r) := sorry
theorem assessedExercice1 : ¬(p ∨ (q ∧ ¬r)) ∧ q ↔ ((¬p ∧ q) ∧ r) :=
(equiTrans
(equiTrans
(equiTrans
(equiTrans
(equiTrans
(equiTrans
(equiTrans
(equiTrans
(equiTrans
(equiTrans
(equiTrans
(equiTrans
(equiTrans
(s1 : ¬(p ∨ (q ∧ ¬r)) ∧ q ↔ (¬p ∧ ¬(q ∧ ¬r)) ∧ q)
(s2 : (¬p ∧ ¬(q ∧ ¬r)) ∧ q ↔ (¬p ∧ (¬q ∨ r)) ∧ q))
(s3 : (¬p ∧ (¬q ∨ r)) ∧ q ↔ ((¬p ∧ ¬q) ∨ (¬p ∧ r)) ∧ q))
(s4 : ((¬p ∧ ¬q) ∨ (¬p ∧ r)) ∧ q ↔ ((¬p ∨ (¬p ∧ r)) ∧ (¬q ∨ (¬p ∧ r))) ∧ q))
(s5 : ((¬p ∨ (¬p ∧ r)) ∧ (¬q ∨ (¬p ∧ r))) ∧ q ↔ (((¬p ∨ ¬p) ∧ (¬p ∨ r)) ∧ (¬q ∨ (¬p ∧ r))) ∧ q))
(s6 : (((¬p ∨ ¬p) ∧ (¬p ∨ r)) ∧ (¬q ∨ (¬p ∧ r))) ∧ q ↔ ((¬p ∨ r) ∧ (¬q ∨ ¬p) ∧ (¬q ∨ r)) ∧ q))
(s7: ((¬p ∨ r) ∧ (¬q ∨ ¬p) ∧ (¬q ∨ r)) ∧ q ↔ (¬p ∨ r) ∧ (¬q ∨ r) ∧ (¬q ∨ ¬p) ∧ q))
(s8: (¬p ∨ r) ∧ (¬q ∨ r) ∧ (¬q ∨ ¬p) ∧ q ↔ (¬(p ∨ q) ∨ r) ∧ ((¬q ∧ q) ∨ (¬p ∧ q))))
(s9 : (¬(p ∨ q) ∨ r) ∧ ((¬q ∧ q) ∨ (¬p ∧ q)) ↔ (¬(p ∨ q) ∨ r) ∧ (¬p ∧ q)))
(s11 : (¬(p ∨ q) ∨ r) ∧ (¬p ∧ q) ↔ (r ∧ (¬p ∧ q)) ∨ (¬(p ∨ q) ∧ (¬p ∧ q))))
(s12 : (r ∧ (¬p ∧ q)) ∨ (¬(p ∨ q) ∧ (¬p ∧ q)) ↔ (r ∧ (¬p ∧ q)) ∨ (¬p ∧ ¬q ∧ ¬p ∧ q)))
(s13 : (r ∧ (¬p ∧ q)) ∨ (¬p ∧ ¬q ∧ ¬p ∧ q) ↔ ((¬p ∧ ¬q) ∨ (¬p ∧ r)) ∧ q))
(s14 : ((¬p ∧ ¬q) ∨ (¬p ∧ r)) ∧ q ↔ ((¬p ∨ (¬p ∧ r)) ∧ (¬q ∨ (¬p ∧ r))) ∧ q))
(s15: ((¬p ∨ (¬p ∧ r)) ∧ (¬q ∨ (¬p ∧ r))) ∧ q ↔ ((¬p ∧ q) ∧ r)))
check assessedExercice1
-- Informally we have to show that:
-- ¬(p ∨ (q ∧ ¬r)) ∧ q ↔
-- (¬p ∧ q) ∧ r
-- We could do it like this:
-- ¬(p ∨ (q ∧ ¬r)) ∧ q ↔ (s1)
-- (¬p ∧ ¬(q ∧ ¬r)) ∧ q ↔ (s2)
-- ¬p ∧ (¬q ∨ r) ∧ q ↔ (s3)
-- ((¬p ∧ ¬q) ∨ (¬p ∧ r)) ∧ q ↔ (s4)
-- ((¬p ∨ (¬p ∧ r)) ∧ (¬q ∨ (¬p ∧ r))) ∧ q ↔ (s5)
-- (((¬p ∨ ¬p) ∧ (¬p ∨ r)) ∧ (¬q ∨ (¬p ∧ r))) ∧ q ↔ (s6)
-- ((¬p ∨ r) ∧ (¬q ∨ ¬p) ∧ (¬q ∨ r)) ∧ q ↔ (s7)
-- (¬p ∨ r) ∧ (¬q ∨ r) ∧ (¬q ∨ ¬p) ∧ q ↔ (s8)
-- (¬(p ∨ q) ∨ r) ∧ ((¬q ∧ q) ∨ (¬p ∧ q)) ↔ (s9)
-- (¬(p ∨ q) ∨ r) ∧ (¬p ∧ q) ↔ (s10)
-- (r ∧ (¬p ∧ q)) ∨ (¬(p ∨ q) ∧ (¬p ∧ q)) ↔ (s11)
-- (r ∧ (¬p ∧ q)) ∨ (¬(p ∨ q) ∧ (¬p ∧ q)) ↔ (s12)
-- (r ∧ (¬p ∧ q)) ∨ (¬p ∧ ¬q ∧ ¬p ∧ q) ↔ (s13)
-- (r ∧ (¬p ∧ q)) ∨ 0 ↔ (s14)
-- ((¬p ∧ q) ∧ r)
|
56198d32de6dc188f03a6416f841c90b4109818f | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/algebra/big_operators/basic.lean | 84b21f722d20d5d4bd524e32b47cd8c465add2a5 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 79,652 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import algebra.group.pi
import algebra.hom.equiv
import algebra.ring.opposite
import data.finset.fold
import data.fintype.basic
import data.set.pairwise
/-!
# Big operators
In this file we define products and sums indexed by finite sets (specifically, `finset`).
## Notation
We introduce the following notation, localized in `big_operators`.
To enable the notation, use `open_locale big_operators`.
Let `s` be a `finset α`, and `f : α → β` a function.
* `∏ x in s, f x` is notation for `finset.prod s f` (assuming `β` is a `comm_monoid`)
* `∑ x in s, f x` is notation for `finset.sum s f` (assuming `β` is an `add_comm_monoid`)
* `∏ x, f x` is notation for `finset.prod finset.univ f`
(assuming `α` is a `fintype` and `β` is a `comm_monoid`)
* `∑ x, f x` is notation for `finset.sum finset.univ f`
(assuming `α` is a `fintype` and `β` is an `add_comm_monoid`)
## Implementation Notes
The first arguments in all definitions and lemmas is the codomain of the function of the big
operator. This is necessary for the heuristic in `@[to_additive]`.
See the documentation of `to_additive.attr` for more information.
-/
universes u v w
variables {ι : Type*} {β : Type u} {α : Type v} {γ : Type w}
open fin
namespace finset
/--
`∏ x in s, f x` is the product of `f x`
as `x` ranges over the elements of the finite set `s`.
-/
@[to_additive "`∑ x in s, f x` is the sum of `f x` as `x` ranges over the elements
of the finite set `s`."]
protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod
@[simp, to_additive] lemma prod_mk [comm_monoid β] (s : multiset α) (hs : s.nodup) (f : α → β) :
(⟨s, hs⟩ : finset α).prod f = (s.map f).prod :=
rfl
@[simp, to_additive] lemma prod_val [comm_monoid α] (s : finset α) : s.1.prod = s.prod id :=
by rw [finset.prod, multiset.map_id]
end finset
/--
There is no established mathematical convention
for the operator precedence of big operators like `∏` and `∑`.
We will have to make a choice.
Online discussions, such as https://math.stackexchange.com/q/185538/30839
seem to suggest that `∏` and `∑` should have the same precedence,
and that this should be somewhere between `*` and `+`.
The latter have precedence levels `70` and `65` respectively,
and we therefore choose the level `67`.
In practice, this means that parentheses should be placed as follows:
```lean
∑ k in K, (a k + b k) = ∑ k in K, a k + ∑ k in K, b k →
∏ k in K, a k * b k = (∏ k in K, a k) * (∏ k in K, b k)
```
(Example taken from page 490 of Knuth's *Concrete Mathematics*.)
-/
library_note "operator precedence of big operators"
localized "notation `∑` binders `, ` r:(scoped:67 f, finset.sum finset.univ f) := r"
in big_operators
localized "notation `∏` binders `, ` r:(scoped:67 f, finset.prod finset.univ f) := r"
in big_operators
localized "notation `∑` binders ` in ` s `, ` r:(scoped:67 f, finset.sum s f) := r"
in big_operators
localized "notation `∏` binders ` in ` s `, ` r:(scoped:67 f, finset.prod s f) := r"
in big_operators
open_locale big_operators
namespace finset
variables {s s₁ s₂ : finset α} {a : α} {f g : α → β}
@[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) :
∏ x in s, f x = (s.1.map f).prod := rfl
@[to_additive]
theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) :
∏ x in s, f x = s.fold (*) 1 f :=
rfl
@[simp] lemma sum_multiset_singleton (s : finset α) :
s.sum (λ x, {x}) = s.val :=
by simp only [sum_eq_multiset_sum, multiset.sum_map_singleton]
end finset
@[to_additive]
lemma map_prod [comm_monoid β] [comm_monoid γ] {G : Type*} [monoid_hom_class G β γ] (g : G)
(f : α → β) (s : finset α) :
g (∏ x in s, f x) = ∏ x in s, g (f x) :=
by simp only [finset.prod_eq_multiset_prod, map_multiset_prod, multiset.map_map]
section deprecated
/-- Deprecated: use `_root_.map_prod` instead. -/
@[to_additive "Deprecated: use `_root_.map_sum` instead."]
protected lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β)
(s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) :=
map_prod g f s
/-- Deprecated: use `_root_.map_prod` instead. -/
@[to_additive "Deprecated: use `_root_.map_sum` instead."]
protected lemma mul_equiv.map_prod [comm_monoid β] [comm_monoid γ] (g : β ≃* γ) (f : α → β)
(s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) :=
map_prod g f s
/-- Deprecated: use `_root_.map_list_prod` instead. -/
protected lemma ring_hom.map_list_prod [semiring β] [semiring γ] (f : β →+* γ) (l : list β) :
f l.prod = (l.map f).prod :=
map_list_prod f l
/-- Deprecated: use `_root_.map_list_sum` instead. -/
protected lemma ring_hom.map_list_sum [non_assoc_semiring β] [non_assoc_semiring γ]
(f : β →+* γ) (l : list β) :
f l.sum = (l.map f).sum :=
map_list_sum f l
/-- A morphism into the opposite ring acts on the product by acting on the reversed elements.
Deprecated: use `_root_.unop_map_list_prod` instead.
-/
protected lemma ring_hom.unop_map_list_prod [semiring β] [semiring γ] (f : β →+* γᵐᵒᵖ)
(l : list β) : mul_opposite.unop (f l.prod) = (l.map (mul_opposite.unop ∘ f)).reverse.prod :=
unop_map_list_prod f l
/-- Deprecated: use `_root_.map_multiset_prod` instead. -/
protected lemma ring_hom.map_multiset_prod [comm_semiring β] [comm_semiring γ] (f : β →+* γ)
(s : multiset β) :
f s.prod = (s.map f).prod :=
map_multiset_prod f s
/-- Deprecated: use `_root_.map_multiset_sum` instead. -/
protected lemma ring_hom.map_multiset_sum [non_assoc_semiring β] [non_assoc_semiring γ]
(f : β →+* γ) (s : multiset β) :
f s.sum = (s.map f).sum :=
map_multiset_sum f s
/-- Deprecated: use `_root_.map_prod` instead. -/
protected lemma ring_hom.map_prod [comm_semiring β] [comm_semiring γ] (g : β →+* γ) (f : α → β)
(s : finset α) :
g (∏ x in s, f x) = ∏ x in s, g (f x) :=
map_prod g f s
/-- Deprecated: use `_root_.map_sum` instead. -/
protected lemma ring_hom.map_sum [non_assoc_semiring β] [non_assoc_semiring γ]
(g : β →+* γ) (f : α → β) (s : finset α) :
g (∑ x in s, f x) = ∑ x in s, g (f x) :=
map_sum g f s
end deprecated
@[to_additive]
lemma monoid_hom.coe_finset_prod [mul_one_class β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) :
⇑(∏ x in s, f x) = ∏ x in s, f x :=
(monoid_hom.coe_fn β γ).map_prod _ _
-- See also `finset.prod_apply`, with the same conclusion
-- but with the weaker hypothesis `f : α → β → γ`.
@[simp, to_additive]
lemma monoid_hom.finset_prod_apply [mul_one_class β] [comm_monoid γ] (f : α → β →* γ)
(s : finset α) (b : β) : (∏ x in s, f x) b = ∏ x in s, f x b :=
(monoid_hom.eval b).map_prod _ _
variables {s s₁ s₂ : finset α} {a : α} {f g : α → β}
namespace finset
section comm_monoid
variables [comm_monoid β]
@[simp, to_additive] lemma prod_empty : ∏ x in ∅, f x = 1 := rfl
@[to_additive] lemma prod_of_empty [is_empty α] : ∏ i, f i = 1 := by rw [univ_eq_empty, prod_empty]
@[simp, to_additive]
lemma prod_cons (h : a ∉ s) : (∏ x in (cons a s h), f x) = f a * ∏ x in s, f x :=
fold_cons h
@[simp, to_additive]
lemma prod_insert [decidable_eq α] : a ∉ s → (∏ x in (insert a s), f x) = f a * ∏ x in s, f x :=
fold_insert
/--
The product of `f` over `insert a s` is the same as
the product over `s`, as long as `a` is in `s` or `f a = 1`.
-/
@[simp, to_additive "The sum of `f` over `insert a s` is the same as
the sum over `s`, as long as `a` is in `s` or `f a = 0`."]
lemma prod_insert_of_eq_one_if_not_mem [decidable_eq α] (h : a ∉ s → f a = 1) :
∏ x in insert a s, f x = ∏ x in s, f x :=
begin
by_cases hm : a ∈ s,
{ simp_rw insert_eq_of_mem hm },
{ rw [prod_insert hm, h hm, one_mul] },
end
/--
The product of `f` over `insert a s` is the same as the product over `s`, as long as `f a = 1`.
-/
@[simp, to_additive "The sum of `f` over `insert a s` is the same as
the sum over `s`, as long as `f a = 0`."]
lemma prod_insert_one [decidable_eq α] (h : f a = 1) :
∏ x in insert a s, f x = ∏ x in s, f x :=
prod_insert_of_eq_one_if_not_mem (λ _, h)
@[simp, to_additive]
lemma prod_singleton : (∏ x in (singleton a), f x) = f a :=
eq.trans fold_singleton $ mul_one _
@[to_additive]
lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) :
(∏ x in ({a, b} : finset α), f x) = f a * f b :=
by rw [prod_insert (not_mem_singleton.2 h), prod_singleton]
@[simp, priority 1100, to_additive]
lemma prod_const_one : (∏ x in s, (1 : β)) = 1 :=
by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow]
@[simp, to_additive]
lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} :
(∀ x ∈ s, ∀ y ∈ s, g x = g y → x = y) → (∏ x in (s.image g), f x) = ∏ x in s, f (g x) :=
fold_image
@[simp, to_additive]
lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) :
(∏ x in (s.map e), f x) = ∏ x in s, f (e x) :=
by rw [finset.prod, finset.map_val, multiset.map_map]; refl
@[congr, to_additive]
lemma prod_congr (h : s₁ = s₂) : (∀ x ∈ s₂, f x = g x) → s₁.prod f = s₂.prod g :=
by rw [h]; exact fold_congr
attribute [congr] finset.sum_congr
@[to_additive]
lemma prod_disj_union (h) : ∏ x in s₁.disj_union s₂ h, f x = (∏ x in s₁, f x) * ∏ x in s₂, f x :=
by { refine eq.trans _ (fold_disj_union h), rw one_mul, refl }
@[to_additive]
lemma prod_union_inter [decidable_eq α] :
(∏ x in (s₁ ∪ s₂), f x) * (∏ x in (s₁ ∩ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) :=
fold_union_inter
@[to_additive]
lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) :
(∏ x in (s₁ ∪ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) :=
by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm
@[to_additive]
lemma prod_filter_mul_prod_filter_not (s : finset α) (p : α → Prop) [decidable_pred p]
[decidable_pred (λ x, ¬p x)] (f : α → β) :
(∏ x in s.filter p, f x) * (∏ x in s.filter (λ x, ¬p x), f x) = ∏ x in s, f x :=
begin
haveI := classical.dec_eq α,
rw [← prod_union (filter_inter_filter_neg_eq p s).le, filter_union_filter_neg_eq]
end
section to_list
@[simp, to_additive]
lemma prod_to_list (s : finset α) (f : α → β) : (s.to_list.map f).prod = s.prod f :=
by rw [finset.prod, ← multiset.coe_prod, ← multiset.coe_map, finset.coe_to_list]
end to_list
@[to_additive]
lemma _root_.equiv.perm.prod_comp (σ : equiv.perm α) (s : finset α) (f : α → β)
(hs : {a | σ a ≠ a} ⊆ s) :
(∏ x in s, f (σ x)) = ∏ x in s, f x :=
by { convert (prod_map _ σ.to_embedding _).symm, exact (map_perm hs).symm }
@[to_additive]
lemma _root_.equiv.perm.prod_comp' (σ : equiv.perm α) (s : finset α) (f : α → α → β)
(hs : {a | σ a ≠ a} ⊆ s) :
(∏ x in s, f (σ x) x) = ∏ x in s, f x (σ.symm x) :=
by { convert σ.prod_comp s (λ x, f x (σ.symm x)) hs, ext, rw equiv.symm_apply_apply }
end comm_monoid
end finset
section
open finset
variables [fintype α] [decidable_eq α] [comm_monoid β]
@[to_additive]
lemma is_compl.prod_mul_prod {s t : finset α} (h : is_compl s t) (f : α → β) :
(∏ i in s, f i) * (∏ i in t, f i) = ∏ i, f i :=
(finset.prod_union h.disjoint).symm.trans $ by rw [← finset.sup_eq_union, h.sup_eq_top]; refl
end
namespace finset
section comm_monoid
variables [comm_monoid β]
/-- Multiplying the products of a function over `s` and over `sᶜ` gives the whole product.
For a version expressed with subtypes, see `fintype.prod_subtype_mul_prod_subtype`. -/
@[to_additive "Adding the sums of a function over `s` and over `sᶜ` gives the whole sum.
For a version expressed with subtypes, see `fintype.sum_subtype_add_sum_subtype`. "]
lemma prod_mul_prod_compl [fintype α] [decidable_eq α] (s : finset α) (f : α → β) :
(∏ i in s, f i) * (∏ i in sᶜ, f i) = ∏ i, f i :=
is_compl.prod_mul_prod is_compl_compl f
@[to_additive]
lemma prod_compl_mul_prod [fintype α] [decidable_eq α] (s : finset α) (f : α → β) :
(∏ i in sᶜ, f i) * (∏ i in s, f i) = ∏ i, f i :=
(@is_compl_compl _ s _).symm.prod_mul_prod f
@[to_additive]
lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) :
(∏ x in (s₂ \ s₁), f x) * (∏ x in s₁, f x) = (∏ x in s₂, f x) :=
by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h]
@[simp, to_additive]
lemma prod_sum_elim [decidable_eq (α ⊕ γ)]
(s : finset α) (t : finset γ) (f : α → β) (g : γ → β) :
∏ x in s.map function.embedding.inl ∪ t.map function.embedding.inr, sum.elim f g x =
(∏ x in s, f x) * (∏ x in t, g x) :=
begin
rw [prod_union, prod_map, prod_map],
{ simp only [sum.elim_inl, function.embedding.inl_apply, function.embedding.inr_apply,
sum.elim_inr] },
{ simp only [disjoint_left, finset.mem_map, finset.mem_map],
rintros _ ⟨i, hi, rfl⟩ ⟨j, hj, H⟩,
cases H }
end
@[simp, to_additive]
lemma prod_on_sum [fintype α] [fintype γ] (f : α ⊕ γ → β) :
∏ (x : α ⊕ γ), f x =
(∏ (x : α), f (sum.inl x)) * (∏ (x : γ), f (sum.inr x)) :=
begin
haveI := classical.dec_eq (α ⊕ γ),
convert prod_sum_elim univ univ (λ x, f (sum.inl x)) (λ x, f (sum.inr x)),
{ ext a,
split,
{ intro x,
cases a,
{ simp only [mem_union, mem_map, mem_univ, function.embedding.inl_apply, or_false,
exists_true_left, exists_apply_eq_apply, function.embedding.inr_apply, exists_false], },
{ simp only [mem_union, mem_map, mem_univ, function.embedding.inl_apply, false_or,
exists_true_left, exists_false, function.embedding.inr_apply,
exists_apply_eq_apply], }, },
{ simp only [mem_univ, implies_true_iff], }, },
{ simp only [sum.elim_comp_inl_inr], },
end
@[to_additive]
lemma prod_bUnion [decidable_eq α] {s : finset γ} {t : γ → finset α}
(hs : set.pairwise_disjoint ↑s t) :
(∏ x in (s.bUnion t), f x) = ∏ x in s, ∏ i in t x, f i :=
begin
haveI := classical.dec_eq γ,
induction s using finset.induction_on with x s hxs ih hd,
{ simp_rw [bUnion_empty, prod_empty] },
{ simp_rw [coe_insert, set.pairwise_disjoint_insert, mem_coe] at hs,
have : disjoint (t x) (finset.bUnion s t),
{ exact (disjoint_bUnion_right _ _ _).mpr (λ y hy, hs.2 y hy $ λ H, hxs $ H.substr hy) },
rw [bUnion_insert, prod_insert hxs, prod_union this, ih hs.1] }
end
/-- Product over a sigma type equals the product of fiberwise products. For rewriting
in the reverse direction, use `finset.prod_sigma'`. -/
@[to_additive "Sum over a sigma type equals the sum of fiberwise sums. For rewriting
in the reverse direction, use `finset.sum_sigma'`"]
lemma prod_sigma {σ : α → Type*}
(s : finset α) (t : Π a, finset (σ a)) (f : sigma σ → β) :
(∏ x in s.sigma t, f x) = ∏ a in s, ∏ s in (t a), f ⟨a, s⟩ :=
by classical;
calc (∏ x in s.sigma t, f x) =
∏ x in s.bUnion (λ a, (t a).map (function.embedding.sigma_mk a)), f x : by rw sigma_eq_bUnion
... = ∏ a in s, ∏ x in (t a).map (function.embedding.sigma_mk a), f x :
prod_bUnion $ assume a₁ ha a₂ ha₂ h x hx,
by { simp only [inf_eq_inter, mem_inter, mem_map, function.embedding.sigma_mk_apply] at hx,
rcases hx with ⟨⟨y, hy, rfl⟩, ⟨z, hz, hz'⟩⟩, cc }
... = ∏ a in s, ∏ s in t a, f ⟨a, s⟩ :
prod_congr rfl $ λ _ _, prod_map _ _ _
@[to_additive]
lemma prod_sigma' {σ : α → Type*}
(s : finset α) (t : Π a, finset (σ a)) (f : Π a, σ a → β) :
(∏ a in s, ∏ s in (t a), f a s) = ∏ x in s.sigma t, f x.1 x.2 :=
eq.symm $ prod_sigma s t (λ x, f x.1 x.2)
/--
Reorder a product.
The difference with `prod_bij'` is that the bijection is specified as a surjective injection,
rather than by an inverse function.
-/
@[to_additive "
Reorder a sum.
The difference with `sum_bij'` is that the bijection is specified as a surjective injection,
rather than by an inverse function.
"]
lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β}
(i : Π a ∈ s, γ) (hi : ∀ a ha, i a ha ∈ t) (h : ∀ a ha, f a = g (i a ha))
(i_inj : ∀ a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀ b ∈ t, ∃ a ha, b = i a ha) :
(∏ x in s, f x) = (∏ x in t, g x) :=
congr_arg multiset.prod
(multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj)
/--
Reorder a product.
The difference with `prod_bij` is that the bijection is specified with an inverse, rather than
as a surjective injection.
-/
@[to_additive "
Reorder a sum.
The difference with `sum_bij` is that the bijection is specified with an inverse, rather than
as a surjective injection.
"]
lemma prod_bij' {s : finset α} {t : finset γ} {f : α → β} {g : γ → β}
(i : Π a ∈ s, γ) (hi : ∀ a ha, i a ha ∈ t) (h : ∀ a ha, f a = g (i a ha))
(j : Π a ∈ t, α) (hj : ∀ a ha, j a ha ∈ s) (left_inv : ∀ a ha, j (i a ha) (hi a ha) = a)
(right_inv : ∀ a ha, i (j a ha) (hj a ha) = a) :
(∏ x in s, f x) = (∏ x in t, g x) :=
begin
refine prod_bij i hi h _ _,
{intros a1 a2 h1 h2 eq, rw [←left_inv a1 h1, ←left_inv a2 h2], cc,},
{intros b hb, use j b hb, use hj b hb, exact (right_inv b hb).symm,},
end
@[to_additive] lemma prod_finset_product
(r : finset (γ × α)) (s : finset γ) (t : γ → finset α)
(h : ∀ p : γ × α, p ∈ r ↔ p.1 ∈ s ∧ p.2 ∈ t p.1) {f : γ × α → β} :
∏ p in r, f p = ∏ c in s, ∏ a in t c, f (c, a) :=
begin
refine eq.trans _ (prod_sigma s t (λ p, f (p.1, p.2))),
exact prod_bij' (λ p hp, ⟨p.1, p.2⟩) (λ p, mem_sigma.mpr ∘ (h p).mp)
(λ p hp, congr_arg f prod.mk.eta.symm) (λ p hp, (p.1, p.2))
(λ p, (h (p.1, p.2)).mpr ∘ mem_sigma.mp) (λ p hp, prod.mk.eta) (λ p hp, p.eta),
end
@[to_additive] lemma prod_finset_product'
(r : finset (γ × α)) (s : finset γ) (t : γ → finset α)
(h : ∀ p : γ × α, p ∈ r ↔ p.1 ∈ s ∧ p.2 ∈ t p.1) {f : γ → α → β} :
∏ p in r, f p.1 p.2 = ∏ c in s, ∏ a in t c, f c a :=
prod_finset_product r s t h
@[to_additive] lemma prod_finset_product_right
(r : finset (α × γ)) (s : finset γ) (t : γ → finset α)
(h : ∀ p : α × γ, p ∈ r ↔ p.2 ∈ s ∧ p.1 ∈ t p.2) {f : α × γ → β} :
∏ p in r, f p = ∏ c in s, ∏ a in t c, f (a, c) :=
begin
refine eq.trans _ (prod_sigma s t (λ p, f (p.2, p.1))),
exact prod_bij' (λ p hp, ⟨p.2, p.1⟩) (λ p, mem_sigma.mpr ∘ (h p).mp)
(λ p hp, congr_arg f prod.mk.eta.symm) (λ p hp, (p.2, p.1))
(λ p, (h (p.2, p.1)).mpr ∘ mem_sigma.mp) (λ p hp, prod.mk.eta) (λ p hp, p.eta),
end
@[to_additive] lemma prod_finset_product_right'
(r : finset (α × γ)) (s : finset γ) (t : γ → finset α)
(h : ∀ p : α × γ, p ∈ r ↔ p.2 ∈ s ∧ p.1 ∈ t p.2) {f : α → γ → β} :
∏ p in r, f p.1 p.2 = ∏ c in s, ∏ a in t c, f a c :=
prod_finset_product_right r s t h
@[to_additive]
lemma prod_fiberwise_of_maps_to [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ}
(h : ∀ x ∈ s, g x ∈ t) (f : α → β) :
(∏ y in t, ∏ x in s.filter (λ x, g x = y), f x) = ∏ x in s, f x :=
begin
letI := classical.dec_eq α,
rw [← bUnion_filter_eq_of_maps_to h] {occs := occurrences.pos [2]},
refine (prod_bUnion $ λ x' hx y' hy hne, _).symm,
rw [function.on_fun, disjoint_filter],
rintros x hx rfl,
exact hne
end
@[to_additive]
lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β)
(eq : ∀ c ∈ s, f (g c) = ∏ x in s.filter (λ c', g c' = g c), h x) :
(∏ x in s.image g, f x) = ∏ x in s, h x :=
calc (∏ x in s.image g, f x) = ∏ x in s.image g, ∏ x in s.filter (λ c', g c' = x), h x :
prod_congr rfl $ λ x hx, let ⟨c, hcs, hc⟩ := mem_image.1 hx in hc ▸ (eq c hcs)
... = ∏ x in s, h x : prod_fiberwise_of_maps_to (λ x, mem_image_of_mem g) _
@[to_additive]
lemma prod_mul_distrib : ∏ x in s, (f x * g x) = (∏ x in s, f x) * (∏ x in s, g x) :=
eq.trans (by rw one_mul; refl) fold_op_distrib
@[to_additive]
lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} :
(∏ x in s ×ˢ t, f x) = ∏ x in s, ∏ y in t, f (x, y) :=
prod_finset_product (s ×ˢ t) s (λ a, t) (λ p, mem_product)
/-- An uncurried version of `finset.prod_product`. -/
@[to_additive "An uncurried version of `finset.sum_product`"]
lemma prod_product' {s : finset γ} {t : finset α} {f : γ → α → β} :
(∏ x in s ×ˢ t, f x.1 x.2) = ∏ x in s, ∏ y in t, f x y :=
prod_product
@[to_additive]
lemma prod_product_right {s : finset γ} {t : finset α} {f : γ×α → β} :
(∏ x in s ×ˢ t, f x) = ∏ y in t, ∏ x in s, f (x, y) :=
prod_finset_product_right (s ×ˢ t) t (λ a, s) (λ p, mem_product.trans and.comm)
/-- An uncurried version of `finset.prod_product_right`. -/
@[to_additive "An uncurried version of `finset.prod_product_right`"]
lemma prod_product_right' {s : finset γ} {t : finset α} {f : γ → α → β} :
(∏ x in s ×ˢ t, f x.1 x.2) = ∏ y in t, ∏ x in s, f x y :=
prod_product_right
/-- Generalization of `finset.prod_comm` to the case when the inner `finset`s depend on the outer
variable. -/
@[to_additive "Generalization of `finset.sum_comm` to the case when the inner `finset`s depend on
the outer variable."]
lemma prod_comm' {s : finset γ} {t : γ → finset α} {t' : finset α} {s' : α → finset γ}
(h : ∀ x y, x ∈ s ∧ y ∈ t x ↔ x ∈ s' y ∧ y ∈ t') {f : γ → α → β} :
(∏ x in s, ∏ y in t x, f x y) = (∏ y in t', ∏ x in s' y, f x y) :=
begin
classical,
have : ∀ z : γ × α,
z ∈ s.bUnion (λ x, (t x).map $ function.embedding.sectr x _) ↔ z.1 ∈ s ∧ z.2 ∈ t z.1,
{ rintro ⟨x, y⟩, simp },
exact (prod_finset_product' _ _ _ this).symm.trans
(prod_finset_product_right' _ _ _ $ λ ⟨x, y⟩, (this _).trans ((h x y).trans and.comm))
end
@[to_additive]
lemma prod_comm {s : finset γ} {t : finset α} {f : γ → α → β} :
(∏ x in s, ∏ y in t, f x y) = (∏ y in t, ∏ x in s, f x y) :=
prod_comm' $ λ _ _, iff.rfl
@[to_additive]
lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α}
(h₁ : r 1 1) (h₂ : ∀ a b c, r b c → r (f a * b) (g a * c)) : r (∏ x in s, f x) (∏ x in s, g x) :=
by { delta finset.prod, apply multiset.prod_hom_rel; assumption }
@[to_additive]
lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀ x ∈ s, f x = 1) : (∏ x in s, f x) = 1 :=
calc (∏ x in s, f x) = ∏ x in s, 1 : finset.prod_congr rfl h
... = 1 : finset.prod_const_one
@[to_additive]
lemma prod_subset_one_on_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) (hg : ∀ x ∈ (s₂ \ s₁), g x = 1)
(hfg : ∀ x ∈ s₁, f x = g x) : ∏ i in s₁, f i = ∏ i in s₂, g i :=
begin
rw [← prod_sdiff h, prod_eq_one hg, one_mul],
exact prod_congr rfl hfg
end
@[to_additive]
lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀ x ∈ s₂, x ∉ s₁ → f x = 1) :
(∏ x in s₁, f x) = ∏ x in s₂, f x :=
by haveI := classical.dec_eq α; exact prod_subset_one_on_sdiff h (by simpa) (λ _ _, rfl)
@[to_additive]
lemma prod_filter_of_ne {p : α → Prop} [decidable_pred p] (hp : ∀ x ∈ s, f x ≠ 1 → p x) :
(∏ x in (s.filter p), f x) = (∏ x in s, f x) :=
prod_subset (filter_subset _ _) $ λ x,
by { classical, rw [not_imp_comm, mem_filter], exact λ h₁ h₂, ⟨h₁, hp _ h₁ h₂⟩ }
-- If we use `[decidable_eq β]` here, some rewrites fail because they find a wrong `decidable`
-- instance first; `{∀ x, decidable (f x ≠ 1)}` doesn't work with `rw ← prod_filter_ne_one`
@[to_additive]
lemma prod_filter_ne_one [∀ x, decidable (f x ≠ 1)] :
(∏ x in (s.filter $ λ x, f x ≠ 1), f x) = (∏ x in s, f x) :=
prod_filter_of_ne $ λ _ _, id
@[to_additive]
lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) :
(∏ a in s.filter p, f a) = (∏ a in s, if p a then f a else 1) :=
calc (∏ a in s.filter p, f a) = ∏ a in s.filter p, if p a then f a else 1 :
prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2])
... = ∏ a in s, if p a then f a else 1 :
begin
refine prod_subset (filter_subset _ s) (assume x hs h, _),
rw [mem_filter, not_and] at h,
exact if_neg (h hs)
end
@[to_additive]
lemma prod_eq_single_of_mem {s : finset α} {f : α → β} (a : α) (h : a ∈ s)
(h₀ : ∀ b ∈ s, b ≠ a → f b = 1) : (∏ x in s, f x) = f a :=
begin
haveI := classical.dec_eq α,
calc (∏ x in s, f x) = ∏ x in {a}, f x :
begin
refine (prod_subset _ _).symm,
{ intros _ H, rwa mem_singleton.1 H },
{ simpa only [mem_singleton] }
end
... = f a : prod_singleton
end
@[to_additive]
lemma prod_eq_single {s : finset α} {f : α → β} (a : α)
(h₀ : ∀ b ∈ s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : (∏ x in s, f x) = f a :=
by haveI := classical.dec_eq α;
from classical.by_cases
(assume : a ∈ s, prod_eq_single_of_mem a this h₀)
(assume : a ∉ s,
(prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $
prod_const_one.trans (h₁ this).symm)
@[to_additive]
lemma prod_eq_mul_of_mem {s : finset α} {f : α → β} (a b : α) (ha : a ∈ s) (hb : b ∈ s) (hn : a ≠ b)
(h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) : (∏ x in s, f x) = (f a) * (f b) :=
begin
haveI := classical.dec_eq α;
let s' := ({a, b} : finset α),
have hu : s' ⊆ s,
{ refine insert_subset.mpr _, apply and.intro ha, apply singleton_subset_iff.mpr hb },
have hf : ∀ c ∈ s, c ∉ s' → f c = 1,
{ intros c hc hcs,
apply h₀ c hc,
apply not_or_distrib.mp,
intro hab,
apply hcs,
apply mem_insert.mpr,
rw mem_singleton,
exact hab },
rw ←prod_subset hu hf,
exact finset.prod_pair hn
end
@[to_additive]
lemma prod_eq_mul {s : finset α} {f : α → β} (a b : α) (hn : a ≠ b)
(h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) (ha : a ∉ s → f a = 1) (hb : b ∉ s → f b = 1) :
(∏ x in s, f x) = (f a) * (f b) :=
begin
haveI := classical.dec_eq α;
by_cases h₁ : a ∈ s; by_cases h₂ : b ∈ s,
{ exact prod_eq_mul_of_mem a b h₁ h₂ hn h₀ },
{ rw [hb h₂, mul_one],
apply prod_eq_single_of_mem a h₁,
exact λ c hc hca, h₀ c hc ⟨hca, ne_of_mem_of_not_mem hc h₂⟩ },
{ rw [ha h₁, one_mul],
apply prod_eq_single_of_mem b h₂,
exact λ c hc hcb, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, hcb⟩ },
{ rw [ha h₁, hb h₂, mul_one],
exact trans
(prod_congr rfl (λ c hc, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, ne_of_mem_of_not_mem hc h₂⟩))
prod_const_one }
end
@[to_additive]
lemma prod_attach {f : α → β} : (∏ x in s.attach, f x) = (∏ x in s, f x) :=
by haveI := classical.dec_eq α; exact
calc (∏ x in s.attach, f x.val) = (∏ x in (s.attach).image subtype.val, f x) :
by rw [prod_image]; exact assume x _ y _, subtype.eq
... = _ : by rw [attach_image_val]
/-- A product over `s.subtype p` equals one over `s.filter p`. -/
@[simp, to_additive "A sum over `s.subtype p` equals one over `s.filter p`."]
lemma prod_subtype_eq_prod_filter (f : α → β) {p : α → Prop} [decidable_pred p] :
∏ x in s.subtype p, f x = ∏ x in s.filter p, f x :=
begin
conv_lhs { erw ←prod_map (s.subtype p) (function.embedding.subtype _) f },
exact prod_congr (subtype_map _) (λ x hx, rfl)
end
/-- If all elements of a `finset` satisfy the predicate `p`, a product
over `s.subtype p` equals that product over `s`. -/
@[to_additive "If all elements of a `finset` satisfy the predicate `p`, a sum
over `s.subtype p` equals that sum over `s`."]
lemma prod_subtype_of_mem (f : α → β) {p : α → Prop} [decidable_pred p]
(h : ∀ x ∈ s, p x) : ∏ x in s.subtype p, f x = ∏ x in s, f x :=
by simp_rw [prod_subtype_eq_prod_filter, filter_true_of_mem h]
/-- A product of a function over a `finset` in a subtype equals a
product in the main type of a function that agrees with the first
function on that `finset`. -/
@[to_additive "A sum of a function over a `finset` in a subtype equals a
sum in the main type of a function that agrees with the first
function on that `finset`."]
lemma prod_subtype_map_embedding {p : α → Prop} {s : finset {x // p x}} {f : {x // p x} → β}
{g : α → β} (h : ∀ x : {x // p x}, x ∈ s → g x = f x) :
∏ x in s.map (function.embedding.subtype _), g x = ∏ x in s, f x :=
begin
rw finset.prod_map,
exact finset.prod_congr rfl h
end
variables (f s)
@[to_additive]
lemma prod_coe_sort_eq_attach (f : s → β) :
∏ (i : s), f i = ∏ i in s.attach, f i :=
rfl
@[to_additive]
lemma prod_coe_sort :
∏ (i : s), f i = ∏ i in s, f i :=
prod_attach
@[to_additive]
lemma prod_finset_coe (f : α → β) (s : finset α) :
∏ (i : (s : set α)), f i = ∏ i in s, f i :=
prod_coe_sort s f
variables {f s}
@[to_additive]
lemma prod_subtype {p : α → Prop} {F : fintype (subtype p)} (s : finset α)
(h : ∀ x, x ∈ s ↔ p x) (f : α → β) :
∏ a in s, f a = ∏ a : subtype p, f a :=
have (∈ s) = p, from set.ext h, by { substI p, rw ← prod_coe_sort, congr }
/-- The product of a function `g` defined only on a set `s` is equal to
the product of a function `f` defined everywhere,
as long as `f` and `g` agree on `s`, and `f = 1` off `s`. -/
@[to_additive "The sum of a function `g` defined only on a set `s` is equal to
the sum of a function `f` defined everywhere,
as long as `f` and `g` agree on `s`, and `f = 0` off `s`."]
lemma prod_congr_set
{α : Type*} [comm_monoid α] {β : Type*} [fintype β]
(s : set β) [decidable_pred (∈s)] (f : β → α) (g : s → α)
(w : ∀ (x : β) (h : x ∈ s), f x = g ⟨x, h⟩) (w' : ∀ (x : β), x ∉ s → f x = 1) :
finset.univ.prod f = finset.univ.prod g :=
begin
rw ←@finset.prod_subset _ _ s.to_finset finset.univ f _ (by simp),
{ rw finset.prod_subtype,
{ apply finset.prod_congr rfl,
exact λ ⟨x, h⟩ _, w x h, },
{ simp, }, },
{ rintro x _ h, exact w' x (by simpa using h), },
end
@[to_additive] lemma prod_apply_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p}
[decidable_pred (λ x, ¬ p x)] (f : Π (x : α), p x → γ) (g : Π (x : α), ¬p x → γ)
(h : γ → β) :
(∏ x in s, h (if hx : p x then f x hx else g x hx)) =
(∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) *
(∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) :=
calc ∏ x in s, h (if hx : p x then f x hx else g x hx)
= (∏ x in s.filter p, h (if hx : p x then f x hx else g x hx)) *
(∏ x in s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx)) :
(prod_filter_mul_prod_filter_not s p _).symm
... = (∏ x in (s.filter p).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) *
(∏ x in (s.filter (λ x, ¬ p x)).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) :
congr_arg2 _ prod_attach.symm prod_attach.symm
... = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) *
(∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) :
congr_arg2 _
(prod_congr rfl (λ x hx, congr_arg h (dif_pos (mem_filter.mp x.2).2)))
(prod_congr rfl (λ x hx, congr_arg h (dif_neg (mem_filter.mp x.2).2)))
@[to_additive] lemma prod_apply_ite {s : finset α}
{p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) :
(∏ x in s, h (if p x then f x else g x)) =
(∏ x in s.filter p, h (f x)) * (∏ x in s.filter (λ x, ¬ p x), h (g x)) :=
trans (prod_apply_dite _ _ _)
(congr_arg2 _ (@prod_attach _ _ _ _ (h ∘ f)) (@prod_attach _ _ _ _ (h ∘ g)))
@[to_additive] lemma prod_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p}
(f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) :
(∏ x in s, if hx : p x then f x hx else g x hx) =
(∏ x in (s.filter p).attach, f x.1 (mem_filter.mp x.2).2) *
(∏ x in (s.filter (λ x, ¬ p x)).attach, g x.1 (mem_filter.mp x.2).2) :=
by simp [prod_apply_dite _ _ (λ x, x)]
@[to_additive] lemma prod_ite {s : finset α}
{p : α → Prop} {hp : decidable_pred p} (f g : α → β) :
(∏ x in s, if p x then f x else g x) =
(∏ x in s.filter p, f x) * (∏ x in s.filter (λ x, ¬ p x), g x) :=
by simp [prod_apply_ite _ _ (λ x, x)]
@[to_additive] lemma prod_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → β)
(h : ∀ x ∈ s, ¬p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, g x) :=
by { rw prod_ite, simp [filter_false_of_mem h, filter_true_of_mem h] }
@[to_additive] lemma prod_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → β)
(h : ∀ x ∈ s, p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, f x) :=
by { simp_rw ←(ite_not (p _)), apply prod_ite_of_false, simpa }
@[to_additive] lemma prod_apply_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → γ)
(k : γ → β) (h : ∀ x ∈ s, ¬p x) :
(∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (g x)) :=
by { simp_rw apply_ite k, exact prod_ite_of_false _ _ h }
@[to_additive] lemma prod_apply_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → γ)
(k : γ → β) (h : ∀ x ∈ s, p x) :
(∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (f x)) :=
by { simp_rw apply_ite k, exact prod_ite_of_true _ _ h }
@[to_additive]
lemma prod_extend_by_one [decidable_eq α] (s : finset α) (f : α → β) :
∏ i in s, (if i ∈ s then f i else 1) = ∏ i in s, f i :=
prod_congr rfl $ λ i hi, if_pos hi
@[simp, to_additive]
lemma prod_dite_eq [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, a = x → β) :
(∏ x in s, (if h : a = x then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 :=
begin
split_ifs with h,
{ rw [finset.prod_eq_single a, dif_pos rfl],
{ intros, rw dif_neg, cc },
{ cc } },
{ rw finset.prod_eq_one,
intros, rw dif_neg, intro, cc }
end
@[simp, to_additive]
lemma prod_dite_eq' [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, x = a → β) :
(∏ x in s, (if h : x = a then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 :=
begin
split_ifs with h,
{ rw [finset.prod_eq_single a, dif_pos rfl],
{ intros, rw dif_neg, cc },
{ cc } },
{ rw finset.prod_eq_one,
intros, rw dif_neg, intro, cc }
end
@[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : α → β) :
(∏ x in s, (ite (a = x) (b x) 1)) = ite (a ∈ s) (b a) 1 :=
prod_dite_eq s a (λ x _, b x)
/-- A product taken over a conditional whose condition is an equality test on the index and whose
alternative is `1` has value either the term at that index or `1`.
The difference with `finset.prod_ite_eq` is that the arguments to `eq` are swapped. -/
@[simp, to_additive "A sum taken over a conditional whose condition is an equality test on the index
and whose alternative is `0` has value either the term at that index or `0`.
The difference with `finset.sum_ite_eq` is that the arguments to `eq` are swapped."]
lemma prod_ite_eq' [decidable_eq α] (s : finset α) (a : α) (b : α → β) :
(∏ x in s, (ite (x = a) (b x) 1)) = ite (a ∈ s) (b a) 1 :=
prod_dite_eq' s a (λ x _, b x)
@[to_additive]
lemma prod_ite_index (p : Prop) [decidable p] (s t : finset α) (f : α → β) :
(∏ x in if p then s else t, f x) = if p then ∏ x in s, f x else ∏ x in t, f x :=
apply_ite (λ s, ∏ x in s, f x) _ _ _
@[simp, to_additive]
lemma prod_ite_irrel (p : Prop) [decidable p] (s : finset α) (f g : α → β) :
(∏ x in s, if p then f x else g x) = if p then ∏ x in s, f x else ∏ x in s, g x :=
by { split_ifs with h; refl }
@[simp, to_additive]
lemma prod_dite_irrel (p : Prop) [decidable p] (s : finset α) (f : p → α → β) (g : ¬p → α → β) :
(∏ x in s, if h : p then f h x else g h x) = if h : p then ∏ x in s, f h x else ∏ x in s, g h x :=
by { split_ifs with h; refl }
@[simp] lemma sum_pi_single' {ι M : Type*} [decidable_eq ι] [add_comm_monoid M]
(i : ι) (x : M) (s : finset ι) :
∑ j in s, pi.single i x j = if i ∈ s then x else 0 :=
sum_dite_eq' _ _ _
@[simp] lemma sum_pi_single {ι : Type*} {M : ι → Type*}
[decidable_eq ι] [Π i, add_comm_monoid (M i)] (i : ι) (f : Π i, M i) (s : finset ι) :
∑ j in s, pi.single j (f j) i = if i ∈ s then f i else 0 :=
sum_dite_eq _ _ _
@[to_additive]
lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β}
(i : Π a ∈ s, f a ≠ 1 → γ) (hi : ∀ a h₁ h₂, i a h₁ h₂ ∈ t)
(i_inj : ∀ a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂)
(i_surj : ∀ b ∈ t, g b ≠ 1 → ∃ a h₁ h₂, b = i a h₁ h₂)
(h : ∀ a h₁ h₂, f a = g (i a h₁ h₂)) :
(∏ x in s, f x) = (∏ x in t, g x) :=
by classical; exact
calc (∏ x in s, f x) = ∏ x in (s.filter $ λ x, f x ≠ 1), f x : prod_filter_ne_one.symm
... = ∏ x in (t.filter $ λ x, g x ≠ 1), g x :
prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2)
(assume a ha, (mem_filter.mp ha).elim $ λ h₁ h₂, mem_filter.mpr
⟨hi a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩)
(assume a ha, (mem_filter.mp ha).elim $ h a)
(assume a₁ a₂ ha₁ ha₂,
(mem_filter.mp ha₁).elim $ λ ha₁₁ ha₁₂,
(mem_filter.mp ha₂).elim $ λ ha₂₁ ha₂₂, i_inj a₁ a₂ _ _ _ _)
(assume b hb, (mem_filter.mp hb).elim $ λ h₁ h₂,
let ⟨a, ha₁, ha₂, eq⟩ := i_surj b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩)
... = (∏ x in t, g x) : prod_filter_ne_one
@[to_additive] lemma prod_dite_of_false {p : α → Prop} {hp : decidable_pred p}
(h : ∀ x ∈ s, ¬ p x) (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) :
(∏ x in s, if hx : p x then f x hx else g x hx) =
∏ (x : s), g x.val (h x.val x.property) :=
prod_bij (λ x hx, ⟨x,hx⟩) (λ x hx, by simp) (λ a ha, by { dsimp, rw dif_neg })
(λ a₁ a₂ h₁ h₂ hh, congr_arg coe hh) (λ b hb, ⟨b.1, b.2, by simp⟩)
@[to_additive] lemma prod_dite_of_true {p : α → Prop} {hp : decidable_pred p}
(h : ∀ x ∈ s, p x) (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) :
(∏ x in s, if hx : p x then f x hx else g x hx) =
∏ (x : s), f x.val (h x.val x.property) :=
prod_bij (λ x hx, ⟨x,hx⟩) (λ x hx, by simp) (λ a ha, by { dsimp, rw dif_pos })
(λ a₁ a₂ h₁ h₂ hh, congr_arg coe hh) (λ b hb, ⟨b.1, b.2, by simp⟩)
@[to_additive]
lemma nonempty_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : s.nonempty :=
s.eq_empty_or_nonempty.elim (λ H, false.elim $ h $ H.symm ▸ prod_empty) id
@[to_additive]
lemma exists_ne_one_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : ∃ a ∈ s, f a ≠ 1 :=
begin
classical,
rw ← prod_filter_ne_one at h,
rcases nonempty_of_prod_ne_one h with ⟨x, hx⟩,
exact ⟨x, (mem_filter.1 hx).1, (mem_filter.1 hx).2⟩
end
@[to_additive]
lemma prod_range_succ_comm (f : ℕ → β) (n : ℕ) :
∏ x in range (n + 1), f x = f n * ∏ x in range n, f x :=
by rw [range_succ, prod_insert not_mem_range_self]
@[to_additive]
lemma prod_range_succ (f : ℕ → β) (n : ℕ) :
∏ x in range (n + 1), f x = (∏ x in range n, f x) * f n :=
by simp only [mul_comm, prod_range_succ_comm]
@[to_additive]
lemma prod_range_succ' (f : ℕ → β) :
∀ n : ℕ, (∏ k in range (n + 1), f k) = (∏ k in range n, f (k+1)) * f 0
| 0 := prod_range_succ _ _
| (n + 1) := by rw [prod_range_succ _ n, mul_right_comm, ← prod_range_succ', prod_range_succ]
@[to_additive]
lemma eventually_constant_prod {u : ℕ → β} {N : ℕ} (hu : ∀ n ≥ N, u n = 1) {n : ℕ} (hn : N ≤ n) :
∏ k in range (n + 1), u k = ∏ k in range (N + 1), u k :=
begin
obtain ⟨m, rfl : n = N + m⟩ := le_iff_exists_add.mp hn,
clear hn,
induction m with m hm,
{ simp },
erw [prod_range_succ, hm],
simp [hu]
end
@[to_additive]
lemma prod_range_add (f : ℕ → β) (n m : ℕ) :
∏ x in range (n + m), f x =
(∏ x in range n, f x) * (∏ x in range m, f (n + x)) :=
begin
induction m with m hm,
{ simp },
{ rw [nat.add_succ, prod_range_succ, hm, prod_range_succ, mul_assoc], },
end
@[to_additive]
lemma prod_range_add_div_prod_range {α : Type*} [comm_group α] (f : ℕ → α) (n m : ℕ) :
(∏ k in range (n + m), f k) / (∏ k in range n, f k) = ∏ k in finset.range m, f (n + k) :=
div_eq_of_eq_mul' (prod_range_add f n m)
@[to_additive]
lemma prod_range_zero (f : ℕ → β) :
∏ k in range 0, f k = 1 :=
by rw [range_zero, prod_empty]
@[to_additive sum_range_one]
lemma prod_range_one (f : ℕ → β) :
∏ k in range 1, f k = f 0 :=
by { rw [range_one], apply @prod_singleton β ℕ 0 f }
open list
@[to_additive] lemma prod_list_map_count [decidable_eq α] (l : list α)
{M : Type*} [comm_monoid M] (f : α → M) :
(l.map f).prod = ∏ m in l.to_finset, (f m) ^ (l.count m) :=
begin
induction l with a s IH, { simp only [map_nil, prod_nil, count_nil, pow_zero, prod_const_one] },
simp only [list.map, list.prod_cons, to_finset_cons, IH],
by_cases has : a ∈ s.to_finset,
{ rw [insert_eq_of_mem has, ← insert_erase has, prod_insert (not_mem_erase _ _),
prod_insert (not_mem_erase _ _), ← mul_assoc, count_cons_self, pow_succ],
congr' 1,
refine prod_congr rfl (λ x hx, _),
rw [count_cons_of_ne (ne_of_mem_erase hx)] },
rw [prod_insert has, count_cons_self, count_eq_zero_of_not_mem (mt mem_to_finset.2 has), pow_one],
congr' 1,
refine prod_congr rfl (λ x hx, _),
rw count_cons_of_ne,
rintro rfl,
exact has hx,
end
@[to_additive]
lemma prod_list_count [decidable_eq α] [comm_monoid α] (s : list α) :
s.prod = ∏ m in s.to_finset, m ^ (s.count m) :=
by simpa using prod_list_map_count s id
@[to_additive]
lemma prod_list_count_of_subset [decidable_eq α] [comm_monoid α]
(m : list α) (s : finset α) (hs : m.to_finset ⊆ s) :
m.prod = ∏ i in s, i ^ (m.count i) :=
begin
rw prod_list_count,
refine prod_subset hs (λ x _ hx, _),
rw [mem_to_finset] at hx,
rw [count_eq_zero_of_not_mem hx, pow_zero],
end
lemma sum_filter_count_eq_countp [decidable_eq α] (p : α → Prop) [decidable_pred p] (l : list α) :
∑ x in l.to_finset.filter p, l.count x = l.countp p :=
by simp [finset.sum, sum_map_count_dedup_filter_eq_countp p l]
open multiset
@[to_additive] lemma prod_multiset_map_count [decidable_eq α] (s : multiset α)
{M : Type*} [comm_monoid M] (f : α → M) :
(s.map f).prod = ∏ m in s.to_finset, (f m) ^ (s.count m) :=
by { refine quot.induction_on s (λ l, _), simp [prod_list_map_count l f] }
@[to_additive]
lemma prod_multiset_count [decidable_eq α] [comm_monoid α] (s : multiset α) :
s.prod = ∏ m in s.to_finset, m ^ (s.count m) :=
by { convert prod_multiset_map_count s id, rw multiset.map_id }
@[to_additive]
lemma prod_multiset_count_of_subset [decidable_eq α] [comm_monoid α]
(m : multiset α) (s : finset α) (hs : m.to_finset ⊆ s) :
m.prod = ∏ i in s, i ^ (m.count i) :=
begin
revert hs,
refine quot.induction_on m (λ l, _),
simp only [quot_mk_to_coe'', coe_prod, coe_count],
apply prod_list_count_of_subset l s
end
@[to_additive] lemma prod_mem_multiset [decidable_eq α]
(m : multiset α) (f : {x // x ∈ m} → β) (g : α → β)
(hfg : ∀ x, f x = g x) :
∏ (x : {x // x ∈ m}), f x = ∏ x in m.to_finset, g x :=
prod_bij (λ x _, x.1) (λ x _, multiset.mem_to_finset.mpr x.2)
(λ _ _, hfg _)
(λ _ _ _ _ h, by { ext, assumption })
(λ y hy, ⟨⟨y, multiset.mem_to_finset.mp hy⟩, finset.mem_univ _, rfl⟩)
/--
To prove a property of a product, it suffices to prove that
the property is multiplicative and holds on factors.
-/
@[to_additive "To prove a property of a sum, it suffices to prove that
the property is additive and holds on summands."]
lemma prod_induction {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop)
(p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ x ∈ s, p $ f x) :
p $ ∏ x in s, f x :=
multiset.prod_induction _ _ p_mul p_one (multiset.forall_mem_map_iff.mpr p_s)
/--
To prove a property of a product, it suffices to prove that
the property is multiplicative and holds on factors.
-/
@[to_additive "To prove a property of a sum, it suffices to prove that
the property is additive and holds on summands."]
lemma prod_induction_nonempty {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop)
(p_mul : ∀ a b, p a → p b → p (a * b)) (hs_nonempty : s.nonempty) (p_s : ∀ x ∈ s, p $ f x) :
p $ ∏ x in s, f x :=
multiset.prod_induction_nonempty p p_mul (by simp [nonempty_iff_ne_empty.mp hs_nonempty])
(multiset.forall_mem_map_iff.mpr p_s)
/-- For any product along `{0, ..., n - 1}` of a commutative-monoid-valued function, we can verify
that it's equal to a different function just by checking ratios of adjacent terms.
This is a multiplicative discrete analogue of the fundamental theorem of calculus. -/
@[to_additive "For any sum along `{0, ..., n - 1}` of a commutative-monoid-valued function, we can
verify that it's equal to a different function just by checking differences of adjacent terms.
This is a discrete analogue of the fundamental theorem of calculus."]
lemma prod_range_induction (f s : ℕ → β) (h0 : s 0 = 1) (h : ∀ n, s (n + 1) = s n * f n) (n : ℕ) :
∏ k in finset.range n, f k = s n :=
begin
induction n with k hk,
{ simp only [h0, finset.prod_range_zero] },
{ simp only [hk, finset.prod_range_succ, h, mul_comm] }
end
/-- A telescoping product along `{0, ..., n - 1}` of a commutative group valued function reduces to
the ratio of the last and first factors. -/
@[to_additive "A telescoping sum along `{0, ..., n - 1}` of an additive commutative group valued
function reduces to the difference of the last and first terms."]
lemma prod_range_div {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) :
∏ i in range n, (f (i + 1) / f i) = f n / f 0 :=
by apply prod_range_induction; simp
@[to_additive]
lemma prod_range_div' {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) :
∏ i in range n, (f i / f (i + 1)) = f 0 / f n :=
by apply prod_range_induction; simp
@[to_additive]
lemma eq_prod_range_div {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) :
f n = f 0 * ∏ i in range n, (f (i + 1) / f i) :=
by rw [prod_range_div, mul_div_cancel'_right]
@[to_additive]
lemma eq_prod_range_div' {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) :
f n = ∏ i in range (n + 1), if i = 0 then f 0 else f i / f (i - 1) :=
by { conv_lhs { rw [finset.eq_prod_range_div f] }, simp [finset.prod_range_succ', mul_comm] }
/--
A telescoping sum along `{0, ..., n-1}` of an `ℕ`-valued function
reduces to the difference of the last and first terms
when the function we are summing is monotone.
-/
lemma sum_range_tsub [canonically_ordered_add_monoid α] [has_sub α] [has_ordered_sub α]
[contravariant_class α α (+) (≤)] {f : ℕ → α} (h : monotone f) (n : ℕ) :
∑ i in range n, (f (i+1) - f i) = f n - f 0 :=
begin
refine sum_range_induction _ _ (tsub_self _) (λ n, _) _,
have h₁ : f n ≤ f (n+1) := h (nat.le_succ _),
have h₂ : f 0 ≤ f n := h (nat.zero_le _),
rw [tsub_add_eq_add_tsub h₂, add_tsub_cancel_of_le h₁],
end
@[simp, to_additive] lemma prod_const (b : β) : (∏ x in s, b) = b ^ s.card :=
by haveI := classical.dec_eq α; exact
finset.induction_on s (by simp) (λ a s has ih,
by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih])
@[to_additive]
lemma pow_eq_prod_const (b : β) : ∀ n, b ^ n = ∏ k in range n, b := by simp
@[to_additive]
lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) :
∏ x in s, f x ^ n = (∏ x in s, f x) ^ n :=
by haveI := classical.dec_eq α; exact
finset.induction_on s (by simp) (by simp [mul_pow] {contextual := tt})
@[to_additive]
lemma prod_flip {n : ℕ} (f : ℕ → β) :
∏ r in range (n + 1), f (n - r) = ∏ k in range (n + 1), f k :=
begin
induction n with n ih,
{ rw [prod_range_one, prod_range_one] },
{ rw [prod_range_succ', prod_range_succ _ (nat.succ n)],
simp [← ih] }
end
@[to_additive]
lemma prod_involution {s : finset α} {f : α → β} :
∀ (g : Π a ∈ s, α)
(h : ∀ a ha, f a * f (g a ha) = 1)
(g_ne : ∀ a ha, f a ≠ 1 → g a ha ≠ a)
(g_mem : ∀ a ha, g a ha ∈ s)
(g_inv : ∀ a ha, g (g a ha) (g_mem a ha) = a),
(∏ x in s, f x) = 1 :=
by haveI := classical.dec_eq α;
haveI := classical.dec_eq β; exact
finset.strong_induction_on s
(λ s ih g h g_ne g_mem g_inv,
s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ rfl)
(λ ⟨x, hx⟩,
have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s,
from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)),
have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y,
from λ x hx y hy h, by rw [← g_inv x hx, ← g_inv y hy]; simp [h],
have ih': ∏ y in erase (erase s x) (g x hx), f y = (1 : β) :=
ih ((s.erase x).erase (g x hx))
⟨subset.trans (erase_subset _ _) (erase_subset _ _),
λ h, not_mem_erase (g x hx) (s.erase x) (h (g_mem x hx))⟩
(λ y hy, g y (hmem y hy))
(λ y hy, h y (hmem y hy))
(λ y hy, g_ne y (hmem y hy))
(λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy,
mem_erase.2 ⟨λ (h : g y _ = x),
have y = g x hx, from g_inv y (hmem y hy) ▸ by simp [h],
by simpa [this] using hy, g_mem y (hmem y hy)⟩⟩)
(λ y hy, g_inv y (hmem y hy)),
if hx1 : f x = 1
then ih' ▸ eq.symm (prod_subset hmem
(λ y hy hy₁,
have y = x ∨ y = g x hx, by simpa [hy, not_and_distrib, or_comm] using hy₁,
this.elim (λ hy, hy.symm ▸ hx1)
(λ hy, h x hx ▸ hy ▸ hx1.symm ▸ (one_mul _).symm)))
else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _),
← insert_erase (mem_erase.2 ⟨g_ne x hx hx1, g_mem x hx⟩),
prod_insert (not_mem_erase _ _), ih', mul_one, h x hx]))
/-- The product of the composition of functions `f` and `g`, is the product over `b ∈ s.image g` of
`f b` to the power of the cardinality of the fibre of `b`. See also `finset.prod_image`. -/
@[to_additive "The sum of the composition of functions `f` and `g`, is the sum over `b ∈ s.image g`
of `f b` times of the cardinality of the fibre of `b`. See also `finset.sum_image`."]
lemma prod_comp [decidable_eq γ] (f : γ → β) (g : α → γ) :
∏ a in s, f (g a) = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card :=
calc ∏ a in s, f (g a)
= ∏ x in (s.image g).sigma (λ b : γ, s.filter (λ a, g a = b)), f (g x.2) :
prod_bij (λ a ha, ⟨g a, a⟩) (by simp; tauto) (λ _ _, rfl) (by simp) -- `(by finish)` closes this
(by { rintro ⟨b_fst, b_snd⟩ H,
simp only [mem_image, exists_prop, mem_filter, mem_sigma] at H,
tauto })
... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f (g a) : prod_sigma _ _ _
... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f b :
prod_congr rfl (λ b hb, prod_congr rfl (by simp {contextual := tt}))
... = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card :
prod_congr rfl (λ _ _, prod_const _)
@[to_additive]
lemma prod_piecewise [decidable_eq α] (s t : finset α) (f g : α → β) :
(∏ x in s, (t.piecewise f g) x) = (∏ x in s ∩ t, f x) * (∏ x in s \ t, g x) :=
by { rw [piecewise, prod_ite, filter_mem_eq_inter, ← sdiff_eq_filter], }
@[to_additive]
lemma prod_inter_mul_prod_diff [decidable_eq α] (s t : finset α) (f : α → β) :
(∏ x in s ∩ t, f x) * (∏ x in s \ t, f x) = (∏ x in s, f x) :=
by { convert (s.prod_piecewise t f f).symm, simp [finset.piecewise] }
@[to_additive]
lemma prod_eq_mul_prod_diff_singleton [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s)
(f : α → β) : ∏ x in s, f x = f i * ∏ x in s \ {i}, f x :=
by { convert (s.prod_inter_mul_prod_diff {i} f).symm, simp [h] }
@[to_additive]
lemma prod_eq_prod_diff_singleton_mul [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s)
(f : α → β) : ∏ x in s, f x = (∏ x in s \ {i}, f x) * f i :=
by { rw [prod_eq_mul_prod_diff_singleton h, mul_comm] }
@[to_additive]
lemma _root_.fintype.prod_eq_mul_prod_compl [decidable_eq α] [fintype α] (a : α) (f : α → β) :
∏ i, f i = (f a) * ∏ i in {a}ᶜ, f i :=
prod_eq_mul_prod_diff_singleton (mem_univ a) f
@[to_additive]
lemma _root_.fintype.prod_eq_prod_compl_mul [decidable_eq α] [fintype α] (a : α) (f : α → β) :
∏ i, f i = (∏ i in {a}ᶜ, f i) * f a :=
prod_eq_prod_diff_singleton_mul (mem_univ a) f
lemma dvd_prod_of_mem (f : α → β) {a : α} {s : finset α} (ha : a ∈ s) :
f a ∣ ∏ i in s, f i :=
begin
classical,
rw finset.prod_eq_mul_prod_diff_singleton ha,
exact dvd_mul_right _ _,
end
/-- A product can be partitioned into a product of products, each equivalent under a setoid. -/
@[to_additive "A sum can be partitioned into a sum of sums, each equivalent under a setoid."]
lemma prod_partition (R : setoid α) [decidable_rel R.r] :
(∏ x in s, f x) = ∏ xbar in s.image quotient.mk, ∏ y in s.filter (λ y, ⟦y⟧ = xbar), f y :=
begin
refine (finset.prod_image' f (λ x hx, _)).symm,
refl,
end
/-- If we can partition a product into subsets that cancel out, then the whole product cancels. -/
@[to_additive "If we can partition a sum into subsets that cancel out, then the whole sum cancels."]
lemma prod_cancels_of_partition_cancels (R : setoid α) [decidable_rel R.r]
(h : ∀ x ∈ s, (∏ a in s.filter (λ y, y ≈ x), f a) = 1) : (∏ x in s, f x) = 1 :=
begin
rw [prod_partition R, ←finset.prod_eq_one],
intros xbar xbar_in_s,
obtain ⟨x, x_in_s, xbar_eq_x⟩ := mem_image.mp xbar_in_s,
rw [←xbar_eq_x, filter_congr (λ y _, @quotient.eq _ R y x)],
apply h x x_in_s,
end
@[to_additive]
lemma prod_update_of_not_mem [decidable_eq α] {s : finset α} {i : α}
(h : i ∉ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = (∏ x in s, f x) :=
begin
apply prod_congr rfl (λ j hj, _),
have : j ≠ i, by { assume eq, rw eq at hj, exact h hj },
simp [this]
end
@[to_additive]
lemma prod_update_of_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) :
(∏ x in s, function.update f i b x) = b * (∏ x in s \ (singleton i), f x) :=
by { rw [update_eq_piecewise, prod_piecewise], simp [h] }
/-- If a product of a `finset` of size at most 1 has a given value, so
do the terms in that product. -/
@[to_additive eq_of_card_le_one_of_sum_eq "If a sum of a `finset` of size at most 1 has a given
value, so do the terms in that sum."]
lemma eq_of_card_le_one_of_prod_eq {s : finset α} (hc : s.card ≤ 1) {f : α → β} {b : β}
(h : ∏ x in s, f x = b) : ∀ x ∈ s, f x = b :=
begin
intros x hx,
by_cases hc0 : s.card = 0,
{ exact false.elim (card_ne_zero_of_mem hx hc0) },
{ have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)),
rw card_eq_one at h1,
cases h1 with x2 hx2,
rw [hx2, mem_singleton] at hx,
simp_rw hx2 at h,
rw hx,
rw prod_singleton at h,
exact h }
end
/-- Taking a product over `s : finset α` is the same as multiplying the value on a single element
`f a` by the product of `s.erase a`.
See `multiset.prod_map_erase` for the `multiset` version. -/
@[to_additive "Taking a sum over `s : finset α` is the same as adding the value on a single element
`f a` to the sum over `s.erase a`.
See `multiset.sum_map_erase` for the `multiset` version."]
lemma mul_prod_erase [decidable_eq α] (s : finset α) (f : α → β) {a : α} (h : a ∈ s) :
f a * (∏ x in s.erase a, f x) = ∏ x in s, f x :=
by rw [← prod_insert (not_mem_erase a s), insert_erase h]
/-- A variant of `finset.mul_prod_erase` with the multiplication swapped. -/
@[to_additive "A variant of `finset.add_sum_erase` with the addition swapped."]
lemma prod_erase_mul [decidable_eq α] (s : finset α) (f : α → β) {a : α} (h : a ∈ s) :
(∏ x in s.erase a, f x) * f a = ∏ x in s, f x :=
by rw [mul_comm, mul_prod_erase s f h]
/-- If a function applied at a point is 1, a product is unchanged by
removing that point, if present, from a `finset`. -/
@[to_additive "If a function applied at a point is 0, a sum is unchanged by
removing that point, if present, from a `finset`."]
lemma prod_erase [decidable_eq α] (s : finset α) {f : α → β} {a : α} (h : f a = 1) :
∏ x in s.erase a, f x = ∏ x in s, f x :=
begin
rw ←sdiff_singleton_eq_erase,
refine prod_subset (sdiff_subset _ _) (λ x hx hnx, _),
rw sdiff_singleton_eq_erase at hnx,
rwa eq_of_mem_of_not_mem_erase hx hnx
end
lemma sum_erase_lt_of_pos {γ : Type*} [decidable_eq α] [ordered_add_comm_monoid γ]
[covariant_class γ γ (+) (<)] {s : finset α} {d : α} (hd : d ∈ s) {f : α → γ} (hdf : 0 < f d) :
∑ (m : α) in s.erase d, f m < ∑ (m : α) in s, f m :=
begin
nth_rewrite_rhs 0 ←finset.insert_erase hd,
rw finset.sum_insert (finset.not_mem_erase d s),
exact lt_add_of_pos_left _ hdf,
end
/-- If a product is 1 and the function is 1 except possibly at one
point, it is 1 everywhere on the `finset`. -/
@[to_additive "If a sum is 0 and the function is 0 except possibly at one
point, it is 0 everywhere on the `finset`."]
lemma eq_one_of_prod_eq_one {s : finset α} {f : α → β} {a : α} (hp : ∏ x in s, f x = 1)
(h1 : ∀ x ∈ s, x ≠ a → f x = 1) : ∀ x ∈ s, f x = 1 :=
begin
intros x hx,
classical,
by_cases h : x = a,
{ rw h,
rw h at hx,
rw [←prod_subset (singleton_subset_iff.2 hx)
(λ t ht ha, h1 t ht (not_mem_singleton.1 ha)),
prod_singleton] at hp,
exact hp },
{ exact h1 x hx h }
end
lemma prod_pow_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) :
(∏ x in s, (f x)^(ite (a = x) 1 0)) = ite (a ∈ s) (f a) 1 :=
by simp
lemma prod_dvd_prod_of_dvd {S : finset α} (g1 g2 : α → β) (h : ∀ a ∈ S, g1 a ∣ g2 a) :
S.prod g1 ∣ S.prod g2 :=
begin
classical,
apply finset.induction_on' S, { simp },
intros a T haS _ haT IH,
repeat {rw finset.prod_insert haT},
exact mul_dvd_mul (h a haS) IH,
end
lemma prod_dvd_prod_of_subset {ι M : Type*} [comm_monoid M] (s t : finset ι) (f : ι → M)
(h : s ⊆ t) : ∏ i in s, f i ∣ ∏ i in t, f i :=
multiset.prod_dvd_prod_of_le $ multiset.map_le_map $ by simpa
end comm_monoid
/-- If `f = g = h` everywhere but at `i`, where `f i = g i + h i`, then the product of `f` over `s`
is the sum of the products of `g` and `h`. -/
lemma prod_add_prod_eq [comm_semiring β] {s : finset α} {i : α} {f g h : α → β}
(hi : i ∈ s) (h1 : g i + h i = f i) (h2 : ∀ j ∈ s, j ≠ i → g j = f j)
(h3 : ∀ j ∈ s, j ≠ i → h j = f j) : ∏ i in s, g i + ∏ i in s, h i = ∏ i in s, f i :=
by { classical, simp_rw [prod_eq_mul_prod_diff_singleton hi, ← h1, right_distrib],
congr' 2; apply prod_congr rfl; simpa }
lemma card_eq_sum_ones (s : finset α) : s.card = ∑ _ in s, 1 :=
by simp
lemma sum_const_nat {m : ℕ} {f : α → ℕ} (h₁ : ∀ x ∈ s, f x = m) :
(∑ x in s, f x) = card s * m :=
begin
rw [← nat.nsmul_eq_mul, ← sum_const],
apply sum_congr rfl h₁
end
@[simp]
lemma sum_boole {s : finset α} {p : α → Prop} [non_assoc_semiring β] {hp : decidable_pred p} :
(∑ x in s, if p x then (1 : β) else (0 : β)) = (s.filter p).card :=
by simp [sum_ite]
lemma _root_.commute.sum_right [non_unital_non_assoc_semiring β] (s : finset α)
(f : α → β) (b : β) (h : ∀ i ∈ s, commute b (f i)) :
commute b (∑ i in s, f i) :=
commute.multiset_sum_right _ _ $ λ b hb, begin
obtain ⟨i, hi, rfl⟩ := multiset.mem_map.mp hb,
exact h _ hi
end
lemma _root_.commute.sum_left [non_unital_non_assoc_semiring β] (s : finset α)
(f : α → β) (b : β) (h : ∀ i ∈ s, commute (f i) b) :
commute (∑ i in s, f i) b :=
(commute.sum_right _ _ _ $ λ i hi, (h _ hi).symm).symm
section opposite
open mul_opposite
/-- Moving to the opposite additive commutative monoid commutes with summing. -/
@[simp] lemma op_sum [add_comm_monoid β] {s : finset α} (f : α → β) :
op (∑ x in s, f x) = ∑ x in s, op (f x) :=
(op_add_equiv : β ≃+ βᵐᵒᵖ).map_sum _ _
@[simp] lemma unop_sum [add_comm_monoid β] {s : finset α} (f : α → βᵐᵒᵖ) :
unop (∑ x in s, f x) = ∑ x in s, unop (f x) :=
(op_add_equiv : β ≃+ βᵐᵒᵖ).symm.map_sum _ _
end opposite
section division_comm_monoid
variables [division_comm_monoid β]
@[simp, to_additive] lemma prod_inv_distrib : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ :=
multiset.prod_map_inv
@[simp, to_additive]
lemma prod_div_distrib : (∏ x in s, f x / g x) = (∏ x in s, f x) / ∏ x in s, g x :=
multiset.prod_map_div
@[to_additive]
lemma prod_zpow (f : α → β) (s : finset α) (n : ℤ) : ∏ a in s, (f a) ^ n = (∏ a in s, f a) ^ n :=
multiset.prod_map_zpow
end division_comm_monoid
section comm_group
variables [comm_group β] [decidable_eq α]
@[simp, to_additive] lemma prod_sdiff_eq_div (h : s₁ ⊆ s₂) :
(∏ x in (s₂ \ s₁), f x) = (∏ x in s₂, f x) / (∏ x in s₁, f x) :=
by rw [eq_div_iff_mul_eq', prod_sdiff h]
@[to_additive] lemma prod_sdiff_div_prod_sdiff :
(∏ x in s₂ \ s₁, f x) / (∏ x in s₁ \ s₂, f x) = (∏ x in s₂, f x) / (∏ x in s₁, f x) :=
by simp [← finset.prod_sdiff (@inf_le_left _ _ s₁ s₂),
← finset.prod_sdiff (@inf_le_right _ _ s₁ s₂)]
@[simp, to_additive]
lemma prod_erase_eq_div {a : α} (h : a ∈ s) : (∏ x in s.erase a, f x) = (∏ x in s, f x) / f a :=
by rw [eq_div_iff_mul_eq', prod_erase_mul _ _ h]
end comm_group
@[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) :
card (s.sigma t) = ∑ a in s, card (t a) :=
multiset.card_sigma _ _
lemma card_bUnion [decidable_eq β] {s : finset α} {t : α → finset β}
(h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) :
(s.bUnion t).card = ∑ u in s, card (t u) :=
calc (s.bUnion t).card = ∑ i in s.bUnion t, 1 : by simp
... = ∑ a in s, ∑ i in t a, 1 : finset.sum_bUnion h
... = ∑ u in s, card (t u) : by simp
lemma card_bUnion_le [decidable_eq β] {s : finset α} {t : α → finset β} :
(s.bUnion t).card ≤ ∑ a in s, (t a).card :=
by haveI := classical.dec_eq α; exact
finset.induction_on s (by simp)
(λ a s has ih,
calc ((insert a s).bUnion t).card ≤ (t a).card + (s.bUnion t).card :
by rw bUnion_insert; exact finset.card_union_le _ _
... ≤ ∑ a in insert a s, card (t a) :
by rw sum_insert has; exact add_le_add_left ih _)
theorem card_eq_sum_card_fiberwise [decidable_eq β] {f : α → β} {s : finset α} {t : finset β}
(H : ∀ x ∈ s, f x ∈ t) :
s.card = ∑ a in t, (s.filter (λ x, f x = a)).card :=
by simp only [card_eq_sum_ones, sum_fiberwise_of_maps_to H]
theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) :
s.card = ∑ a in s.image f, (s.filter (λ x, f x = a)).card :=
card_eq_sum_card_fiberwise (λ _, mem_image_of_mem _)
lemma mem_sum {f : α → multiset β} (s : finset α) (b : β) :
b ∈ ∑ x in s, f x ↔ ∃ a ∈ s, b ∈ f a :=
begin
classical,
refine s.induction_on (by simp) _,
{ intros a t hi ih,
simp [sum_insert hi, ih, or_and_distrib_right, exists_or_distrib] }
end
section prod_eq_zero
variables [comm_monoid_with_zero β]
lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : (∏ x in s, f x) = 0 :=
by { haveI := classical.dec_eq α, rw [←prod_erase_mul _ _ ha, h, mul_zero] }
lemma prod_boole {s : finset α} {p : α → Prop} [decidable_pred p] :
∏ i in s, ite (p i) (1 : β) (0 : β) = ite (∀ i ∈ s, p i) 1 0 :=
begin
split_ifs,
{ apply prod_eq_one,
intros i hi,
rw if_pos (h i hi) },
{ push_neg at h,
rcases h with ⟨i, hi, hq⟩,
apply prod_eq_zero hi,
rw [if_neg hq] },
end
variables [nontrivial β] [no_zero_divisors β]
lemma prod_eq_zero_iff : (∏ x in s, f x) = 0 ↔ (∃ a ∈ s, f a = 0) :=
begin
classical,
apply finset.induction_on s,
exact ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩,
assume a s ha ih,
rw [prod_insert ha, mul_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def]
end
theorem prod_ne_zero_iff : (∏ x in s, f x) ≠ 0 ↔ (∀ a ∈ s, f a ≠ 0) :=
by { rw [ne, prod_eq_zero_iff], push_neg }
end prod_eq_zero
@[to_additive]
lemma prod_unique_nonempty {α β : Type*} [comm_monoid β] [unique α]
(s : finset α) (f : α → β) (h : s.nonempty) :
(∏ x in s, f x) = f default :=
by rw [h.eq_singleton_default, finset.prod_singleton]
end finset
namespace fintype
open finset
/-- `fintype.prod_bijective` is a variant of `finset.prod_bij` that accepts `function.bijective`.
See `function.bijective.prod_comp` for a version without `h`. -/
@[to_additive "`fintype.sum_equiv` is a variant of `finset.sum_bij` that accepts
`function.bijective`.
See `function.bijective.sum_comp` for a version without `h`. "]
lemma prod_bijective {α β M : Type*} [fintype α] [fintype β] [comm_monoid M]
(e : α → β) (he : function.bijective e) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) :
∏ x : α, f x = ∏ x : β, g x :=
prod_bij
(λ x _, e x)
(λ x _, mem_univ (e x))
(λ x _, h x)
(λ x x' _ _ h, he.injective h)
(λ y _, (he.surjective y).imp $ λ a h, ⟨mem_univ _, h.symm⟩)
/-- `fintype.prod_equiv` is a specialization of `finset.prod_bij` that
automatically fills in most arguments.
See `equiv.prod_comp` for a version without `h`.
-/
@[to_additive "`fintype.sum_equiv` is a specialization of `finset.sum_bij` that
automatically fills in most arguments.
See `equiv.sum_comp` for a version without `h`.
"]
lemma prod_equiv {α β M : Type*} [fintype α] [fintype β] [comm_monoid M]
(e : α ≃ β) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) :
∏ x : α, f x = ∏ x : β, g x :=
prod_bijective e e.bijective f g h
variables {f s}
@[to_additive]
lemma prod_unique {α β : Type*} [comm_monoid β] [unique α] (f : α → β) :
(∏ x : α, f x) = f default :=
by rw [univ_unique, prod_singleton]
@[to_additive] lemma prod_empty {α β : Type*} [comm_monoid β] [is_empty α] (f : α → β) :
(∏ x : α, f x) = 1 :=
by rw [eq_empty_of_is_empty (univ : finset α), finset.prod_empty]
@[to_additive] lemma prod_subsingleton {α β : Type*} [comm_monoid β] [subsingleton α] [fintype α]
(f : α → β) (a : α) :
(∏ x : α, f x) = f a :=
begin
haveI : unique α := unique_of_subsingleton a,
convert prod_unique f
end
@[to_additive]
lemma prod_subtype_mul_prod_subtype {α β : Type*} [fintype α] [comm_monoid β]
(p : α → Prop) (f : α → β) [decidable_pred p] :
(∏ (i : {x // p x}), f i) * (∏ i : {x // ¬ p x}, f i) = ∏ i, f i :=
begin
classical,
let s := {x | p x}.to_finset,
rw [← finset.prod_subtype s, ← finset.prod_subtype sᶜ],
{ exact finset.prod_mul_prod_compl _ _ },
{ simp },
{ simp }
end
end fintype
namespace list
@[to_additive] lemma prod_to_finset {M : Type*} [decidable_eq α] [comm_monoid M]
(f : α → M) : ∀ {l : list α} (hl : l.nodup), l.to_finset.prod f = (l.map f).prod
| [] _ := by simp
| (a :: l) hl := let ⟨not_mem, hl⟩ := list.nodup_cons.mp hl in
by simp [finset.prod_insert (mt list.mem_to_finset.mp not_mem), prod_to_finset hl]
end list
namespace multiset
lemma disjoint_list_sum_left {a : multiset α} {l : list (multiset α)} :
multiset.disjoint l.sum a ↔ ∀ b ∈ l, multiset.disjoint b a :=
begin
induction l with b bs ih,
{ simp only [zero_disjoint, list.not_mem_nil, is_empty.forall_iff, forall_const, list.sum_nil], },
{ simp_rw [list.sum_cons, disjoint_add_left, list.mem_cons_iff, forall_eq_or_imp],
simp [and.congr_left_iff, iff_self, ih], },
end
lemma disjoint_list_sum_right {a : multiset α} {l : list (multiset α)} :
multiset.disjoint a l.sum ↔ ∀ b ∈ l, multiset.disjoint a b :=
by simpa only [disjoint_comm] using disjoint_list_sum_left
lemma disjoint_sum_left {a : multiset α} {i : multiset (multiset α)} :
multiset.disjoint i.sum a ↔ ∀ b ∈ i, multiset.disjoint b a :=
quotient.induction_on i $ λ l, begin
rw [quot_mk_to_coe, multiset.coe_sum],
exact disjoint_list_sum_left,
end
lemma disjoint_sum_right {a : multiset α} {i : multiset (multiset α)} :
multiset.disjoint a i.sum ↔ ∀ b ∈ i, multiset.disjoint a b :=
by simpa only [disjoint_comm] using disjoint_sum_left
lemma disjoint_finset_sum_left {β : Type*} {i : finset β} {f : β → multiset α} {a : multiset α} :
multiset.disjoint (i.sum f) a ↔ ∀ b ∈ i, multiset.disjoint (f b) a :=
begin
convert (@disjoint_sum_left _ a) (map f i.val),
simp [finset.mem_def, and.congr_left_iff, iff_self],
end
lemma disjoint_finset_sum_right {β : Type*} {i : finset β} {f : β → multiset α} {a : multiset α} :
multiset.disjoint a (i.sum f) ↔ ∀ b ∈ i, multiset.disjoint a (f b) :=
by simpa only [disjoint_comm] using disjoint_finset_sum_left
variables [decidable_eq α]
lemma add_eq_union_left_of_le {x y z : multiset α} (h : y ≤ x) :
z + x = z ∪ y ↔ z.disjoint x ∧ x = y :=
begin
rw ←add_eq_union_iff_disjoint,
split,
{ intro h0,
rw and_iff_right_of_imp,
{ exact (le_of_add_le_add_left $ h0.trans_le $ union_le_add z y).antisymm h, },
{ rintro rfl,
exact h0, } },
{ rintro ⟨h0, rfl⟩,
exact h0, }
end
lemma add_eq_union_right_of_le {x y z : multiset α} (h : z ≤ y) :
x + y = x ∪ z ↔ y = z ∧ x.disjoint y :=
by simpa only [and_comm] using add_eq_union_left_of_le h
lemma finset_sum_eq_sup_iff_disjoint {β : Type*} {i : finset β} {f : β → multiset α} :
i.sum f = i.sup f ↔ ∀ x y ∈ i, x ≠ y → multiset.disjoint (f x) (f y) :=
begin
induction i using finset.cons_induction_on with z i hz hr,
{ simp only [finset.not_mem_empty, is_empty.forall_iff, implies_true_iff,
finset.sum_empty, finset.sup_empty, bot_eq_zero, eq_self_iff_true], },
{ simp_rw [finset.sum_cons hz, finset.sup_cons, finset.mem_cons, multiset.sup_eq_union,
forall_eq_or_imp, ne.def, eq_self_iff_true, not_true, is_empty.forall_iff, true_and,
imp_and_distrib, forall_and_distrib, ←hr, @eq_comm _ z],
have := λ x ∈ i, ne_of_mem_of_not_mem H hz,
simp only [this, not_false_iff, true_implies_iff] {contextual := tt},
simp_rw [←disjoint_finset_sum_left, ←disjoint_finset_sum_right, disjoint_comm, ←and_assoc,
and_self],
exact add_eq_union_left_of_le (finset.sup_le (λ x hx, le_sum_of_mem (mem_map_of_mem f hx))), },
end
lemma sup_powerset_len {α : Type*} [decidable_eq α] (x : multiset α) :
finset.sup (finset.range (x.card + 1)) (λ k, x.powerset_len k) = x.powerset :=
begin
convert bind_powerset_len x,
rw [multiset.bind, multiset.join, ←finset.range_coe, ←finset.sum_eq_multiset_sum],
exact eq.symm (finset_sum_eq_sup_iff_disjoint.mpr (λ _ _ _ _ h, disjoint_powerset_len x h)),
end
@[simp] lemma to_finset_sum_count_eq (s : multiset α) :
(∑ a in s.to_finset, s.count a) = s.card :=
multiset.induction_on s rfl
(assume a s ih,
calc (∑ x in to_finset (a ::ₘ s), count x (a ::ₘ s)) =
∑ x in to_finset (a ::ₘ s), ((if x = a then 1 else 0) + count x s) :
finset.sum_congr rfl $ λ _ _, by split_ifs;
[simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]]
... = card (a ::ₘ s) :
begin
by_cases a ∈ s.to_finset,
{ have : ∑ x in s.to_finset, ite (x = a) 1 0 = ∑ x in {a}, ite (x = a) 1 0,
{ rw [finset.sum_ite_eq', if_pos h, finset.sum_singleton, if_pos rfl], },
rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this,
finset.sum_singleton, if_pos rfl, add_comm, card_cons] },
{ have ha : a ∉ s, by rwa mem_to_finset at h,
have : ∑ x in to_finset s, ite (x = a) 1 0 = ∑ x in to_finset s, 0, from
finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc),
rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this,
finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] }
end)
lemma count_sum' {s : finset β} {a : α} {f : β → multiset α} :
count a (∑ x in s, f x) = ∑ x in s, count a (f x) :=
by { dunfold finset.sum, rw count_sum }
@[simp] lemma to_finset_sum_count_nsmul_eq (s : multiset α) :
(∑ a in s.to_finset, s.count a • {a}) = s :=
begin
apply ext', intro b,
rw count_sum',
have h : count b s = count b (count b s • {b}),
{ rw [count_nsmul, count_singleton_self, mul_one] },
rw h, clear h,
apply finset.sum_eq_single b,
{ intros c h hcb, rw count_nsmul, convert mul_zero (count c s),
apply count_eq_zero.mpr, exact finset.not_mem_singleton.mpr (ne.symm hcb) },
{ intro hb, rw [count_eq_zero_of_not_mem (mt mem_to_finset.2 hb), count_nsmul, zero_mul]}
end
theorem exists_smul_of_dvd_count (s : multiset α) {k : ℕ}
(h : ∀ (a : α), a ∈ s → k ∣ multiset.count a s) :
∃ (u : multiset α), s = k • u :=
begin
use ∑ a in s.to_finset, (s.count a / k) • {a},
have h₂ : ∑ (x : α) in s.to_finset, k • (count x s / k) • ({x} : multiset α) =
∑ (x : α) in s.to_finset, count x s • {x},
{ apply finset.sum_congr rfl,
intros x hx,
rw [← mul_nsmul, nat.mul_div_cancel' (h x (mem_to_finset.mp hx))] },
rw [← finset.sum_nsmul, h₂, to_finset_sum_count_nsmul_eq]
end
lemma to_finset_prod_dvd_prod [comm_monoid α] (S : multiset α) : S.to_finset.prod id ∣ S.prod :=
begin
rw finset.prod_eq_multiset_prod,
refine multiset.prod_dvd_prod_of_le _,
simp [multiset.dedup_le S],
end
@[to_additive]
lemma prod_sum {α : Type*} {ι : Type*} [comm_monoid α] (f : ι → multiset α) (s : finset ι) :
(∑ x in s, f x).prod = ∏ x in s, (f x).prod :=
begin
classical,
induction s using finset.induction_on with a t hat ih,
{ rw [finset.sum_empty, finset.prod_empty, multiset.prod_zero] },
{ rw [finset.sum_insert hat, finset.prod_insert hat, multiset.prod_add, ih] }
end
end multiset
namespace nat
@[simp, norm_cast] lemma cast_list_sum [add_monoid_with_one β] (s : list ℕ) :
(↑(s.sum) : β) = (s.map coe).sum :=
map_list_sum (cast_add_monoid_hom β) _
@[simp, norm_cast] lemma cast_list_prod [semiring β] (s : list ℕ) :
(↑(s.prod) : β) = (s.map coe).prod :=
map_list_prod (cast_ring_hom β) _
@[simp, norm_cast] lemma cast_multiset_sum [add_comm_monoid_with_one β] (s : multiset ℕ) :
(↑(s.sum) : β) = (s.map coe).sum :=
map_multiset_sum (cast_add_monoid_hom β) _
@[simp, norm_cast] lemma cast_multiset_prod [comm_semiring β] (s : multiset ℕ) :
(↑(s.prod) : β) = (s.map coe).prod :=
map_multiset_prod (cast_ring_hom β) _
@[simp, norm_cast] lemma cast_sum [add_comm_monoid_with_one β] (s : finset α) (f : α → ℕ) :
↑(∑ x in s, f x : ℕ) = (∑ x in s, (f x : β)) :=
map_sum (cast_add_monoid_hom β) _ _
@[simp, norm_cast] lemma cast_prod [comm_semiring β] (f : α → ℕ) (s : finset α) :
(↑∏ i in s, f i : β) = ∏ i in s, f i :=
map_prod (cast_ring_hom β) _ _
end nat
namespace int
@[simp, norm_cast] lemma cast_list_sum [add_group_with_one β] (s : list ℤ) :
(↑(s.sum) : β) = (s.map coe).sum :=
map_list_sum (cast_add_hom β) _
@[simp, norm_cast] lemma cast_list_prod [ring β] (s : list ℤ) :
(↑(s.prod) : β) = (s.map coe).prod :=
map_list_prod (cast_ring_hom β) _
@[simp, norm_cast] lemma cast_multiset_sum [add_comm_group_with_one β] (s : multiset ℤ) :
(↑(s.sum) : β) = (s.map coe).sum :=
map_multiset_sum (cast_add_hom β) _
@[simp, norm_cast] lemma cast_multiset_prod {R : Type*} [comm_ring R] (s : multiset ℤ) :
(↑(s.prod) : R) = (s.map coe).prod :=
map_multiset_prod (cast_ring_hom R) _
@[simp, norm_cast] lemma cast_sum [add_comm_group_with_one β] (s : finset α) (f : α → ℤ) :
↑(∑ x in s, f x : ℤ) = (∑ x in s, (f x : β)) :=
map_sum (cast_add_hom β) _ _
@[simp, norm_cast] lemma cast_prod {R : Type*} [comm_ring R] (f : α → ℤ) (s : finset α) :
(↑∏ i in s, f i : R) = ∏ i in s, f i :=
(int.cast_ring_hom R).map_prod _ _
end int
@[simp, norm_cast] lemma units.coe_prod {M : Type*} [comm_monoid M] (f : α → Mˣ)
(s : finset α) : (↑∏ i in s, f i : M) = ∏ i in s, f i :=
(units.coe_hom M).map_prod _ _
lemma units.mk0_prod [comm_group_with_zero β] (s : finset α) (f : α → β) (h) :
units.mk0 (∏ b in s, f b) h =
∏ b in s.attach, units.mk0 (f b) (λ hh, h (finset.prod_eq_zero b.2 hh)) :=
by { classical, induction s using finset.induction_on; simp* }
lemma nat_abs_sum_le {ι : Type*} (s : finset ι) (f : ι → ℤ) :
(∑ i in s, f i).nat_abs ≤ ∑ i in s, (f i).nat_abs :=
begin
classical,
apply finset.induction_on s,
{ simp only [finset.sum_empty, int.nat_abs_zero] },
{ intros i s his IH,
simp only [his, finset.sum_insert, not_false_iff],
exact (int.nat_abs_add_le _ _).trans (add_le_add le_rfl IH) }
end
/-! ### `additive`, `multiplicative` -/
open additive multiplicative
section monoid
variables [monoid α]
@[simp] lemma of_mul_list_prod (s : list α) : of_mul s.prod = (s.map of_mul).sum :=
by simpa [of_mul]
@[simp] lemma to_mul_list_sum (s : list (additive α)) :
to_mul s.sum = (s.map to_mul).prod := by simpa [to_mul, of_mul]
end monoid
section add_monoid
variables [add_monoid α]
@[simp] lemma of_add_list_prod (s : list α) : of_add s.sum = (s.map of_add).prod :=
by simpa [of_add]
@[simp] lemma to_add_list_sum (s : list (multiplicative α)) :
to_add s.prod = (s.map to_add).sum := by simpa [to_add, of_add]
end add_monoid
section comm_monoid
variables [comm_monoid α]
@[simp] lemma of_mul_multiset_prod (s : multiset α) :
of_mul s.prod = (s.map of_mul).sum := by simpa [of_mul]
@[simp] lemma to_mul_multiset_sum (s : multiset (additive α)) :
to_mul s.sum = (s.map to_mul).prod := by simpa [to_mul, of_mul]
@[simp] lemma of_mul_prod (s : finset ι) (f : ι → α) :
of_mul (∏ i in s, f i) = ∑ i in s, of_mul (f i) := rfl
@[simp] lemma to_mul_sum (s : finset ι) (f : ι → additive α) :
to_mul (∑ i in s, f i) = ∏ i in s, to_mul (f i) := rfl
end comm_monoid
section add_comm_monoid
variables [add_comm_monoid α]
@[simp] lemma of_add_multiset_prod (s : multiset α) :
of_add s.sum = (s.map of_add).prod := by simpa [of_add]
@[simp] lemma to_add_multiset_sum (s : multiset (multiplicative α)) :
to_add s.prod = (s.map to_add).sum := by simpa [to_add, of_add]
@[simp] lemma of_add_sum (s : finset ι) (f : ι → α) :
of_add (∑ i in s, f i) = ∏ i in s, of_add (f i) := rfl
@[simp] lemma to_add_prod (s : finset ι) (f : ι → multiplicative α) :
to_add (∏ i in s, f i) = ∑ i in s, to_add (f i) := rfl
end add_comm_monoid
|
663d96b4ee8c83d5816d408f64f40c5f937d1123 | bb31430994044506fa42fd667e2d556327e18dfe | /src/order/antisymmetrization.lean | 33d319b56e7d70d04f7e0dea20f7d39fb9d2a873 | [
"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 | 9,299 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import order.hom.basic
import logic.relation
/-!
# Turning a preorder into a partial order
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file allows to make a preorder into a partial order by quotienting out the elements `a`, `b`
such that `a ≤ b` and `b ≤ a`.
`antisymmetrization` is a functor from `Preorder` to `PartialOrder`. See `Preorder_to_PartialOrder`.
## Main declarations
* `antisymm_rel`: The antisymmetrization relation. `antisymm_rel r a b` means that `a` and `b` are
related both ways by `r`.
* `antisymmetrization α r`: The quotient of `α` by `antisymm_rel r`. Even when `r` is just a
preorder, `antisymmetrization α` is a partial order.
-/
open function order_dual
variables {α β : Type*}
section relation
variables (r : α → α → Prop)
/-- The antisymmetrization relation. -/
def antisymm_rel (a b : α) : Prop := r a b ∧ r b a
lemma antisymm_rel_swap : antisymm_rel (swap r) = antisymm_rel r :=
funext $ λ _, funext $ λ _, propext and.comm
@[refl] lemma antisymm_rel_refl [is_refl α r] (a : α) : antisymm_rel r a a := ⟨refl _, refl _⟩
variables {r}
@[symm] lemma antisymm_rel.symm {a b : α} : antisymm_rel r a b → antisymm_rel r b a := and.symm
@[trans] lemma antisymm_rel.trans [is_trans α r] {a b c : α} (hab : antisymm_rel r a b)
(hbc : antisymm_rel r b c) :
antisymm_rel r a c :=
⟨trans hab.1 hbc.1, trans hbc.2 hab.2⟩
instance antisymm_rel.decidable_rel [decidable_rel r] : decidable_rel (antisymm_rel r) :=
λ _ _, and.decidable
@[simp] lemma antisymm_rel_iff_eq [is_refl α r] [is_antisymm α r] {a b : α} :
antisymm_rel r a b ↔ a = b := antisymm_iff
alias antisymm_rel_iff_eq ↔ antisymm_rel.eq _
end relation
section is_preorder
variables (α) (r : α → α → Prop) [is_preorder α r]
/-- The antisymmetrization relation as an equivalence relation. -/
@[simps] def antisymm_rel.setoid : setoid α :=
⟨antisymm_rel r, antisymm_rel_refl _, λ _ _, antisymm_rel.symm, λ _ _ _, antisymm_rel.trans⟩
/-- The partial order derived from a preorder by making pairwise comparable elements equal. This is
the quotient by `λ a b, a ≤ b ∧ b ≤ a`. -/
def antisymmetrization : Type* := quotient $ antisymm_rel.setoid α r
variables {α}
/-- Turn an element into its antisymmetrization. -/
def to_antisymmetrization : α → antisymmetrization α r := quotient.mk'
/-- Get a representative from the antisymmetrization. -/
noncomputable def of_antisymmetrization : antisymmetrization α r → α := quotient.out'
instance [inhabited α] : inhabited (antisymmetrization α r) := quotient.inhabited _
@[elab_as_eliminator]
protected lemma antisymmetrization.ind {p : antisymmetrization α r → Prop} :
(∀ a, p $ to_antisymmetrization r a) → ∀ q, p q :=
quot.ind
@[elab_as_eliminator]
protected lemma antisymmetrization.induction_on {p : antisymmetrization α r → Prop}
(a : antisymmetrization α r) (h : ∀ a, p $ to_antisymmetrization r a) : p a :=
quotient.induction_on' a h
@[simp] lemma to_antisymmetrization_of_antisymmetrization (a : antisymmetrization α r) :
to_antisymmetrization r (of_antisymmetrization r a) = a := quotient.out_eq' _
end is_preorder
section preorder
variables {α} [preorder α] [preorder β] {a b : α}
lemma antisymm_rel.image {a b : α} (h : antisymm_rel (≤) a b) {f : α → β} (hf : monotone f) :
antisymm_rel (≤) (f a) (f b) :=
⟨hf h.1, hf h.2⟩
instance : partial_order (antisymmetrization α (≤)) :=
{ le := λ a b, quotient.lift_on₂' a b (≤) $ λ (a₁ a₂ b₁ b₂ : α) h₁ h₂,
propext ⟨λ h, h₁.2.trans $ h.trans h₂.1, λ h, h₁.1.trans $ h.trans h₂.2⟩,
lt := λ a b, quotient.lift_on₂' a b (<) $ λ (a₁ a₂ b₁ b₂ : α) h₁ h₂,
propext ⟨λ h, h₁.2.trans_lt $ h.trans_le h₂.1, λ h, h₁.1.trans_lt $ h.trans_le h₂.2⟩,
le_refl := λ a, quotient.induction_on' a $ le_refl,
le_trans := λ a b c, quotient.induction_on₃' a b c $ λ a b c, le_trans,
lt_iff_le_not_le := λ a b, quotient.induction_on₂' a b $ λ a b, lt_iff_le_not_le,
le_antisymm := λ a b, quotient.induction_on₂' a b $ λ a b hab hba, quotient.sound' ⟨hab, hba⟩ }
lemma antisymmetrization_fibration :
relation.fibration (<) (<) (@to_antisymmetrization α (≤) _) :=
by { rintro a ⟨b⟩ h, exact ⟨b, h, rfl⟩ }
lemma acc_antisymmetrization_iff : acc (<) (to_antisymmetrization (≤) a) ↔ acc (<) a :=
⟨λ h, by { have := inv_image.accessible _ h, exact this },
acc.of_fibration _ antisymmetrization_fibration⟩
lemma well_founded_antisymmetrization_iff :
well_founded (@has_lt.lt (antisymmetrization α (≤)) _) ↔ well_founded (@has_lt.lt α _) :=
⟨λ h, ⟨λ a, acc_antisymmetrization_iff.1 $ h.apply _⟩,
λ h, ⟨by { rintro ⟨a⟩, exact acc_antisymmetrization_iff.2 (h.apply a) }⟩⟩
instance [well_founded_lt α] : well_founded_lt (antisymmetrization α (≤)) :=
⟨well_founded_antisymmetrization_iff.2 is_well_founded.wf⟩
instance [@decidable_rel α (≤)] [@decidable_rel α (<)] [is_total α (≤)] :
linear_order (antisymmetrization α (≤)) :=
{ le_total := λ a b, quotient.induction_on₂' a b $ total_of (≤),
decidable_eq := @quotient.decidable_eq _ (antisymm_rel.setoid _ (≤)) antisymm_rel.decidable_rel,
decidable_le := λ _ _, quotient.lift_on₂'.decidable _ _ _ _,
decidable_lt := λ _ _, quotient.lift_on₂'.decidable _ _ _ _,
..antisymmetrization.partial_order }
@[simp] lemma to_antisymmetrization_le_to_antisymmetrization_iff :
to_antisymmetrization (≤) a ≤ to_antisymmetrization (≤) b ↔ a ≤ b := iff.rfl
@[simp] lemma to_antisymmetrization_lt_to_antisymmetrization_iff :
to_antisymmetrization (≤) a < to_antisymmetrization (≤) b ↔ a < b := iff.rfl
@[simp] lemma of_antisymmetrization_le_of_antisymmetrization_iff {a b : antisymmetrization α (≤)} :
of_antisymmetrization (≤) a ≤ of_antisymmetrization (≤) b ↔ a ≤ b :=
by convert to_antisymmetrization_le_to_antisymmetrization_iff.symm;
exact (to_antisymmetrization_of_antisymmetrization _ _).symm
@[simp] lemma of_antisymmetrization_lt_of_antisymmetrization_iff {a b : antisymmetrization α (≤)} :
of_antisymmetrization (≤) a < of_antisymmetrization (≤) b ↔ a < b :=
by convert to_antisymmetrization_lt_to_antisymmetrization_iff.symm;
exact (to_antisymmetrization_of_antisymmetrization _ _).symm
@[mono] lemma to_antisymmetrization_mono : monotone (@to_antisymmetrization α (≤) _) := λ a b, id
/-- `to_antisymmetrization` as an order homomorphism. -/
@[simps] def order_hom.to_antisymmetrization : α →o antisymmetrization α (≤) :=
⟨to_antisymmetrization (≤), λ a b, id⟩
private lemma lift_fun_antisymm_rel (f : α →o β) :
((antisymm_rel.setoid α (≤)).r ⇒ (antisymm_rel.setoid β (≤)).r) f f :=
λ a b h, ⟨f.mono h.1, f.mono h.2⟩
/-- Turns an order homomorphism from `α` to `β` into one from `antisymmetrization α` to
`antisymmetrization β`. `antisymmetrization` is actually a functor. See `Preorder_to_PartialOrder`.
-/
protected def order_hom.antisymmetrization (f : α →o β) :
antisymmetrization α (≤) →o antisymmetrization β (≤) :=
⟨quotient.map' f $ lift_fun_antisymm_rel f, λ a b, quotient.induction_on₂' a b $ f.mono⟩
@[simp] lemma order_hom.coe_antisymmetrization (f : α →o β) :
⇑f.antisymmetrization = quotient.map' f (lift_fun_antisymm_rel f) := rfl
@[simp] lemma order_hom.antisymmetrization_apply (f : α →o β) (a : antisymmetrization α (≤)) :
f.antisymmetrization a = quotient.map' f (lift_fun_antisymm_rel f) a := rfl
@[simp] lemma order_hom.antisymmetrization_apply_mk (f : α →o β) (a : α) :
f.antisymmetrization (to_antisymmetrization _ a) = (to_antisymmetrization _ (f a)) :=
quotient.map'_mk' f (lift_fun_antisymm_rel f) _
variables (α)
/-- `of_antisymmetrization` as an order embedding. -/
@[simps] noncomputable def order_embedding.of_antisymmetrization : antisymmetrization α (≤) ↪o α :=
{ to_fun := of_antisymmetrization _,
inj' := λ _ _, quotient.out_inj.1,
map_rel_iff' := λ a b, of_antisymmetrization_le_of_antisymmetrization_iff }
/-- `antisymmetrization` and `order_dual` commute. -/
def order_iso.dual_antisymmetrization :
(antisymmetrization α (≤))ᵒᵈ ≃o antisymmetrization αᵒᵈ (≤) :=
{ to_fun := quotient.map' id $ λ _ _, and.symm,
inv_fun := quotient.map' id $ λ _ _, and.symm,
left_inv := λ a, quotient.induction_on' a $ λ a, by simp_rw [quotient.map'_mk', id],
right_inv := λ a, quotient.induction_on' a $ λ a, by simp_rw [quotient.map'_mk', id],
map_rel_iff' := λ a b, quotient.induction_on₂' a b $ λ a b, iff.rfl }
@[simp] lemma order_iso.dual_antisymmetrization_apply (a : α) :
order_iso.dual_antisymmetrization _ (to_dual $ to_antisymmetrization _ a) =
to_antisymmetrization _ (to_dual a) := rfl
@[simp] lemma order_iso.dual_antisymmetrization_symm_apply (a : α) :
(order_iso.dual_antisymmetrization _).symm (to_antisymmetrization _ $ to_dual a) =
to_dual (to_antisymmetrization _ a) := rfl
end preorder
|
36e4594c9ee1ecb7bf1aab63c5e1899ec8deeb1b | 4a092885406df4e441e9bb9065d9405dacb94cd8 | /src/for_mathlib/monotone.lean | ca7d508ed4718d8e338b773e541b0e0732003027 | [
"Apache-2.0"
] | permissive | semorrison/lean-perfectoid-spaces | 78c1572cedbfae9c3e460d8aaf91de38616904d8 | bb4311dff45791170bcb1b6a983e2591bee88a19 | refs/heads/master | 1,588,841,765,494 | 1,554,805,620,000 | 1,554,805,620,000 | 180,353,546 | 0 | 1 | null | 1,554,809,880,000 | 1,554,809,880,000 | null | UTF-8 | Lean | false | false | 1,330 | lean | import order.basic
open function
variables {α : Type*} {β : Type*}
/-- A function between preorders is strictly monotone if
`a < b` implies `f a < f b`. -/
def strict_mono [preorder α] [preorder β] (f : α → β) :=
∀ a b, a < b → f a < f b
namespace strict_mono
variables [linear_order α] [preorder β] {f : α → β}
lemma lt_iff_lt (H : strict_mono f) {a b} :
f a < f b ↔ a < b :=
⟨λ h, ((lt_trichotomy b a)
.resolve_left $ λ h', lt_asymm h $ H _ _ h')
.resolve_left $ λ e, ne_of_gt h $ congr_arg _ e, H _ _⟩
lemma le_iff_le (H : strict_mono f) {a b} :
f a ≤ f b ↔ a ≤ b :=
⟨λ h, le_of_not_gt $ λ h', not_le_of_lt (H b a h') h,
λ h, (lt_or_eq_of_le h).elim (λ h', le_of_lt (H _ _ h')) (λ h', h' ▸ le_refl _)⟩
lemma injective (H : strict_mono f) : function.injective f
| a b e := ((lt_trichotomy a b)
.resolve_left $ λ h, ne_of_lt (H _ _ h) e)
.resolve_right $ λ h, ne_of_gt (H _ _ h) e
lemma monotone (H : strict_mono f) :
monotone f :=
λ a b, iff.mpr $ H.le_iff_le
end strict_mono
section
variables [partial_order α] [partial_order β] {f : α → β}
lemma strict_mono_of_monotone_of_injective (h₁ : monotone f) (h₂ : injective f) :
strict_mono f :=
λ a b h,
begin
rw lt_iff_le_and_ne at ⊢ h,
exact ⟨h₁ h.1, λ e, h.2 (h₂ e)⟩
end
end
|
08d7801c12e5b5297ba3f027c2c6cc88ce6bc553 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/order/ord_continuous.lean | d4a4f24ce34f7eabe41f290247957073d6f94133 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 8,088 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov, Johannes Hölzl
-/
import order.conditionally_complete_lattice.basic
import order.rel_iso.basic
/-!
# Order continuity
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We say that a function is *left order continuous* if it sends all least upper bounds
to least upper bounds. The order dual notion is called *right order continuity*.
For monotone functions `ℝ → ℝ` these notions correspond to the usual left and right continuity.
We prove some basic lemmas (`map_sup`, `map_Sup` etc) and prove that an `rel_iso` is both left
and right order continuous.
-/
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
open function order_dual set
/-!
### Definitions
-/
/-- A function `f` between preorders is left order continuous if it preserves all suprema. We
define it using `is_lub` instead of `Sup` so that the proof works both for complete lattices and
conditionally complete lattices. -/
def left_ord_continuous [preorder α] [preorder β] (f : α → β) :=
∀ ⦃s : set α⦄ ⦃x⦄, is_lub s x → is_lub (f '' s) (f x)
/-- A function `f` between preorders is right order continuous if it preserves all infima. We
define it using `is_glb` instead of `Inf` so that the proof works both for complete lattices and
conditionally complete lattices. -/
def right_ord_continuous [preorder α] [preorder β] (f : α → β) :=
∀ ⦃s : set α⦄ ⦃x⦄, is_glb s x → is_glb (f '' s) (f x)
namespace left_ord_continuous
section preorder
variables (α) [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β}
protected lemma id : left_ord_continuous (id : α → α) := λ s x h, by simpa only [image_id] using h
variable {α}
protected lemma order_dual : left_ord_continuous f → right_ord_continuous (to_dual ∘ f ∘ of_dual) :=
id
lemma map_is_greatest (hf : left_ord_continuous f) {s : set α} {x : α} (h : is_greatest s x):
is_greatest (f '' s) (f x) :=
⟨mem_image_of_mem f h.1, (hf h.is_lub).1⟩
lemma mono (hf : left_ord_continuous f) : monotone f :=
λ a₁ a₂ h,
have is_greatest {a₁, a₂} a₂ := ⟨or.inr rfl, by simp [*]⟩,
(hf.map_is_greatest this).2 $ mem_image_of_mem _ (or.inl rfl)
lemma comp (hg : left_ord_continuous g) (hf : left_ord_continuous f) :
left_ord_continuous (g ∘ f) :=
λ s x h, by simpa only [image_image] using hg (hf h)
protected lemma iterate {f : α → α} (hf : left_ord_continuous f) (n : ℕ) :
left_ord_continuous (f^[n]) :=
nat.rec_on n (left_ord_continuous.id α) $ λ n ihn, ihn.comp hf
end preorder
section semilattice_sup
variables [semilattice_sup α] [semilattice_sup β] {f : α → β}
lemma map_sup (hf : left_ord_continuous f) (x y : α) :
f (x ⊔ y) = f x ⊔ f y :=
(hf is_lub_pair).unique $ by simp only [image_pair, is_lub_pair]
lemma le_iff (hf : left_ord_continuous f) (h : injective f) {x y} :
f x ≤ f y ↔ x ≤ y :=
by simp only [← sup_eq_right, ← hf.map_sup, h.eq_iff]
lemma lt_iff (hf : left_ord_continuous f) (h : injective f) {x y} :
f x < f y ↔ x < y :=
by simp only [lt_iff_le_not_le, hf.le_iff h]
variable (f)
/-- Convert an injective left order continuous function to an order embedding. -/
def to_order_embedding (hf : left_ord_continuous f) (h : injective f) :
α ↪o β :=
⟨⟨f, h⟩, λ x y, hf.le_iff h⟩
variable {f}
@[simp] lemma coe_to_order_embedding (hf : left_ord_continuous f) (h : injective f) :
⇑(hf.to_order_embedding f h) = f := rfl
end semilattice_sup
section complete_lattice
variables [complete_lattice α] [complete_lattice β] {f : α → β}
lemma map_Sup' (hf : left_ord_continuous f) (s : set α) :
f (Sup s) = Sup (f '' s) :=
(hf $ is_lub_Sup s).Sup_eq.symm
lemma map_Sup (hf : left_ord_continuous f) (s : set α) :
f (Sup s) = ⨆ x ∈ s, f x :=
by rw [hf.map_Sup', Sup_image]
lemma map_supr (hf : left_ord_continuous f) (g : ι → α) :
f (⨆ i, g i) = ⨆ i, f (g i) :=
by simp only [supr, hf.map_Sup', ← range_comp]
end complete_lattice
section conditionally_complete_lattice
variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι]
{f : α → β}
lemma map_cSup (hf : left_ord_continuous f) {s : set α} (sne : s.nonempty) (sbdd : bdd_above s) :
f (Sup s) = Sup (f '' s) :=
((hf $ is_lub_cSup sne sbdd).cSup_eq $ sne.image f).symm
lemma map_csupr (hf : left_ord_continuous f) {g : ι → α} (hg : bdd_above (range g)) :
f (⨆ i, g i) = ⨆ i, f (g i) :=
by simp only [supr, hf.map_cSup (range_nonempty _) hg, ← range_comp]
end conditionally_complete_lattice
end left_ord_continuous
namespace right_ord_continuous
section preorder
variables (α) [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β}
protected lemma id : right_ord_continuous (id : α → α) := λ s x h, by simpa only [image_id] using h
variable {α}
protected lemma order_dual : right_ord_continuous f → left_ord_continuous (to_dual ∘ f ∘ of_dual) :=
id
lemma map_is_least (hf : right_ord_continuous f) {s : set α} {x : α} (h : is_least s x):
is_least (f '' s) (f x) :=
hf.order_dual.map_is_greatest h
lemma mono (hf : right_ord_continuous f) : monotone f :=
hf.order_dual.mono.dual
lemma comp (hg : right_ord_continuous g) (hf : right_ord_continuous f) :
right_ord_continuous (g ∘ f) :=
hg.order_dual.comp hf.order_dual
protected lemma iterate {f : α → α} (hf : right_ord_continuous f) (n : ℕ) :
right_ord_continuous (f^[n]) :=
hf.order_dual.iterate n
end preorder
section semilattice_inf
variables [semilattice_inf α] [semilattice_inf β] {f : α → β}
lemma map_inf (hf : right_ord_continuous f) (x y : α) :
f (x ⊓ y) = f x ⊓ f y :=
hf.order_dual.map_sup x y
lemma le_iff (hf : right_ord_continuous f) (h : injective f) {x y} :
f x ≤ f y ↔ x ≤ y :=
hf.order_dual.le_iff h
lemma lt_iff (hf : right_ord_continuous f) (h : injective f) {x y} :
f x < f y ↔ x < y :=
hf.order_dual.lt_iff h
variable (f)
/-- Convert an injective left order continuous function to a `order_embedding`. -/
def to_order_embedding (hf : right_ord_continuous f) (h : injective f) : α ↪o β :=
⟨⟨f, h⟩, λ x y, hf.le_iff h⟩
variable {f}
@[simp] lemma coe_to_order_embedding (hf : right_ord_continuous f) (h : injective f) :
⇑(hf.to_order_embedding f h) = f := rfl
end semilattice_inf
section complete_lattice
variables [complete_lattice α] [complete_lattice β] {f : α → β}
lemma map_Inf' (hf : right_ord_continuous f) (s : set α) :
f (Inf s) = Inf (f '' s) :=
hf.order_dual.map_Sup' s
lemma map_Inf (hf : right_ord_continuous f) (s : set α) :
f (Inf s) = ⨅ x ∈ s, f x :=
hf.order_dual.map_Sup s
lemma map_infi (hf : right_ord_continuous f) (g : ι → α) :
f (⨅ i, g i) = ⨅ i, f (g i) :=
hf.order_dual.map_supr g
end complete_lattice
section conditionally_complete_lattice
variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι]
{f : α → β}
lemma map_cInf (hf : right_ord_continuous f) {s : set α} (sne : s.nonempty) (sbdd : bdd_below s) :
f (Inf s) = Inf (f '' s) :=
hf.order_dual.map_cSup sne sbdd
lemma map_cinfi (hf : right_ord_continuous f) {g : ι → α} (hg : bdd_below (range g)) :
f (⨅ i, g i) = ⨅ i, f (g i) :=
hf.order_dual.map_csupr hg
end conditionally_complete_lattice
end right_ord_continuous
namespace order_iso
section preorder
variables [preorder α] [preorder β] (e : α ≃o β)
{s : set α} {x : α}
protected lemma left_ord_continuous : left_ord_continuous e :=
λ s x hx,
⟨monotone.mem_upper_bounds_image (λ x y, e.map_rel_iff.2) hx.1,
λ y hy, e.rel_symm_apply.1 $ (is_lub_le_iff hx).2 $ λ x' hx', e.rel_symm_apply.2 $ hy $
mem_image_of_mem _ hx'⟩
protected lemma right_ord_continuous : right_ord_continuous e :=
order_iso.left_ord_continuous e.dual
end preorder
end order_iso
|
0fa3b9a11c831c21fc968175d2998c06d271bbe8 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Lean/Elab/Command.lean | 1823c708e5caa0bb97315f0e6337dabce671dde1 | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 25,702 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Lean.Elab.Alias
import Init.Lean.Elab.Log
import Init.Lean.Elab.ResolveName
import Init.Lean.Elab.Term
import Init.Lean.Elab.Binders
import Init.Lean.Elab.SyntheticMVars
namespace Lean
namespace Elab
namespace Command
structure Scope :=
(kind : String)
(header : String)
(opts : Options := {})
(currNamespace : Name := Name.anonymous)
(openDecls : List OpenDecl := [])
(levelNames : List Name := [])
(varDecls : Array Syntax := #[])
instance Scope.inhabited : Inhabited Scope := ⟨{ kind := "", header := "" }⟩
structure State :=
(env : Environment)
(messages : MessageLog := {})
(scopes : List Scope := [{ kind := "root", header := "" }])
(nextMacroScope : Nat := firstFrontendMacroScope + 1)
(maxRecDepth : Nat)
instance State.inhabited : Inhabited State := ⟨{ env := arbitrary _, maxRecDepth := 0 }⟩
def mkState (env : Environment) (messages : MessageLog := {}) (opts : Options := {}) : State :=
{ env := env, messages := messages, scopes := [{ kind := "root", header := "", opts := opts }], maxRecDepth := getMaxRecDepth opts }
structure Context :=
(fileName : String)
(fileMap : FileMap)
(stateRef : IO.Ref State)
(currRecDepth : Nat := 0)
(cmdPos : String.Pos := 0)
(macroStack : MacroStack := [])
(currMacroScope : MacroScope := firstFrontendMacroScope)
instance Exception.inhabited : Inhabited Exception := ⟨Exception.error $ arbitrary _⟩
abbrev CommandElabCoreM (ε) := ReaderT Context (EIO ε)
abbrev CommandElabM := CommandElabCoreM Exception
abbrev CommandElab := Syntax → CommandElabM Unit
def mkMessageAux (ctx : Context) (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity) : Message :=
mkMessageCore ctx.fileName ctx.fileMap msgData severity (ref.getPos.getD ctx.cmdPos)
private def ioErrorToMessage (ctx : Context) (ref : Syntax) (err : IO.Error) : Message :=
let ref := getBetterRef ref ctx.macroStack;
mkMessageAux ctx ref (addMacroStack (toString err) ctx.macroStack) MessageSeverity.error
@[inline] def liftIOCore {α} (ctx : Context) (ref : Syntax) (x : IO α) : EIO Exception α :=
EIO.adaptExcept (fun ex => Exception.error $ ioErrorToMessage ctx ref ex) x
@[inline] def liftIO {α} (ref : Syntax) (x : IO α) : CommandElabM α :=
fun ctx => liftIOCore ctx ref x
private def getState : CommandElabM State :=
fun ctx => liftIOCore ctx Syntax.missing $ ctx.stateRef.get
private def setState (s : State) : CommandElabM Unit :=
fun ctx => liftIOCore ctx Syntax.missing $ ctx.stateRef.set s
@[inline] private def modifyGetState {α} (f : State → α × State) : CommandElabM α := do
s ← getState; let (a, s) := f s; setState s; pure a
instance CommandElabCoreM.monadState : MonadState State CommandElabM :=
{ get := getState,
set := setState,
modifyGet := @modifyGetState }
def getEnv : CommandElabM Environment := do s ← get; pure s.env
def getScope : CommandElabM Scope := do s ← get; pure s.scopes.head!
def getOptions : CommandElabM Options := do scope ← getScope; pure scope.opts
def addContext (msg : MessageData) : CommandElabM MessageData := do
env ← getEnv; opts ← getOptions;
pure (MessageData.withContext { env := env, mctx := {}, lctx := {}, opts := opts } msg)
instance CommandElabM.monadLog : MonadLog CommandElabM :=
{ getCmdPos := do ctx ← read; pure ctx.cmdPos,
getFileMap := do ctx ← read; pure ctx.fileMap,
getFileName := do ctx ← read; pure ctx.fileName,
addContext := addContext,
logMessage := fun msg => modify $ fun s => { messages := s.messages.add msg, .. s } }
/--
Throws an error with the given `msgData` and extracting position information from `ref`.
If `ref` does not contain position information, then use `cmdPos` -/
def throwError {α} (ref : Syntax) (msgData : MessageData) : CommandElabM α := do
ctx ← read;
let ref := getBetterRef ref ctx.macroStack;
let msgData := addMacroStack msgData ctx.macroStack;
msg ← mkMessage msgData MessageSeverity.error ref;
throw (Exception.error msg)
def logTrace (cls : Name) (ref : Syntax) (msg : MessageData) : CommandElabM Unit := do
msg ← addContext $ MessageData.tagged cls msg;
logInfo ref msg
@[inline] def trace (cls : Name) (ref : Syntax) (msg : Unit → MessageData) : CommandElabM Unit := do
opts ← getOptions;
when (checkTraceOption opts cls) $ logTrace cls ref (msg ())
def throwUnsupportedSyntax {α} : CommandElabM α :=
throw Elab.Exception.unsupportedSyntax
protected def getCurrMacroScope : CommandElabM Nat := do ctx ← read; pure ctx.currMacroScope
protected def getMainModule : CommandElabM Name := do env ← getEnv; pure env.mainModule
@[inline] protected def withFreshMacroScope {α} (x : CommandElabM α) : CommandElabM α := do
fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 }));
adaptReader (fun (ctx : Context) => { ctx with currMacroScope := fresh }) x
instance CommandElabM.MonadQuotation : MonadQuotation CommandElabM := {
getCurrMacroScope := Command.getCurrMacroScope,
getMainModule := Command.getMainModule,
withFreshMacroScope := @Command.withFreshMacroScope
}
unsafe def mkCommandElabAttribute : IO (KeyedDeclsAttribute CommandElab) :=
mkElabAttribute CommandElab `Lean.Elab.Command.commandElabAttribute `builtinCommandElab `commandElab `Lean.Parser.Command `Lean.Elab.Command.CommandElab "command"
@[init mkCommandElabAttribute] constant commandElabAttribute : KeyedDeclsAttribute CommandElab := arbitrary _
@[inline] def withIncRecDepth {α} (ref : Syntax) (x : CommandElabM α) : CommandElabM α := do
ctx ← read; s ← get;
when (ctx.currRecDepth == s.maxRecDepth) $ throwError ref maxRecDepthErrorMessage;
adaptReader (fun (ctx : Context) => { currRecDepth := ctx.currRecDepth + 1, .. ctx }) x
private def elabCommandUsing (s : State) (stx : Syntax) : List CommandElab → CommandElabM Unit
| [] => do
let refFmt := stx.prettyPrint;
throwError stx ("unexpected syntax" ++ MessageData.nest 2 (Format.line ++ refFmt))
| (elabFn::elabFns) => catch (elabFn stx)
(fun ex => match ex with
| Exception.error _ => throw ex
| Exception.unsupportedSyntax => do set s; elabCommandUsing elabFns)
/- Elaborate `x` with `stx` on the macro stack -/
@[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : CommandElabM α) : CommandElabM α :=
adaptReader (fun (ctx : Context) => { macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack, .. ctx }) x
instance : MonadMacroAdapter CommandElabM :=
{ getEnv := getEnv,
getCurrMacroScope := getCurrMacroScope,
getNextMacroScope := do s ← get; pure s.nextMacroScope,
setNextMacroScope := fun next => modify $ fun s => { nextMacroScope := next, .. s },
throwError := @throwError,
throwUnsupportedSyntax := @throwUnsupportedSyntax}
partial def elabCommand : Syntax → CommandElabM Unit
| stx => withIncRecDepth stx $ withFreshMacroScope $ match stx with
| Syntax.node k args =>
if k == nullKind then
-- list of commands => elaborate in order
-- The parser will only ever return a single command at a time, but syntax quotations can return multiple ones
args.forM elabCommand
else do
trace `Elab.step stx $ fun _ => stx;
s ← get;
stxNew? ← catch
(do newStx ← adaptMacro (getMacros s.env) stx; pure (some newStx))
(fun ex => match ex with
| Exception.unsupportedSyntax => pure none
| _ => throw ex);
match stxNew? with
| some stxNew => withMacroExpansion stx stxNew $ elabCommand stxNew
| _ => do
let table := (commandElabAttribute.ext.getState s.env).table;
let k := stx.getKind;
match table.find? k with
| some elabFns => elabCommandUsing s stx elabFns
| none => throwError stx ("elaboration function for '" ++ toString k ++ "' has not been implemented")
| _ => throwError stx "unexpected command"
/-- Adapt a syntax transformation to a regular, command-producing elaborator. -/
def adaptExpander (exp : Syntax → CommandElabM Syntax) : CommandElab :=
fun stx => do
stx' ← exp stx;
withMacroExpansion stx stx' $ elabCommand stx'
private def mkTermContext (ctx : Context) (s : State) (declName? : Option Name) : Term.Context :=
let scope := s.scopes.head!;
{ config := { opts := scope.opts, foApprox := true, ctxApprox := true, quasiPatternApprox := true, isDefEqStuckEx := true },
fileName := ctx.fileName,
fileMap := ctx.fileMap,
currRecDepth := ctx.currRecDepth,
maxRecDepth := s.maxRecDepth,
cmdPos := ctx.cmdPos,
declName? := declName?,
macroStack := ctx.macroStack,
currMacroScope := ctx.currMacroScope,
currNamespace := scope.currNamespace,
levelNames := scope.levelNames,
openDecls := scope.openDecls }
private def mkTermState (s : State) : Term.State :=
{ env := s.env,
messages := s.messages,
nextMacroScope := s.nextMacroScope }
private def updateState (s : State) (newS : Term.State) : State :=
{ env := newS.env, messages := newS.messages, nextMacroScope := newS.nextMacroScope, .. s }
private def getVarDecls (s : State) : Array Syntax :=
s.scopes.head!.varDecls
private def toCommandResult {α} (ctx : Context) (s : State) (result : EStateM.Result Term.Exception Term.State α) : EStateM.Result Exception State α :=
match result with
| EStateM.Result.ok a newS => EStateM.Result.ok a (updateState s newS)
| EStateM.Result.error (Term.Exception.ex ex) newS => EStateM.Result.error ex (updateState s newS)
| EStateM.Result.error Term.Exception.postpone newS => unreachable!
instance CommandElabM.inhabited {α} : Inhabited (CommandElabM α) :=
⟨throw $ arbitrary _⟩
@[inline] def liftTermElabM {α} (declName? : Option Name) (x : TermElabM α) : CommandElabM α := do
ctx ← read;
s ← get;
match (x $ mkTermContext ctx s declName?).run (mkTermState s) with
| EStateM.Result.ok a newS => do modify $ fun s => { env := newS.env, messages := newS.messages, .. s }; pure a
| EStateM.Result.error (Term.Exception.ex ex) newS => do modify $ fun s => { env := newS.env, messages := newS.messages, .. s }; throw ex
| EStateM.Result.error Term.Exception.postpone newS => unreachable!
@[inline] def runTermElabM {α} (declName? : Option Name) (elab : Array Expr → TermElabM α) : CommandElabM α := do
s ← get; liftTermElabM declName? (Term.elabBinders (getVarDecls s) elab)
@[inline] def withLogging (x : CommandElabM Unit) : CommandElabM Unit :=
catch x (fun ex => match ex with
| Exception.error ex => do logMessage ex; pure ()
| Exception.unsupportedSyntax => unreachable!)
@[inline] def catchExceptions (x : CommandElabM Unit) : CommandElabCoreM Empty Unit :=
fun ctx => EIO.catchExceptions (withLogging x ctx) (fun _ => pure ())
def dbgTrace {α} [HasToString α] (a : α) : CommandElabM Unit :=
_root_.dbgTrace (toString a) $ fun _ => pure ()
def setEnv (newEnv : Environment) : CommandElabM Unit :=
modify $ fun s => { env := newEnv, .. s }
def getCurrNamespace : CommandElabM Name := do
scope ← getScope; pure scope.currNamespace
private def addScope (kind : String) (header : String) (newNamespace : Name) : CommandElabM Unit :=
modify $ fun s => {
env := s.env.registerNamespace newNamespace,
scopes := { kind := kind, header := header, currNamespace := newNamespace, .. s.scopes.head! } :: s.scopes,
.. s }
private def addScopes (ref : Syntax) (kind : String) (updateNamespace : Bool) : Name → CommandElabM Unit
| Name.anonymous => pure ()
| Name.str p header _ => do
addScopes p;
currNamespace ← getCurrNamespace;
addScope kind header (if updateNamespace then currNamespace ++ header else currNamespace)
| _ => throwError ref "invalid scope"
private def addNamespace (ref : Syntax) (header : Name) : CommandElabM Unit :=
addScopes ref "namespace" true header
@[builtinCommandElab «namespace»] def elabNamespace : CommandElab :=
fun stx => match_syntax stx with
| `(namespace $n) => addNamespace stx n.getId
| _ => throw Exception.unsupportedSyntax
@[builtinCommandElab «section»] def elabSection : CommandElab :=
fun stx => match_syntax stx with
| `(section $header:ident) => addScopes stx "section" false header.getId
| `(section) => do currNamespace ← getCurrNamespace; addScope "section" "" currNamespace
| _ => throw Exception.unsupportedSyntax
def getScopes : CommandElabM (List Scope) := do
s ← get; pure s.scopes
private def checkAnonymousScope : List Scope → Bool
| { header := "", .. } :: _ => true
| _ => false
private def checkEndHeader : Name → List Scope → Bool
| Name.anonymous, _ => true
| Name.str p s _, { header := h, .. } :: scopes => h == s && checkEndHeader p scopes
| _, _ => false
@[builtinCommandElab «end»] def elabEnd : CommandElab :=
fun stx => do
let header? := (stx.getArg 1).getOptionalIdent?;
let endSize := match header? with
| none => 1
| some n => n.getNumParts;
scopes ← getScopes;
if endSize < scopes.length then
modify $ fun s => { scopes := s.scopes.drop endSize, .. s }
else do {
-- we keep "root" scope
modify $ fun s => { scopes := s.scopes.drop (s.scopes.length - 1), .. s };
throwError stx "invalid 'end', insufficient scopes"
};
match header? with
| none => unless (checkAnonymousScope scopes) $ throwError stx "invalid 'end', name is missing"
| some header => unless (checkEndHeader header scopes) $ throwError stx "invalid 'end', name mismatch"
@[inline] def withNamespace {α} (ref : Syntax) (ns : Name) (elab : CommandElabM α) : CommandElabM α := do
addNamespace ref ns;
a ← elab;
modify $ fun s => { scopes := s.scopes.drop ns.getNumParts, .. s };
pure a
@[specialize] def modifyScope (f : Scope → Scope) : CommandElabM Unit :=
modify $ fun s =>
{ scopes := match s.scopes with
| h::t => f h :: t
| [] => unreachable!,
.. s }
def getLevelNames : CommandElabM (List Name) := do
scope ← getScope; pure scope.levelNames
def throwAlreadyDeclaredUniverseLevel {α} (ref : Syntax) (u : Name) : CommandElabM α :=
throwError ref ("a universe level named '" ++ toString u ++ "' has already been declared")
def addUnivLevel (idStx : Syntax) : CommandElabM Unit := do
let id := idStx.getId;
levelNames ← getLevelNames;
if levelNames.elem id then
throwAlreadyDeclaredUniverseLevel idStx id
else
modifyScope $ fun scope => { levelNames := id :: scope.levelNames, .. scope }
partial def elabChoiceAux (cmds : Array Syntax) : Nat → CommandElabM Unit
| i =>
if h : i < cmds.size then
let cmd := cmds.get ⟨i, h⟩;
catch
(elabCommand cmd)
(fun ex => match ex with
| Exception.unsupportedSyntax => elabChoiceAux (i+1)
| _ => throw ex)
else
throwUnsupportedSyntax
@[builtinCommandElab choice] def elbChoice : CommandElab :=
fun stx => elabChoiceAux stx.getArgs 0
@[builtinCommandElab «universe»] def elabUniverse : CommandElab :=
fun n => do
addUnivLevel (n.getArg 1)
@[builtinCommandElab «universes»] def elabUniverses : CommandElab :=
fun n => do
let idsStx := n.getArg 1;
idsStx.forArgsM addUnivLevel
@[builtinCommandElab «init_quot»] def elabInitQuot : CommandElab :=
fun stx => do
env ← getEnv;
match env.addDecl Declaration.quotDecl with
| Except.ok env => setEnv env
| Except.error ex => do
opts ← getOptions;
throwError stx (ex.toMessageData opts)
def getOpenDecls : CommandElabM (List OpenDecl) := do
scope ← getScope; pure scope.openDecls
def logUnknownDecl (stx : Syntax) (declName : Name) : CommandElabM Unit :=
logError stx ("unknown declaration '" ++ toString declName ++ "'")
def resolveNamespace (id : Name) : CommandElabM Name := do
env ← getEnv;
currNamespace ← getCurrNamespace;
openDecls ← getOpenDecls;
match Elab.resolveNamespace env currNamespace openDecls id with
| some ns => pure ns
| none => throw Exception.unsupportedSyntax
@[builtinCommandElab «export»] def elabExport : CommandElab :=
fun stx => do
-- `stx` is of the form (Command.export "export" <namespace> "(" (null <ids>*) ")")
let id := stx.getIdAt 1;
ns ← resolveNamespace id;
currNamespace ← getCurrNamespace;
when (ns == currNamespace) $ throwError stx "invalid 'export', self export";
env ← getEnv;
let ids := (stx.getArg 3).getArgs;
aliases ← ids.foldlM
(fun (aliases : List (Name × Name)) (idStx : Syntax) => do {
let id := idStx.getId;
let declName := ns ++ id;
if env.contains declName then
pure $ (currNamespace ++ id, declName) :: aliases
else do
logUnknownDecl idStx declName;
pure aliases
})
[];
modify $ fun s => { env := aliases.foldl (fun env p => addAlias env p.1 p.2) s.env, .. s }
def addOpenDecl (d : OpenDecl) : CommandElabM Unit :=
modifyScope $ fun scope => { openDecls := d :: scope.openDecls, .. scope }
def elabOpenSimple (n : SyntaxNode) : CommandElabM Unit :=
-- `open` id+
let nss := n.getArg 0;
nss.forArgsM $ fun ns => do
ns ← resolveNamespace ns.getId;
addOpenDecl (OpenDecl.simple ns [])
-- `open` id `(` id+ `)`
def elabOpenOnly (n : SyntaxNode) : CommandElabM Unit := do
let ns := n.getIdAt 0;
ns ← resolveNamespace ns;
let ids := n.getArg 2;
ids.forArgsM $ fun idStx => do
let id := idStx.getId;
let declName := ns ++ id;
env ← getEnv;
if env.contains declName then
addOpenDecl (OpenDecl.explicit id declName)
else
logUnknownDecl idStx declName
-- `open` id `hiding` id+
def elabOpenHiding (n : SyntaxNode) : CommandElabM Unit := do
let ns := n.getIdAt 0;
ns ← resolveNamespace ns;
let idsStx := n.getArg 2;
env ← getEnv;
ids : List Name ← idsStx.foldArgsM (fun idStx ids => do
let id := idStx.getId;
let declName := ns ++ id;
if env.contains declName then
pure (id::ids)
else do
logUnknownDecl idStx declName;
pure ids)
[];
addOpenDecl (OpenDecl.simple ns ids)
-- `open` id `renaming` sepBy (id `->` id) `,`
def elabOpenRenaming (n : SyntaxNode) : CommandElabM Unit := do
let ns := n.getIdAt 0;
ns ← resolveNamespace ns;
let rs := (n.getArg 2);
rs.forSepArgsM $ fun stx => do
let fromId := stx.getIdAt 0;
let toId := stx.getIdAt 2;
let declName := ns ++ fromId;
env ← getEnv;
if env.contains declName then
addOpenDecl (OpenDecl.explicit toId declName)
else
logUnknownDecl stx declName
@[builtinCommandElab «open»] def elabOpen : CommandElab :=
fun n => do
let body := (n.getArg 1).asNode;
let k := body.getKind;
if k == `Lean.Parser.Command.openSimple then
elabOpenSimple body
else if k == `Lean.Parser.Command.openOnly then
elabOpenOnly body
else if k == `Lean.Parser.Command.openHiding then
elabOpenHiding body
else
elabOpenRenaming body
@[builtinCommandElab «variable»] def elabVariable : CommandElab :=
fun n => do
-- `variable` bracktedBinder
let binder := n.getArg 1;
-- Try to elaborate `binder` for sanity checking
runTermElabM none $ fun _ => Term.elabBinder binder $ fun _ => pure ();
modifyScope $ fun scope => { varDecls := scope.varDecls.push binder, .. scope }
@[builtinCommandElab «variables»] def elabVariables : CommandElab :=
fun n => do
-- `variables` bracktedBinder+
let binders := (n.getArg 1).getArgs;
-- Try to elaborate `binders` for sanity checking
runTermElabM none $ fun _ => Term.elabBinders binders $ fun _ => pure ();
modifyScope $ fun scope => { varDecls := scope.varDecls ++ binders, .. scope }
@[inline] def withoutModifyingEnv {α} (x : CommandElabM α) : CommandElabM α := do
env ← getEnv;
finally x (setEnv env)
@[builtinCommandElab «check»] def elabCheck : CommandElab :=
fun stx => do
let term := stx.getArg 1;
withoutModifyingEnv $ runTermElabM (some `_check) $ fun _ => do
e ← Term.elabTerm term none;
Term.synthesizeSyntheticMVars false;
type ← Term.inferType stx e;
logInfo stx (e ++ " : " ++ type);
pure ()
def hasNoErrorMessages : CommandElabM Bool := do
s ← get; pure $ !s.messages.hasErrors
def failIfSucceeds {α} (ref : Syntax) (x : CommandElabM α) : CommandElabM Unit := do
let resetMessages : CommandElabM MessageLog := do {
s ← get;
let messages := s.messages;
modify $ fun s => { messages := {}, .. s };
pure messages
};
let restoreMessages (prevMessages : MessageLog) : CommandElabM Unit := do {
modify $ fun s => { messages := prevMessages ++ s.messages.errorsToWarnings, .. s }
};
prevMessages ← resetMessages;
succeeded ← finally
(catch
(do x; hasNoErrorMessages)
(fun ex => match ex with
| Exception.error msg => do modify (fun s => { messages := s.messages.add msg, .. s }); pure false
| Exception.unsupportedSyntax => do logError ref "unsupported syntax"; pure false))
(restoreMessages prevMessages);
when succeeded $
throwError ref "unexpected success"
@[builtinCommandElab «check_failure»] def elabCheckFailure : CommandElab :=
fun stx => failIfSucceeds stx $ elabCheck stx
@[builtinCommandElab «synth»] def elabSynth : CommandElab :=
fun stx => do
let ref := stx;
let term := stx.getArg 1;
withoutModifyingEnv $ runTermElabM `_synth_cmd $ fun _ => do
inst ← Term.elabTerm term none;
Term.synthesizeSyntheticMVars false;
inst ← Term.instantiateMVars ref inst;
val ← Term.liftMetaM ref $ Meta.synthInstance inst;
logInfo stx val;
pure ()
def setOption (ref : Syntax) (optionName : Name) (val : DataValue) : CommandElabM Unit := do
decl ← liftIO ref $ getOptionDecl optionName;
unless (decl.defValue.sameCtor val) $ throwError ref "type mismatch at set_option";
modifyScope $ fun scope => { opts := scope.opts.insert optionName val, .. scope };
match optionName, val with
| `maxRecDepth, DataValue.ofNat max => modify $ fun s => { maxRecDepth := max, .. s}
| _, _ => pure ()
@[builtinCommandElab «set_option»] def elabSetOption : CommandElab :=
fun stx => do
let ref := stx;
let optionName := stx.getIdAt 1;
let val := stx.getArg 2;
match val.isStrLit? with
| some str => setOption ref optionName (DataValue.ofString str)
| none =>
match val.isNatLit? with
| some num => setOption ref optionName (DataValue.ofNat num)
| none =>
match val with
| Syntax.atom _ "true" => setOption ref optionName (DataValue.ofBool true)
| Syntax.atom _ "false" => setOption ref optionName (DataValue.ofBool false)
| _ => logError val ("unexpected set_option value " ++ toString val)
/-
`declId` is of the form
```
parser! ident >> optional (".{" >> sepBy1 ident ", " >> "}")
```
but we also accept a single identifier to users to make macro writing more convenient .
-/
def expandDeclId (declId : Syntax) : Name × Syntax :=
if declId.isIdent then
(declId.getId, mkNullNode)
else
let id := declId.getIdAt 0;
let optUnivDeclStx := declId.getArg 1;
(id, optUnivDeclStx)
@[inline] def withDeclId (declId : Syntax) (f : Name → CommandElabM Unit) : CommandElabM Unit := do
-- ident >> optional (".{" >> sepBy1 ident ", " >> "}")
let (id, optUnivDeclStx) := expandDeclId declId;
savedLevelNames ← getLevelNames;
levelNames ←
if optUnivDeclStx.isNone then
pure savedLevelNames
else do {
let extraLevels := (optUnivDeclStx.getArg 1).getArgs.getEvenElems;
extraLevels.foldlM
(fun levelNames idStx =>
let id := idStx.getId;
if levelNames.elem id then
throwAlreadyDeclaredUniverseLevel idStx id
else
pure (id :: levelNames))
savedLevelNames
};
let ref := declId;
-- extract (optional) namespace part of id, after decoding macro scopes that would interfere with the check
let scpView := extractMacroScopes id;
match scpView.name with
| Name.str pre s _ =>
/- Add back macro scopes. We assume a declaration like `def a.b[1,2] ...` with macro scopes `[1,2]`
is always meant to mean `namespace a def b[1,2] ...`. -/
let id := { name := mkNameSimple s, .. scpView }.review;
withNamespace ref pre $ do
modifyScope $ fun scope => { levelNames := levelNames, .. scope };
finally (f id) (modifyScope $ fun scope => { levelNames := savedLevelNames, .. scope })
| _ => throwError ref "invalid declaration name"
/--
Sort the given list of `usedParams` using the following order:
- If it is an explicit level `explicitParams`, then use user given order.
- Otherwise, use lexicographical.
Remark: `explicitParams` are in reverse declaration order. That is, the head is the last declared parameter. -/
def sortDeclLevelParams (explicitParams : List Name) (usedParams : Array Name) : List Name :=
let result := explicitParams.foldl (fun result levelName => if usedParams.elem levelName then levelName :: result else result) [];
let remaining := usedParams.filter (fun levelParam => !explicitParams.elem levelParam);
let remaining := remaining.qsort Name.lt;
result ++ remaining.toList
def addDecl (ref : Syntax) (decl : Declaration) : CommandElabM Unit := liftTermElabM none $ Term.addDecl ref decl
def compileDecl (ref : Syntax) (decl : Declaration) : CommandElabM Unit := liftTermElabM none $ Term.compileDecl ref decl
end Command
end Elab
end Lean
|
e16caff901315f6d0a48020b956601d8c746b22b | 07c76fbd96ea1786cc6392fa834be62643cea420 | /tests/lean/hott/rw_binders.hlean | b0e6c412d8a89426ac79b66bbc858f4bee7d1d02 | [
"Apache-2.0"
] | permissive | fpvandoorn/lean2 | 5a430a153b570bf70dc8526d06f18fc000a60ad9 | 0889cf65b7b3cebfb8831b8731d89c2453dd1e9f | refs/heads/master | 1,592,036,508,364 | 1,545,093,958,000 | 1,545,093,958,000 | 75,436,854 | 0 | 0 | null | 1,480,718,780,000 | 1,480,718,780,000 | null | UTF-8 | Lean | false | false | 206 | hlean | import types.eq
open eq
variables {A : Type} {a1 a2 a3 : A}
definition my_transport_eq_l (p : a1 = a2) (q : a1 = a3)
: transport (λx, x = a3) p q = p⁻¹ ⬝ q :=
begin
rewrite eq_transport_l,
end
|
c37a574238c750fb9992736bf9706cc334a830bc | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/elide_auto.lean | 8c8bbcfa64bd30eaaed2bf5becd05eb0cc72109f | [] | 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 | 896 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.core
import Mathlib.PostPort
namespace Mathlib
namespace tactic
namespace elide
end elide
namespace interactive
/-- The `elide n (at ...)` tactic hides all subterms of the target goal or hypotheses
beyond depth `n` by replacing them with `hidden`, which is a variant
on the identity function. (Tactics should still mostly be able to see
through the abbreviation, but if you want to unhide the term you can use
`unelide`.) -/
/-- The `unelide (at ...)` tactic removes all `hidden` subterms in the target
types (usually added by `elide`). -/
/--
The `elide n (at ...)` tactic hides all subterms of the target goal or hypotheses
end Mathlib |
793c554d6304f9ffb2949116b2a755cd6f64fc0d | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/data/complex/module.lean | 00266c0609ee6478d2e1ea438c3d741cc088c4d5 | [
"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 | 11,171 | lean | /-
Copyright (c) 2020 Alexander Bentkamp, Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp, Sébastien Gouëzel, Eric Wieser
-/
import algebra.module.ordered
import data.complex.basic
import data.matrix.notation
import field_theory.tower
/-!
# Complex number as a vector space over `ℝ`
This file contains the following instances:
* Any `•`-structure (`has_scalar`, `mul_action`, `distrib_mul_action`, `module`, `algebra`) on
`ℝ` imbues a corresponding structure on `ℂ`. This includes the statement that `ℂ` is an `ℝ`
algebra.
* any complex vector space is a real vector space;
* any finite dimensional complex vector space is a finite dimensional real vector space;
* the space of `ℝ`-linear maps from a real vector space to a complex vector space is a complex
vector space.
It also defines bundled versions of four standard maps (respectively, the real part, the imaginary
part, the embedding of `ℝ` in `ℂ`, and the complex conjugate):
* `complex.re_lm` (`ℝ`-linear map);
* `complex.im_lm` (`ℝ`-linear map);
* `complex.of_real_am` (`ℝ`-algebra (homo)morphism);
* `complex.conj_ae` (`ℝ`-algebra equivalence).
It also provides a universal property of the complex numbers `complex.lift`, which constructs a
`ℂ →ₐ[ℝ] A` into any `ℝ`-algebra `A` given a square root of `-1`.
-/
namespace complex
variables {R : Type*} {S : Type*}
section
variables [has_scalar R ℝ]
/- The useless `0` multiplication in `smul` is to make sure that
`restrict_scalars.module ℝ ℂ ℂ = complex.module` definitionally. -/
instance : has_scalar R ℂ :=
{ smul := λ r x, ⟨r • x.re - 0 * x.im, r • x.im + 0 * x.re⟩ }
lemma smul_re (r : R) (z : ℂ) : (r • z).re = r • z.re := by simp [(•)]
lemma smul_im (r : R) (z : ℂ) : (r • z).im = r • z.im := by simp [(•)]
@[simp] lemma smul_coe {x : ℝ} {z : ℂ} : x • z = x * z :=
by ext; simp [smul_re, smul_im]
end
instance [has_scalar R ℝ] [has_scalar S ℝ] [smul_comm_class R S ℝ] : smul_comm_class R S ℂ :=
{ smul_comm := λ r s x, by ext; simp [smul_re, smul_im, smul_comm] }
instance [has_scalar R S] [has_scalar R ℝ] [has_scalar S ℝ] [is_scalar_tower R S ℝ] :
is_scalar_tower R S ℂ :=
{ smul_assoc := λ r s x, by ext; simp [smul_re, smul_im, smul_assoc] }
instance [monoid R] [mul_action R ℝ] : mul_action R ℂ :=
{ one_smul := λ x, by ext; simp [smul_re, smul_im, one_smul],
mul_smul := λ r s x, by ext; simp [smul_re, smul_im, mul_smul] }
instance [semiring R] [distrib_mul_action R ℝ] : distrib_mul_action R ℂ :=
{ smul_add := λ r x y, by ext; simp [smul_re, smul_im, smul_add],
smul_zero := λ r, by ext; simp [smul_re, smul_im, smul_zero] }
instance [semiring R] [module R ℝ] : module R ℂ :=
{ add_smul := λ r s x, by ext; simp [smul_re, smul_im, add_smul],
zero_smul := λ r, by ext; simp [smul_re, smul_im, zero_smul] }
instance [comm_semiring R] [algebra R ℝ] : algebra R ℂ :=
{ smul := (•),
smul_def' := λ r x, by ext; simp [smul_re, smul_im, algebra.smul_def],
commutes' := λ r ⟨xr, xi⟩, by ext; simp [smul_re, smul_im, algebra.commutes],
..complex.of_real.comp (algebra_map R ℝ) }
/-- Note that when applied the RHS is further simplified by `complex.of_real_eq_coe`. -/
@[simp] lemma coe_algebra_map : ⇑(algebra_map ℝ ℂ) = complex.of_real := rfl
section
variables {A : Type*} [semiring A] [algebra ℝ A]
/-- We need this lemma since `complex.coe_algebra_map` diverts the simp-normal form away from
`alg_hom.commutes`. -/
@[simp] lemma _root_.alg_hom.map_coe_real_complex (f : ℂ →ₐ[ℝ] A) (x : ℝ) :
f x = algebra_map ℝ A x :=
f.commutes x
/-- Two `ℝ`-algebra homomorphisms from ℂ are equal if they agree on `complex.I`. -/
@[ext]
lemma alg_hom_ext ⦃f g : ℂ →ₐ[ℝ] A⦄ (h : f I = g I) : f = g :=
begin
ext ⟨x, y⟩,
simp only [mk_eq_add_mul_I, alg_hom.map_add, alg_hom.map_coe_real_complex, alg_hom.map_mul, h]
end
end
section
open_locale complex_order
lemma complex_ordered_smul : ordered_smul ℝ ℂ :=
{ smul_lt_smul_of_pos := λ z w x h₁ h₂,
begin
obtain ⟨y, l, rfl⟩ := lt_def.mp h₁,
refine lt_def.mpr ⟨x * y, _, _⟩,
exact mul_pos h₂ l,
ext; simp [mul_add],
end,
lt_of_smul_lt_smul_of_pos := λ z w x h₁ h₂,
begin
obtain ⟨y, l, e⟩ := lt_def.mp h₁,
by_cases h : x = 0,
{ subst h, exfalso, apply lt_irrefl 0 h₂, },
{ refine lt_def.mpr ⟨y / x, div_pos l h₂, _⟩,
replace e := congr_arg (λ z, (x⁻¹ : ℂ) * z) e,
simp only [mul_add, ←mul_assoc, h, one_mul, of_real_eq_zero, smul_coe, ne.def,
not_false_iff, inv_mul_cancel] at e,
convert e,
simp only [div_eq_iff_mul_eq, h, of_real_eq_zero, of_real_div, ne.def, not_false_iff],
norm_cast,
simp [mul_comm _ y, mul_assoc, h] },
end }
localized "attribute [instance] complex_ordered_smul" in complex_order
end
open submodule finite_dimensional
/-- `ℂ` has a basis over `ℝ` given by `1` and `I`. -/
noncomputable def basis_one_I : basis (fin 2) ℝ ℂ :=
basis.of_equiv_fun
{ to_fun := λ z, ![z.re, z.im],
inv_fun := λ c, c 0 + c 1 • I,
left_inv := λ z, by simp,
right_inv := λ c, by { ext i, fin_cases i; simp },
map_add' := λ z z', by simp,
map_smul' := λ c z, by simp }
@[simp] lemma coe_basis_one_I_repr (z : ℂ) : ⇑(basis_one_I.repr z) = ![z.re, z.im] := rfl
@[simp] lemma coe_basis_one_I : ⇑basis_one_I = ![1, I] :=
funext $ λ i, basis.apply_eq_iff.mpr $ finsupp.ext $ λ j,
by fin_cases i; fin_cases j;
simp only [coe_basis_one_I_repr, finsupp.single_eq_same, finsupp.single_eq_of_ne,
matrix.cons_val_zero, matrix.cons_val_one, matrix.head_cons,
nat.one_ne_zero, fin.one_eq_zero_iff, fin.zero_eq_one_iff, ne.def, not_false_iff,
one_re, one_im, I_re, I_im]
instance : finite_dimensional ℝ ℂ := of_fintype_basis basis_one_I
@[simp] lemma finrank_real_complex : finite_dimensional.finrank ℝ ℂ = 2 :=
by rw [finrank_eq_card_basis basis_one_I, fintype.card_fin]
@[simp] lemma dim_real_complex : module.rank ℝ ℂ = 2 :=
by simp [← finrank_eq_dim, finrank_real_complex]
lemma {u} dim_real_complex' : cardinal.lift.{0 u} (module.rank ℝ ℂ) = 2 :=
by simp [← finrank_eq_dim, finrank_real_complex, bit0]
/-- `fact` version of the dimension of `ℂ` over `ℝ`, locally useful in the definition of the
circle. -/
lemma finrank_real_complex_fact : fact (finrank ℝ ℂ = 2) := ⟨finrank_real_complex⟩
end complex
/- Register as an instance (with low priority) the fact that a complex vector space is also a real
vector space. -/
@[priority 900]
instance module.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E] : module ℝ E :=
restrict_scalars.module ℝ ℂ E
instance module.real_complex_tower (E : Type*) [add_comm_group E] [module ℂ E] :
is_scalar_tower ℝ ℂ E :=
restrict_scalars.is_scalar_tower ℝ ℂ E
@[priority 100]
instance finite_dimensional.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E]
[finite_dimensional ℂ E] : finite_dimensional ℝ E :=
finite_dimensional.trans ℝ ℂ E
lemma dim_real_of_complex (E : Type*) [add_comm_group E] [module ℂ E] :
module.rank ℝ E = 2 * module.rank ℂ E :=
cardinal.lift_inj.1 $
by { rw [← dim_mul_dim' ℝ ℂ E, complex.dim_real_complex], simp [bit0] }
lemma finrank_real_of_complex (E : Type*) [add_comm_group E] [module ℂ E] :
finite_dimensional.finrank ℝ E = 2 * finite_dimensional.finrank ℂ E :=
by rw [← finite_dimensional.finrank_mul_finrank ℝ ℂ E, complex.finrank_real_complex]
namespace complex
/-- Linear map version of the real part function, from `ℂ` to `ℝ`. -/
def re_lm : ℂ →ₗ[ℝ] ℝ :=
{ to_fun := λx, x.re,
map_add' := add_re,
map_smul' := by simp, }
@[simp] lemma re_lm_coe : ⇑re_lm = re := rfl
/-- Linear map version of the imaginary part function, from `ℂ` to `ℝ`. -/
def im_lm : ℂ →ₗ[ℝ] ℝ :=
{ to_fun := λx, x.im,
map_add' := add_im,
map_smul' := by simp, }
@[simp] lemma im_lm_coe : ⇑im_lm = im := rfl
/-- `ℝ`-algebra morphism version of the canonical embedding of `ℝ` in `ℂ`. -/
def of_real_am : ℝ →ₐ[ℝ] ℂ := algebra.of_id ℝ ℂ
@[simp] lemma of_real_am_coe : ⇑of_real_am = coe := rfl
/-- `ℝ`-algebra isomorphism version of the complex conjugation function from `ℂ` to `ℂ` -/
def conj_ae : ℂ ≃ₐ[ℝ] ℂ :=
{ inv_fun := conj,
left_inv := conj_conj,
right_inv := conj_conj,
commutes' := conj_of_real,
.. conj }
@[simp] lemma conj_ae_coe : ⇑conj_ae = conj := rfl
section lift
variables {A : Type*} [ring A] [algebra ℝ A]
/-- There is an alg_hom from `ℂ` to any `ℝ`-algebra with an element that squares to `-1`.
See `complex.lift` for this as an equiv. -/
def lift_aux (I' : A) (hf : I' * I' = -1) : ℂ →ₐ[ℝ] A :=
alg_hom.of_linear_map
((algebra.of_id ℝ A).to_linear_map.comp re_lm + (linear_map.to_span_singleton _ _ I').comp im_lm)
(show algebra_map ℝ A 1 + (0 : ℝ) • I' = 1,
by rw [ring_hom.map_one, zero_smul, add_zero])
(λ ⟨x₁, y₁⟩ ⟨x₂, y₂⟩, show algebra_map ℝ A (x₁ * x₂ - y₁ * y₂) + (x₁ * y₂ + y₁ * x₂) • I'
= (algebra_map ℝ A x₁ + y₁ • I') * (algebra_map ℝ A x₂ + y₂ • I'),
begin
rw [add_mul, mul_add, mul_add, add_comm _ (y₁ • I' * y₂ • I'), add_add_add_comm],
congr' 1, -- equate "real" and "imaginary" parts
{ rw [smul_mul_smul, hf, smul_neg, ←algebra.algebra_map_eq_smul_one, ←sub_eq_add_neg,
←ring_hom.map_mul, ←ring_hom.map_sub], },
{ rw [algebra.smul_def, algebra.smul_def, algebra.smul_def, ←algebra.right_comm _ x₂,
←mul_assoc, ←add_mul, ←ring_hom.map_mul, ←ring_hom.map_mul, ←ring_hom.map_add] }
end)
@[simp]
lemma lift_aux_apply (I' : A) (hI') (z : ℂ) :
lift_aux I' hI' z = algebra_map ℝ A z.re + z.im • I' := rfl
lemma lift_aux_apply_I (I' : A) (hI') : lift_aux I' hI' I = I' := by simp
/-- A universal property of the complex numbers, providing a unique `ℂ →ₐ[ℝ] A` for every element
of `A` which squares to `-1`.
This can be used to embed the complex numbers in the `quaternion`s.
This isomorphism is named to match the very similar `zsqrtd.lift`. -/
@[simps {simp_rhs := tt}]
def lift : {I' : A // I' * I' = -1} ≃ (ℂ →ₐ[ℝ] A) :=
{ to_fun := λ I', lift_aux I' I'.prop,
inv_fun := λ F, ⟨F I, by rw [←F.map_mul, I_mul_I, alg_hom.map_neg, alg_hom.map_one]⟩,
left_inv := λ I', subtype.ext $ lift_aux_apply_I I' I'.prop,
right_inv := λ F, alg_hom_ext $ lift_aux_apply_I _ _, }
/- When applied to `complex.I` itself, `lift` is the identity. -/
@[simp]
lemma lift_aux_I : lift_aux I I_mul_I = alg_hom.id ℝ ℂ :=
alg_hom_ext $ lift_aux_apply_I _ _
/- When applied to `-complex.I`, `lift` is conjugation, `conj`. -/
@[simp]
lemma lift_aux_neg_I : lift_aux (-I) ((neg_mul_neg _ _).trans I_mul_I) = conj_ae :=
alg_hom_ext $ (lift_aux_apply_I _ _).trans conj_I.symm
end lift
end complex
|
b810d2291eff9fdda1343059840ef553d9e315e9 | 0e175f34f8dca5ea099671777e8d7446d7d74227 | /library/init/core.lean | d976742f6b68f2016ded38cf5319dda79f101839 | [
"Apache-2.0"
] | permissive | utensil-contrib/lean | b31266738071c654d96dac8b35d9ccffc8172fda | a28b9c8f78d982a4e82b1e4f7ce7988d87183ae8 | refs/heads/master | 1,670,045,564,075 | 1,597,397,599,000 | 1,597,397,599,000 | 287,528,503 | 0 | 0 | Apache-2.0 | 1,597,408,338,000 | 1,597,408,337,000 | null | UTF-8 | Lean | false | false | 18,790 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
notation, basic datatypes and type classes
-/
prelude
notation `Prop` := Sort 0
notation f ` $ `:1 a:0 := f a
/- Reserving notation. We do this sot that the precedence of all of the operators
can be seen in one place and to prevent core notation being accidentally overloaded later. -/
/- Notation for logical operations and relations -/
reserve prefix `¬`:40
reserve prefix `~`:40 -- not used
reserve infixr ` ∧ `:35
reserve infixr ` /\ `:35
reserve infixr ` \/ `:30
reserve infixr ` ∨ `:30
reserve infix ` <-> `:20
reserve infix ` ↔ `:20
reserve infix ` = `:50 -- eq
reserve infix ` == `:50 -- heq
reserve infix ` ≠ `:50
reserve infix ` ≈ `:50 -- has_equiv.equiv
reserve infix ` ~ `:50 -- used as local notation for relations
reserve infix ` ≡ `:50 -- not used
reserve infixl ` ⬝ `:75 -- not used
reserve infixr ` ▸ `:75 -- eq.subst
reserve infixr ` ▹ `:75 -- not used
/- types and type constructors -/
reserve infixr ` ⊕ `:30 -- sum (defined in init/data/sum/basic.lean)
reserve infixr ` × `:35
/- arithmetic operations -/
reserve infixl ` + `:65
reserve infixl ` - `:65
reserve infixl ` * `:70
reserve infixl ` / `:70
reserve infixl ` % `:70
reserve prefix `-`:75
reserve infixr ` ^ `:80
reserve infixr ` ∘ `:90 -- function composition
reserve infix ` <= `:50
reserve infix ` ≤ `:50
reserve infix ` < `:50
reserve infix ` >= `:50
reserve infix ` ≥ `:50
reserve infix ` > `:50
/- boolean operations -/
reserve infixl ` && `:70
reserve infixl ` || `:65
/- set operations -/
reserve infix ` ∈ `:50
reserve infix ` ∉ `:50
reserve infixl ` ∩ `:70
reserve infixl ` ∪ `:65
reserve infix ` ⊆ `:50
reserve infix ` ⊇ `:50
reserve infix ` ⊂ `:50
reserve infix ` ⊃ `:50
reserve infix ` \ `:70 -- symmetric difference
/- other symbols -/
reserve infix ` ∣ `:50 -- has_dvd.dvd. Note this is different to `|`.
reserve infixl ` ++ `:65 -- has_append.append
reserve infixr ` :: `:67 -- list.cons
reserve infixl `; `:1 -- has_andthen.andthen
universes u v w
/--
The kernel definitional equality test (t =?= s) has special support for id_delta applications.
It implements the following rules
1) (id_delta t) =?= t
2) t =?= (id_delta t)
3) (id_delta t) =?= s IF (unfold_of t) =?= s
4) t =?= id_delta s IF t =?= (unfold_of s)
This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel.
We use id_delta applications to address performance problems when type checking
lemmas generated by the equation compiler.
-/
@[inline] def id_delta {α : Sort u} (a : α) : α :=
a
/-- Gadget for optional parameter support. -/
@[reducible] def opt_param (α : Sort u) (default : α) : Sort u :=
α
/-- Gadget for marking output parameters in type classes. -/
@[reducible] def out_param (α : Sort u) : Sort u := α
/-
id_rhs is an auxiliary declaration used in the equation compiler to address performance
issues when proving equational lemmas. The equation compiler uses it as a marker.
-/
abbreviation id_rhs (α : Sort u) (a : α) : α := a
inductive punit : Sort u
| star : punit
/-- An abbreviation for `punit.{0}`, its most common instantiation.
This type should be preferred over `punit` where possible to avoid
unnecessary universe parameters. -/
abbreviation unit : Type := punit
@[pattern] abbreviation unit.star : unit := punit.star
/--
Gadget for defining thunks, thunk parameters have special treatment.
Example: given
def f (s : string) (t : thunk nat) : nat
an application
f "hello" 10
is converted into
f "hello" (λ _, 10)
-/
@[reducible] def thunk (α : Type u) : Type u :=
unit → α
inductive true : Prop
| intro : true
inductive false : Prop
inductive empty : Type
def not (a : Prop) := a → false
prefix `¬` := not
inductive eq {α : Sort u} (a : α) : α → Prop
| refl [] : eq a
/-
Initialize the quotient module, which effectively adds the following definitions:
constant quot {α : Sort u} (r : α → α → Prop) : Sort u
constant quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : quot r
constant quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) :
(∀ a b : α, r a b → eq (f a) (f b)) → quot r → β
constant quot.ind {α : Sort u} {r : α → α → Prop} {β : quot r → Prop} :
(∀ a : α, β (quot.mk r a)) → ∀ q : quot r, β q
Also the reduction rule:
quot.lift f _ (quot.mk a) ~~> f a
-/
init_quotient
/-- Heterogeneous equality.
It's purpose is to write down equalities between terms whose types are not definitionally equal.
For example, given `x : vector α n` and `y : vector α (0+n)`, `x = y` doesn't typecheck but `x == y` does.
-/
inductive heq {α : Sort u} (a : α) : Π {β : Sort u}, β → Prop
| refl [] : heq a
structure prod (α : Type u) (β : Type v) :=
(fst : α) (snd : β)
/-- Similar to `prod`, but α and β can be propositions.
We use this type internally to automatically generate the brec_on recursor. -/
structure pprod (α : Sort u) (β : Sort v) :=
(fst : α) (snd : β)
structure and (a b : Prop) : Prop :=
intro :: (left : a) (right : b)
def and.elim_left {a b : Prop} (h : and a b) : a := h.1
def and.elim_right {a b : Prop} (h : and a b) : b := h.2
/- eq basic support -/
infix = := eq
attribute [refl] eq.refl
@[pattern] def rfl {α : Sort u} {a : α} : a = a := eq.refl a
@[elab_as_eliminator, subst]
lemma eq.subst {α : Sort u} {P : α → Prop} {a b : α} (h₁ : a = b) (h₂ : P a) : P b :=
eq.rec h₂ h₁
notation h1 ▸ h2 := eq.subst h1 h2
@[trans] lemma eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c :=
h₂ ▸ h₁
@[symm] lemma eq.symm {α : Sort u} {a b : α} (h : a = b) : b = a :=
h ▸ rfl
infix == := heq
@[pattern] def heq.rfl {α : Sort u} {a : α} : a == a := heq.refl a
lemma eq_of_heq {α : Sort u} {a a' : α} (h : a == a') : a = a' :=
have ∀ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a') (h₂ : α = α'), (eq.rec_on h₂ a : α') = a', from
λ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a'), heq.rec_on h₁ (λ h₂ : α = α, rfl),
show (eq.rec_on (eq.refl α) a : α) = a', from
this α a' h (eq.refl α)
/- The following four lemmas could not be automatically generated when the
structures were declared, so we prove them manually here. -/
lemma prod.mk.inj {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: (x₁, y₁) = (x₂, y₂) → and (x₁ = x₂) (y₁ = y₂) :=
λ h, prod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩)
lemma prod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P :=
λ h₁ _ h₂, prod.no_confusion h₁ h₂
lemma pprod.mk.inj {α : Sort u} {β : Sort v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: pprod.mk x₁ y₁ = pprod.mk x₂ y₂ → and (x₁ = x₂) (y₁ = y₂) :=
λ h, pprod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩)
lemma pprod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P :=
λ h₁ _ h₂, prod.no_confusion h₁ h₂
inductive sum (α : Type u) (β : Type v)
| inl (val : α) : sum
| inr (val : β) : sum
inductive psum (α : Sort u) (β : Sort v)
| inl (val : α) : psum
| inr (val : β) : psum
inductive or (a b : Prop) : Prop
| inl (h : a) : or
| inr (h : b) : or
def or.intro_left {a : Prop} (b : Prop) (ha : a) : or a b :=
or.inl ha
def or.intro_right (a : Prop) {b : Prop} (hb : b) : or a b :=
or.inr hb
structure sigma {α : Type u} (β : α → Type v) :=
mk :: (fst : α) (snd : β fst)
structure psigma {α : Sort u} (β : α → Sort v) :=
mk :: (fst : α) (snd : β fst)
inductive bool : Type
| ff : bool
| tt : bool
/- Remark: subtype must take a Sort instead of Type because of the axiom strong_indefinite_description. -/
structure subtype {α : Sort u} (p : α → Prop) :=
(val : α) (property : p val)
attribute [pp_using_anonymous_constructor] sigma psigma subtype pprod and
class inductive decidable (p : Prop)
| is_false (h : ¬p) : decidable
| is_true (h : p) : decidable
@[reducible]
def decidable_pred {α : Sort u} (r : α → Prop) :=
Π (a : α), decidable (r a)
@[reducible]
def decidable_rel {α : Sort u} (r : α → α → Prop) :=
Π (a b : α), decidable (r a b)
@[reducible]
def decidable_eq (α : Sort u) :=
decidable_rel (@eq α)
inductive option (α : Type u)
| none : option
| some (val : α) : option
export option (none some)
export bool (ff tt)
inductive list (T : Type u)
| nil : list
| cons (hd : T) (tl : list) : list
notation h :: t := list.cons h t
notation `[` l:(foldr `, ` (h t, list.cons h t) list.nil `]`) := l
inductive nat
| zero : nat
| succ (n : nat) : nat
structure unification_constraint :=
{α : Type u} (lhs : α) (rhs : α)
infix ` ≟ `:50 := unification_constraint.mk
infix ` =?= `:50 := unification_constraint.mk
structure unification_hint :=
(pattern : unification_constraint)
(constraints : list unification_constraint)
/- Declare builtin and reserved notation -/
class has_zero (α : Type u) := (zero : α)
class has_one (α : Type u) := (one : α)
class has_add (α : Type u) := (add : α → α → α)
class has_mul (α : Type u) := (mul : α → α → α)
class has_inv (α : Type u) := (inv : α → α)
class has_neg (α : Type u) := (neg : α → α)
class has_sub (α : Type u) := (sub : α → α → α)
class has_div (α : Type u) := (div : α → α → α)
class has_dvd (α : Type u) := (dvd : α → α → Prop)
class has_mod (α : Type u) := (mod : α → α → α)
class has_le (α : Type u) := (le : α → α → Prop)
class has_lt (α : Type u) := (lt : α → α → Prop)
class has_append (α : Type u) := (append : α → α → α)
class has_andthen (α : Type u) (β : Type v) (σ : out_param $ Type w) := (andthen : α → β → σ)
class has_union (α : Type u) := (union : α → α → α)
class has_inter (α : Type u) := (inter : α → α → α)
class has_sdiff (α : Type u) := (sdiff : α → α → α)
class has_equiv (α : Sort u) := (equiv : α → α → Prop)
class has_subset (α : Type u) := (subset : α → α → Prop)
class has_ssubset (α : Type u) := (ssubset : α → α → Prop)
/- Type classes has_emptyc and has_insert are
used to implement polymorphic notation for collections.
Example: {a, b, c}. -/
class has_emptyc (α : Type u) := (emptyc : α)
class has_insert (α : out_param $ Type u) (γ : Type v) := (insert : α → γ → γ)
class has_singleton (α : out_param $ Type u) (β : Type v) := (singleton : α → β)
/- Type class used to implement the notation { a ∈ c | p a } -/
class has_sep (α : out_param $ Type u) (γ : Type v) :=
(sep : (α → Prop) → γ → γ)
/- Type class for set-like membership -/
class has_mem (α : out_param $ Type u) (γ : Type v) := (mem : α → γ → Prop)
class has_pow (α : Type u) (β : Type v) :=
(pow : α → β → α)
export has_andthen (andthen)
export has_pow (pow)
infix ∈ := has_mem.mem
notation a ∉ s := ¬ has_mem.mem a s
infix + := has_add.add
infix * := has_mul.mul
infix - := has_sub.sub
infix / := has_div.div
infix ∣ := has_dvd.dvd
infix % := has_mod.mod
prefix - := has_neg.neg
infix <= := has_le.le
infix ≤ := has_le.le
infix < := has_lt.lt
infix ++ := has_append.append
infix ; := andthen
notation `∅` := has_emptyc.emptyc
infix ∪ := has_union.union
infix ∩ := has_inter.inter
infix ⊆ := has_subset.subset
infix ⊂ := has_ssubset.ssubset
infix \ := has_sdiff.sdiff
infix ≈ := has_equiv.equiv
infixr ^ := has_pow.pow
export has_append (append)
@[reducible] def ge {α : Type u} [has_le α] (a b : α) : Prop := has_le.le b a
@[reducible] def gt {α : Type u} [has_lt α] (a b : α) : Prop := has_lt.lt b a
infix >= := ge
infix ≥ := ge
infix > := gt
@[reducible] def superset {α : Type u} [has_subset α] (a b : α) : Prop := has_subset.subset b a
@[reducible] def ssuperset {α : Type u} [has_ssubset α] (a b : α) : Prop := has_ssubset.ssubset b a
infix ⊇ := superset
infix ⊃ := ssuperset
def bit0 {α : Type u} [s : has_add α] (a : α) : α := a + a
def bit1 {α : Type u} [s₁ : has_one α] [s₂ : has_add α] (a : α) : α := (bit0 a) + 1
attribute [pattern] has_zero.zero has_one.one bit0 bit1 has_add.add has_neg.neg
export has_insert (insert)
class is_lawful_singleton (α : Type u) (β : Type v) [has_emptyc β] [has_insert α β]
[has_singleton α β] :=
(insert_emptyc_eq : ∀ (x : α), (insert x ∅ : β) = {x})
export has_singleton (singleton)
export is_lawful_singleton (insert_emptyc_eq)
attribute [simp] insert_emptyc_eq
/- nat basic instances -/
namespace nat
protected def add : nat → nat → nat
| a zero := a
| a (succ b) := succ (add a b)
/- We mark the following definitions as pattern to make sure they can be used in recursive equations,
and reduced by the equation compiler. -/
attribute [pattern] nat.add nat.add._main
end nat
instance : has_zero nat := ⟨nat.zero⟩
instance : has_one nat := ⟨nat.succ (nat.zero)⟩
instance : has_add nat := ⟨nat.add⟩
def std.priority.default : nat := 1000
def std.priority.max : nat := 0xFFFFFFFF
namespace nat
protected def prio := std.priority.default + 100
end nat
/-
Global declarations of right binding strength
If a module reassigns these, it will be incompatible with other modules that adhere to these
conventions.
When hovering over a symbol, use "C-c C-k" to see how to input it.
-/
def std.prec.max : nat := 1024 -- the strength of application, identifiers, (, [, etc.
def std.prec.arrow : nat := 25
/-
The next def is "max + 10". It can be used e.g. for postfix operations that should
be stronger than application.
-/
def std.prec.max_plus : nat := std.prec.max + 10
reserve postfix `⁻¹`:std.prec.max_plus -- input with \sy or \-1 or \inv
postfix ⁻¹ := has_inv.inv
notation α × β := prod α β
-- notation for n-ary tuples
/- sizeof -/
class has_sizeof (α : Sort u) :=
(sizeof : α → nat)
def sizeof {α : Sort u} [s : has_sizeof α] : α → nat :=
has_sizeof.sizeof
/-
Declare sizeof instances and lemmas for types declared before has_sizeof.
From now on, the inductive compiler will automatically generate sizeof instances and lemmas.
-/
/- Every type `α` has a default has_sizeof instance that just returns 0 for every element of `α` -/
protected def default.sizeof (α : Sort u) : α → nat
| a := 0
instance default_has_sizeof (α : Sort u) : has_sizeof α :=
⟨default.sizeof α⟩
protected def nat.sizeof : nat → nat
| n := n
instance : has_sizeof nat :=
⟨nat.sizeof⟩
protected def prod.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (prod α β) → nat
| ⟨a, b⟩ := 1 + sizeof a + sizeof b
instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (prod α β) :=
⟨prod.sizeof⟩
protected def sum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (sum α β) → nat
| (sum.inl a) := 1 + sizeof a
| (sum.inr b) := 1 + sizeof b
instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (sum α β) :=
⟨sum.sizeof⟩
protected def psum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (psum α β) → nat
| (psum.inl a) := 1 + sizeof a
| (psum.inr b) := 1 + sizeof b
instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (psum α β) :=
⟨psum.sizeof⟩
protected def sigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : sigma β → nat
| ⟨a, b⟩ := 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (sigma β) :=
⟨sigma.sizeof⟩
protected def psigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : psigma β → nat
| ⟨a, b⟩ := 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (psigma β) :=
⟨psigma.sizeof⟩
protected def punit.sizeof : punit → nat
| u := 1
instance : has_sizeof punit := ⟨punit.sizeof⟩
protected def bool.sizeof : bool → nat
| b := 1
instance : has_sizeof bool := ⟨bool.sizeof⟩
protected def option.sizeof {α : Type u} [has_sizeof α] : option α → nat
| none := 1
| (some a) := 1 + sizeof a
instance (α : Type u) [has_sizeof α] : has_sizeof (option α) :=
⟨option.sizeof⟩
protected def list.sizeof {α : Type u} [has_sizeof α] : list α → nat
| list.nil := 1
| (list.cons a l) := 1 + sizeof a + list.sizeof l
instance (α : Type u) [has_sizeof α] : has_sizeof (list α) :=
⟨list.sizeof⟩
protected def subtype.sizeof {α : Type u} [has_sizeof α] {p : α → Prop} : subtype p → nat
| ⟨a, _⟩ := sizeof a
instance {α : Type u} [has_sizeof α] (p : α → Prop) : has_sizeof (subtype p) :=
⟨subtype.sizeof⟩
lemma nat_add_zero (n : nat) : n + 0 = n := rfl
/- Combinator calculus -/
namespace combinator
universes u₁ u₂ u₃
def I {α : Type u₁} (a : α) := a
def K {α : Type u₁} {β : Type u₂} (a : α) (b : β) := a
def S {α : Type u₁} {β : Type u₂} {γ : Type u₃} (x : α → β → γ) (y : α → β) (z : α) := x z (y z)
end combinator
/-- Auxiliary datatype for #[ ... ] notation.
#[1, 2, 3, 4] is notation for
bin_tree.node
(bin_tree.node (bin_tree.leaf 1) (bin_tree.leaf 2))
(bin_tree.node (bin_tree.leaf 3) (bin_tree.leaf 4))
We use this notation to input long sequences without exhausting the system stack space.
Later, we define a coercion from `bin_tree` into `list`.
-/
inductive bin_tree (α : Type u)
| empty : bin_tree
| leaf (val : α) : bin_tree
| node (left right : bin_tree) : bin_tree
attribute [elab_simple] bin_tree.node bin_tree.leaf
/- Basic unification hints -/
@[unify] def add_succ_defeq_succ_add_hint (x y z : nat) : unification_hint :=
{ pattern := x + nat.succ y ≟ nat.succ z,
constraints := [z ≟ x + y] }
/-- Like `by apply_instance`, but not dependent on the tactic framework. -/
@[reducible] def infer_instance {α : Type u} [i : α] : α := i
|
9d0d76ac401be6c2eb162c4f7842e8879cf106da | f6124fee10424c8e1c21a4681488620467936253 | /lean4/LFSC.lean | 19248a505ebbd83905eaf3ef4f65012495952750 | [
"BSD-3-Clause"
] | permissive | GaloisInc/lean4-lfsc-parser | 0e4b5db1bb3fa6fbc37d6b1b488491a279d0f6bf | 052a788702c84fd8cdc5c636aba0d8b2778d0808 | refs/heads/master | 1,615,000,862,052 | 1,586,190,656,000 | 1,586,190,656,000 | 246,176,496 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 50,074 | lean | /-
A fledging LFSC paser written in Lean 4.
Copyright Galois, Inc, 2020
Maintainer: Joe Hendrix
Available for redistribution under Apache 2.0 license.
It can be run on a PLF file with `lean --run lfsc.lean <filename.plf>`
-/
import Init.Lean.Data.Position
import Init.Data.PersistentHashMap
namespace Array
def fromList {α} (l:List α) : Array α := l.foldl Array.push Array.empty
end Array
namespace HashMap
def fromList {α β} [Hashable α] [HasBeq α] : List (α × β) → HashMap α β :=
let f (m:HashMap α β) (p : α × β) := m.insert p.fst p.snd;
λl => l.foldl f HashMap.empty
end HashMap
namespace lfsc
/- A symbol in LFSC is currently just a string that doesn't contain whitespace or parens. -/
def Symbol := String
/- Variable name -/
def Var := Symbol
@[reducible]
def FamilyIndex := Nat
/- Family tag -/
structure Family :=
(name : Symbol)
(idx : FamilyIndex)
@[reducible]
def CtorIndex := Nat
/- Constructor tag -/
structure Ctor :=
(name : Symbol)
(idx : CtorIndex)
@[reducible]
def ProgArgIndex := Nat
/- A reference to a program argument. -/
structure ProgArg :=
(name : Symbol)
(tp : Family)
(idx : ProgArgIndex)
@[reducible]
def ProgramIndex := Nat
/- A reference to a program -/
structure Program :=
(name : Symbol)
(idx : ProgramIndex)
/- Print rest of arguments for slist below -/
def slistAux : List String → String
| [] => ")"
| h::r => " " ++ h ++ slistAux r
/- Print an sexpression with a list of strings as parameters. -/
def slist : List String → String
| [] => "()"
| h::r => "(" ++ h ++ slistAux r
@[reducible]
def VarLevel := Nat
inductive VExpr : Type
| ctorInst : Ctor → Array VExpr → VExpr
-- A variable that comes from a bit lambda
| checkvarRef : Nat → String → VExpr
-- A reference to a lambda , phi or match statementvariable
| varRef : VarLevel → String → VExpr
| letvarRef : VarLevel → String → VExpr
-- An integer literal
| intLit : Int → VExpr
| lambda : Symbol → VExpr → VExpr
| letExpr : Symbol → VExpr → VExpr → VExpr
| hole : VExpr
namespace VExpr
-- Pretty print an expression
partial
def reprAux : VExpr → String
| ctorInst c args =>
if args.isEmpty then
c.name
else
slist (c.name :: reprAux <$> args.toList)
| checkvarRef _ nm => nm
| varRef _ nm => nm
| letvarRef _ nm => nm
| intLit i => repr i
| lambda v x => slist ["\\", v, reprAux x]
| letExpr nm val x => slist ["@", nm, reprAux val, reprAux x]
| hole => "_"
instance : HasRepr VExpr := ⟨VExpr.reprAux⟩
partial
def pisubst : VExpr → Array VExpr → VExpr
| ctorInst c args, r => ctorInst c (args.map (λa => pisubst a r))
| checkvarRef lvl nm, _ => checkvarRef lvl nm
| varRef lvl nm, r =>
if h : lvl < r.size then
r.get ⟨lvl, h⟩
else
varRef (lvl-r.size) nm
| letvarRef lvl nm, _ => letvarRef (lvl-1) nm
| intLit i, _ => intLit i
| lambda v x, r => lambda v (pisubst x r)
| letExpr nm val x, r => letExpr nm (pisubst val r) (pisubst val r)
| hole, _ => hole
end VExpr
inductive CodeVal
| expr : VExpr → CodeVal
| call : Program → Array CodeVal → CodeVal
namespace CodeVal
-- Pretty print an expression
partial
def reprAux : CodeVal → String
| expr c => repr c
| call p args => slist (p.name :: args.toList.map reprAux)
instance : HasRepr CodeVal := ⟨reprAux⟩
partial
def pisubst: CodeVal → Array VExpr → CodeVal
| expr e, val => expr (e.pisubst val)
| call pgm args, val => call pgm (args.map (λa => a.pisubst val))
end CodeVal
structure Check :=
(program : Program)
(args : Array CodeVal)
(res : CodeVal)
namespace Check
instance : HasRepr Check := ⟨λc => slist ["^", slist (c.program.name :: repr <$> c.args.toList), repr c.res]⟩
partial
def pisubst (c:Check) (val:Array VExpr) : Check :=
{ program := c.program, args := c.args.map (λa => a.pisubst val), res := c.res.pisubst val }
end Check
-- Expression type for definitions and code.
inductive AExpr : Type
-- References a type family with the given arguments.
| fam : Family → Array VExpr → AExpr
-- A pi type with the argument and expression.
| pi : String → AExpr → AExpr → AExpr
| check : Option String → Check → AExpr → AExpr
-- A reference to a global type synonym with the given definition.
| ref : String → AExpr → AExpr
namespace AExpr
-- Pretty print an expression
partial
def reprAux : AExpr → String
| fam f args =>
if args.isEmpty then
f.name
else
slist (f.name :: args.toList.map repr)
| pi nm tp x => slist ["!", nm, reprAux tp, reprAux x]
| check (Option.some nm) chk x => slist ["!", nm, repr chk, reprAux x]
| check Option.none chk x => slist ["!", repr chk, reprAux x]
| ref nm _ => nm
--| ._, codeVar _ nm => nm
instance : HasRepr AExpr := ⟨reprAux⟩
partial
def pisubst : AExpr → Array VExpr → AExpr
| fam f args, val => fam f (args.map (λa => a.pisubst val))
| pi nm tp v, val => pi nm (tp.pisubst val) (v.pisubst val)
| check mnm tp v, val => check mnm (tp.pisubst val) (v.pisubst val)
| ref nm gtp, _ => ref nm gtp
end AExpr
-- Expression type for definitions and code.
inductive KExpr : Type
-- Kind constructors
| type : KExpr
| pi : String → AExpr → KExpr → KExpr
| check : Option String → Check → KExpr → KExpr
namespace KExpr
-- Pretty print an expression
partial
def reprAux : KExpr → String
| type => "type"
| pi nm tp x => slist ["!", nm, repr tp, reprAux x]
| check (Option.some nm) chk x => slist ["!", nm, repr chk, reprAux x]
| check Option.none chk x => slist ["!", repr chk, reprAux x]
instance : HasRepr KExpr := ⟨reprAux⟩
partial
def pisubst : KExpr → Array VExpr → KExpr
| type, _ => type
| pi nm tp v, val => pi nm (tp.pisubst val) (pisubst v val)
| check mnm chk v, val => check mnm (chk.pisubst val) (pisubst v val)
end KExpr
/- A Pattern with list of argument.. -/
structure Pat :=
(ctor : Ctor)
(args : Array (String × AExpr))
namespace Pat
protected
partial
def repr (p:Pat) : String :=
if p.args.size = 0 then
p.ctor.name
else
slist (p.ctor.name :: (Prod.fst <$> p.args.toList))
instance : HasRepr Pat := ⟨Pat.repr⟩
end Pat
inductive Code
| ctor : Ctor → Array Code → Code
| casevar : VarLevel → String → Code
| letvar : Nat → String → Code
| progarg : ProgArg → Code
| codeIntLit : Int → Code
| matchStmt : Code → Array (Pat × Code) → Option Code → Code
| doStmt : Array Code → Code
| letStmt : String → Nat → Code → Code → Code
| markvar : Nat → Code → Code
| ifequal : Code → Code → Code → Code → Code
| ifmarked : Nat → Code → Code → Code → Code
| mp_ifzero : Code → Code → Code → Code
| mp_ifneg : Code → Code → Code → Code
| fail : AExpr → Code
| call : Program → Array Code → Code
namespace Code
partial
def reprAux : Code → String
--| codeSym nm => nm
| ctor c a =>
if a.isEmpty then
c.name
else
slist (c.name :: a.toList.map reprAux)
| progarg p => p.name
| casevar _ nm => nm
| letvar _ nm => nm
| codeIntLit i => repr i
| matchStmt e cases mdef =>
let caseReprs := (λ(p : Pat × Code) => slist [repr p.fst, reprAux p.snd]) <$> cases.toList;
let defReprs : List String :=
match mdef with
| Option.some c => [reprAux c]
| Option.none => [];
slist ("match" :: reprAux e :: caseReprs ++ defReprs)
| doStmt l => slist ("do" :: reprAux <$> l.toList)
| letStmt var _ d x => slist ["let", reprAux d, reprAux x]
| markvar idx x =>
let fnm := if idx = 1 then "markvar" else ("markvar" ++ repr idx);
slist [fnm, reprAux x]
| ifequal x y t f => slist ["ifequal", reprAux x, reprAux y, reprAux t, reprAux f]
| ifmarked idx x t f =>
let fnm := if idx = 1 then "ifmarked" else ("ifmarked" ++ repr idx);
slist [fnm, reprAux x, reprAux t, reprAux f]
| mp_ifzero n t f =>
slist ["mp_ifzero", reprAux n, reprAux t, reprAux f]
| mp_ifneg n t f =>
slist ["mp_ifneg", reprAux n, reprAux t, reprAux f]
| fail tp => slist ["fail", repr tp]
| call pgm args => slist (pgm.name :: args.toList.map reprAux)
instance : HasRepr Code := ⟨Code.reprAux⟩
end Code
inductive SomeExpr
| embedKind (x:KExpr) : SomeExpr
| embedFam (x:AExpr) : SomeExpr
| embedCheck (x:Check) : SomeExpr
| embedVal (x:VExpr) : SomeExpr
namespace SomeExpr
-- Pretty print an expression
partial
def reprAux : SomeExpr → String
| embedKind x => repr x
| embedFam x => repr x
| embedCheck x => repr x
| embedVal x => repr x
instance : HasRepr SomeExpr := ⟨reprAux⟩
end SomeExpr
inductive CheckValue
| bigLambda (v:Symbol) (tp:AExpr) (x:CheckValue) : CheckValue
| letExpr (v:Symbol) (val:VExpr) (x:CheckValue) : CheckValue
| proof (v:SomeExpr) : CheckValue
namespace CheckValue
-- Pretty print an expression
partial
def reprAux : CheckValue → String
| bigLambda v tp x => slist ["%", v, repr tp, reprAux x]
| letExpr nm val x => slist ["@", nm, repr val, reprAux x]
| proof x => repr x
instance : HasRepr CheckValue := ⟨reprAux⟩
end CheckValue
inductive Command
| declareType (nm:Symbol) (tp:KExpr) : Command
| declareCtor (nm:Symbol) (tp:AExpr) : Command
| define (nm:Symbol) (v:SomeExpr) : Command
| program (nm:Symbol) (args : Array (Symbol × Family)) (ret : Family) (d : Code) : Command
| check (v:CheckValue) : Command
namespace Command
def ppArg : Symbol × Family → String
| (nm, f) => slist [nm, f.name]
protected
def reprAux : Command → String
| (declareType s tp) => slist ["declare", s, repr tp]
| (declareCtor s tp) => slist ["declare", s, repr tp]
| (define s tp) => slist ["declare", s, repr tp]
| (program s args ret d) => slist ["program", s, slist (ppArg <$> args.toList), ret.name, repr d]
| (check e) => slist ["check", repr e]
instance : HasRepr Command := ⟨Command.reprAux⟩
end Command
structure ParserContext :=
(source : String)
(input : String)
(fileMap : Lean.FileMap)
structure ParserState :=
(index : String.Pos)
/- Read to end-of-line -/
partial
def ParserContext.eol (ctx:ParserContext) : ParserState → ParserState
| s =>
if ctx.input.atEnd s.index then
s
else
let c := ctx.input.get s.index;
if c = '\n' then
{ index := s.index + 1 }
else
ParserContext.eol { index := s.index + c.utf8Size.toNat }
/- Read to next token -/
partial
def ParserContext.next (ctx:ParserContext) : ParserState → ParserState
| s =>
if ctx.input.atEnd s.index then
s
else
let c := ctx.input.get s.index;
if c = ';' then
ParserContext.next (ctx.eol { index := s.index + 1})
else if c.isWhitespace then
ParserContext.next { index := s.index + c.utf8Size.toNat }
else
s
structure ParserError :=
(source : String)
(pos : Lean.Position)
(message : String)
namespace ParserError
def new (ctx:ParserContext) (s:ParserState) (msg:String) : ParserError :=
{ source := ctx.source, pos := ctx.fileMap.toPosition s.index, message := msg }
instance : HasRepr ParserError := ⟨λe => e.source ++ toString e.pos ++ ": " ++ e.message⟩
instance : Inhabited ParserError := ⟨{ source := "arbitrary", pos := arbitrary _, message := "default" }⟩
end ParserError
def Parser := ReaderT ParserContext (EStateM ParserError ParserState)
def Parser.run {α} (m:Parser α) (src:String) (s:String) : Except ParserError α :=
let ctx := { ParserContext . source := src, input := s, fileMap := s.toFileMap };
match (ReaderT.run m ctx) (ctx.next { index := 0 }) with
| EStateM.Result.ok a _ => Except.ok a
| EStateM.Result.error e _ => Except.error e
namespace Parser
protected
def orelse {α} (x y : Parser α) : Parser α := λctx s =>
match x ctx s with
| EStateM.Result.ok a s => EStateM.Result.ok a s
| EStateM.Result.error e _ => y ctx s
instance {α} : HasOrelse (Parser α) := ⟨Parser.orelse⟩
instance {α} : Inhabited (Parser α) := inferInstanceAs (Inhabited (ParserContext → EStateM ParserError ParserState α))
instance : Functor Parser := inferInstanceAs (Functor (ReaderT ParserContext (EStateM ParserError ParserState)))
instance : HasSeq Parser := inferInstanceAs (HasSeq (ReaderT ParserContext (EStateM ParserError ParserState)))
instance : HasSeqLeft Parser := inferInstanceAs (HasSeqLeft (ReaderT ParserContext (EStateM ParserError ParserState)))
instance : HasSeqRight Parser := inferInstanceAs (HasSeqRight (ReaderT ParserContext (EStateM ParserError ParserState)))
instance : HasBind Parser := inferInstanceAs (HasBind (ReaderT ParserContext (EStateM ParserError ParserState)))
instance : HasPure Parser := inferInstanceAs (HasPure (ReaderT ParserContext (EStateM ParserError ParserState)))
instance : Monad Parser := inferInstanceAs (Monad (ReaderT ParserContext (EStateM ParserError ParserState)))
instance : MonadState ParserState Parser :=
inferInstanceAs (MonadState ParserState (ReaderT ParserContext (EStateM ParserError ParserState)))
end Parser
partial
def hasMore : Parser Bool
| ctx, s => EStateM.Result.ok (not (ctx.input.atEnd s.index)) s
def fail {α} (msg:String) : Parser α := λctx s =>
EStateM.Result.error (ParserError.new ctx s msg) s
def peek : Parser Char
| ctx, s =>
if ctx.input.atEnd s.index then
fail "End of string" ctx s
else
EStateM.Result.ok (ctx.input.get s.index) s
def skip : Parser Unit
| ctx, s =>
if ctx.input.atEnd s.index then
fail "End of string" ctx s
else
let c := ctx.input.get s.index;
EStateM.Result.ok () (ctx.next { index := s.index + c.utf8Size.toNat })
def char (e:Char) : Parser Unit
| ctx, s =>
if ctx.input.atEnd s.index then
fail "End of string" ctx s
else
let c := ctx.input.get s.index;
if c = e then
EStateM.Result.ok () (ctx.next { index := s.index + c.utf8Size.toNat })
else
fail ("char match " ++ repr e ++ " failed") ctx s
partial
def keywordAux (expected:String) : String.Pos → Parser Unit
| i, ctx, s =>
if expected.atEnd i then
EStateM.Result.ok () (ctx.next s)
else
let e := expected.get i;
if ctx.input.atEnd s.index then
fail "End of string" ctx s
else
let c := ctx.input.get s.index;
if c = e then
let sz := e.utf8Size.toNat;
keywordAux (i + sz) ctx { index := s.index + sz }
else
fail "Match failed" ctx s
partial
def keyword (expected:String) : Parser Unit := keywordAux expected 0
def lparen : Parser Unit := char '('
def rparen : Parser Unit := char ')'
partial
def listRestAux {α} (m:Parser α) : Array α → Parser (Array α)
| prev => do
c ← peek;
if c = ')' then
skip $> prev
else
m >>= λv => listRestAux (prev.push v)
/-- `listRest m` read values using `m` until we encounter right paren. -/
partial
def listRest {α} (m:Parser α) : Parser (Array α) := listRestAux m Array.empty
/-- `list m` reads an expression of the form '(' m* ')`. -/
partial
def list {α} (m:Parser α) : Parser (Array α) := do
c ← peek;
if c = '(' then
skip *> listRest m
else
fail "Expected start of list"
-- Helper for `match1 below.
partial
def matchAux (r:Char → Bool) (b:String.Pos) : Parser String
| ctx, s =>
if ctx.input.atEnd s.index then
EStateM.Result.ok (ctx.input.extract b s.index) (ctx.next s)
else
let c := ctx.input.get s.index;
if r c then
matchAux ctx { index := s.index + c.utf8Size.toNat }
else
EStateM.Result.ok (ctx.input.extract b s.index) (ctx.next s)
-- Recognize longest string that starts with a character matching
-- `h` and is followed by any number of characters matching `r`.
def match1 (nm:String) (h:Char → Bool) (r:Char → Bool) : Parser String
| ctx, s =>
if ctx.input.atEnd s.index then
fail "End of string" ctx s
else
let c := ctx.input.get s.index;
if h c then
matchAux r s.index ctx { index := s.index + c.utf8Size.toNat }
else
fail ("Unexpected " ++ nm ++ " start character: " ++ repr c) ctx s
def symbol : Parser Symbol :=
let h (c:Char) : Bool := c ≠ '(' ∧ c ≠ ')' ∧ not c.isWhitespace;
match1 "symbol" h h
def isPosDigit (c:Char) : Bool := c.val ≥ '1'.val && c.val ≤ '9'.val
def nat : Parser Nat := String.toNat <$> match1 "nat" isPosDigit Char.isDigit
def isNat (s:String) : Bool := s.all Char.isDigit && s ≠ "" && (s = "0" || s.front ≠ '0')
def parens {α} (i:Parser α) : Parser α := do
c ← peek;
if c = '(' then
skip *> i <* rparen
else
fail "Expected start of parenthesis"
inductive SExprStart
| openparen : SExprStart
| symbol : String → SExprStart
def sexprStart : Parser SExprStart := do
c ← peek;
if c = '(' then
skip $> SExprStart.openparen
else
SExprStart.symbol <$> symbol
------------------------------------------------------------------------
-- LFSC specific stuff
@[reducible]
def CheckVarIndex := Nat
inductive EnvDef
-- A global type with the given name.
| famDecl (f:Family) (k:KExpr) : EnvDef
-- A constructor declared
| ctorDecl (c:Ctor) (tp:AExpr) : EnvDef
-- A global defined expression with the given expression
| defDecl (e:SomeExpr) : EnvDef
-- A program declared in a top-level program definition
| programDecl (p:Program) (args : Array (Symbol × Family)) (resultType : Family) : EnvDef
-- A variable declaration from a big lambda
| checkVarDecl (var:CheckVarIndex) (tp:AExpr) : EnvDef
-- A variable declared from a pi that is a programmatic check
| checkDecl : EnvDef
-- A variable declaration from a pi
| pivarDecl (lvl:VarLevel) (tp:AExpr) : EnvDef
-- A variable declared in a label and having the given type.
| lambdavarDecl (lvl:VarLevel) (tp:AExpr) : EnvDef
-- A let declaration
| letDecl (lvl:VarLevel) (v:VExpr) : EnvDef
-- A program argument
| progarg : ProgArg → EnvDef
-- A program argument
| caseVar (lvl:VarLevel) (tp:AExpr) : EnvDef
-- A Program let
| codelet : VarLevel → Code → EnvDef
namespace EnvDef
def type : EnvDef → String
| famDecl _ _ => "family"
| ctorDecl _ _ => "constructor"
| defDecl _ => "define"
| programDecl _ _ _ => "program"
| checkVarDecl _ _ => "constant"
| pivarDecl _ _ => "pi variable"
| checkDecl => "check"
| lambdavarDecl _ _ => "lambda variable"
| letDecl _ _ => "let declaration"
| progarg _ => "program argument"
| caseVar _ _ => "case variable"
| codelet _ _ => "code let"
end EnvDef
structure ProgramInfo :=
(args : Array (Symbol × Family))
(ret : Family)
(code : Code)
structure GlobalEnvironment :=
(commands : List Command)
(globals : HashMap String EnvDef)
(families : Array KExpr)
(ctors : Array AExpr)
(programCount : Nat)
def mpz : Family := ⟨"mpz", 0⟩
def mp_add : Program := ⟨"mp_add", 0⟩
def mp_mul : Program := ⟨"mp_mul", 0⟩
namespace GlobalEnvironment
def init : GlobalEnvironment :=
{ commands := [],
globals := HashMap.fromList
[("mpz", EnvDef.famDecl mpz KExpr.type),
("mp_add", EnvDef.programDecl mp_add (Array.fromList [("x",mpz), ("y", mpz)]) mpz),
("mp_mul", EnvDef.programDecl mp_add (Array.fromList [("x",mpz), ("y", mpz)]) mpz)
],
families := Array.empty.push KExpr.type,
ctors := Array.empty,
programCount := 2
}
def addCommand (e:GlobalEnvironment) (c:Command) : GlobalEnvironment :=
{ e with commands := c :: e.commands }
def insert (e:GlobalEnvironment) (nm:String) (d:EnvDef) : GlobalEnvironment :=
{ e with globals := e.globals.insert nm d }
def addFamily (e:GlobalEnvironment) (nm:String) (k:KExpr) (addCommand:Bool) : GlobalEnvironment :=
let f : Family := ⟨nm,e.families.size⟩;
{ e with commands := if addCommand then Command.declareType nm k :: e.commands else e.commands,
globals := e.globals.insert nm (EnvDef.famDecl f k),
families := e.families.push k
}
def addCtor (e:GlobalEnvironment) (nm:String) (tp:AExpr) : GlobalEnvironment :=
let cmd := Command.declareCtor nm tp;
let c : Ctor := ⟨nm,e.ctors.size⟩;
{ e with commands := cmd :: e.commands,
globals := e.globals.insert nm (EnvDef.ctorDecl c tp),
ctors := e.ctors.push tp
}
def addProgramDecl (e:GlobalEnvironment) (nm:String) (args : Array (Symbol × Family)) (ret : Family)
: GlobalEnvironment :=
let p : Program := ⟨nm,e.programCount⟩;
{ e with globals := e.globals.insert nm (EnvDef.programDecl p args ret),
}
def find? (e:GlobalEnvironment) (nm:String) : Option EnvDef := e.globals.find? nm
def ctorType? (e:GlobalEnvironment) (c:Ctor) : Option AExpr := e.ctors.get? c.idx
end GlobalEnvironment
structure Environment :=
(global : GlobalEnvironment)
(locals : PHashMap String EnvDef)
(varCnt : VarLevel)
(checkVarCnt : CheckVarIndex)
-- Bindings of variables
(ctx : Array VExpr)
namespace Environment
def new (env:GlobalEnvironment) : Environment :=
{ global := env
, locals := PersistentHashMap.empty
, varCnt := 0
, checkVarCnt := 0
, ctx := Array.empty
}
-- Create environment for program
def code (env:GlobalEnvironment) (args : Array (String × Family)) : Environment :=
let insArg (m : PHashMap String EnvDef) (p : String × Family) :=
let a : ProgArg := ⟨p.fst, p.snd, m.size⟩;
m.insert p.fst (EnvDef.progarg a);
{ global := env
, locals := args.foldl insArg PersistentHashMap.empty
, varCnt := 0
, checkVarCnt := 0
, ctx := Array.empty
}
def find? (e:Environment) (nm:String) : Option EnvDef :=
match e.locals.find? nm with
| Option.some d => Option.some d
| Option.none => e.global.find? nm
def insertCheckVar (e:Environment) (nm:String) (tp:AExpr) : Environment :=
{ e with locals := e.locals.insert nm (EnvDef.checkVarDecl e.checkVarCnt tp),
checkVarCnt := e.checkVarCnt + 1
}
def insertPiVar (e:Environment) (nm:String) (tp:AExpr) : Environment :=
{ e with locals := e.locals.insert nm (EnvDef.pivarDecl e.varCnt tp),
varCnt := e.varCnt + 1,
ctx := e.ctx.push (VExpr.varRef e.varCnt nm)
}
def insertCheck (e:Environment) (mnm:Option String) (tpc:Check) : Environment :=
match mnm with
| Option.none => e
| Option.some nm =>
{ e with locals := e.locals.insert nm EnvDef.checkDecl,
varCnt := e.varCnt + 1,
ctx := e.ctx.push (VExpr.varRef e.varCnt nm)
}
def insertLambdaVar (e:Environment) (nm:String) (tp:AExpr) : Environment :=
{ e with locals := e.locals.insert nm (EnvDef.lambdavarDecl e.varCnt tp),
varCnt := e.varCnt + 1,
ctx := e.ctx.push (VExpr.varRef e.varCnt nm)
}
def insertLetDef (e:Environment) (nm:String) (v:VExpr) : Environment :=
{ e with locals := e.locals.insert nm (EnvDef.letDecl e.varCnt v),
varCnt := e.varCnt + 1,
ctx := e.ctx.push (VExpr.varRef e.varCnt nm)
}
-- Add code let
def addLet (e:Environment) (nm:String) (d:Code) : Environment :=
{ e with locals := e.locals.insert nm (EnvDef.codelet e.varCnt d), varCnt := e.varCnt + 1 }
-- Add a match patterhn
def addMatchPat (e:Environment) (nm:String) (tp:AExpr) : Environment :=
{ e with locals := e.locals.insert nm (EnvDef.caseVar e.varCnt tp), varCnt := e.varCnt + 1 }
end Environment
def index : String → Parser Nat
| "" => pure 1
| idx =>
let c := idx.toNat;
if 1 ≤ c ∧ c ≤ 32 then
pure c
else
fail ("Illegal index: " ++ idx)
def checkNoTypeArgs (f:Family) : KExpr → Parser Unit
| KExpr.type => pure ()
| KExpr.pi _ _ _ => fail $ "Expected arguments to " ++ f.name
| KExpr.check _ _ _ => fail $ "Expected arguments to " ++ f.name
def checkNoCtorArgs (c:Ctor) : AExpr → Parser Unit
| AExpr.fam _ _ => pure ()
| AExpr.pi _ _ _ => fail $ "Expected arguments to " ++ c.name
| AExpr.check _ _ _ => fail $ "Expected arguments to " ++ c.name
| AExpr.ref _ d => checkNoCtorArgs d
section
open Option
def EqEnv := Array AExpr -- Type for pi variables
partial
def vexprEq : VExpr → VExpr → Except String VExpr
| VExpr.ctorInst xc xa, VExpr.ctorInst yc ya =>
if xc.idx ≠ yc.idx then
Except.error ("Incompatible constructors: " ++ xc.name ++ " " ++ yc.name)
else do
let f (i:Nat) (xa1:VExpr) : Except String VExpr :=
match ya.get? i with
| Option.none => Except.error "Unexpected array length"
| Option.some ya1 => vexprEq xa1 ya1;
za ← xa.mapIdxM f;
pure (VExpr.ctorInst xc za)
| VExpr.checkvarRef xl xnm, VExpr.checkvarRef yl ynm =>
if xl = yl then
pure $ VExpr.checkvarRef xl xnm
else
Except.error $ "Incompatible check variables: " ++ xnm ++ " " ++ ynm
| VExpr.hole, y =>
pure y
| x, VExpr.hole =>
pure x
| VExpr.varRef xl xnm, VExpr.varRef yl ynm =>
if xl = yl then
pure $ VExpr.varRef xl xnm
else
Except.error $ "Incompatible variables: " ++ xnm ++ " " ++ ynm
| x, y =>
Except.error ("Value mismatch -- found: " ++ repr x ++ ", expected: " ++ repr y)
partial
def vexprEqV : VExpr → Array VExpr → VExpr → Except String VExpr
| VExpr.ctorInst xc xa, yctx, VExpr.ctorInst yc ya =>
if xc.idx ≠ yc.idx then
Except.error ("Incompatible constructors: " ++ xc.name ++ " " ++ yc.name)
else do
let f (i:Nat) (xa1:VExpr) : Except String VExpr :=
match ya.get? i with
| Option.none => Except.error "Unexpected array length"
| Option.some ya1 => vexprEqV xa1 yctx ya1;
za ← xa.mapIdxM f;
pure (VExpr.ctorInst xc za)
| VExpr.checkvarRef xl xnm, yctx, VExpr.checkvarRef yl ynm =>
if xl = yl then
pure $ VExpr.checkvarRef xl xnm
else
Except.error $ "Incompatible check variables: " ++ xnm ++ " " ++ ynm
| VExpr.hole, yctx, y =>
pure (y.pisubst yctx)
| x, _, VExpr.hole =>
pure x
| x, yctx, VExpr.varRef yl ynm =>
if h : yl < yctx.size then
vexprEq x (yctx.get ⟨yl, h⟩)
else
Except.error ("Illegal ctx index: (" ++ repr yl ++ ", " ++ ynm ++ ") " ++ repr yctx.size)
--| env, VExpr.varRef xl xnm, yctx, VExpr.varRef yl ynm =>
-- if xl = yl then
-- pure $ VExpr.varRef xl xnm
-- else
-- Except.error $ "Incompatible variables: " ++ xnm ++ " " ++ ynm
| x, yctx, y =>
Except.error $
"Lazy value mismatch -- found: " ++ repr x ++ ", expected: " ++ repr (y.pisubst yctx)
partial
def aexprEqV : AExpr → Array VExpr → AExpr → Except String AExpr
| AExpr.fam xf xa, yctx, AExpr.fam yf ya => do
if xf.idx ≠ yf.idx then
Except.error ("Incompatible families: " ++ xf.name ++ " " ++ yf.name)
else do
let f (i:Nat) (xa1:VExpr) : Except String VExpr :=
match ya.get? i with
| Option.none => Except.error "Unexpected array length"
| Option.some ya1 => vexprEqV xa1 yctx ya1;
za ← xa.mapIdxM f;
pure (AExpr.fam xf za)
| AExpr.ref xnm xd, yctx, AExpr.ref ynm yd => do
if xnm = ynm then
pure (AExpr.ref xnm xd)
else
aexprEqV xd Array.empty yd
| x, yctx, AExpr.ref ynm yd => aexprEqV x Array.empty yd
| AExpr.ref xnm xd, yctx, y => aexprEqV xd yctx y
| x, yctx, y =>
Except.error ("Family mismatch -- found: " ++ repr x ++ ", expected: " ++ repr y)
end
partial
def asPi : Array VExpr → AExpr → Option (Array VExpr × String × AExpr × AExpr)
| _, AExpr.fam _ _ => Option.none
| yctx, AExpr.pi nm a r => Option.some (yctx, nm, a, r)
| _, AExpr.check _ _ _ => Option.none
| yctx, AExpr.ref _ x => asPi Array.empty x
def checkIntLitType (tpctx : Array VExpr) (tp:AExpr) : Parser Unit :=
match aexprEqV (AExpr.fam mpz Array.empty) tpctx tp with
| Except.error e => fail $ "Integer literal must have type mpz: " ++ e
| Except.ok _ => pure ()
inductive ExprCtx
| Fam : ExprCtx
-- This parsed expressions of type `nm type`, `nm (^ .. ..)`, and `(^ .. ..).
| FamCheck : ExprCtx
-- @Value prev r@ produces a value with type @r.pisubst prev@.
| Value : Array VExpr → AExpr → ExprCtx
-- Code with the given value expected.
| codeVal : Family → ExprCtx
-- Any expression
| Any : ExprCtx
-- Current level of expression in tp and type
| TypeArgs (prev:Array VExpr) (tp:KExpr) : ExprCtx
-- `CtorArgs p r` parse a constructor with previous arguments `p`,
-- and remaining type `r`.
| CtorArgs (prev:Array VExpr) (tp:AExpr) : ExprCtx
inductive FamCheckRes
| arg : String → AExpr → FamCheckRes
| check : Option String → Check → FamCheckRes
namespace ExprCtx
@[reducible]
def result : ExprCtx → Type
| Fam => AExpr
| FamCheck => FamCheckRes
| Value _ _ => VExpr
-- Map to value and arguments to family
| codeVal f => CodeVal
| Any => SomeExpr
| TypeArgs _ _ => Array VExpr
| CtorArgs _ _ => Array VExpr × AExpr
end ExprCtx
open ExprCtx
open SomeExpr
partial
def matchFamily (expected:Family) : AExpr → Parser (Array VExpr)
| AExpr.fam f args =>
if f.idx = expected.idx then
pure args
else
fail $ "Did not match expected type " ++ expected.name
| AExpr.pi _ _ _ =>
fail $ "Pi encountered when family expected: " ++ expected.name
| AExpr.check _ _ _ =>
fail $ "Check encountered when family expected: " ++ expected.name
| AExpr.ref _ d => matchFamily d
partial
def expr : ∀(c:ExprCtx) (env:Environment), Parser (ExprCtx.result c)
| TypeArgs prev KExpr.type, env => do
rparen $> prev
| TypeArgs prev (KExpr.pi nm tp r), env => do
v ← expr (Value prev tp) env;
expr (TypeArgs (prev.push v) r) env
| TypeArgs prev (KExpr.check _ _ r), env =>
expr (TypeArgs prev r) env
| CtorArgs prev (AExpr.fam f args), env => do
rparen $> (prev, AExpr.fam f args)
| CtorArgs prev (AExpr.pi _nm tp r), env => do
v ← expr (Value prev tp) env;
expr (CtorArgs (prev.push v) r) env
| CtorArgs prev (AExpr.check _ _ r), env => do
expr (CtorArgs prev r) env
| CtorArgs prev (AExpr.ref _ d), env => do
expr (CtorArgs prev d) env
| Fam, env => do
c ← sexprStart;
match c with
| SExprStart.openparen => do
c ← peek;
match c with
-- Pi variable
| '!' => do
skip;
r ← expr FamCheck env;
match r with
| FamCheckRes.arg nm tp => do
val ← expr Fam (env.insertPiVar nm tp) <* rparen;
pure $ AExpr.pi nm tp val
| FamCheckRes.check mnm chk => do
val ← expr Fam (env.insertCheck mnm chk) <* rparen;
pure $ AExpr.check mnm chk val
| _ => do
sym ← symbol;
match env.find? sym with
| Option.some (EnvDef.famDecl f k) =>
AExpr.fam f <$> expr (TypeArgs Array.empty k) env
| Option.none => fail $ "Unknown type app symbol: " ++ sym
| Option.some _ => fail $ "Expected type: " ++ sym
| SExprStart.symbol sym => do
match env.find? sym with
| Option.none => fail $ "Unknown type single symbol: " ++ sym
| Option.some (EnvDef.famDecl f k) => do
checkNoTypeArgs f k $> AExpr.fam f Array.empty
| Option.some _ => fail $ "Expected type: " ++ sym
| FamCheck, env => do
c ← sexprStart;
match c with
| SExprStart.openparen => do
c ← peek;
if c = '^' then do
skip;
lparen;
pgmName ← symbol;
match env.find? pgmName with
| Option.some (EnvDef.programDecl pgm argTypes resType) => do
let f (a : Symbol × Family) : Parser CodeVal := expr (codeVal a.snd) env;
args ← argTypes.mapM f <* rparen;
res ← expr (codeVal resType) env;
let chk : Check := { program := pgm, args := args, res := res };
rparen $> FamCheckRes.check Option.none chk
| _ => fail $ "Unknown program: " ++ pgmName
else
fail $ "Expected check"
| SExprStart.symbol var => do
c ← sexprStart;
match c with
| SExprStart.openparen => do
c ← peek;
match c with
-- A Pi variable
| '!' => do
skip;
r ← expr FamCheck env;
match r with
| FamCheckRes.arg nm tp => do
val ← expr Fam (env.insertPiVar nm tp) <* rparen;
pure $ FamCheckRes.arg var (AExpr.pi nm tp val)
| FamCheckRes.check mnm chk => do
val ← expr Fam (env.insertCheck mnm chk) <* rparen;
pure $ FamCheckRes.arg var (AExpr.check mnm chk val)
| '^' => do
skip;
lparen;
sym ← symbol;
match env.find? sym with
| Option.some (EnvDef.programDecl pgm argTypes resType) => do
let f (a : Symbol × Family) : Parser CodeVal := expr (codeVal a.snd) env;
args ← argTypes.mapM f <* rparen;
res ← expr (codeVal resType) env;
let chk : Check := { program := pgm, args := args, res := res };
rparen $> FamCheckRes.check (Option.some var) chk
| _ => fail $ "Unknown program: " ++ sym
| _ => do
sym ← symbol;
match env.find? sym with
| Option.none => fail ("Unknown family or check function: " ++ sym)
| Option.some (EnvDef.famDecl f k) =>
(λr => FamCheckRes.arg var (AExpr.fam f r)) <$> expr (TypeArgs Array.empty k) env
| Option.some _ =>
fail $ "Expected type: " ++ sym
| SExprStart.symbol sym =>
match env.find? sym with
| Option.some (EnvDef.famDecl f k) =>
checkNoTypeArgs f k $> FamCheckRes.arg var (AExpr.fam f Array.empty)
| Option.none => fail $ "Unknown family of check constant: " ++ sym
| Option.some _ => fail $ "Expected type: " ++ sym
| Value tpctx tp, env => do
c ← sexprStart;
match c with
| SExprStart.openparen => do
c ← peek;
match c with
-- Pi term
| '!' => fail "Did not expect a type"
-- Type annotation
| ':' => do
skip;
annType ← expr Fam env;
match aexprEqV annType tpctx tp with
| Except.error e => fail e
| Except.ok ztp => expr (Value env.ctx ztp) env <* rparen
-- Let expression
| '@' => do
skip;
nm ← symbol;
da ← expr Any env;
d ← match da with
| embedVal v => pure v
| _ => fail $ "Expected let value: " ++ repr da;
val ← expr (Value tpctx tp) (env.insertLetDef nm d);
rparen $> VExpr.letExpr nm d val
-- Lambda
| '\\' => do
skip;
match asPi tpctx tp with
| Option.none => fail "Lambda encountered when function not expected."
| Option.some (pictx, anm, atp,rtp) => do
nm ← symbol;
let v := VExpr.varRef pictx.size anm;
rhs ← expr (Value (pictx.push v) rtp) (env.insertLambdaVar nm atp);
rparen $> VExpr.lambda nm rhs
| '~' => do
skip;
checkIntLitType tpctx tp;
(λ(n:Nat) => VExpr.intLit (HasNeg.neg (Int.ofNat n))) <$> nat
| _ => do
sym ← symbol;
match env.find? sym with
| Option.none => fail ("Unknown typed function: " ++ sym)
| Option.some (EnvDef.ctorDecl c ctorType) => do
l ← expr (CtorArgs Array.empty ctorType) env;
pure (VExpr.ctorInst c l.fst)
| Option.some d => do
fail (d.type ++ " unsupported as " ++ repr tp ++ " function:" ++ sym)
| SExprStart.symbol sym =>
if sym = "_" then
pure VExpr.hole
else if isNat sym then do
checkIntLitType tpctx tp;
pure $ VExpr.intLit (Int.ofNat sym.toNat)
else
match env.find? sym with
| Option.none => fail ("Unknown typed constant: " ++ sym ++ " " ++ repr tp)
| Option.some (EnvDef.ctorDecl c ctorType) => do
checkNoCtorArgs c ctorType;
match aexprEqV ctorType tpctx tp with
| Except.error e => fail $ "Ctor failed: " ++ e
| Except.ok ztp => pure $ VExpr.ctorInst c Array.empty
| Option.some (EnvDef.checkVarDecl lvl cvarType) => do
match aexprEqV cvarType tpctx tp with
| Except.error e => fail e
| Except.ok ztp => pure $ VExpr.checkvarRef lvl sym
| Option.some (EnvDef.defDecl val) => do
-- FIXME: Check type of definition
match val with
| embedVal x => pure x
| _ => fail $ "Unsupported value definition: " ++ sym
| Option.some (EnvDef.pivarDecl lvl varType) => do
match aexprEqV varType tpctx tp with
| Except.error e => fail $ "Pi var failed: " ++ e ++ "\n"
++ repr varType ++ " " ++ repr tp ++ " " ++ repr tpctx.size
| Except.ok ztp => pure $ VExpr.varRef lvl sym
| Option.some (EnvDef.lambdavarDecl lvl vtp) => do
match aexprEqV vtp tpctx tp with
| Except.error e => fail e
| Except.ok ztp => pure $ VExpr.varRef lvl sym
| Option.some (EnvDef.letDecl lvl vtp) => do
pure $ VExpr.letvarRef lvl sym
| Option.some d =>
fail $ d.type ++ " unsupported as " ++ repr tp ++ " constant: " ++ sym
| Any, env => do
c ← sexprStart;
match c with
| SExprStart.openparen => do
c ← peek;
match c with
-- Pi term
| '!' => do
skip;
r ← expr FamCheck env;
match r with
| FamCheckRes.arg nm tp => do
val ← expr Any (env.insertPiVar nm tp) <* rparen;
match val with
| embedKind k => pure $ embedKind $ KExpr.pi nm tp k
| embedFam d => pure $ embedFam $ AExpr.pi nm tp d
| _ => fail $ "Expected kind or type: " ++ repr val
| FamCheckRes.check mnm chk => do
val ← expr Any (env.insertCheck mnm chk) <* rparen;
match val with
| embedKind k => pure $ embedKind $ KExpr.check mnm chk k
| embedFam d => pure $ embedFam $ AExpr.check mnm chk d
| _ => fail $ "Expected kind or type: " ++ repr val
-- Type annotation
| ':' => do
skip;
annType ← expr Fam env;
embedVal <$> expr (Value env.ctx annType) env <* rparen
-- Let expression
| '@' => do
skip;
nm ← symbol;
da ← expr Any env;
d ← match da with
| embedVal v => pure v
| _ => fail $ "Expected let value: " ++ repr da;
va ← expr Any (env.insertLetDef nm d);
rparen;
match va with
| embedVal v => pure (embedVal (VExpr.letExpr nm d v))
| _ => fail $ "Expected let rhs: " ++ repr va
-- Lambda
| '\\' => do
fail "Lambda can only appear when type is known."
-- Check
| '^' => do
skip;
lparen;
sym ← symbol;
match env.find? sym with
| Option.some (EnvDef.programDecl pgm argTypes resType) => do
let f (a : Symbol × Family) : Parser CodeVal := expr (codeVal a.snd) env;
args ← argTypes.mapM f;
rparen;
res ← expr (codeVal resType) env;
let chk : Check := { program := pgm, args := args, res := res };
rparen $> embedCheck chk
| _ => fail ("Unknown program: " ++ sym)
| '~' => skip *> (λ(n:Nat) => embedVal (VExpr.intLit (HasNeg.neg (Int.ofNat n)))) <$> nat
| _ => do
sym ← symbol;
match env.find? sym with
| Option.none => fail ("Unknown untyped function: " ++ sym)
| Option.some (EnvDef.famDecl f k) => do
(λr => embedFam (AExpr.fam f r)) <$> expr (TypeArgs Array.empty k) env
| Option.some (EnvDef.ctorDecl c ctorType) => do
l ← expr (CtorArgs Array.empty ctorType) env;
pure (embedVal (VExpr.ctorInst c l.fst))
| Option.some d =>
fail $ d.type ++ " unsupported as function: " ++ sym
| SExprStart.symbol sym => do
match sym with
| "type" => pure $ embedKind KExpr.type
| "_" => pure $ embedVal VExpr.hole
| _ => do
match env.find? sym with
| Option.none => fail ("Unknown untyped constant: " ++ sym)
| Option.some (EnvDef.famDecl f k) =>
checkNoTypeArgs f k $> embedFam (AExpr.fam f Array.empty)
| Option.some (EnvDef.ctorDecl c ctorType) => do
checkNoCtorArgs c ctorType;
pure $ embedVal (VExpr.ctorInst c Array.empty)
| Option.some (EnvDef.defDecl val) => do
match val with
| embedFam x => pure $ embedFam $ AExpr.ref sym x
| _ => fail ("Unsupported definition: " ++ sym)
| Option.some (EnvDef.checkVarDecl lvl tp) => do
pure $ embedVal $ VExpr.checkvarRef lvl sym
| Option.some (EnvDef.pivarDecl lvl tp) => do
pure $ embedVal $ VExpr.varRef lvl sym
| Option.some (EnvDef.lambdavarDecl lvl tp) => do
pure $ embedVal $ VExpr.varRef lvl sym
| Option.some d =>
fail $ d.type ++ " unsupported as constant: " ++ sym
| codeVal expected, env => do
c ← sexprStart;
match c with
| SExprStart.openparen => do
c ← peek;
match c with
-- Pi term
| '!' => fail "Unexpected pi term"
-- Type annotation
| ':' => fail "Unexpected type annotation"
-- Let expression
| '@' => fail "Unexpected let expression"
| '\\' => fail "Unexpected lambda expression."
| '^' => fail "Family expected instead of check"
| '~' => fail "Family expected instead of int literal"
| _ => do
sym ← symbol;
match env.find? sym with
| Option.some (EnvDef.programDecl pgm argTypes resType) => do
let f (a : Symbol × Family) : Parser CodeVal := expr (codeVal a.snd) env;
args ← argTypes.mapM f <* rparen;
when (expected.idx ≠ resType.idx) $ fail "Program type mismatch";
pure $ CodeVal.call pgm args
| Option.some d =>
fail $ d.type ++ " unsupported as code function: " ++ sym
| Option.none =>
fail $ "Unknown untyped function: " ++ sym
| SExprStart.symbol sym =>
match sym with
| "type" => fail "type not expected"
| "_" => fail "hole not expected"
| _ =>
match env.find? sym with
| Option.some (EnvDef.ctorDecl c ctorType) => do
args ← matchFamily expected ctorType;
when (args.size > 0) $ fail $ "Expected arguments.";
pure $ CodeVal.expr (VExpr.ctorInst c Array.empty)
| Option.some (EnvDef.pivarDecl lvl tp) => do
_ ← matchFamily expected tp;
pure $ CodeVal.expr (VExpr.varRef lvl sym)
| Option.some d =>
fail $ d.type ++ " unsupported as code constant: " ++ sym
| Option.none => fail $ "Unknown untyped constant: " ++ sym
partial
def patVars : Array (String × AExpr)
→ Environment
→ AExpr
→ Parser (Array (String × AExpr) × Environment × AExpr)
| prev, env, AExpr.fam f args =>
rparen $> (prev, env, AExpr.fam f args)
| prev, env, AExpr.pi nm tp r => do
nm ← symbol;
let v := VExpr.varRef env.varCnt nm;
let env' := env.addMatchPat nm tp;
patVars (prev.push (nm,tp)) env' r
| prev, env, AExpr.check _ _ r => do
patVars prev env r
| prev, env, AExpr.ref _ d => do
patVars prev env d
def patternOrDefault (env:Environment) : Parser (Option (Pat × Environment)) := do
c ← sexprStart;
match c with
| SExprStart.openparen => do
sym ← symbol;
match env.find? sym with
| Option.some (EnvDef.ctorDecl c ctorType) => do
(vars,env', rtp) ← patVars Array.empty env ctorType;
pure (Option.some ({ ctor := c, args := vars }, env'))
| _ => do
fail ("Could not find constructor: " ++ sym)
| SExprStart.symbol "default" =>
pure $ Option.none
| SExprStart.symbol sym => do
match env.find? sym with
| Option.some (EnvDef.ctorDecl c corType) => do
pure $ Option.some ({ ctor := c, args := Array.empty }, env)
| _ => do
fail ("Could not find constructor: " ++ sym)
inductive CodeReq
| anyCode : CodeReq
| ctorArgs : Array Code → Nat → AExpr → CodeReq
namespace CodeReq
def type : CodeReq → Type
| anyCode => Code
| ctorArgs _ _ _ => Array Code × Nat × Family × Array VExpr
end CodeReq
open CodeReq
partial
def matchRest (env:Environment) (e:Code) (m : Environment → Parser Code) : Array (Pat × Code) → Parser Code
| prev => do
c ← peek;
match c with
| '(' => do
skip;
mp ← patternOrDefault env;
match mp with
| Option.some (p,env') => do
v ← m env';
rparen;
matchRest (prev.push (p,v))
| Option.none => do
v ← m env;
rparen;
rparen $> Code.matchStmt e prev (Option.some v)
| ')' => skip $> Code.matchStmt e prev Option.none
| _ => fail "Expected match case"
partial
def code : ∀(ctx:CodeReq), Environment → Parser ctx.type
| ctorArgs prev n (AExpr.fam f args), env => do
rparen $> (prev, n, f, args)
| ctorArgs prev n (AExpr.pi nm tp r ), env => do
v ← code anyCode env;
code (ctorArgs (prev.push v) (n+1) r) env
| ctorArgs prev n (AExpr.check _ _ r), env =>
-- TODO Add some notion of check here
code (ctorArgs prev n r) env
| ctorArgs prev _ (AExpr.ref _ d), env =>
code (ctorArgs prev 0 d) env
| anyCode, env => do
c ← peek;
match c with
| '(' => do
skip;
c ← peek;
match c with
| '~' => skip *> (λ(n:Nat) => Code.codeIntLit (HasNeg.neg (Int.ofNat n))) <$> nat <* rparen
| _ => do
sym ← symbol;
if sym = "ifequal" then do
(Code.ifequal <$> code anyCode env <*> code anyCode env <*> code anyCode env <*> code anyCode env) <* rparen
else if sym = "match" then do
code anyCode env >>= λe => matchRest env e (code anyCode) Array.empty
else if sym = "do" then do
Code.doStmt <$> listRest (code anyCode env)
else if sym = "let" then do
nm ← symbol;
let idx := env.varCnt;
symdef ← code anyCode env;
rest ← code anyCode (env.addLet nm symdef);
rparen $> Code.letStmt nm idx symdef rest
else if sym = "fail" then do
Code.fail <$> expr Fam env <* rparen
else if "markvar".isPrefixOf sym then do
let rest := sym.drop "markvar".length;
Code.markvar <$> index rest <*> code anyCode env <* rparen
else if "ifmarked".isPrefixOf sym then do
let rest := sym.drop "ifmarked".length;
(Code.ifmarked <$> index rest <*> code anyCode env <*> code anyCode env <*> code anyCode env) <* rparen
else if sym = "mp_ifzero" then do
c ← code anyCode env;
t ← code anyCode env;
f ← code anyCode env;
rparen $> Code.mp_ifzero c t f
else if sym = "mp_ifneg" then do
c ← code anyCode env;
t ← code anyCode env;
f ← code anyCode env;
rparen $> Code.mp_ifneg c t f
else do
match env.find? sym with
| Option.none => fail $ "Unknown code function symbol: " ++ sym
| Option.some (EnvDef.ctorDecl c ctorType) => do
⟨l,_,_⟩ ← code (ctorArgs Array.empty 0 ctorType) env;
pure (Code.ctor c l)
| Option.some (EnvDef.programDecl p args res) => do
argValues ← args.mapM (λ⟨nm,f⟩ => code anyCode env);
rparen;
pure (Code.call p argValues)
| Option.some d => fail $ d.type ++ " unsupported as code function: " ++ sym
-- Code.ctor sym <$> listRest (code env)
| _ => do
sym ← symbol;
match env.find? sym with
| Option.none => fail $ "Unknown symbol: " ++ sym
| Option.some (EnvDef.progarg p) => pure $ Code.progarg p
| Option.some (EnvDef.caseVar lvl tp) => pure $ Code.casevar lvl sym
| Option.some (EnvDef.ctorDecl c ctorType) => do
checkNoCtorArgs c ctorType;
pure (Code.ctor c Array.empty)
| Option.some (EnvDef.codelet v _) => do
pure (Code.letvar v sym)
| Option.some d => fail $ d.type ++ " unsupported as code: " ++ sym
--Code.codeSym <$> symbol
partial
def checkValue : Environment → Parser CheckValue
| env => do
s ← get;
c ← peek;
if c == '(' then do
skip;
c ← peek;
match c with
| '%' => do
skip;
nm ← symbol;
tp ← expr Fam env;
r ← checkValue (env.insertCheckVar nm tp);
rparen;
pure (CheckValue.bigLambda nm tp r)
-- Let
| '@' => do
skip;
nm ← symbol;
da ← expr Any env;
d ← match da with
| embedVal v => pure v
| _ => fail $ "Expected let value: " ++ repr da;
x ← checkValue (env.insertLetDef nm d);
rparen $> CheckValue.letExpr nm d x
| _ => do set s; CheckValue.proof <$> expr Any env
else
CheckValue.proof <$> expr Any env
partial
def familyName (env:GlobalEnvironment) : Parser Family := do
sym ← symbol;
match env.find? sym with
| Option.none => fail $ "Unknown symbol: " ++ sym
| Option.some (EnvDef.famDecl f k) => pure f
| Option.some _ => fail $ "Expected family: " ++ sym
partial
def command : GlobalEnvironment → Parser GlobalEnvironment
| genv => do
c ← peek;
if c = '(' then do
skip;
h ← symbol;
match h with
| "declare" => do
nm ← symbol;
let env := Environment.new genv;
e ← expr Any env <* rparen;
match e with
| embedKind k => pure (genv.addFamily nm k true)
| embedFam tp => pure (genv.addCtor nm tp)
| _ => fail ("Expected kind or type: " ++ repr e)
| "define" => do
nm ← symbol;
val ← expr Any (Environment.new genv);
let cmd := Command.define nm val;
rparen;
pure $ (genv.addCommand cmd).insert nm (EnvDef.defDecl val)
| "program" => do
nm ← symbol;
args ← list (parens (Prod.mk <$> symbol <*> familyName genv));
ret ← familyName genv;
let genv' := genv.addProgramDecl nm args ret;
d ← code CodeReq.anyCode (Environment.code genv' args);
rparen;
let cmd := Command.program nm args ret d;
pure $ genv'.addCommand cmd
| "check" => do
cmd ← Command.check <$> checkValue (Environment.new genv);
rparen;
pure (genv.addCommand cmd)
| _ => do
fail ("Unexpected command " ++ h)
-- plf files sometimes contain extra rparens that are ignored
else if c = ')' then do
skip $> genv
else
fail "Expected start of command"
partial
def plf : GlobalEnvironment → Parser GlobalEnvironment
| env => do
b ← hasMore;
if b then
command env >>= plf
else
pure env
def processFile (env:GlobalEnvironment) (path:String) : IO GlobalEnvironment := do
contents ← IO.readTextFile path;
match (plf env).run path contents with
| Except.ok env' =>
pure env'
| Except.error e =>
throw (IO.userError ("LFSC Error: " ++ repr e ++ "\n"))
end lfsc
def main (args:List String) : IO Unit := do
let env1 := lfsc.GlobalEnvironment.init;
env ← args.foldlM lfsc.processFile env1;
env.commands.reverse.forM (λc => IO.Prim.putStr (repr c ++ "\n"))
|
adeab83f33ac0333c0b0de445ecdbd7f35757e9a | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/algebra/support.lean | b28568d01a4ba7b913ea93d5564d7ccae5afc52b | [
"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 | 10,885 | 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 order.conditionally_complete_lattice
import algebra.big_operators.basic
import algebra.group.prod
import algebra.group.pi
import algebra.module.pi
/-!
# Support of a function
In this file we define `function.support f = {x | f x ≠ 0}` and prove its basic properties.
We also define `function.mul_support f = {x | f x ≠ 1}`.
-/
open set
open_locale big_operators
namespace function
variables {α β A B M N P R S G M₀ G₀ : Type*} {ι : Sort*}
section has_one
variables [has_one M] [has_one N] [has_one P]
/-- `support` of a function is the set of points `x` such that `f x ≠ 0`. -/
def support [has_zero A] (f : α → A) : set α := {x | f x ≠ 0}
/-- `mul_support` of a function is the set of points `x` such that `f x ≠ 1`. -/
@[to_additive] def mul_support (f : α → M) : set α := {x | f x ≠ 1}
@[to_additive] lemma nmem_mul_support {f : α → M} {x : α} :
x ∉ mul_support f ↔ f x = 1 :=
not_not
@[to_additive] lemma compl_mul_support {f : α → M} :
(mul_support f)ᶜ = {x | f x = 1} :=
ext $ λ x, nmem_mul_support
@[simp, to_additive] lemma mem_mul_support {f : α → M} {x : α} :
x ∈ mul_support f ↔ f x ≠ 1 :=
iff.rfl
@[simp, to_additive] lemma mul_support_subset_iff {f : α → M} {s : set α} :
mul_support f ⊆ s ↔ ∀ x, f x ≠ 1 → x ∈ s :=
iff.rfl
@[to_additive] lemma mul_support_subset_iff' {f : α → M} {s : set α} :
mul_support f ⊆ s ↔ ∀ x ∉ s, f x = 1 :=
forall_congr $ λ x, not_imp_comm
@[simp, to_additive] lemma mul_support_eq_empty_iff {f : α → M} :
mul_support f = ∅ ↔ f = 1 :=
by { simp_rw [← subset_empty_iff, mul_support_subset_iff', funext_iff], simp }
@[simp, to_additive] lemma mul_support_one' : mul_support (1 : α → M) = ∅ :=
mul_support_eq_empty_iff.2 rfl
@[simp, to_additive] lemma mul_support_one : mul_support (λ x : α, (1 : M)) = ∅ :=
mul_support_one'
@[to_additive] lemma mul_support_const {c : M} (hc : c ≠ 1) :
mul_support (λ x : α, c) = set.univ :=
by { ext x, simp [hc] }
@[to_additive] lemma mul_support_binop_subset (op : M → N → P) (op1 : op 1 1 = 1)
(f : α → M) (g : α → N) :
mul_support (λ x, op (f x) (g x)) ⊆ mul_support f ∪ mul_support g :=
λ x hx, classical.by_cases
(λ hf : f x = 1, or.inr $ λ hg, hx $ by simp only [hf, hg, op1])
or.inl
@[to_additive] lemma mul_support_sup [semilattice_sup M] (f g : α → M) :
mul_support (λ x, f x ⊔ g x) ⊆ mul_support f ∪ mul_support g :=
mul_support_binop_subset (⊔) sup_idem f g
@[to_additive] lemma mul_support_inf [semilattice_inf M] (f g : α → M) :
mul_support (λ x, f x ⊓ g x) ⊆ mul_support f ∪ mul_support g :=
mul_support_binop_subset (⊓) inf_idem f g
@[to_additive] lemma mul_support_max [linear_order M] (f g : α → M) :
mul_support (λ x, max (f x) (g x)) ⊆ mul_support f ∪ mul_support g :=
mul_support_sup f g
@[to_additive] lemma mul_support_min [linear_order M] (f g : α → M) :
mul_support (λ x, min (f x) (g x)) ⊆ mul_support f ∪ mul_support g :=
mul_support_inf f g
@[to_additive] lemma mul_support_supr [conditionally_complete_lattice M] [nonempty ι]
(f : ι → α → M) :
mul_support (λ x, ⨆ i, f i x) ⊆ ⋃ i, mul_support (f i) :=
begin
rw mul_support_subset_iff',
simp only [mem_Union, not_exists, nmem_mul_support],
intros x hx,
simp only [hx, csupr_const]
end
@[to_additive] lemma mul_support_infi [conditionally_complete_lattice M] [nonempty ι]
(f : ι → α → M) :
mul_support (λ x, ⨅ i, f i x) ⊆ ⋃ i, mul_support (f i) :=
@mul_support_supr _ (order_dual M) ι ⟨(1:M)⟩ _ _ f
@[to_additive] lemma mul_support_comp_subset {g : M → N} (hg : g 1 = 1) (f : α → M) :
mul_support (g ∘ f) ⊆ mul_support f :=
λ x, mt $ λ h, by simp only [(∘), *]
@[to_additive] lemma mul_support_subset_comp {g : M → N} (hg : ∀ {x}, g x = 1 → x = 1)
(f : α → M) :
mul_support f ⊆ mul_support (g ∘ f) :=
λ x, mt hg
@[to_additive] lemma mul_support_comp_eq (g : M → N) (hg : ∀ {x}, g x = 1 ↔ x = 1)
(f : α → M) :
mul_support (g ∘ f) = mul_support f :=
set.ext $ λ x, not_congr hg
@[to_additive] lemma mul_support_comp_eq_preimage (g : β → M) (f : α → β) :
mul_support (g ∘ f) = f ⁻¹' mul_support g :=
rfl
@[to_additive support_prod_mk] lemma mul_support_prod_mk (f : α → M) (g : α → N) :
mul_support (λ x, (f x, g x)) = mul_support f ∪ mul_support g :=
set.ext $ λ x, by simp only [mul_support, not_and_distrib, mem_union_eq, mem_set_of_eq,
prod.mk_eq_one, ne.def]
@[to_additive support_prod_mk'] lemma mul_support_prod_mk' (f : α → M × N) :
mul_support f = mul_support (λ x, (f x).1) ∪ mul_support (λ x, (f x).2) :=
by simp only [← mul_support_prod_mk, prod.mk.eta]
@[to_additive] lemma mul_support_along_fiber_subset (f : α × β → M) (a : α) :
mul_support (λ b, f (a, b)) ⊆ (mul_support f).image prod.snd :=
by tidy
@[simp, to_additive] lemma mul_support_along_fiber_finite_of_finite
(f : α × β → M) (a : α) (h : (mul_support f).finite) :
(mul_support (λ b, f (a, b))).finite :=
(h.image prod.snd).subset (mul_support_along_fiber_subset f a)
end has_one
@[to_additive] lemma mul_support_mul [monoid M] (f g : α → M) :
mul_support (λ x, f x * g x) ⊆ mul_support f ∪ mul_support g :=
mul_support_binop_subset (*) (one_mul _) f g
@[simp, to_additive] lemma mul_support_inv [group G] (f : α → G) :
mul_support (λ x, (f x)⁻¹) = mul_support f :=
set.ext $ λ x, not_congr inv_eq_one
@[simp, to_additive] lemma mul_support_inv' [group G] (f : α → G) :
mul_support (f⁻¹) = mul_support f :=
mul_support_inv f
@[simp] lemma mul_support_inv₀ [group_with_zero G₀] (f : α → G₀) :
mul_support (λ x, (f x)⁻¹) = mul_support f :=
set.ext $ λ x, not_congr inv_eq_one₀
@[to_additive] lemma mul_support_mul_inv [group G] (f g : α → G) :
mul_support (λ x, f x * (g x)⁻¹) ⊆ mul_support f ∪ mul_support g :=
mul_support_binop_subset (λ a b, a * b⁻¹) (by simp) f g
@[to_additive support_sub] lemma mul_support_group_div [group G] (f g : α → G) :
mul_support (λ x, f x / g x) ⊆ mul_support f ∪ mul_support g :=
mul_support_binop_subset (/) (by simp only [one_div, one_inv]) f g
lemma mul_support_div [group_with_zero G₀] (f g : α → G₀) :
mul_support (λ x, f x / g x) ⊆ mul_support f ∪ mul_support g :=
mul_support_binop_subset (/) (by simp only [div_one]) f g
@[simp] lemma support_mul [mul_zero_class R] [no_zero_divisors R] (f g : α → R) :
support (λ x, f x * g x) = support f ∩ support g :=
set.ext $ λ x, by simp only [mem_support, mul_ne_zero_iff, mem_inter_eq, not_or_distrib]
lemma support_smul_subset_right [add_monoid A] [monoid B] [distrib_mul_action B A]
(b : B) (f : α → A) :
support (b • f) ⊆ support f :=
λ x hbf hf, hbf $ by rw [pi.smul_apply, hf, smul_zero]
lemma support_smul_subset_left [semiring R] [add_comm_monoid M] [module R M]
(f : α → R) (g : α → M) :
support (f • g) ⊆ support f :=
λ x hfg hf, hfg $ by rw [pi.smul_apply', hf, zero_smul]
lemma support_smul [semiring R] [add_comm_monoid M] [module R M]
[no_zero_smul_divisors R M] (f : α → R) (g : α → M) :
support (f • g) = support f ∩ support g :=
ext $ λ x, smul_ne_zero
@[simp] lemma support_inv [group_with_zero G₀] (f : α → G₀) :
support (λ x, (f x)⁻¹) = support f :=
set.ext $ λ x, not_congr inv_eq_zero
@[simp] lemma support_div [group_with_zero G₀] (f g : α → G₀) :
support (λ x, f x / g x) = support f ∩ support g :=
by simp [div_eq_mul_inv]
@[to_additive] lemma mul_support_prod [comm_monoid M] (s : finset α) (f : α → β → M) :
mul_support (λ x, ∏ i in s, f i x) ⊆ ⋃ i ∈ s, mul_support (f i) :=
begin
rw mul_support_subset_iff',
simp only [mem_Union, not_exists, nmem_mul_support],
exact λ x, finset.prod_eq_one
end
lemma support_prod_subset [comm_monoid_with_zero A] (s : finset α) (f : α → β → A) :
support (λ x, ∏ i in s, f i x) ⊆ ⋂ i ∈ s, support (f i) :=
λ x hx, mem_bInter_iff.2 $ λ i hi H, hx $ finset.prod_eq_zero hi H
lemma support_prod [comm_monoid_with_zero A] [no_zero_divisors A] [nontrivial A]
(s : finset α) (f : α → β → A) :
support (λ x, ∏ i in s, f i x) = ⋂ i ∈ s, support (f i) :=
set.ext $ λ x, by
simp only [support, ne.def, finset.prod_eq_zero_iff, mem_set_of_eq, set.mem_Inter, not_exists]
lemma mul_support_one_add [has_one R] [add_left_cancel_monoid R] (f : α → R) :
mul_support (λ x, 1 + f x) = support f :=
set.ext $ λ x, not_congr add_right_eq_self
lemma mul_support_one_add' [has_one R] [add_left_cancel_monoid R] (f : α → R) :
mul_support (1 + f) = support f :=
mul_support_one_add f
lemma mul_support_add_one [has_one R] [add_right_cancel_monoid R] (f : α → R) :
mul_support (λ x, f x + 1) = support f :=
set.ext $ λ x, not_congr add_left_eq_self
lemma mul_support_add_one' [has_one R] [add_right_cancel_monoid R] (f : α → R) :
mul_support (f + 1) = support f :=
mul_support_add_one f
lemma mul_support_one_sub' [has_one R] [add_group R] (f : α → R) :
mul_support (1 - f) = support f :=
by rw [sub_eq_add_neg, mul_support_one_add', support_neg']
lemma mul_support_one_sub [has_one R] [add_group R] (f : α → R) :
mul_support (λ x, 1 - f x) = support f :=
mul_support_one_sub' f
end function
namespace set
open function
variables {α β M : Type*} [has_one M] {f : α → M}
@[to_additive] lemma image_inter_mul_support_eq {s : set β} {g : β → α} :
(g '' s ∩ mul_support f) = g '' (s ∩ mul_support (f ∘ g)) :=
by rw [mul_support_comp_eq_preimage f g, image_inter_preimage]
end set
namespace pi
variables {A : Type*} {B : Type*} [decidable_eq A] [has_zero B] {a : A} {b : B}
lemma support_single_zero : function.support (pi.single a (0 : B)) = ∅ := by simp
@[simp] lemma support_single_of_ne (h : b ≠ 0) :
function.support (pi.single a b) = {a} :=
begin
ext,
simp only [mem_singleton_iff, ne.def, function.mem_support],
split,
{ contrapose!,
exact λ h', single_eq_of_ne h' b },
{ rintro rfl,
rw single_eq_same,
exact h }
end
lemma support_single [decidable_eq B] :
function.support (pi.single a b) = if b = 0 then ∅ else {a} := by { split_ifs with h; simp [h] }
lemma support_single_subset : function.support (pi.single a b) ⊆ {a} :=
begin
classical,
rw support_single,
split_ifs; simp
end
lemma support_single_disjoint {b' : B} (hb : b ≠ 0) (hb' : b' ≠ 0) {i j : A} :
disjoint (function.support (single i b)) (function.support (single j b')) ↔ i ≠ j :=
by rw [support_single_of_ne hb, support_single_of_ne hb', disjoint_singleton]
end pi
|
49f1e890b677273bc60bc6ae20f6eea5e97518e3 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/measure_theory/function/lp_space.lean | 9b8e9a316546e50ed85eab46f02aacb4a57a21f0 | [
"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 | 109,588 | lean | /-
Copyright (c) 2020 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.indicator_function
import analysis.normed.group.hom
import measure_theory.function.ess_sup
import measure_theory.function.ae_eq_fun
import measure_theory.integral.mean_inequalities
import topology.continuous_function.compact
/-!
# ℒp space and Lp space
This file describes properties of almost everywhere measurable functions with finite seminorm,
denoted by `snorm f p μ` and defined for `p:ℝ≥0∞` as `0` if `p=0`, `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for
`0 < p < ∞` and `ess_sup ∥f∥ μ` for `p=∞`.
The Prop-valued `mem_ℒp f p μ` states that a function `f : α → E` has finite seminorm.
The space `Lp E p μ` is the subtype of elements of `α →ₘ[μ] E` (see ae_eq_fun) such that
`snorm f p μ` is finite. For `1 ≤ p`, `snorm` defines a norm and `Lp` is a complete metric space.
## Main definitions
* `snorm' f p μ` : `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `f : α → F` and `p : ℝ`, where `α` is a measurable
space and `F` is a normed group.
* `snorm_ess_sup f μ` : seminorm in `ℒ∞`, equal to the essential supremum `ess_sup ∥f∥ μ`.
* `snorm f p μ` : for `p : ℝ≥0∞`, seminorm in `ℒp`, equal to `0` for `p=0`, to `snorm' f p μ`
for `0 < p < ∞` and to `snorm_ess_sup f μ` for `p = ∞`.
* `mem_ℒp f p μ` : property that the function `f` is almost everywhere measurable and has finite
p-seminorm for measure `μ` (`snorm f p μ < ∞`)
* `Lp E p μ` : elements of `α →ₘ[μ] E` (see ae_eq_fun) such that `snorm f p μ` is finite. Defined
as an `add_subgroup` of `α →ₘ[μ] E`.
Lipschitz functions vanishing at zero act by composition on `Lp`. We define this action, and prove
that it is continuous. In particular,
* `continuous_linear_map.comp_Lp` defines the action on `Lp` of a continuous linear map.
* `Lp.pos_part` is the positive part of an `Lp` function.
* `Lp.neg_part` is the negative part of an `Lp` function.
When `α` is a topological space equipped with a finite Borel measure, there is a bounded linear map
from the normed space of bounded continuous functions (`α →ᵇ E`) to `Lp E p μ`. We construct this
as `bounded_continuous_function.to_Lp`.
## Notations
* `α →₁[μ] E` : the type `Lp E 1 μ`.
* `α →₂[μ] E` : the type `Lp E 2 μ`.
## Implementation
Since `Lp` is defined as an `add_subgroup`, dot notation does not work. Use `Lp.measurable f` to
say that the coercion of `f` to a genuine function is measurable, instead of the non-working
`f.measurable`.
To prove that two `Lp` elements are equal, it suffices to show that their coercions to functions
coincide almost everywhere (this is registered as an `ext` rule). This can often be done using
`filter_upwards`. For instance, a proof from first principles that `f + (g + h) = (f + g) + h`
could read (in the `Lp` namespace)
```
example (f g h : Lp E p μ) : (f + g) + h = f + (g + h) :=
begin
ext1,
filter_upwards [coe_fn_add (f + g) h, coe_fn_add f g, coe_fn_add f (g + h), coe_fn_add g h],
assume a ha1 ha2 ha3 ha4,
simp only [ha1, ha2, ha3, ha4, add_assoc],
end
```
The lemma `coe_fn_add` states that the coercion of `f + g` coincides almost everywhere with the sum
of the coercions of `f` and `g`. All such lemmas use `coe_fn` in their name, to distinguish the
function coercion from the coercion to almost everywhere defined functions.
-/
noncomputable theory
open topological_space measure_theory filter
open_locale nnreal ennreal big_operators topological_space measure_theory
lemma fact_one_le_one_ennreal : fact ((1 : ℝ≥0∞) ≤ 1) := ⟨le_refl _⟩
lemma fact_one_le_two_ennreal : fact ((1 : ℝ≥0∞) ≤ 2) :=
⟨ennreal.coe_le_coe.2 (show (1 : ℝ≥0) ≤ 2, by norm_num)⟩
lemma fact_one_le_top_ennreal : fact ((1 : ℝ≥0∞) ≤ ∞) := ⟨le_top⟩
local attribute [instance] fact_one_le_one_ennreal fact_one_le_two_ennreal fact_one_le_top_ennreal
variables {α E F G : Type*} {m m0 : measurable_space α} {p : ℝ≥0∞} {q : ℝ} {μ ν : measure α}
[measurable_space E] [normed_group E]
[normed_group F] [normed_group G]
namespace measure_theory
section ℒp
/-!
### ℒp seminorm
We define the ℒp seminorm, denoted by `snorm f p μ`. For real `p`, it is given by an integral
formula (for which we use the notation `snorm' f p μ`), and for `p = ∞` it is the essential
supremum (for which we use the notation `snorm_ess_sup f μ`).
We also define a predicate `mem_ℒp f p μ`, requesting that a function is almost everywhere
measurable and has finite `snorm f p μ`.
This paragraph is devoted to the basic properties of these definitions. It is constructed as
follows: for a given property, we prove it for `snorm'` and `snorm_ess_sup` when it makes sense,
deduce it for `snorm`, and translate it in terms of `mem_ℒp`.
-/
section ℒp_space_definition
/-- `(∫ ∥f a∥^q ∂μ) ^ (1/q)`, which is a seminorm on the space of measurable functions for which
this quantity is finite -/
def snorm' {m : measurable_space α} (f : α → F) (q : ℝ) (μ : measure α) : ℝ≥0∞ :=
(∫⁻ a, (nnnorm (f a))^q ∂μ) ^ (1/q)
/-- seminorm for `ℒ∞`, equal to the essential supremum of `∥f∥`. -/
def snorm_ess_sup {m : measurable_space α} (f : α → F) (μ : measure α) :=
ess_sup (λ x, (nnnorm (f x) : ℝ≥0∞)) μ
/-- `ℒp` seminorm, equal to `0` for `p=0`, to `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `0 < p < ∞` and to
`ess_sup ∥f∥ μ` for `p = ∞`. -/
def snorm {m : measurable_space α} (f : α → F) (p : ℝ≥0∞) (μ : measure α) : ℝ≥0∞ :=
if p = 0 then 0 else (if p = ∞ then snorm_ess_sup f μ else snorm' f (ennreal.to_real p) μ)
lemma snorm_eq_snorm' (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) {f : α → F} :
snorm f p μ = snorm' f (ennreal.to_real p) μ :=
by simp [snorm, hp_ne_zero, hp_ne_top]
lemma snorm_eq_lintegral_rpow_nnnorm (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) {f : α → F} :
snorm f p μ = (∫⁻ x, (nnnorm (f x)) ^ p.to_real ∂μ) ^ (1 / p.to_real) :=
by rw [snorm_eq_snorm' hp_ne_zero hp_ne_top, snorm']
lemma snorm_one_eq_lintegral_nnnorm {f : α → F} : snorm f 1 μ = ∫⁻ x, nnnorm (f x) ∂μ :=
by simp_rw [snorm_eq_lintegral_rpow_nnnorm one_ne_zero ennreal.coe_ne_top, ennreal.one_to_real,
one_div_one, ennreal.rpow_one]
@[simp] lemma snorm_exponent_top {f : α → F} : snorm f ∞ μ = snorm_ess_sup f μ := by simp [snorm]
/-- The property that `f:α→E` is ae_measurable and `(∫ ∥f a∥^p ∂μ)^(1/p)` is finite if `p < ∞`, or
`ess_sup f < ∞` if `p = ∞`. -/
def mem_ℒp {α} {m : measurable_space α} (f : α → E) (p : ℝ≥0∞) (μ : measure α) : Prop :=
ae_measurable f μ ∧ snorm f p μ < ∞
lemma mem_ℒp.ae_measurable {f : α → E} {p : ℝ≥0∞} (h : mem_ℒp f p μ) : ae_measurable f μ := h.1
lemma lintegral_rpow_nnnorm_eq_rpow_snorm' {f : α → F} (hq0_lt : 0 < q) :
∫⁻ a, (nnnorm (f a)) ^ q ∂μ = (snorm' f q μ) ^ q :=
begin
rw [snorm', ←ennreal.rpow_mul, one_div, inv_mul_cancel, ennreal.rpow_one],
exact (ne_of_lt hq0_lt).symm,
end
end ℒp_space_definition
section top
lemma mem_ℒp.snorm_lt_top {f : α → E} (hfp : mem_ℒp f p μ) : snorm f p μ < ∞ := hfp.2
lemma mem_ℒp.snorm_ne_top {f : α → E} (hfp : mem_ℒp f p μ) : snorm f p μ ≠ ∞ := ne_of_lt (hfp.2)
lemma lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top {f : α → F} (hq0_lt : 0 < q)
(hfq : snorm' f q μ < ∞) :
∫⁻ a, (nnnorm (f a)) ^ q ∂μ < ∞ :=
begin
rw lintegral_rpow_nnnorm_eq_rpow_snorm' hq0_lt,
exact ennreal.rpow_lt_top_of_nonneg (le_of_lt hq0_lt) (ne_of_lt hfq),
end
lemma lintegral_rpow_nnnorm_lt_top_of_snorm_lt_top {f : α → F} (hp_ne_zero : p ≠ 0)
(hp_ne_top : p ≠ ∞) (hfp : snorm f p μ < ∞) :
∫⁻ a, (nnnorm (f a)) ^ p.to_real ∂μ < ∞ :=
begin
apply lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top,
{ exact ennreal.to_real_pos_iff.mpr ⟨bot_lt_iff_ne_bot.mpr hp_ne_zero, hp_ne_top⟩ },
{ simpa [snorm_eq_snorm' hp_ne_zero hp_ne_top] using hfp }
end
lemma snorm_lt_top_iff_lintegral_rpow_nnnorm_lt_top {f : α → F} (hp_ne_zero : p ≠ 0)
(hp_ne_top : p ≠ ∞) :
snorm f p μ < ∞ ↔ ∫⁻ a, (nnnorm (f a)) ^ p.to_real ∂μ < ∞ :=
⟨lintegral_rpow_nnnorm_lt_top_of_snorm_lt_top hp_ne_zero hp_ne_top,
begin
intros h,
have hp' := ennreal.to_real_pos_iff.mpr ⟨bot_lt_iff_ne_bot.mpr hp_ne_zero, hp_ne_top⟩,
have : 0 < 1 / p.to_real := div_pos zero_lt_one hp',
simpa [snorm_eq_lintegral_rpow_nnnorm hp_ne_zero hp_ne_top] using
ennreal.rpow_lt_top_of_nonneg (le_of_lt this) (ne_of_lt h)
end⟩
end top
section zero
@[simp] lemma snorm'_exponent_zero {f : α → F} : snorm' f 0 μ = 1 :=
by rw [snorm', div_zero, ennreal.rpow_zero]
@[simp] lemma snorm_exponent_zero {f : α → F} : snorm f 0 μ = 0 :=
by simp [snorm]
lemma mem_ℒp_zero_iff_ae_measurable {f : α → E} : mem_ℒp f 0 μ ↔ ae_measurable f μ :=
by simp [mem_ℒp, snorm_exponent_zero]
@[simp] lemma snorm'_zero (hp0_lt : 0 < q) : snorm' (0 : α → F) q μ = 0 :=
by simp [snorm', hp0_lt]
@[simp] lemma snorm'_zero' (hq0_ne : q ≠ 0) (hμ : μ ≠ 0) : snorm' (0 : α → F) q μ = 0 :=
begin
cases le_or_lt 0 q with hq0 hq_neg,
{ exact snorm'_zero (lt_of_le_of_ne hq0 hq0_ne.symm), },
{ simp [snorm', ennreal.rpow_eq_zero_iff, hμ, hq_neg], },
end
@[simp] lemma snorm_ess_sup_zero : snorm_ess_sup (0 : α → F) μ = 0 :=
begin
simp_rw [snorm_ess_sup, pi.zero_apply, nnnorm_zero, ennreal.coe_zero, ←ennreal.bot_eq_zero],
exact ess_sup_const_bot,
end
@[simp] lemma snorm_zero : snorm (0 : α → F) p μ = 0 :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
by_cases h_top : p = ∞,
{ simp only [h_top, snorm_exponent_top, snorm_ess_sup_zero], },
rw ←ne.def at h0,
simp [snorm_eq_snorm' h0 h_top,
ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩],
end
@[simp] lemma snorm_zero' : snorm (λ x : α, (0 : F)) p μ = 0 :=
by convert snorm_zero
lemma zero_mem_ℒp : mem_ℒp (0 : α → E) p μ :=
⟨measurable_zero.ae_measurable, by { rw snorm_zero, exact ennreal.coe_lt_top, } ⟩
lemma zero_mem_ℒp' : mem_ℒp (λ x : α, (0 : E)) p μ :=
by convert zero_mem_ℒp
variables [measurable_space α]
lemma snorm'_measure_zero_of_pos {f : α → F} (hq_pos : 0 < q) :
snorm' f q (0 : measure α) = 0 :=
by simp [snorm', hq_pos]
lemma snorm'_measure_zero_of_exponent_zero {f : α → F} : snorm' f 0 (0 : measure α) = 1 :=
by simp [snorm']
lemma snorm'_measure_zero_of_neg {f : α → F} (hq_neg : q < 0) : snorm' f q (0 : measure α) = ∞ :=
by simp [snorm', hq_neg]
@[simp] lemma snorm_ess_sup_measure_zero {f : α → F} : snorm_ess_sup f (0 : measure α) = 0 :=
by simp [snorm_ess_sup]
@[simp] lemma snorm_measure_zero {f : α → F} : snorm f p (0 : measure α) = 0 :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
by_cases h_top : p = ∞,
{ simp [h_top], },
rw ←ne.def at h0,
simp [snorm_eq_snorm' h0 h_top, snorm',
ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩],
end
end zero
section const
lemma snorm'_const (c : F) (hq_pos : 0 < q) :
snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/q) :=
begin
rw [snorm', lintegral_const, ennreal.mul_rpow_of_nonneg _ _ (by simp [hq_pos.le] : 0 ≤ 1 / q)],
congr,
rw ←ennreal.rpow_mul,
suffices hq_cancel : q * (1/q) = 1, by rw [hq_cancel, ennreal.rpow_one],
rw [one_div, mul_inv_cancel (ne_of_lt hq_pos).symm],
end
lemma snorm'_const' [is_finite_measure μ] (c : F) (hc_ne_zero : c ≠ 0) (hq_ne_zero : q ≠ 0) :
snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/q) :=
begin
rw [snorm', lintegral_const, ennreal.mul_rpow_of_ne_top _ (measure_ne_top μ set.univ)],
{ congr,
rw ←ennreal.rpow_mul,
suffices hp_cancel : q * (1/q) = 1, by rw [hp_cancel, ennreal.rpow_one],
rw [one_div, mul_inv_cancel hq_ne_zero], },
{ rw [ne.def, ennreal.rpow_eq_top_iff, auto.not_or_eq, auto.not_and_eq, auto.not_and_eq],
split,
{ left,
rwa [ennreal.coe_eq_zero, nnnorm_eq_zero], },
{ exact or.inl ennreal.coe_ne_top, }, },
end
lemma snorm_ess_sup_const (c : F) (hμ : μ ≠ 0) :
snorm_ess_sup (λ x : α, c) μ = (nnnorm c : ℝ≥0∞) :=
by rw [snorm_ess_sup, ess_sup_const _ hμ]
lemma snorm'_const_of_is_probability_measure (c : F) (hq_pos : 0 < q) [is_probability_measure μ] :
snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) :=
by simp [snorm'_const c hq_pos, measure_univ]
lemma snorm_const (c : F) (h0 : p ≠ 0) (hμ : μ ≠ 0) :
snorm (λ x : α , c) p μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/(ennreal.to_real p)) :=
begin
by_cases h_top : p = ∞,
{ simp [h_top, snorm_ess_sup_const c hμ], },
simp [snorm_eq_snorm' h0 h_top, snorm'_const,
ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩],
end
lemma snorm_const' (c : F) (h0 : p ≠ 0) (h_top: p ≠ ∞) :
snorm (λ x : α , c) p μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/(ennreal.to_real p)) :=
begin
simp [snorm_eq_snorm' h0 h_top, snorm'_const,
ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩],
end
lemma snorm_const_lt_top_iff {p : ℝ≥0∞} {c : F} (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) :
snorm (λ x : α, c) p μ < ∞ ↔ c = 0 ∨ μ set.univ < ∞ :=
begin
have hp : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨hp_ne_zero.bot_lt, hp_ne_top⟩,
by_cases hμ : μ = 0,
{ simp only [hμ, measure.coe_zero, pi.zero_apply, or_true, with_top.zero_lt_top,
snorm_measure_zero], },
by_cases hc : c = 0,
{ simp only [hc, true_or, eq_self_iff_true, with_top.zero_lt_top, snorm_zero'], },
rw snorm_const' c hp_ne_zero hp_ne_top,
by_cases hμ_top : μ set.univ = ∞,
{ simp [hc, hμ_top, hp], },
rw ennreal.mul_lt_top_iff,
simp only [true_and, one_div, ennreal.rpow_eq_zero_iff, hμ, false_or, or_false,
ennreal.coe_lt_top, nnnorm_eq_zero, ennreal.coe_eq_zero,
measure_theory.measure.measure_univ_eq_zero, hp, inv_lt_zero, hc, and_false, false_and,
_root_.inv_pos, or_self, hμ_top, ne.lt_top hμ_top, iff_true],
exact ennreal.rpow_lt_top_of_nonneg (inv_nonneg.mpr hp.le) hμ_top,
end
lemma mem_ℒp_const (c : E) [is_finite_measure μ] : mem_ℒp (λ a:α, c) p μ :=
begin
refine ⟨measurable_const.ae_measurable, _⟩,
by_cases h0 : p = 0,
{ simp [h0], },
by_cases hμ : μ = 0,
{ simp [hμ], },
rw snorm_const c h0 hμ,
refine ennreal.mul_lt_top ennreal.coe_ne_top _,
refine (ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ)).ne,
simp,
end
lemma mem_ℒp_const_iff {p : ℝ≥0∞} {c : E} (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) :
mem_ℒp (λ x : α, c) p μ ↔ c = 0 ∨ μ set.univ < ∞ :=
begin
rw ← snorm_const_lt_top_iff hp_ne_zero hp_ne_top,
exact ⟨λ h, h.2, λ h, ⟨ae_measurable_const, h⟩⟩,
end
end const
lemma snorm'_mono_ae {f : α → F} {g : α → G} (hq : 0 ≤ q) (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) :
snorm' f q μ ≤ snorm' g q μ :=
begin
rw [snorm'],
refine ennreal.rpow_le_rpow _ (one_div_nonneg.2 hq),
refine lintegral_mono_ae (h.mono $ λ x hx, _),
exact ennreal.rpow_le_rpow (ennreal.coe_le_coe.2 hx) hq
end
lemma snorm'_congr_norm_ae {f g : α → F} (hfg : ∀ᵐ x ∂μ, ∥f x∥ = ∥g x∥) :
snorm' f q μ = snorm' g q μ :=
begin
have : (λ x, (nnnorm (f x) ^ q : ℝ≥0∞)) =ᵐ[μ] (λ x, nnnorm (g x) ^ q),
from hfg.mono (λ x hx, by { simp only [← coe_nnnorm, nnreal.coe_eq] at hx, simp [hx] }),
simp only [snorm', lintegral_congr_ae this]
end
lemma snorm'_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm' f q μ = snorm' g q μ :=
snorm'_congr_norm_ae (hfg.fun_comp _)
lemma snorm_ess_sup_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) :
snorm_ess_sup f μ = snorm_ess_sup g μ :=
ess_sup_congr_ae (hfg.fun_comp (coe ∘ nnnorm))
lemma snorm_mono_ae {f : α → F} {g : α → G} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) :
snorm f p μ ≤ snorm g p μ :=
begin
simp only [snorm],
split_ifs,
{ exact le_rfl },
{ refine ess_sup_mono_ae (h.mono $ λ x hx, _),
exact_mod_cast hx },
{ exact snorm'_mono_ae ennreal.to_real_nonneg h }
end
lemma snorm_mono_ae_real {f : α → F} {g : α → ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ g x) :
snorm f p μ ≤ snorm g p μ :=
snorm_mono_ae $ h.mono (λ x hx, hx.trans ((le_abs_self _).trans (real.norm_eq_abs _).symm.le))
lemma snorm_mono {f : α → F} {g : α → G} (h : ∀ x, ∥f x∥ ≤ ∥g x∥) :
snorm f p μ ≤ snorm g p μ :=
snorm_mono_ae (eventually_of_forall (λ x, h x))
lemma snorm_mono_real {f : α → F} {g : α → ℝ} (h : ∀ x, ∥f x∥ ≤ g x) :
snorm f p μ ≤ snorm g p μ :=
snorm_mono_ae_real (eventually_of_forall (λ x, h x))
lemma snorm_ess_sup_le_of_ae_bound {f : α → F} {C : ℝ} (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) :
snorm_ess_sup f μ ≤ ennreal.of_real C:=
begin
simp_rw [snorm_ess_sup, ← of_real_norm_eq_coe_nnnorm],
refine ess_sup_le_of_ae_le (ennreal.of_real C) (hfC.mono (λ x hx, _)),
exact ennreal.of_real_le_of_real hx,
end
lemma snorm_ess_sup_lt_top_of_ae_bound {f : α → F} {C : ℝ} (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) :
snorm_ess_sup f μ < ∞ :=
(snorm_ess_sup_le_of_ae_bound hfC).trans_lt ennreal.of_real_lt_top
lemma snorm_le_of_ae_bound {f : α → F} {C : ℝ} (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) :
snorm f p μ ≤ ((μ set.univ) ^ p.to_real⁻¹) * (ennreal.of_real C) :=
begin
by_cases hμ : μ = 0,
{ simp [hμ] },
haveI : μ.ae.ne_bot := ae_ne_bot.mpr hμ,
by_cases hp : p = 0,
{ simp [hp] },
have hC : 0 ≤ C, from le_trans (norm_nonneg _) hfC.exists.some_spec,
have hC' : ∥C∥ = C := by rw [real.norm_eq_abs, abs_eq_self.mpr hC],
have : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥(λ _, C) x∥, from hfC.mono (λ x hx, hx.trans (le_of_eq hC'.symm)),
convert snorm_mono_ae this,
rw [snorm_const _ hp hμ, mul_comm, ← of_real_norm_eq_coe_nnnorm, hC', one_div]
end
lemma snorm_congr_norm_ae {f : α → F} {g : α → G} (hfg : ∀ᵐ x ∂μ, ∥f x∥ = ∥g x∥) :
snorm f p μ = snorm g p μ :=
le_antisymm (snorm_mono_ae $ eventually_eq.le hfg)
(snorm_mono_ae $ (eventually_eq.symm hfg).le)
@[simp] lemma snorm'_norm {f : α → F} : snorm' (λ a, ∥f a∥) q μ = snorm' f q μ :=
by simp [snorm']
@[simp] lemma snorm_norm (f : α → F) : snorm (λ x, ∥f x∥) p μ = snorm f p μ :=
snorm_congr_norm_ae $ eventually_of_forall $ λ x, norm_norm _
lemma snorm'_norm_rpow (f : α → F) (p q : ℝ) (hq_pos : 0 < q) :
snorm' (λ x, ∥f x∥ ^ q) p μ = (snorm' f (p * q) μ) ^ q :=
begin
simp_rw snorm',
rw [← ennreal.rpow_mul, ←one_div_mul_one_div],
simp_rw one_div,
rw [mul_assoc, inv_mul_cancel hq_pos.ne.symm, mul_one],
congr,
ext1 x,
simp_rw ← of_real_norm_eq_coe_nnnorm,
rw [real.norm_eq_abs, abs_eq_self.mpr (real.rpow_nonneg_of_nonneg (norm_nonneg _) _),
mul_comm, ← ennreal.of_real_rpow_of_nonneg (norm_nonneg _) hq_pos.le, ennreal.rpow_mul],
end
lemma snorm_norm_rpow (f : α → F) (hq_pos : 0 < q) :
snorm (λ x, ∥f x∥ ^ q) p μ = (snorm f (p * ennreal.of_real q) μ) ^ q :=
begin
by_cases h0 : p = 0,
{ simp [h0, ennreal.zero_rpow_of_pos hq_pos], },
by_cases hp_top : p = ∞,
{ simp only [hp_top, snorm_exponent_top, ennreal.top_mul, hq_pos.not_le, ennreal.of_real_eq_zero,
if_false, snorm_exponent_top, snorm_ess_sup],
have h_rpow : ess_sup (λ (x : α), (nnnorm (∥f x∥ ^ q) : ℝ≥0∞)) μ
= ess_sup (λ (x : α), (↑(nnnorm (f x))) ^ q) μ,
{ congr,
ext1 x,
nth_rewrite 1 ← nnnorm_norm,
rw [ennreal.coe_rpow_of_nonneg _ hq_pos.le, ennreal.coe_eq_coe],
ext,
push_cast,
rw real.norm_rpow_of_nonneg (norm_nonneg _), },
rw h_rpow,
have h_rpow_mono := ennreal.rpow_left_strict_mono_of_pos hq_pos,
have h_rpow_surj := (ennreal.rpow_left_bijective hq_pos.ne.symm).2,
let iso := h_rpow_mono.order_iso_of_surjective _ h_rpow_surj,
exact (iso.ess_sup_apply (λ x, ((nnnorm (f x)) : ℝ≥0∞)) μ).symm, },
rw [snorm_eq_snorm' h0 hp_top, snorm_eq_snorm' _ _],
swap, { refine mul_ne_zero h0 _, rwa [ne.def, ennreal.of_real_eq_zero, not_le], },
swap, { exact ennreal.mul_ne_top hp_top ennreal.of_real_ne_top, },
rw [ennreal.to_real_mul, ennreal.to_real_of_real hq_pos.le],
exact snorm'_norm_rpow f p.to_real q hq_pos,
end
lemma snorm_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm f p μ = snorm g p μ :=
snorm_congr_norm_ae $ hfg.mono (λ x hx, hx ▸ rfl)
lemma mem_ℒp_congr_ae {f g : α → E} (hfg : f =ᵐ[μ] g) : mem_ℒp f p μ ↔ mem_ℒp g p μ :=
by simp only [mem_ℒp, snorm_congr_ae hfg, ae_measurable_congr hfg]
lemma mem_ℒp.ae_eq {f g : α → E} (hfg : f =ᵐ[μ] g) (hf_Lp : mem_ℒp f p μ) : mem_ℒp g p μ :=
(mem_ℒp_congr_ae hfg).1 hf_Lp
lemma mem_ℒp.of_le [measurable_space F] {f : α → E} {g : α → F}
(hg : mem_ℒp g p μ) (hf : ae_measurable f μ) (hfg : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : mem_ℒp f p μ :=
⟨hf, (snorm_mono_ae hfg).trans_lt hg.snorm_lt_top⟩
alias mem_ℒp.of_le ← measure_theory.mem_ℒp.mono
lemma mem_ℒp.mono' {f : α → E} {g : α → ℝ} (hg : mem_ℒp g p μ)
(hf : ae_measurable f μ) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ g a) : mem_ℒp f p μ :=
hg.mono hf $ h.mono $ λ x hx, le_trans hx (le_abs_self _)
lemma mem_ℒp.congr_norm [measurable_space F] {f : α → E} {g : α → F} (hf : mem_ℒp f p μ)
(hg : ae_measurable g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) :
mem_ℒp g p μ :=
hf.mono hg $ eventually_eq.le $ eventually_eq.symm h
lemma mem_ℒp_congr_norm [measurable_space F] {f : α → E} {g : α → F}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) :
mem_ℒp f p μ ↔ mem_ℒp g p μ :=
⟨λ h2f, h2f.congr_norm hg h, λ h2g, h2g.congr_norm hf $ eventually_eq.symm h⟩
lemma mem_ℒp_top_of_bound {f : α → E} (hf : ae_measurable f μ) (C : ℝ)
(hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) :
mem_ℒp f ∞ μ :=
⟨hf, by { rw snorm_exponent_top, exact snorm_ess_sup_lt_top_of_ae_bound hfC, }⟩
lemma mem_ℒp.of_bound [is_finite_measure μ] {f : α → E} (hf : ae_measurable f μ)
(C : ℝ) (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) :
mem_ℒp f p μ :=
(mem_ℒp_const C).of_le hf (hfC.mono (λ x hx, le_trans hx (le_abs_self _)))
@[mono] lemma snorm'_mono_measure (f : α → F) (hμν : ν ≤ μ) (hq : 0 ≤ q) :
snorm' f q ν ≤ snorm' f q μ :=
begin
simp_rw snorm',
suffices h_integral_mono : (∫⁻ a, (nnnorm (f a) : ℝ≥0∞) ^ q ∂ν) ≤ ∫⁻ a, (nnnorm (f a)) ^ q ∂μ,
from ennreal.rpow_le_rpow h_integral_mono (by simp [hq]),
exact lintegral_mono' hμν le_rfl,
end
@[mono] lemma snorm_ess_sup_mono_measure (f : α → F) (hμν : ν ≪ μ) :
snorm_ess_sup f ν ≤ snorm_ess_sup f μ :=
by { simp_rw snorm_ess_sup, exact ess_sup_mono_measure hμν, }
@[mono] lemma snorm_mono_measure (f : α → F) (hμν : ν ≤ μ) :
snorm f p ν ≤ snorm f p μ :=
begin
by_cases hp0 : p = 0,
{ simp [hp0], },
by_cases hp_top : p = ∞,
{ simp [hp_top, snorm_ess_sup_mono_measure f (measure.absolutely_continuous_of_le hμν)], },
simp_rw snorm_eq_snorm' hp0 hp_top,
exact snorm'_mono_measure f hμν ennreal.to_real_nonneg,
end
lemma mem_ℒp.mono_measure {f : α → E} (hμν : ν ≤ μ) (hf : mem_ℒp f p μ) :
mem_ℒp f p ν :=
⟨hf.1.mono_measure hμν, (snorm_mono_measure f hμν).trans_lt hf.2⟩
lemma mem_ℒp.restrict (s : set α) {f : α → E} (hf : mem_ℒp f p μ) :
mem_ℒp f p (μ.restrict s) :=
hf.mono_measure measure.restrict_le_self
lemma snorm'_smul_measure {p : ℝ} (hp : 0 ≤ p) {f : α → F} (c : ℝ≥0∞) :
snorm' f p (c • μ) = c ^ (1 / p) * snorm' f p μ :=
by { rw [snorm', lintegral_smul_measure, ennreal.mul_rpow_of_nonneg, snorm'], simp [hp], }
lemma snorm_ess_sup_smul_measure {f : α → F} {c : ℝ≥0∞} (hc : c ≠ 0) :
snorm_ess_sup f (c • μ) = snorm_ess_sup f μ :=
by { simp_rw [snorm_ess_sup], exact ess_sup_smul_measure hc, }
/-- Use `snorm_smul_measure_of_ne_top` instead. -/
private lemma snorm_smul_measure_of_ne_zero_of_ne_top {p : ℝ≥0∞} (hp_ne_zero : p ≠ 0)
(hp_ne_top : p ≠ ∞) {f : α → F} (c : ℝ≥0∞) :
snorm f p (c • μ) = c ^ (1 / p).to_real • snorm f p μ :=
begin
simp_rw snorm_eq_snorm' hp_ne_zero hp_ne_top,
rw snorm'_smul_measure ennreal.to_real_nonneg,
congr,
simp_rw one_div,
rw ennreal.to_real_inv,
end
lemma snorm_smul_measure_of_ne_zero {p : ℝ≥0∞} {f : α → F} {c : ℝ≥0∞} (hc : c ≠ 0) :
snorm f p (c • μ) = c ^ (1 / p).to_real • snorm f p μ :=
begin
by_cases hp0 : p = 0,
{ simp [hp0], },
by_cases hp_top : p = ∞,
{ simp [hp_top, snorm_ess_sup_smul_measure hc], },
exact snorm_smul_measure_of_ne_zero_of_ne_top hp0 hp_top c,
end
lemma snorm_smul_measure_of_ne_top {p : ℝ≥0∞} (hp_ne_top : p ≠ ∞) {f : α → F} (c : ℝ≥0∞) :
snorm f p (c • μ) = c ^ (1 / p).to_real • snorm f p μ :=
begin
by_cases hp0 : p = 0,
{ simp [hp0], },
{ exact snorm_smul_measure_of_ne_zero_of_ne_top hp0 hp_ne_top c, },
end
lemma snorm_one_smul_measure {f : α → F} (c : ℝ≥0∞) :
snorm f 1 (c • μ) = c * snorm f 1 μ :=
by { rw @snorm_smul_measure_of_ne_top _ _ _ μ _ 1 (@ennreal.coe_ne_top 1) f c, simp, }
section opens_measurable_space
variable [opens_measurable_space E]
lemma mem_ℒp.norm {f : α → E} (h : mem_ℒp f p μ) : mem_ℒp (λ x, ∥f x∥) p μ :=
h.of_le h.ae_measurable.norm (eventually_of_forall (λ x, by simp))
lemma mem_ℒp_norm_iff {f : α → E} (hf : ae_measurable f μ) :
mem_ℒp (λ x, ∥f x∥) p μ ↔ mem_ℒp f p μ :=
⟨λ h, ⟨hf, by { rw ← snorm_norm, exact h.2, }⟩, λ h, h.norm⟩
lemma snorm'_eq_zero_of_ae_zero {f : α → F} (hq0_lt : 0 < q) (hf_zero : f =ᵐ[μ] 0) :
snorm' f q μ = 0 :=
by rw [snorm'_congr_ae hf_zero, snorm'_zero hq0_lt]
lemma snorm'_eq_zero_of_ae_zero' (hq0_ne : q ≠ 0) (hμ : μ ≠ 0) {f : α → F} (hf_zero : f =ᵐ[μ] 0) :
snorm' f q μ = 0 :=
by rw [snorm'_congr_ae hf_zero, snorm'_zero' hq0_ne hμ]
lemma ae_eq_zero_of_snorm'_eq_zero {f : α → E} (hq0 : 0 ≤ q) (hf : ae_measurable f μ)
(h : snorm' f q μ = 0) : f =ᵐ[μ] 0 :=
begin
rw [snorm', ennreal.rpow_eq_zero_iff] at h,
cases h,
{ rw lintegral_eq_zero_iff' (hf.ennnorm.pow_const q) at h,
refine h.left.mono (λ x hx, _),
rw [pi.zero_apply, ennreal.rpow_eq_zero_iff] at hx,
cases hx,
{ cases hx with hx _,
rwa [←ennreal.coe_zero, ennreal.coe_eq_coe, nnnorm_eq_zero] at hx, },
{ exact absurd hx.left ennreal.coe_ne_top, }, },
{ exfalso,
rw [one_div, inv_lt_zero] at h,
exact hq0.not_lt h.right },
end
lemma snorm'_eq_zero_iff (hq0_lt : 0 < q) {f : α → E} (hf : ae_measurable f μ) :
snorm' f q μ = 0 ↔ f =ᵐ[μ] 0 :=
⟨ae_eq_zero_of_snorm'_eq_zero (le_of_lt hq0_lt) hf, snorm'_eq_zero_of_ae_zero hq0_lt⟩
lemma coe_nnnorm_ae_le_snorm_ess_sup {m : measurable_space α} (f : α → F) (μ : measure α) :
∀ᵐ x ∂μ, (nnnorm (f x) : ℝ≥0∞) ≤ snorm_ess_sup f μ :=
ennreal.ae_le_ess_sup (λ x, (nnnorm (f x) : ℝ≥0∞))
@[simp] lemma snorm_ess_sup_eq_zero_iff {f : α → F} : snorm_ess_sup f μ = 0 ↔ f =ᵐ[μ] 0 :=
by simp [eventually_eq, snorm_ess_sup]
lemma snorm_eq_zero_iff {f : α → E} (hf : ae_measurable f μ) (h0 : p ≠ 0) :
snorm f p μ = 0 ↔ f =ᵐ[μ] 0 :=
begin
by_cases h_top : p = ∞,
{ rw [h_top, snorm_exponent_top, snorm_ess_sup_eq_zero_iff], },
rw snorm_eq_snorm' h0 h_top,
exact snorm'_eq_zero_iff
(ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩) hf,
end
lemma snorm'_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hq1 : 1 ≤ q) :
snorm' (f + g) q μ ≤ snorm' f q μ + snorm' g q μ :=
calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ q ∂μ) ^ (1 / q)
≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ℝ≥0∞))
+ (λ a, (nnnorm (g a) : ℝ≥0∞))) a) ^ q ∂μ) ^ (1 / q) :
begin
refine ennreal.rpow_le_rpow _ (by simp [le_trans zero_le_one hq1] : 0 ≤ 1 / q),
refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ (le_trans zero_le_one hq1)),
simp [←ennreal.coe_add, nnnorm_add_le],
end
... ≤ snorm' f q μ + snorm' g q μ :
ennreal.lintegral_Lp_add_le hf.ennnorm hg.ennnorm hq1
lemma snorm_ess_sup_add_le {f g : α → F} :
snorm_ess_sup (f + g) μ ≤ snorm_ess_sup f μ + snorm_ess_sup g μ :=
begin
refine le_trans (ess_sup_mono_ae (eventually_of_forall (λ x, _)))
(ennreal.ess_sup_add_le _ _),
simp_rw [pi.add_apply, ←ennreal.coe_add, ennreal.coe_le_coe],
exact nnnorm_add_le _ _,
end
lemma snorm_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hp1 : 1 ≤ p) :
snorm (f + g) p μ ≤ snorm f p μ + snorm g p μ :=
begin
by_cases hp0 : p = 0,
{ simp [hp0], },
by_cases hp_top : p = ∞,
{ simp [hp_top, snorm_ess_sup_add_le], },
have hp1_real : 1 ≤ p.to_real,
by rwa [← ennreal.one_to_real, ennreal.to_real_le_to_real ennreal.one_ne_top hp_top],
repeat { rw snorm_eq_snorm' hp0 hp_top, },
exact snorm'_add_le hf hg hp1_real,
end
lemma snorm_sub_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hp1 : 1 ≤ p) :
snorm (f - g) p μ ≤ snorm f p μ + snorm g p μ :=
calc snorm (f - g) p μ = snorm (f + - g) p μ : by rw sub_eq_add_neg
-- We cannot use snorm_add_le on f and (-g) because we don't have `ae_measurable (-g) μ`, since
-- we don't suppose `[borel_space E]`.
... = snorm (λ x, ∥f x + - g x∥) p μ : (snorm_norm (f + - g)).symm
... ≤ snorm (λ x, ∥f x∥ + ∥- g x∥) p μ : by
{ refine snorm_mono_real (λ x, _), rw norm_norm, exact norm_add_le _ _, }
... = snorm (λ x, ∥f x∥ + ∥g x∥) p μ : by simp_rw norm_neg
... ≤ snorm (λ x, ∥f x∥) p μ + snorm (λ x, ∥g x∥) p μ : snorm_add_le hf.norm hg.norm hp1
... = snorm f p μ + snorm g p μ : by rw [← snorm_norm f, ← snorm_norm g]
lemma snorm_add_lt_top_of_one_le {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ)
(hq1 : 1 ≤ p) : snorm (f + g) p μ < ∞ :=
lt_of_le_of_lt (snorm_add_le hf.1 hg.1 hq1) (ennreal.add_lt_top.mpr ⟨hf.2, hg.2⟩)
lemma snorm'_add_lt_top_of_le_one {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ)
(hf_snorm : snorm' f q μ < ∞) (hg_snorm : snorm' g q μ < ∞) (hq_pos : 0 < q) (hq1 : q ≤ 1) :
snorm' (f + g) q μ < ∞ :=
calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ q ∂μ) ^ (1 / q)
≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ℝ≥0∞))
+ (λ a, (nnnorm (g a) : ℝ≥0∞))) a) ^ q ∂μ) ^ (1 / q) :
begin
refine ennreal.rpow_le_rpow _ (by simp [hq_pos.le] : 0 ≤ 1 / q),
refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ hq_pos.le),
simp [←ennreal.coe_add, nnnorm_add_le],
end
... ≤ (∫⁻ a, (nnnorm (f a) : ℝ≥0∞) ^ q + (nnnorm (g a) : ℝ≥0∞) ^ q ∂μ) ^ (1 / q) :
begin
refine ennreal.rpow_le_rpow (lintegral_mono (λ a, _)) (by simp [hq_pos.le] : 0 ≤ 1 / q),
exact ennreal.rpow_add_le_add_rpow _ _ hq_pos hq1,
end
... < ∞ :
begin
refine ennreal.rpow_lt_top_of_nonneg (by simp [hq_pos.le] : 0 ≤ 1 / q) _,
rw [lintegral_add' (hf.ennnorm.pow_const q)
(hg.ennnorm.pow_const q), ennreal.add_ne_top, ←lt_top_iff_ne_top,
←lt_top_iff_ne_top],
exact ⟨lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hq_pos hf_snorm,
lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hq_pos hg_snorm⟩,
end
lemma snorm_add_lt_top {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) :
snorm (f + g) p μ < ∞ :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
rw ←ne.def at h0,
cases le_total 1 p with hp1 hp1,
{ exact snorm_add_lt_top_of_one_le hf hg hp1, },
have hp_top : p ≠ ∞, from (lt_of_le_of_lt hp1 ennreal.coe_lt_top).ne,
have hp_pos : 0 < p.to_real,
{ rw [← ennreal.zero_to_real, @ennreal.to_real_lt_to_real 0 p ennreal.coe_ne_top hp_top],
exact ((zero_le p).lt_of_ne h0.symm), },
have hp1_real : p.to_real ≤ 1,
{ rwa [← ennreal.one_to_real, @ennreal.to_real_le_to_real p 1 hp_top ennreal.coe_ne_top], },
rw snorm_eq_snorm' h0 hp_top,
rw [mem_ℒp, snorm_eq_snorm' h0 hp_top] at hf hg,
exact snorm'_add_lt_top_of_le_one hf.1 hg.1 hf.2 hg.2 hp_pos hp1_real,
end
section trim
lemma snorm'_trim (hm : m ≤ m0) {f : α → E} (hf : @measurable _ _ m _ f) :
snorm' f q (ν.trim hm) = snorm' f q ν :=
begin
simp_rw snorm',
congr' 1,
refine lintegral_trim hm _,
refine @measurable.pow_const _ _ _ _ _ _ _ m _ (@measurable.coe_nnreal_ennreal _ m _ _) _,
exact @measurable.nnnorm E _ _ _ _ m _ hf,
end
lemma limsup_trim (hm : m ≤ m0) {f : α → ℝ≥0∞} (hf : @measurable _ _ m _ f) :
(ν.trim hm).ae.limsup f = ν.ae.limsup f :=
begin
simp_rw limsup_eq,
suffices h_set_eq : {a : ℝ≥0∞ | ∀ᵐ n ∂(ν.trim hm), f n ≤ a} = {a : ℝ≥0∞ | ∀ᵐ n ∂ν, f n ≤ a},
by rw h_set_eq,
ext1 a,
suffices h_meas_eq : ν {x | ¬ f x ≤ a} = ν.trim hm {x | ¬ f x ≤ a},
by simp_rw [set.mem_set_of_eq, ae_iff, h_meas_eq],
refine (trim_measurable_set_eq hm _).symm,
refine @measurable_set.compl _ _ m (@measurable_set_le ℝ≥0∞ _ _ _ _ m _ _ _ _ _ hf _),
exact @measurable_const _ _ _ m _,
end
lemma ess_sup_trim (hm : m ≤ m0) {f : α → ℝ≥0∞} (hf : @measurable _ _ m _ f) :
ess_sup f (ν.trim hm) = ess_sup f ν :=
by { simp_rw ess_sup, exact limsup_trim hm hf, }
lemma snorm_ess_sup_trim (hm : m ≤ m0) {f : α → E} (hf : @measurable _ _ m _ f) :
snorm_ess_sup f (ν.trim hm) = snorm_ess_sup f ν :=
ess_sup_trim hm (@measurable.coe_nnreal_ennreal _ m _ (@measurable.nnnorm E _ _ _ _ m _ hf))
lemma snorm_trim (hm : m ≤ m0) {f : α → E} (hf : @measurable _ _ m _ f) :
snorm f p (ν.trim hm) = snorm f p ν :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
by_cases h_top : p = ∞,
{ simpa only [h_top, snorm_exponent_top] using snorm_ess_sup_trim hm hf, },
simpa only [snorm_eq_snorm' h0 h_top] using snorm'_trim hm hf,
end
lemma snorm_trim_ae (hm : m ≤ m0) {f : α → E} (hf : ae_measurable f (ν.trim hm)) :
snorm f p (ν.trim hm) = snorm f p ν :=
begin
rw [snorm_congr_ae hf.ae_eq_mk, snorm_congr_ae (ae_eq_of_ae_eq_trim hf.ae_eq_mk)],
exact snorm_trim hm hf.measurable_mk,
end
lemma mem_ℒp_of_mem_ℒp_trim (hm : m ≤ m0) {f : α → E} (hf : mem_ℒp f p (ν.trim hm)) :
mem_ℒp f p ν :=
⟨ae_measurable_of_ae_measurable_trim hm hf.1, (le_of_eq (snorm_trim_ae hm hf.1).symm).trans_lt hf.2⟩
end trim
end opens_measurable_space
@[simp] lemma snorm'_neg {f : α → F} : snorm' (-f) q μ = snorm' f q μ := by simp [snorm']
@[simp] lemma snorm_neg {f : α → F} : snorm (-f) p μ = snorm f p μ :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
by_cases h_top : p = ∞,
{ simp [h_top, snorm_ess_sup], },
simp [snorm_eq_snorm' h0 h_top],
end
section borel_space
variable [borel_space E]
lemma mem_ℒp.neg {f : α → E} (hf : mem_ℒp f p μ) : mem_ℒp (-f) p μ :=
⟨ae_measurable.neg hf.1, by simp [hf.right]⟩
lemma mem_ℒp_neg_iff {f : α → E} : mem_ℒp (-f) p μ ↔ mem_ℒp f p μ :=
⟨λ h, neg_neg f ▸ h.neg, mem_ℒp.neg⟩
lemma snorm'_le_snorm'_mul_rpow_measure_univ {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q)
{f : α → E} (hf : ae_measurable f μ) :
snorm' f p μ ≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) :=
begin
have hq0_lt : 0 < q, from lt_of_lt_of_le hp0_lt hpq,
by_cases hpq_eq : p = q,
{ rw [hpq_eq, sub_self, ennreal.rpow_zero, mul_one],
exact le_refl _, },
have hpq : p < q, from lt_of_le_of_ne hpq hpq_eq,
let g := λ a : α, (1 : ℝ≥0∞),
have h_rw : ∫⁻ a, ↑(nnnorm (f a))^p ∂ μ = ∫⁻ a, (nnnorm (f a) * (g a))^p ∂ μ,
from lintegral_congr (λ a, by simp),
repeat {rw snorm'},
rw h_rw,
let r := p * q / (q - p),
have hpqr : 1/p = 1/q + 1/r,
{ field_simp [(ne_of_lt hp0_lt).symm,
(ne_of_lt hq0_lt).symm],
ring, },
calc (∫⁻ (a : α), (↑(nnnorm (f a)) * g a) ^ p ∂μ) ^ (1/p)
≤ (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * (∫⁻ (a : α), (g a) ^ r ∂μ) ^ (1/r) :
ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hf.ennnorm
ae_measurable_const
... = (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * μ set.univ ^ (1/p - 1/q) :
by simp [hpqr],
end
lemma snorm'_le_snorm_ess_sup_mul_rpow_measure_univ (hq_pos : 0 < q) {f : α → F} :
snorm' f q μ ≤ snorm_ess_sup f μ * (μ set.univ) ^ (1/q) :=
begin
have h_le : ∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ ≤ ∫⁻ (a : α), (snorm_ess_sup f μ) ^ q ∂μ,
{ refine lintegral_mono_ae _,
have h_nnnorm_le_snorm_ess_sup := coe_nnnorm_ae_le_snorm_ess_sup f μ,
refine h_nnnorm_le_snorm_ess_sup.mono (λ x hx, ennreal.rpow_le_rpow hx (le_of_lt hq_pos)), },
rw [snorm', ←ennreal.rpow_one (snorm_ess_sup f μ)],
nth_rewrite 1 ←mul_inv_cancel (ne_of_lt hq_pos).symm,
rw [ennreal.rpow_mul, one_div,
←ennreal.mul_rpow_of_nonneg _ _ (by simp [hq_pos.le] : 0 ≤ q⁻¹)],
refine ennreal.rpow_le_rpow _ (by simp [hq_pos.le]),
rwa lintegral_const at h_le,
end
lemma snorm_le_snorm_mul_rpow_measure_univ {p q : ℝ≥0∞} (hpq : p ≤ q) {f : α → E}
(hf : ae_measurable f μ) :
snorm f p μ ≤ snorm f q μ * (μ set.univ) ^ (1/p.to_real - 1/q.to_real) :=
begin
by_cases hp0 : p = 0,
{ simp [hp0, zero_le], },
rw ← ne.def at hp0,
have hp0_lt : 0 < p, from lt_of_le_of_ne (zero_le _) hp0.symm,
have hq0_lt : 0 < q, from lt_of_lt_of_le hp0_lt hpq,
by_cases hq_top : q = ∞,
{ simp only [hq_top, div_zero, one_div, ennreal.top_to_real, sub_zero, snorm_exponent_top,
inv_zero],
by_cases hp_top : p = ∞,
{ simp only [hp_top, ennreal.rpow_zero, mul_one, ennreal.top_to_real, sub_zero, inv_zero,
snorm_exponent_top],
exact le_rfl, },
rw snorm_eq_snorm' hp0 hp_top,
have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨hp0_lt, hp_top⟩,
refine (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos).trans (le_of_eq _),
congr,
exact one_div _, },
have hp_lt_top : p < ∞, from hpq.trans_lt (lt_top_iff_ne_top.mpr hq_top),
have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨hp0_lt, hp_lt_top.ne⟩,
rw [snorm_eq_snorm' hp0_lt.ne.symm hp_lt_top.ne, snorm_eq_snorm' hq0_lt.ne.symm hq_top],
have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_lt_top.ne hq_top,
exact snorm'_le_snorm'_mul_rpow_measure_univ hp_pos hpq_real hf,
end
lemma snorm'_le_snorm'_of_exponent_le {m : measurable_space α} {p q : ℝ} (hp0_lt : 0 < p)
(hpq : p ≤ q) (μ : measure α) [is_probability_measure μ] {f : α → E} (hf : ae_measurable f μ) :
snorm' f p μ ≤ snorm' f q μ :=
begin
have h_le_μ := snorm'_le_snorm'_mul_rpow_measure_univ hp0_lt hpq hf,
rwa [measure_univ, ennreal.one_rpow, mul_one] at h_le_μ,
end
lemma snorm'_le_snorm_ess_sup (hq_pos : 0 < q) {f : α → F} [is_probability_measure μ] :
snorm' f q μ ≤ snorm_ess_sup f μ :=
le_trans (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hq_pos) (le_of_eq (by simp [measure_univ]))
lemma snorm_le_snorm_of_exponent_le {p q : ℝ≥0∞} (hpq : p ≤ q) [is_probability_measure μ]
{f : α → E} (hf : ae_measurable f μ) :
snorm f p μ ≤ snorm f q μ :=
(snorm_le_snorm_mul_rpow_measure_univ hpq hf).trans (le_of_eq (by simp [measure_univ]))
lemma snorm'_lt_top_of_snorm'_lt_top_of_exponent_le {p q : ℝ} [is_finite_measure μ] {f : α → E}
(hf : ae_measurable f μ) (hfq_lt_top : snorm' f q μ < ∞) (hp_nonneg : 0 ≤ p) (hpq : p ≤ q) :
snorm' f p μ < ∞ :=
begin
cases le_or_lt p 0 with hp_nonpos hp_pos,
{ rw le_antisymm hp_nonpos hp_nonneg,
simp, },
have hq_pos : 0 < q, from lt_of_lt_of_le hp_pos hpq,
calc snorm' f p μ
≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) :
snorm'_le_snorm'_mul_rpow_measure_univ hp_pos hpq hf
... < ∞ :
begin
rw ennreal.mul_lt_top_iff,
refine or.inl ⟨hfq_lt_top, ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ)⟩,
rwa [le_sub, sub_zero, one_div, one_div, inv_le_inv hq_pos hp_pos],
end
end
lemma mem_ℒp.mem_ℒp_of_exponent_le {p q : ℝ≥0∞} [is_finite_measure μ] {f : α → E}
(hfq : mem_ℒp f q μ) (hpq : p ≤ q) :
mem_ℒp f p μ :=
begin
cases hfq with hfq_m hfq_lt_top,
by_cases hp0 : p = 0,
{ rwa [hp0, mem_ℒp_zero_iff_ae_measurable], },
rw ←ne.def at hp0,
refine ⟨hfq_m, _⟩,
by_cases hp_top : p = ∞,
{ have hq_top : q = ∞,
by rwa [hp_top, top_le_iff] at hpq,
rw [hp_top],
rwa hq_top at hfq_lt_top, },
have hp_pos : 0 < p.to_real,
from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩,
by_cases hq_top : q = ∞,
{ rw snorm_eq_snorm' hp0 hp_top,
rw [hq_top, snorm_exponent_top] at hfq_lt_top,
refine lt_of_le_of_lt (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos) _,
refine ennreal.mul_lt_top hfq_lt_top.ne _,
exact (ennreal.rpow_lt_top_of_nonneg (by simp [hp_pos.le]) (measure_ne_top μ set.univ)).ne },
have hq0 : q ≠ 0,
{ by_contra hq_eq_zero,
push_neg at hq_eq_zero,
have hp_eq_zero : p = 0, from le_antisymm (by rwa hq_eq_zero at hpq) (zero_le _),
rw [hp_eq_zero, ennreal.zero_to_real] at hp_pos,
exact (lt_irrefl _) hp_pos, },
have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_top hq_top,
rw snorm_eq_snorm' hp0 hp_top,
rw snorm_eq_snorm' hq0 hq_top at hfq_lt_top,
exact snorm'_lt_top_of_snorm'_lt_top_of_exponent_le hfq_m hfq_lt_top (le_of_lt hp_pos) hpq_real,
end
lemma snorm'_sum_le [second_countable_topology E] {ι} {f : ι → α → E} {s : finset ι}
(hfs : ∀ i, i ∈ s → ae_measurable (f i) μ) (hq1 : 1 ≤ q) :
snorm' (∑ i in s, f i) q μ ≤ ∑ i in s, snorm' (f i) q μ :=
finset.le_sum_of_subadditive_on_pred (λ (f : α → E), snorm' f q μ)
(λ f, ae_measurable f μ) (snorm'_zero (zero_lt_one.trans_le hq1))
(λ f g hf hg, snorm'_add_le hf hg hq1) (λ x y, ae_measurable.add) _ hfs
lemma snorm_sum_le [second_countable_topology E] {ι} {f : ι → α → E} {s : finset ι}
(hfs : ∀ i, i ∈ s → ae_measurable (f i) μ) (hp1 : 1 ≤ p) :
snorm (∑ i in s, f i) p μ ≤ ∑ i in s, snorm (f i) p μ :=
finset.le_sum_of_subadditive_on_pred (λ (f : α → E), snorm f p μ)
(λ f, ae_measurable f μ) snorm_zero (λ f g hf hg, snorm_add_le hf hg hp1)
(λ x y, ae_measurable.add) _ hfs
section second_countable_topology
variable [second_countable_topology E]
lemma mem_ℒp.add {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f + g) p μ :=
⟨ae_measurable.add hf.1 hg.1, snorm_add_lt_top hf hg⟩
lemma mem_ℒp.sub {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f - g) p μ :=
by { rw sub_eq_add_neg, exact hf.add hg.neg }
lemma mem_ℒp_finset_sum {ι} (s : finset ι) {f : ι → α → E} (hf : ∀ i ∈ s, mem_ℒp (f i) p μ) :
mem_ℒp (λ a, ∑ i in s, f i a) p μ :=
begin
haveI : decidable_eq ι := classical.dec_eq _,
revert hf,
refine finset.induction_on s _ _,
{ simp only [zero_mem_ℒp', finset.sum_empty, implies_true_iff], },
{ intros i s his ih hf,
simp only [his, finset.sum_insert, not_false_iff],
exact (hf i (s.mem_insert_self i)).add (ih (λ j hj, hf j (finset.mem_insert_of_mem hj))), },
end
end second_countable_topology
end borel_space
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F]
lemma snorm'_const_smul {f : α → F} (c : 𝕜) (hq_pos : 0 < q) :
snorm' (c • f) q μ = (nnnorm c : ℝ≥0∞) * snorm' f q μ :=
begin
rw snorm',
simp_rw [pi.smul_apply, nnnorm_smul, ennreal.coe_mul,
ennreal.mul_rpow_of_nonneg _ _ hq_pos.le],
suffices h_integral : ∫⁻ a, ↑(nnnorm c) ^ q * ↑(nnnorm (f a)) ^ q ∂μ
= (nnnorm c : ℝ≥0∞)^q * ∫⁻ a, (nnnorm (f a)) ^ q ∂μ,
{ apply_fun (λ x, x ^ (1/q)) at h_integral,
rw [h_integral, ennreal.mul_rpow_of_nonneg _ _ (by simp [hq_pos.le] : 0 ≤ 1 / q)],
congr,
simp_rw [←ennreal.rpow_mul, one_div, mul_inv_cancel hq_pos.ne.symm, ennreal.rpow_one], },
rw lintegral_const_mul',
rw ennreal.coe_rpow_of_nonneg _ hq_pos.le,
exact ennreal.coe_ne_top,
end
lemma snorm_ess_sup_const_smul {f : α → F} (c : 𝕜) :
snorm_ess_sup (c • f) μ = (nnnorm c : ℝ≥0∞) * snorm_ess_sup f μ :=
by simp_rw [snorm_ess_sup, pi.smul_apply, nnnorm_smul, ennreal.coe_mul, ennreal.ess_sup_const_mul]
lemma snorm_const_smul {f : α → F} (c : 𝕜) :
snorm (c • f) p μ = (nnnorm c : ℝ≥0∞) * snorm f p μ :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
by_cases h_top : p = ∞,
{ simp [h_top, snorm_ess_sup_const_smul], },
repeat { rw snorm_eq_snorm' h0 h_top, },
rw ←ne.def at h0,
exact snorm'_const_smul c
(ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩),
end
lemma mem_ℒp.const_smul [measurable_space 𝕜] [opens_measurable_space 𝕜] [borel_space E] {f : α → E}
(hf : mem_ℒp f p μ) (c : 𝕜) :
mem_ℒp (c • f) p μ :=
⟨ae_measurable.const_smul hf.1 c,
(snorm_const_smul c).le.trans_lt (ennreal.mul_lt_top ennreal.coe_ne_top hf.2.ne)⟩
lemma mem_ℒp.const_mul [measurable_space 𝕜] [borel_space 𝕜]
{f : α → 𝕜} (hf : mem_ℒp f p μ) (c : 𝕜) : mem_ℒp (λ x, c * f x) p μ :=
hf.const_smul c
lemma snorm'_smul_le_mul_snorm' [opens_measurable_space E] [measurable_space 𝕜]
[opens_measurable_space 𝕜] {p q r : ℝ}
{f : α → E} (hf : ae_measurable f μ) {φ : α → 𝕜} (hφ : ae_measurable φ μ)
(hp0_lt : 0 < p) (hpq : p < q) (hpqr : 1/p = 1/q + 1/r) :
snorm' (φ • f) p μ ≤ snorm' φ q μ * snorm' f r μ :=
begin
simp_rw [snorm', pi.smul_apply', nnnorm_smul, ennreal.coe_mul],
exact ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hφ.ennnorm
hf.ennnorm,
end
end normed_space
section monotonicity
lemma snorm_le_mul_snorm_aux_of_nonneg {f : α → F} {g : α → G} {c : ℝ}
(h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (hc : 0 ≤ c) (p : ℝ≥0∞) :
snorm f p μ ≤ (ennreal.of_real c) * snorm g p μ :=
begin
lift c to ℝ≥0 using hc,
rw [ennreal.of_real_coe_nnreal, ← c.nnnorm_eq, ← snorm_norm g, ← snorm_const_smul (c : ℝ)],
swap, apply_instance,
refine snorm_mono_ae _,
simpa
end
lemma snorm_le_mul_snorm_aux_of_neg {f : α → F} {g : α → G} {c : ℝ}
(h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (hc : c < 0) (p : ℝ≥0∞) :
snorm f p μ = 0 ∧ snorm g p μ = 0 :=
begin
suffices : f =ᵐ[μ] 0 ∧ g =ᵐ[μ] 0,
by simp [snorm_congr_ae this.1, snorm_congr_ae this.2],
refine ⟨h.mono $ λ x hx, _, h.mono $ λ x hx, _⟩,
{ refine norm_le_zero_iff.1 (hx.trans _),
exact mul_nonpos_of_nonpos_of_nonneg hc.le (norm_nonneg _) },
{ refine norm_le_zero_iff.1 (nonpos_of_mul_nonneg_right _ hc),
exact (norm_nonneg _).trans hx }
end
lemma snorm_le_mul_snorm_of_ae_le_mul {f : α → F} {g : α → G} {c : ℝ}
(h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (p : ℝ≥0∞) :
snorm f p μ ≤ (ennreal.of_real c) * snorm g p μ :=
begin
cases le_or_lt 0 c with hc hc,
{ exact snorm_le_mul_snorm_aux_of_nonneg h hc p },
{ simp [snorm_le_mul_snorm_aux_of_neg h hc p] }
end
lemma mem_ℒp.of_le_mul [measurable_space F] {f : α → E} {g : α → F} {c : ℝ}
(hg : mem_ℒp g p μ) (hf : ae_measurable f μ) (hfg : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) :
mem_ℒp f p μ :=
begin
simp only [mem_ℒp, hf, true_and],
apply lt_of_le_of_lt (snorm_le_mul_snorm_of_ae_le_mul hfg p),
simp [lt_top_iff_ne_top, hg.snorm_ne_top],
end
end monotonicity
section is_R_or_C
variables {𝕜 : Type*} [is_R_or_C 𝕜] [measurable_space 𝕜] [opens_measurable_space 𝕜] {f : α → 𝕜}
lemma mem_ℒp.re (hf : mem_ℒp f p μ) : mem_ℒp (λ x, is_R_or_C.re (f x)) p μ :=
begin
have : ∀ x, ∥is_R_or_C.re (f x)∥ ≤ 1 * ∥f x∥,
by { intro x, rw one_mul, exact is_R_or_C.norm_re_le_norm (f x), },
exact hf.of_le_mul hf.1.re (eventually_of_forall this),
end
lemma mem_ℒp.im (hf : mem_ℒp f p μ) : mem_ℒp (λ x, is_R_or_C.im (f x)) p μ :=
begin
have : ∀ x, ∥is_R_or_C.im (f x)∥ ≤ 1 * ∥f x∥,
by { intro x, rw one_mul, exact is_R_or_C.norm_im_le_norm (f x), },
exact hf.of_le_mul hf.1.im (eventually_of_forall this),
end
end is_R_or_C
section inner_product
variables {E' 𝕜 : Type*} [is_R_or_C 𝕜] [measurable_space 𝕜] [borel_space 𝕜]
[inner_product_space 𝕜 E']
[measurable_space E'] [opens_measurable_space E'] [second_countable_topology E']
local notation `⟪`x`, `y`⟫` := @inner 𝕜 E' _ x y
lemma mem_ℒp.const_inner (c : E') {f : α → E'} (hf : mem_ℒp f p μ) :
mem_ℒp (λ a, ⟪c, f a⟫) p μ :=
hf.of_le_mul (ae_measurable.inner ae_measurable_const hf.1)
(eventually_of_forall (λ x, norm_inner_le_norm _ _))
lemma mem_ℒp.inner_const {f : α → E'} (hf : mem_ℒp f p μ) (c : E') :
mem_ℒp (λ a, ⟪f a, c⟫) p μ :=
hf.of_le_mul (ae_measurable.inner hf.1 ae_measurable_const)
(eventually_of_forall (λ x, by { rw mul_comm, exact norm_inner_le_norm _ _, }))
end inner_product
end ℒp
/-!
### Lp space
The space of equivalence classes of measurable functions for which `snorm f p μ < ∞`.
-/
@[simp] lemma snorm_ae_eq_fun {α E : Type*} [measurable_space α] {μ : measure α}
[measurable_space E] [normed_group E] {p : ℝ≥0∞} {f : α → E} (hf : ae_measurable f μ) :
snorm (ae_eq_fun.mk f hf) p μ = snorm f p μ :=
snorm_congr_ae (ae_eq_fun.coe_fn_mk _ _)
lemma mem_ℒp.snorm_mk_lt_top {α E : Type*} [measurable_space α] {μ : measure α}
[measurable_space E] [normed_group E] {p : ℝ≥0∞} {f : α → E} (hfp : mem_ℒp f p μ) :
snorm (ae_eq_fun.mk f hfp.1) p μ < ∞ :=
by simp [hfp.2]
/-- Lp space -/
def Lp {α} (E : Type*) {m : measurable_space α} [measurable_space E] [normed_group E]
[borel_space E] [second_countable_topology E]
(p : ℝ≥0∞) (μ : measure α) : add_subgroup (α →ₘ[μ] E) :=
{ carrier := {f | snorm f p μ < ∞},
zero_mem' := by simp [snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero],
add_mem' := λ f g hf hg, by simp [snorm_congr_ae (ae_eq_fun.coe_fn_add _ _),
snorm_add_lt_top ⟨f.ae_measurable, hf⟩ ⟨g.ae_measurable, hg⟩],
neg_mem' := λ f hf,
by rwa [set.mem_set_of_eq, snorm_congr_ae (ae_eq_fun.coe_fn_neg _), snorm_neg] }
localized "notation α ` →₁[`:25 μ `] ` E := measure_theory.Lp E 1 μ" in measure_theory
localized "notation α ` →₂[`:25 μ `] ` E := measure_theory.Lp E 2 μ" in measure_theory
namespace mem_ℒp
variables [borel_space E] [second_countable_topology E]
/-- make an element of Lp from a function verifying `mem_ℒp` -/
def to_Lp (f : α → E) (h_mem_ℒp : mem_ℒp f p μ) : Lp E p μ :=
⟨ae_eq_fun.mk f h_mem_ℒp.1, h_mem_ℒp.snorm_mk_lt_top⟩
lemma coe_fn_to_Lp {f : α → E} (hf : mem_ℒp f p μ) : hf.to_Lp f =ᵐ[μ] f :=
ae_eq_fun.coe_fn_mk _ _
@[simp] lemma to_Lp_eq_to_Lp_iff {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) :
hf.to_Lp f = hg.to_Lp g ↔ f =ᵐ[μ] g :=
by simp [to_Lp]
@[simp] lemma to_Lp_zero (h : mem_ℒp (0 : α → E) p μ) : h.to_Lp 0 = 0 := rfl
lemma to_Lp_add {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) :
(hf.add hg).to_Lp (f + g) = hf.to_Lp f + hg.to_Lp g := rfl
lemma to_Lp_neg {f : α → E} (hf : mem_ℒp f p μ) : hf.neg.to_Lp (-f) = - hf.to_Lp f := rfl
lemma to_Lp_sub {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) :
(hf.sub hg).to_Lp (f - g) = hf.to_Lp f - hg.to_Lp g := rfl
end mem_ℒp
namespace Lp
variables [borel_space E] [second_countable_topology E]
instance : has_coe_to_fun (Lp E p μ) := ⟨λ _, α → E, λ f, ((f : α →ₘ[μ] E) : α → E)⟩
@[ext] lemma ext {f g : Lp E p μ} (h : f =ᵐ[μ] g) : f = g :=
begin
cases f,
cases g,
simp only [subtype.mk_eq_mk],
exact ae_eq_fun.ext h
end
lemma ext_iff {f g : Lp E p μ} : f = g ↔ f =ᵐ[μ] g :=
⟨λ h, by rw h, λ h, ext h⟩
lemma mem_Lp_iff_snorm_lt_top {f : α →ₘ[μ] E} : f ∈ Lp E p μ ↔ snorm f p μ < ∞ := iff.refl _
lemma mem_Lp_iff_mem_ℒp {f : α →ₘ[μ] E} : f ∈ Lp E p μ ↔ mem_ℒp f p μ :=
by simp [mem_Lp_iff_snorm_lt_top, mem_ℒp, f.measurable.ae_measurable]
protected lemma antitone [is_finite_measure μ] {p q : ℝ≥0∞} (hpq : p ≤ q) : Lp E q μ ≤ Lp E p μ :=
λ f hf, (mem_ℒp.mem_ℒp_of_exponent_le ⟨f.ae_measurable, hf⟩ hpq).2
@[simp] lemma coe_fn_mk {f : α →ₘ[μ] E} (hf : snorm f p μ < ∞) :
((⟨f, hf⟩ : Lp E p μ) : α → E) = f := rfl
@[simp] lemma coe_mk {f : α →ₘ[μ] E} (hf : snorm f p μ < ∞) :
((⟨f, hf⟩ : Lp E p μ) : α →ₘ[μ] E) = f := rfl
@[simp] lemma to_Lp_coe_fn (f : Lp E p μ) (hf : mem_ℒp f p μ) : hf.to_Lp f = f :=
by { cases f, simp [mem_ℒp.to_Lp] }
lemma snorm_lt_top (f : Lp E p μ) : snorm f p μ < ∞ := f.prop
lemma snorm_ne_top (f : Lp E p μ) : snorm f p μ ≠ ∞ := (snorm_lt_top f).ne
@[measurability]
protected lemma measurable (f : Lp E p μ) : measurable f := f.val.measurable
@[measurability]
protected lemma ae_measurable (f : Lp E p μ) : ae_measurable f μ := f.val.ae_measurable
protected lemma mem_ℒp (f : Lp E p μ) : mem_ℒp f p μ := ⟨Lp.ae_measurable f, f.prop⟩
variables (E p μ)
lemma coe_fn_zero : ⇑(0 : Lp E p μ) =ᵐ[μ] 0 := ae_eq_fun.coe_fn_zero
variables {E p μ}
lemma coe_fn_neg (f : Lp E p μ) : ⇑(-f) =ᵐ[μ] -f := ae_eq_fun.coe_fn_neg _
lemma coe_fn_add (f g : Lp E p μ) : ⇑(f + g) =ᵐ[μ] f + g := ae_eq_fun.coe_fn_add _ _
lemma coe_fn_sub (f g : Lp E p μ) : ⇑(f - g) =ᵐ[μ] f - g := ae_eq_fun.coe_fn_sub _ _
lemma mem_Lp_const (α) {m : measurable_space α} (μ : measure α) (c : E) [is_finite_measure μ] :
@ae_eq_fun.const α _ _ μ _ c ∈ Lp E p μ :=
(mem_ℒp_const c).snorm_mk_lt_top
instance : has_norm (Lp E p μ) := { norm := λ f, ennreal.to_real (snorm f p μ) }
instance : has_dist (Lp E p μ) := { dist := λ f g, ∥f - g∥}
instance : has_edist (Lp E p μ) := { edist := λ f g, ennreal.of_real (dist f g) }
lemma norm_def (f : Lp E p μ) : ∥f∥ = ennreal.to_real (snorm f p μ) := rfl
@[simp] lemma norm_to_Lp (f : α → E) (hf : mem_ℒp f p μ) :
∥hf.to_Lp f∥ = ennreal.to_real (snorm f p μ) :=
by rw [norm_def, snorm_congr_ae (mem_ℒp.coe_fn_to_Lp hf)]
lemma dist_def (f g : Lp E p μ) : dist f g = (snorm (f - g) p μ).to_real :=
begin
simp_rw [dist, norm_def],
congr' 1,
apply snorm_congr_ae (coe_fn_sub _ _),
end
lemma edist_def (f g : Lp E p μ) : edist f g = snorm (f - g) p μ :=
begin
simp_rw [edist, dist, norm_def, ennreal.of_real_to_real (snorm_ne_top _)],
exact snorm_congr_ae (coe_fn_sub _ _)
end
@[simp] lemma edist_to_Lp_to_Lp (f g : α → E) (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) :
edist (hf.to_Lp f) (hg.to_Lp g) = snorm (f - g) p μ :=
by { rw edist_def, exact snorm_congr_ae (hf.coe_fn_to_Lp.sub hg.coe_fn_to_Lp) }
@[simp] lemma edist_to_Lp_zero (f : α → E) (hf : mem_ℒp f p μ) :
edist (hf.to_Lp f) 0 = snorm f p μ :=
by { convert edist_to_Lp_to_Lp f 0 hf zero_mem_ℒp, simp }
@[simp] lemma norm_zero : ∥(0 : Lp E p μ)∥ = 0 :=
begin
change (snorm ⇑(0 : α →ₘ[μ] E) p μ).to_real = 0,
simp [snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero]
end
lemma norm_eq_zero_iff {f : Lp E p μ} (hp : 0 < p) : ∥f∥ = 0 ↔ f = 0 :=
begin
refine ⟨λ hf, _, λ hf, by simp [hf]⟩,
rw [norm_def, ennreal.to_real_eq_zero_iff] at hf,
cases hf,
{ rw snorm_eq_zero_iff (Lp.ae_measurable f) hp.ne.symm at hf,
exact subtype.eq (ae_eq_fun.ext (hf.trans ae_eq_fun.coe_fn_zero.symm)), },
{ exact absurd hf (snorm_ne_top f), },
end
lemma eq_zero_iff_ae_eq_zero {f : Lp E p μ} : f = 0 ↔ f =ᵐ[μ] 0 :=
begin
split,
{ assume h,
rw h,
exact ae_eq_fun.coe_fn_const _ _ },
{ assume h,
ext1,
filter_upwards [h, ae_eq_fun.coe_fn_const α (0 : E)],
assume a ha h'a,
rw ha,
exact h'a.symm }
end
@[simp] lemma norm_neg {f : Lp E p μ} : ∥-f∥ = ∥f∥ :=
by rw [norm_def, norm_def, snorm_congr_ae (coe_fn_neg _), snorm_neg]
lemma norm_le_mul_norm_of_ae_le_mul
[second_countable_topology F] [measurable_space F] [borel_space F]
{c : ℝ} {f : Lp E p μ} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : ∥f∥ ≤ c * ∥g∥ :=
begin
by_cases pzero : p = 0,
{ simp [pzero, norm_def] },
cases le_or_lt 0 c with hc hc,
{ have := snorm_le_mul_snorm_aux_of_nonneg h hc p,
rw [← ennreal.to_real_le_to_real, ennreal.to_real_mul, ennreal.to_real_of_real hc] at this,
{ exact this },
{ exact (Lp.mem_ℒp _).snorm_ne_top },
{ simp [(Lp.mem_ℒp _).snorm_ne_top] } },
{ have := snorm_le_mul_snorm_aux_of_neg h hc p,
simp only [snorm_eq_zero_iff (Lp.ae_measurable _) pzero, ← eq_zero_iff_ae_eq_zero] at this,
simp [this] }
end
lemma norm_le_norm_of_ae_le [second_countable_topology F] [measurable_space F] [borel_space F]
{f : Lp E p μ} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : ∥f∥ ≤ ∥g∥ :=
begin
rw [norm_def, norm_def, ennreal.to_real_le_to_real (snorm_ne_top _) (snorm_ne_top _)],
exact snorm_mono_ae h
end
lemma mem_Lp_of_ae_le_mul [second_countable_topology F] [measurable_space F] [borel_space F]
{c : ℝ} {f : α →ₘ[μ] E} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : f ∈ Lp E p μ :=
mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_le_mul (Lp.mem_ℒp g) f.ae_measurable h
lemma mem_Lp_of_ae_le [second_countable_topology F] [measurable_space F] [borel_space F]
{f : α →ₘ[μ] E} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : f ∈ Lp E p μ :=
mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_le (Lp.mem_ℒp g) f.ae_measurable h
lemma mem_Lp_of_ae_bound [is_finite_measure μ] {f : α →ₘ[μ] E} (C : ℝ) (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) :
f ∈ Lp E p μ :=
mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_bound f.ae_measurable _ hfC
lemma norm_le_of_ae_bound [is_finite_measure μ] {f : Lp E p μ} {C : ℝ} (hC : 0 ≤ C)
(hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) :
∥f∥ ≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ * C :=
begin
by_cases hμ : μ = 0,
{ by_cases hp : p.to_real⁻¹ = 0,
{ simpa [hp, hμ, norm_def] using hC },
{ simp [hμ, norm_def, real.zero_rpow hp] } },
let A : ℝ≥0 := (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ * ⟨C, hC⟩,
suffices : snorm f p μ ≤ A,
{ exact ennreal.to_real_le_coe_of_le_coe this },
convert snorm_le_of_ae_bound hfC,
rw [← coe_measure_univ_nnreal μ, ennreal.coe_rpow_of_ne_zero (measure_univ_nnreal_pos hμ).ne',
ennreal.coe_mul],
congr,
rw max_eq_left hC
end
instance [hp : fact (1 ≤ p)] : normed_group (Lp E p μ) :=
normed_group.of_core _
{ norm_eq_zero_iff := λ f, norm_eq_zero_iff (ennreal.zero_lt_one.trans_le hp.1),
triangle := begin
assume f g,
simp only [norm_def],
rw ← ennreal.to_real_add (snorm_ne_top f) (snorm_ne_top g),
suffices h_snorm : snorm ⇑(f + g) p μ ≤ snorm ⇑f p μ + snorm ⇑g p μ,
{ rwa ennreal.to_real_le_to_real (snorm_ne_top (f + g)),
exact ennreal.add_ne_top.mpr ⟨snorm_ne_top f, snorm_ne_top g⟩, },
rw [snorm_congr_ae (coe_fn_add _ _)],
exact snorm_add_le (Lp.ae_measurable f) (Lp.ae_measurable g) hp.1,
end,
norm_neg := by simp }
instance normed_group_L1 : normed_group (Lp E 1 μ) := by apply_instance
instance normed_group_L2 : normed_group (Lp E 2 μ) := by apply_instance
instance normed_group_Ltop : normed_group (Lp E ∞ μ) := by apply_instance
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜]
[opens_measurable_space 𝕜]
lemma mem_Lp_const_smul (c : 𝕜) (f : Lp E p μ) : c • ↑f ∈ Lp E p μ :=
begin
rw [mem_Lp_iff_snorm_lt_top, snorm_congr_ae (ae_eq_fun.coe_fn_smul _ _), snorm_const_smul,
ennreal.mul_lt_top_iff],
exact or.inl ⟨ennreal.coe_lt_top, f.prop⟩,
end
variables (E p μ 𝕜)
/-- The `𝕜`-submodule of elements of `α →ₘ[μ] E` whose `Lp` norm is finite. This is `Lp E p μ`,
with extra structure. -/
def Lp_submodule : submodule 𝕜 (α →ₘ[μ] E) :=
{ smul_mem' := λ c f hf, by simpa using mem_Lp_const_smul c ⟨f, hf⟩,
.. Lp E p μ }
variables {E p μ 𝕜}
lemma coe_Lp_submodule : (Lp_submodule E p μ 𝕜).to_add_subgroup = Lp E p μ := rfl
instance : module 𝕜 (Lp E p μ) :=
{ .. (Lp_submodule E p μ 𝕜).module }
lemma coe_fn_smul (c : 𝕜) (f : Lp E p μ) : ⇑(c • f) =ᵐ[μ] c • f := ae_eq_fun.coe_fn_smul _ _
lemma norm_const_smul (c : 𝕜) (f : Lp E p μ) : ∥c • f∥ = ∥c∥ * ∥f∥ :=
by rw [norm_def, snorm_congr_ae (coe_fn_smul _ _), snorm_const_smul c,
ennreal.to_real_mul, ennreal.coe_to_real, coe_nnnorm, norm_def]
instance [fact (1 ≤ p)] : normed_space 𝕜 (Lp E p μ) :=
{ norm_smul_le := λ _ _, by simp [norm_const_smul] }
instance normed_space_L1 : normed_space 𝕜 (Lp E 1 μ) := by apply_instance
instance normed_space_L2 : normed_space 𝕜 (Lp E 2 μ) := by apply_instance
instance normed_space_Ltop : normed_space 𝕜 (Lp E ∞ μ) := by apply_instance
instance [normed_space ℝ E] [has_scalar ℝ 𝕜] [is_scalar_tower ℝ 𝕜 E] :
is_scalar_tower ℝ 𝕜 (Lp E p μ) :=
begin
refine ⟨λ r c f, _⟩,
ext1,
refine (Lp.coe_fn_smul _ _).trans _,
rw smul_assoc,
refine eventually_eq.trans _ (Lp.coe_fn_smul _ _).symm,
refine (Lp.coe_fn_smul c f).mono (λ x hx, _),
rw [pi.smul_apply, pi.smul_apply, pi.smul_apply, hx, pi.smul_apply],
end
end normed_space
end Lp
namespace mem_ℒp
variables
[borel_space E] [second_countable_topology E]
{𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜]
lemma to_Lp_const_smul {f : α → E} (c : 𝕜) (hf : mem_ℒp f p μ) :
(hf.const_smul c).to_Lp (c • f) = c • hf.to_Lp f := rfl
end mem_ℒp
/-! ### Indicator of a set as an element of Lᵖ
For a set `s` with `(hs : measurable_set s)` and `(hμs : μ s < ∞)`, we build
`indicator_const_Lp p hs hμs c`, the element of `Lp` corresponding to `s.indicator (λ x, c)`.
-/
section indicator
variables {s : set α} {hs : measurable_set s} {c : E} {f : α → E} {hf : ae_measurable f μ}
lemma snorm_ess_sup_indicator_le (s : set α) (f : α → G) :
snorm_ess_sup (s.indicator f) μ ≤ snorm_ess_sup f μ :=
begin
refine ess_sup_mono_ae (eventually_of_forall (λ x, _)),
rw [ennreal.coe_le_coe, nnnorm_indicator_eq_indicator_nnnorm],
exact set.indicator_le_self s _ x,
end
lemma snorm_ess_sup_indicator_const_le (s : set α) (c : G) :
snorm_ess_sup (s.indicator (λ x : α , c)) μ ≤ ∥c∥₊ :=
begin
by_cases hμ0 : μ = 0,
{ rw [hμ0, snorm_ess_sup_measure_zero, ennreal.coe_nonneg],
exact zero_le', },
{ exact (snorm_ess_sup_indicator_le s (λ x, c)).trans (snorm_ess_sup_const c hμ0).le, },
end
lemma snorm_ess_sup_indicator_const_eq (s : set α) (c : G) (hμs : μ s ≠ 0) :
snorm_ess_sup (s.indicator (λ x : α , c)) μ = ∥c∥₊ :=
begin
refine le_antisymm (snorm_ess_sup_indicator_const_le s c) _,
by_contra h,
push_neg at h,
have h' := ae_iff.mp (ae_lt_of_ess_sup_lt h),
push_neg at h',
refine hμs (measure_mono_null (λ x hx_mem, _) h'),
rw [set.mem_set_of_eq, set.indicator_of_mem hx_mem],
exact le_rfl,
end
variables (hs)
lemma snorm_indicator_le {E : Type*} [normed_group E] (f : α → E) :
snorm (s.indicator f) p μ ≤ snorm f p μ :=
begin
refine snorm_mono_ae (eventually_of_forall (λ x, _)),
suffices : ∥s.indicator f x∥₊ ≤ ∥f x∥₊,
{ exact nnreal.coe_mono this },
rw nnnorm_indicator_eq_indicator_nnnorm,
exact s.indicator_le_self _ x,
end
variables {hs}
lemma snorm_indicator_const {c : G} (hs : measurable_set s) (hp : p ≠ 0) (hp_top : p ≠ ∞) :
snorm (s.indicator (λ x, c)) p μ = ∥c∥₊ * (μ s) ^ (1 / p.to_real) :=
begin
have hp_pos : 0 < p.to_real,
from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp.symm, hp_top⟩,
rw snorm_eq_lintegral_rpow_nnnorm hp hp_top,
simp_rw [nnnorm_indicator_eq_indicator_nnnorm, ennreal.coe_indicator],
have h_indicator_pow : (λ a : α, s.indicator (λ (x : α), (∥c∥₊ : ℝ≥0∞)) a ^ p.to_real)
= s.indicator (λ (x : α), ↑∥c∥₊ ^ p.to_real),
{ rw set.comp_indicator_const (∥c∥₊ : ℝ≥0∞) (λ x, x ^ p.to_real) _,
simp [hp_pos], },
rw [h_indicator_pow, lintegral_indicator _ hs, set_lintegral_const, ennreal.mul_rpow_of_nonneg],
{ rw [← ennreal.rpow_mul, mul_one_div_cancel hp_pos.ne.symm, ennreal.rpow_one], },
{ simp [hp_pos.le], },
end
lemma snorm_indicator_const' {c : G} (hs : measurable_set s) (hμs : μ s ≠ 0) (hp : p ≠ 0) :
snorm (s.indicator (λ _, c)) p μ = ∥c∥₊ * (μ s) ^ (1 / p.to_real) :=
begin
by_cases hp_top : p = ∞,
{ simp [hp_top, snorm_ess_sup_indicator_const_eq s c hμs], },
{ exact snorm_indicator_const hs hp hp_top, },
end
lemma mem_ℒp.indicator (hs : measurable_set s) (hf : mem_ℒp f p μ) :
mem_ℒp (s.indicator f) p μ :=
⟨hf.ae_measurable.indicator hs, lt_of_le_of_lt (snorm_indicator_le f) hf.snorm_lt_top⟩
lemma snorm_ess_sup_indicator_eq_snorm_ess_sup_restrict {f : α → F} (hs : measurable_set s) :
snorm_ess_sup (s.indicator f) μ = snorm_ess_sup f (μ.restrict s) :=
begin
simp_rw [snorm_ess_sup, nnnorm_indicator_eq_indicator_nnnorm, ennreal.coe_indicator],
by_cases hs_null : μ s = 0,
{ rw measure.restrict_zero_set hs_null,
simp only [ess_sup_measure_zero, ennreal.ess_sup_eq_zero_iff, ennreal.bot_eq_zero],
have hs_empty : s =ᵐ[μ] (∅ : set α), by { rw ae_eq_set, simpa using hs_null, },
refine (indicator_ae_eq_of_ae_eq_set hs_empty).trans _,
rw set.indicator_empty,
refl, },
rw ess_sup_indicator_eq_ess_sup_restrict (eventually_of_forall (λ x, _)) hs hs_null,
rw pi.zero_apply,
exact zero_le _,
end
lemma snorm_indicator_eq_snorm_restrict {f : α → F} (hs : measurable_set s) :
snorm (s.indicator f) p μ = snorm f p (μ.restrict s) :=
begin
by_cases hp_zero : p = 0,
{ simp only [hp_zero, snorm_exponent_zero], },
by_cases hp_top : p = ∞,
{ simp_rw [hp_top, snorm_exponent_top],
exact snorm_ess_sup_indicator_eq_snorm_ess_sup_restrict hs, },
simp_rw snorm_eq_lintegral_rpow_nnnorm hp_zero hp_top,
suffices : ∫⁻ x, ∥s.indicator f x∥₊ ^ p.to_real ∂μ = ∫⁻ x in s, ∥f x∥₊ ^ p.to_real ∂μ,
by rw this,
rw ← lintegral_indicator _ hs,
congr,
simp_rw [nnnorm_indicator_eq_indicator_nnnorm, ennreal.coe_indicator],
have h_zero : (λ x, x ^ p.to_real) (0 : ℝ≥0∞) = 0,
by simp [ennreal.to_real_pos_iff.mpr ⟨ne.bot_lt hp_zero, hp_top⟩],
exact (set.indicator_comp_of_zero h_zero).symm,
end
lemma mem_ℒp_indicator_iff_restrict (hs : measurable_set s) :
mem_ℒp (s.indicator f) p μ ↔ mem_ℒp f p (μ.restrict s) :=
by simp [mem_ℒp, ae_measurable_indicator_iff hs, snorm_indicator_eq_snorm_restrict hs]
lemma mem_ℒp_indicator_const (p : ℝ≥0∞) (hs : measurable_set s) (c : E) (hμsc : c = 0 ∨ μ s ≠ ∞) :
mem_ℒp (s.indicator (λ _, c)) p μ :=
begin
rw mem_ℒp_indicator_iff_restrict hs,
by_cases hp_zero : p = 0,
{ rw hp_zero, exact mem_ℒp_zero_iff_ae_measurable.mpr ae_measurable_const, },
by_cases hp_top : p = ∞,
{ rw hp_top,
exact mem_ℒp_top_of_bound ae_measurable_const (∥c∥) (eventually_of_forall (λ x, le_rfl)), },
rw [mem_ℒp_const_iff hp_zero hp_top, measure.restrict_apply_univ],
cases hμsc,
{ exact or.inl hμsc, },
{ exact or.inr hμsc.lt_top, },
end
end indicator
section indicator_const_Lp
open set function
variables {s : set α} {hs : measurable_set s} {hμs : μ s ≠ ∞} {c : E}
[borel_space E] [second_countable_topology E]
/-- Indicator of a set as an element of `Lp`. -/
def indicator_const_Lp (p : ℝ≥0∞) (hs : measurable_set s) (hμs : μ s ≠ ∞) (c : E) : Lp E p μ :=
mem_ℒp.to_Lp (s.indicator (λ _, c)) (mem_ℒp_indicator_const p hs c (or.inr hμs))
lemma indicator_const_Lp_coe_fn : ⇑(indicator_const_Lp p hs hμs c) =ᵐ[μ] s.indicator (λ _, c) :=
mem_ℒp.coe_fn_to_Lp (mem_ℒp_indicator_const p hs c (or.inr hμs))
lemma indicator_const_Lp_coe_fn_mem :
∀ᵐ (x : α) ∂μ, x ∈ s → indicator_const_Lp p hs hμs c x = c :=
indicator_const_Lp_coe_fn.mono (λ x hx hxs, hx.trans (set.indicator_of_mem hxs _))
lemma indicator_const_Lp_coe_fn_nmem :
∀ᵐ (x : α) ∂μ, x ∉ s → indicator_const_Lp p hs hμs c x = 0 :=
indicator_const_Lp_coe_fn.mono (λ x hx hxs, hx.trans (set.indicator_of_not_mem hxs _))
lemma norm_indicator_const_Lp (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) :
∥indicator_const_Lp p hs hμs c∥ = ∥c∥ * (μ s).to_real ^ (1 / p.to_real) :=
by rw [Lp.norm_def, snorm_congr_ae indicator_const_Lp_coe_fn,
snorm_indicator_const hs hp_ne_zero hp_ne_top, ennreal.to_real_mul, ennreal.to_real_rpow,
ennreal.coe_to_real, coe_nnnorm]
lemma norm_indicator_const_Lp_top (hμs_ne_zero : μ s ≠ 0) : ∥indicator_const_Lp ∞ hs hμs c∥ = ∥c∥ :=
by rw [Lp.norm_def, snorm_congr_ae indicator_const_Lp_coe_fn,
snorm_indicator_const' hs hμs_ne_zero ennreal.top_ne_zero, ennreal.top_to_real, div_zero,
ennreal.rpow_zero, mul_one, ennreal.coe_to_real, coe_nnnorm]
lemma norm_indicator_const_Lp' (hp_pos : p ≠ 0) (hμs_pos : μ s ≠ 0) :
∥indicator_const_Lp p hs hμs c∥ = ∥c∥ * (μ s).to_real ^ (1 / p.to_real) :=
begin
by_cases hp_top : p = ∞,
{ rw [hp_top, ennreal.top_to_real, div_zero, real.rpow_zero, mul_one],
exact norm_indicator_const_Lp_top hμs_pos, },
{ exact norm_indicator_const_Lp hp_pos hp_top, },
end
@[simp] lemma indicator_const_empty :
indicator_const_Lp p measurable_set.empty (by simp : μ ∅ ≠ ∞) c = 0 :=
begin
rw Lp.eq_zero_iff_ae_eq_zero,
convert indicator_const_Lp_coe_fn,
simp [set.indicator_empty'],
end
lemma mem_ℒp_add_of_disjoint {f g : α → E}
(h : disjoint (support f) (support g)) (hf : measurable f) (hg : measurable g) :
mem_ℒp (f + g) p μ ↔ mem_ℒp f p μ ∧ mem_ℒp g p μ :=
begin
refine ⟨λ hfg, ⟨_, _⟩, λ h, h.1.add h.2⟩,
{ rw ← indicator_add_eq_left h, exact hfg.indicator (measurable_set_support hf) },
{ rw ← indicator_add_eq_right h, exact hfg.indicator (measurable_set_support hg) }
end
/-- The indicator of a disjoint union of two sets is the sum of the indicators of the sets. -/
lemma indicator_const_Lp_disjoint_union {s t : set α} (hs : measurable_set s)
(ht : measurable_set t) (hμs : μ s ≠ ∞) (hμt : μ t ≠ ∞) (hst : s ∩ t = ∅) (c : E) :
(indicator_const_Lp p (hs.union ht) ((measure_union_le s t).trans_lt
(lt_top_iff_ne_top.mpr (ennreal.add_ne_top.mpr ⟨hμs, hμt⟩))).ne c)
= indicator_const_Lp p hs hμs c + indicator_const_Lp p ht hμt c :=
begin
ext1,
refine indicator_const_Lp_coe_fn.trans (eventually_eq.trans _ (Lp.coe_fn_add _ _).symm),
refine eventually_eq.trans _
(eventually_eq.add indicator_const_Lp_coe_fn.symm indicator_const_Lp_coe_fn.symm),
rw set.indicator_union_of_disjoint (set.disjoint_iff_inter_eq_empty.mpr hst) _,
end
end indicator_const_Lp
end measure_theory
open measure_theory
/-!
### Composition on `L^p`
We show that Lipschitz functions vanishing at zero act by composition on `L^p`, and specialize
this to the composition with continuous linear maps, and to the definition of the positive
part of an `L^p` function.
-/
section composition
variables [second_countable_topology E] [borel_space E]
[second_countable_topology F] [measurable_space F] [borel_space F]
{g : E → F} {c : ℝ≥0}
namespace lipschitz_with
lemma mem_ℒp_comp_iff_of_antilipschitz {α E F} {K K'} [measurable_space α] {μ : measure α}
[measurable_space E] [measurable_space F] [normed_group E] [normed_group F] [borel_space E]
[borel_space F] [complete_space E]
{f : α → E} {g : E → F} (hg : lipschitz_with K g) (hg' : antilipschitz_with K' g) (g0 : g 0 = 0) :
mem_ℒp (g ∘ f) p μ ↔ mem_ℒp f p μ :=
begin
have := ae_measurable_comp_iff_of_closed_embedding g (hg'.closed_embedding hg.uniform_continuous),
split,
{ assume H,
have A : ∀ᵐ x ∂μ, ∥f x∥ ≤ K' * ∥g (f x)∥,
{ apply filter.eventually_of_forall (λ x, _),
rw [← dist_zero_right, ← dist_zero_right, ← g0],
apply hg'.le_mul_dist },
exact H.of_le_mul (this.1 H.ae_measurable) A },
{ assume H,
have A : ∀ᵐ x ∂μ, ∥g (f x)∥ ≤ K * ∥f x∥,
{ apply filter.eventually_of_forall (λ x, _),
rw [← dist_zero_right, ← dist_zero_right, ← g0],
apply hg.dist_le_mul },
exact H.of_le_mul (this.2 H.ae_measurable) A }
end
/-- When `g` is a Lipschitz function sending `0` to `0` and `f` is in `Lp`, then `g ∘ f` is well
defined as an element of `Lp`. -/
def comp_Lp (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) : Lp F p μ :=
⟨ae_eq_fun.comp g hg.continuous.measurable (f : α →ₘ[μ] E),
begin
suffices : ∀ᵐ x ∂μ, ∥ae_eq_fun.comp g hg.continuous.measurable (f : α →ₘ[μ] E) x∥ ≤ c * ∥f x∥,
{ exact Lp.mem_Lp_of_ae_le_mul this },
filter_upwards [ae_eq_fun.coe_fn_comp g hg.continuous.measurable (f : α →ₘ[μ] E)],
assume a ha,
simp only [ha],
rw [← dist_zero_right, ← dist_zero_right, ← g0],
exact hg.dist_le_mul (f a) 0,
end⟩
lemma coe_fn_comp_Lp (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) :
hg.comp_Lp g0 f =ᵐ[μ] g ∘ f :=
ae_eq_fun.coe_fn_comp _ _ _
@[simp] lemma comp_Lp_zero (hg : lipschitz_with c g) (g0 : g 0 = 0) :
hg.comp_Lp g0 (0 : Lp E p μ) = 0 :=
begin
rw Lp.eq_zero_iff_ae_eq_zero,
apply (coe_fn_comp_Lp _ _ _).trans,
filter_upwards [Lp.coe_fn_zero E p μ],
assume a ha,
simp [ha, g0]
end
lemma norm_comp_Lp_sub_le (hg : lipschitz_with c g) (g0 : g 0 = 0) (f f' : Lp E p μ) :
∥hg.comp_Lp g0 f - hg.comp_Lp g0 f'∥ ≤ c * ∥f - f'∥ :=
begin
apply Lp.norm_le_mul_norm_of_ae_le_mul,
filter_upwards [hg.coe_fn_comp_Lp g0 f, hg.coe_fn_comp_Lp g0 f',
Lp.coe_fn_sub (hg.comp_Lp g0 f) (hg.comp_Lp g0 f'), Lp.coe_fn_sub f f'],
assume a ha1 ha2 ha3 ha4,
simp [ha1, ha2, ha3, ha4, ← dist_eq_norm],
exact hg.dist_le_mul (f a) (f' a)
end
lemma norm_comp_Lp_le (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) :
∥hg.comp_Lp g0 f∥ ≤ c * ∥f∥ :=
by simpa using hg.norm_comp_Lp_sub_le g0 f 0
lemma lipschitz_with_comp_Lp [fact (1 ≤ p)] (hg : lipschitz_with c g) (g0 : g 0 = 0) :
lipschitz_with c (hg.comp_Lp g0 : Lp E p μ → Lp F p μ) :=
lipschitz_with.of_dist_le_mul $ λ f g, by simp [dist_eq_norm, norm_comp_Lp_sub_le]
lemma continuous_comp_Lp [fact (1 ≤ p)] (hg : lipschitz_with c g) (g0 : g 0 = 0) :
continuous (hg.comp_Lp g0 : Lp E p μ → Lp F p μ) :=
(lipschitz_with_comp_Lp hg g0).continuous
end lipschitz_with
namespace continuous_linear_map
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F]
/-- Composing `f : Lp ` with `L : E →L[𝕜] F`. -/
def comp_Lp (L : E →L[𝕜] F) (f : Lp E p μ) : Lp F p μ :=
L.lipschitz.comp_Lp (map_zero L) f
lemma coe_fn_comp_Lp (L : E →L[𝕜] F) (f : Lp E p μ) :
∀ᵐ a ∂μ, (L.comp_Lp f) a = L (f a) :=
lipschitz_with.coe_fn_comp_Lp _ _ _
lemma coe_fn_comp_Lp' (L : E →L[𝕜] F) (f : Lp E p μ) :
L.comp_Lp f =ᵐ[μ] λ a, L (f a) :=
L.coe_fn_comp_Lp f
lemma add_comp_Lp (L L' : E →L[𝕜] F) (f : Lp E p μ) :
(L + L').comp_Lp f = L.comp_Lp f + L'.comp_Lp f :=
begin
ext1,
refine (coe_fn_comp_Lp' (L + L') f).trans _,
refine eventually_eq.trans _ (Lp.coe_fn_add _ _).symm,
refine eventually_eq.trans _
(eventually_eq.add (L.coe_fn_comp_Lp' f).symm (L'.coe_fn_comp_Lp' f).symm),
refine eventually_of_forall (λ x, _),
refl,
end
lemma smul_comp_Lp {𝕜'} [normed_field 𝕜'] [measurable_space 𝕜'] [opens_measurable_space 𝕜']
[normed_space 𝕜' F] [smul_comm_class 𝕜 𝕜' F] (c : 𝕜') (L : E →L[𝕜] F) (f : Lp E p μ) :
(c • L).comp_Lp f = c • L.comp_Lp f :=
begin
ext1,
refine (coe_fn_comp_Lp' (c • L) f).trans _,
refine eventually_eq.trans _ (Lp.coe_fn_smul _ _).symm,
refine (L.coe_fn_comp_Lp' f).mono (λ x hx, _),
rw [pi.smul_apply, hx],
refl,
end
lemma norm_comp_Lp_le (L : E →L[𝕜] F) (f : Lp E p μ) : ∥L.comp_Lp f∥ ≤ ∥L∥ * ∥f∥ :=
lipschitz_with.norm_comp_Lp_le _ _ _
variables (μ p) [measurable_space 𝕜] [opens_measurable_space 𝕜]
/-- Composing `f : Lp E p μ` with `L : E →L[𝕜] F`, seen as a `𝕜`-linear map on `Lp E p μ`. -/
def comp_Lpₗ (L : E →L[𝕜] F) : (Lp E p μ) →ₗ[𝕜] (Lp F p μ) :=
{ to_fun := λ f, L.comp_Lp f,
map_add' := begin
intros f g,
ext1,
filter_upwards [Lp.coe_fn_add f g, coe_fn_comp_Lp L (f + g), coe_fn_comp_Lp L f,
coe_fn_comp_Lp L g, Lp.coe_fn_add (L.comp_Lp f) (L.comp_Lp g)],
assume a ha1 ha2 ha3 ha4 ha5,
simp only [ha1, ha2, ha3, ha4, ha5, map_add, pi.add_apply],
end,
map_smul' := begin
intros c f,
dsimp,
ext1,
filter_upwards [Lp.coe_fn_smul c f, coe_fn_comp_Lp L (c • f), Lp.coe_fn_smul c (L.comp_Lp f),
coe_fn_comp_Lp L f],
assume a ha1 ha2 ha3 ha4,
simp only [ha1, ha2, ha3, ha4, map_smul, pi.smul_apply],
end }
/-- Composing `f : Lp E p μ` with `L : E →L[𝕜] F`, seen as a continuous `𝕜`-linear map on
`Lp E p μ`. See also the similar
* `linear_map.comp_left` for functions,
* `continuous_linear_map.comp_left_continuous` for continuous functions,
* `continuous_linear_map.comp_left_continuous_bounded` for bounded continuous functions,
* `continuous_linear_map.comp_left_continuous_compact` for continuous functions on compact spaces.
-/
def comp_LpL [fact (1 ≤ p)] (L : E →L[𝕜] F) : (Lp E p μ) →L[𝕜] (Lp F p μ) :=
linear_map.mk_continuous (L.comp_Lpₗ p μ) ∥L∥ L.norm_comp_Lp_le
variables {μ p}
lemma coe_fn_comp_LpL [fact (1 ≤ p)] (L : E →L[𝕜] F) (f : Lp E p μ) :
L.comp_LpL p μ f =ᵐ[μ] λ a, L (f a) :=
L.coe_fn_comp_Lp f
lemma add_comp_LpL [fact (1 ≤ p)] (L L' : E →L[𝕜] F) :
(L + L').comp_LpL p μ = L.comp_LpL p μ + L'.comp_LpL p μ :=
by { ext1 f, exact add_comp_Lp L L' f }
lemma smul_comp_LpL [fact (1 ≤ p)] (c : 𝕜) (L : E →L[𝕜] F) :
(c • L).comp_LpL p μ = c • (L.comp_LpL p μ) :=
by { ext1 f, exact smul_comp_Lp c L f }
/-- TODO: written in an "apply" way because of a missing `has_scalar` instance. -/
lemma smul_comp_LpL_apply [fact (1 ≤ p)] {𝕜'} [normed_field 𝕜'] [measurable_space 𝕜']
[opens_measurable_space 𝕜'] [normed_space 𝕜' F] [smul_comm_class 𝕜 𝕜' F]
(c : 𝕜') (L : E →L[𝕜] F) (f : Lp E p μ) :
(c • L).comp_LpL p μ f = c • (L.comp_LpL p μ f) :=
smul_comp_Lp c L f
lemma norm_compLpL_le [fact (1 ≤ p)] (L : E →L[𝕜] F) :
∥L.comp_LpL p μ∥ ≤ ∥L∥ :=
linear_map.mk_continuous_norm_le _ (norm_nonneg _) _
end continuous_linear_map
namespace measure_theory
lemma indicator_const_Lp_eq_to_span_singleton_comp_Lp {s : set α} [normed_space ℝ F]
(hs : measurable_set s) (hμs : μ s ≠ ∞) (x : F) :
indicator_const_Lp 2 hs hμs x =
(continuous_linear_map.to_span_singleton ℝ x).comp_Lp (indicator_const_Lp 2 hs hμs (1 : ℝ)) :=
begin
ext1,
refine indicator_const_Lp_coe_fn.trans _,
have h_comp_Lp := (continuous_linear_map.to_span_singleton ℝ x).coe_fn_comp_Lp
(indicator_const_Lp 2 hs hμs (1 : ℝ)),
rw ← eventually_eq at h_comp_Lp,
refine eventually_eq.trans _ h_comp_Lp.symm,
refine (@indicator_const_Lp_coe_fn _ _ _ 2 μ _ _ s hs hμs (1 : ℝ) _ _).mono (λ y hy, _),
dsimp only,
rw hy,
simp_rw [continuous_linear_map.to_span_singleton_apply],
by_cases hy_mem : y ∈ s; simp [hy_mem, continuous_linear_map.lsmul_apply],
end
namespace Lp
section pos_part
lemma lipschitz_with_pos_part : lipschitz_with 1 (λ (x : ℝ), max x 0) :=
lipschitz_with.of_dist_le_mul $ λ x y, by simp [dist, abs_max_sub_max_le_abs]
/-- Positive part of a function in `L^p`. -/
def pos_part (f : Lp ℝ p μ) : Lp ℝ p μ :=
lipschitz_with_pos_part.comp_Lp (max_eq_right (le_refl _)) f
/-- Negative part of a function in `L^p`. -/
def neg_part (f : Lp ℝ p μ) : Lp ℝ p μ := pos_part (-f)
@[norm_cast]
lemma coe_pos_part (f : Lp ℝ p μ) : (pos_part f : α →ₘ[μ] ℝ) = (f : α →ₘ[μ] ℝ).pos_part := rfl
lemma coe_fn_pos_part (f : Lp ℝ p μ) : ⇑(pos_part f) =ᵐ[μ] λ a, max (f a) 0 :=
ae_eq_fun.coe_fn_pos_part _
lemma coe_fn_neg_part_eq_max (f : Lp ℝ p μ) : ∀ᵐ a ∂μ, neg_part f a = max (- f a) 0 :=
begin
rw neg_part,
filter_upwards [coe_fn_pos_part (-f), coe_fn_neg f],
assume a h₁ h₂,
rw [h₁, h₂, pi.neg_apply]
end
lemma coe_fn_neg_part (f : Lp ℝ p μ) : ∀ᵐ a ∂μ, neg_part f a = - min (f a) 0 :=
(coe_fn_neg_part_eq_max f).mono $ assume a h,
by rw [h, ← max_neg_neg, neg_zero]
lemma continuous_pos_part [fact (1 ≤ p)] : continuous (λf : Lp ℝ p μ, pos_part f) :=
lipschitz_with.continuous_comp_Lp _ _
lemma continuous_neg_part [fact (1 ≤ p)] : continuous (λf : Lp ℝ p μ, neg_part f) :=
have eq : (λf : Lp ℝ p μ, neg_part f) = (λf : Lp ℝ p μ, pos_part (-f)) := rfl,
by { rw eq, exact continuous_pos_part.comp continuous_neg }
end pos_part
end Lp
end measure_theory
end composition
/-!
## `L^p` is a complete space
We show that `L^p` is a complete space for `1 ≤ p`.
-/
section complete_space
variables [borel_space E] [second_countable_topology E]
namespace measure_theory
namespace Lp
lemma snorm'_lim_eq_lintegral_liminf {ι} [nonempty ι] [linear_order ι] {f : ι → α → G} {p : ℝ}
(hp_nonneg : 0 ≤ p) {f_lim : α → G}
(h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) :
snorm' f_lim p μ = (∫⁻ a, at_top.liminf (λ m, (nnnorm (f m a) : ℝ≥0∞)^p) ∂μ) ^ (1/p) :=
begin
suffices h_no_pow : (∫⁻ a, (nnnorm (f_lim a)) ^ p ∂μ)
= (∫⁻ a, at_top.liminf (λ m, (nnnorm (f m a) : ℝ≥0∞)^p) ∂μ),
{ rw [snorm', h_no_pow], },
refine lintegral_congr_ae (h_lim.mono (λ a ha, _)),
rw tendsto.liminf_eq,
simp_rw [ennreal.coe_rpow_of_nonneg _ hp_nonneg, ennreal.tendsto_coe],
refine ((nnreal.continuous_rpow_const hp_nonneg).tendsto (nnnorm (f_lim a))).comp _,
exact (continuous_nnnorm.tendsto (f_lim a)).comp ha,
end
lemma snorm'_lim_le_liminf_snorm' {E} [measurable_space E]
[normed_group E] [borel_space E] {f : ℕ → α → E} {p : ℝ} (hp_pos : 0 < p)
(hf : ∀ n, ae_measurable (f n) μ) {f_lim : α → E}
(h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) :
snorm' f_lim p μ ≤ at_top.liminf (λ n, snorm' (f n) p μ) :=
begin
rw snorm'_lim_eq_lintegral_liminf hp_pos.le h_lim,
rw [←ennreal.le_rpow_one_div_iff (by simp [hp_pos] : 0 < 1 / p), one_div_one_div],
refine (lintegral_liminf_le' (λ m, ((hf m).ennnorm.pow_const _))).trans_eq _,
have h_pow_liminf : at_top.liminf (λ n, snorm' (f n) p μ) ^ p
= at_top.liminf (λ n, (snorm' (f n) p μ) ^ p),
{ have h_rpow_mono := ennreal.rpow_left_strict_mono_of_pos hp_pos,
have h_rpow_surj := (ennreal.rpow_left_bijective hp_pos.ne.symm).2,
refine (h_rpow_mono.order_iso_of_surjective _ h_rpow_surj).liminf_apply _ _ _ _,
all_goals { is_bounded_default }, },
rw h_pow_liminf,
simp_rw [snorm', ← ennreal.rpow_mul, one_div, inv_mul_cancel hp_pos.ne.symm, ennreal.rpow_one],
end
lemma snorm_exponent_top_lim_eq_ess_sup_liminf {ι} [nonempty ι] [linear_order ι] {f : ι → α → G}
{f_lim : α → G}
(h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) :
snorm f_lim ∞ μ = ess_sup (λ x, at_top.liminf (λ m, (nnnorm (f m x) : ℝ≥0∞))) μ :=
begin
rw [snorm_exponent_top, snorm_ess_sup],
refine ess_sup_congr_ae (h_lim.mono (λ x hx, _)),
rw tendsto.liminf_eq,
rw ennreal.tendsto_coe,
exact (continuous_nnnorm.tendsto (f_lim x)).comp hx,
end
lemma snorm_exponent_top_lim_le_liminf_snorm_exponent_top {ι} [nonempty ι] [encodable ι]
[linear_order ι] {f : ι → α → F} {f_lim : α → F}
(h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) :
snorm f_lim ∞ μ ≤ at_top.liminf (λ n, snorm (f n) ∞ μ) :=
begin
rw snorm_exponent_top_lim_eq_ess_sup_liminf h_lim,
simp_rw [snorm_exponent_top, snorm_ess_sup],
exact ennreal.ess_sup_liminf_le (λ n, (λ x, (nnnorm (f n x) : ℝ≥0∞))),
end
lemma snorm_lim_le_liminf_snorm {E} [measurable_space E] [normed_group E] [borel_space E]
{f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) (f_lim : α → E)
(h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) :
snorm f_lim p μ ≤ at_top.liminf (λ n, snorm (f n) p μ) :=
begin
by_cases hp0 : p = 0,
{ simp [hp0], },
rw ← ne.def at hp0,
by_cases hp_top : p = ∞,
{ simp_rw [hp_top],
exact snorm_exponent_top_lim_le_liminf_snorm_exponent_top h_lim, },
simp_rw snorm_eq_snorm' hp0 hp_top,
have hp_pos : 0 < p.to_real,
from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩,
exact snorm'_lim_le_liminf_snorm' hp_pos hf h_lim,
end
/-! ### `Lp` is complete iff Cauchy sequences of `ℒp` have limits in `ℒp` -/
lemma tendsto_Lp_iff_tendsto_ℒp' {ι} {fi : filter ι} [fact (1 ≤ p)]
(f : ι → Lp E p μ) (f_lim : Lp E p μ) :
fi.tendsto f (𝓝 f_lim) ↔ fi.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) :=
begin
rw tendsto_iff_dist_tendsto_zero,
simp_rw dist_def,
rw [← ennreal.zero_to_real, ennreal.tendsto_to_real_iff (λ n, _) ennreal.zero_ne_top],
rw snorm_congr_ae (Lp.coe_fn_sub _ _).symm,
exact Lp.snorm_ne_top _,
end
lemma tendsto_Lp_iff_tendsto_ℒp {ι} {fi : filter ι} [fact (1 ≤ p)]
(f : ι → Lp E p μ) (f_lim : α → E) (f_lim_ℒp : mem_ℒp f_lim p μ) :
fi.tendsto f (𝓝 (f_lim_ℒp.to_Lp f_lim)) ↔ fi.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) :=
begin
rw tendsto_Lp_iff_tendsto_ℒp',
suffices h_eq : (λ n, snorm (f n - mem_ℒp.to_Lp f_lim f_lim_ℒp) p μ)
= (λ n, snorm (f n - f_lim) p μ),
by rw h_eq,
exact funext (λ n, snorm_congr_ae (eventually_eq.rfl.sub (mem_ℒp.coe_fn_to_Lp f_lim_ℒp))),
end
lemma tendsto_Lp_iff_tendsto_ℒp'' {ι} {fi : filter ι} [fact (1 ≤ p)]
(f : ι → α → E) (f_ℒp : ∀ n, mem_ℒp (f n) p μ) (f_lim : α → E) (f_lim_ℒp : mem_ℒp f_lim p μ) :
fi.tendsto (λ n, (f_ℒp n).to_Lp (f n)) (𝓝 (f_lim_ℒp.to_Lp f_lim))
↔ fi.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) :=
begin
convert Lp.tendsto_Lp_iff_tendsto_ℒp' _ _,
ext1 n,
apply snorm_congr_ae,
filter_upwards [((f_ℒp n).sub f_lim_ℒp).coe_fn_to_Lp,
Lp.coe_fn_sub ((f_ℒp n).to_Lp (f n)) (f_lim_ℒp.to_Lp f_lim)],
intros x hx₁ hx₂,
rw ← hx₂,
exact hx₁.symm
end
lemma tendsto_Lp_of_tendsto_ℒp {ι} {fi : filter ι} [hp : fact (1 ≤ p)]
{f : ι → Lp E p μ} (f_lim : α → E) (f_lim_ℒp : mem_ℒp f_lim p μ)
(h_tendsto : fi.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0)) :
fi.tendsto f (𝓝 (f_lim_ℒp.to_Lp f_lim)) :=
(tendsto_Lp_iff_tendsto_ℒp f f_lim f_lim_ℒp).mpr h_tendsto
lemma cauchy_seq_Lp_iff_cauchy_seq_ℒp {ι} [nonempty ι] [semilattice_sup ι] [hp : fact (1 ≤ p)]
(f : ι → Lp E p μ) :
cauchy_seq f ↔ tendsto (λ (n : ι × ι), snorm (f n.fst - f n.snd) p μ) at_top (𝓝 0) :=
begin
simp_rw [cauchy_seq_iff_tendsto_dist_at_top_0, dist_def],
rw [← ennreal.zero_to_real, ennreal.tendsto_to_real_iff (λ n, _) ennreal.zero_ne_top],
rw snorm_congr_ae (Lp.coe_fn_sub _ _).symm,
exact snorm_ne_top _,
end
lemma complete_space_Lp_of_cauchy_complete_ℒp [hp : fact (1 ≤ p)]
(H : ∀ (f : ℕ → α → E) (hf : ∀ n, mem_ℒp (f n) p μ) (B : ℕ → ℝ≥0∞) (hB : ∑' i, B i < ∞)
(h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N),
∃ (f_lim : α → E) (hf_lim_meas : mem_ℒp f_lim p μ),
at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0)) :
complete_space (Lp E p μ) :=
begin
let B := λ n : ℕ, ((1:ℝ) / 2) ^ n,
have hB_pos : ∀ n, 0 < B n, from λ n, pow_pos (div_pos zero_lt_one zero_lt_two) n,
refine metric.complete_of_convergent_controlled_sequences B hB_pos (λ f hf, _),
suffices h_limit : ∃ (f_lim : α → E) (hf_lim_meas : mem_ℒp f_lim p μ),
at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0),
{ rcases h_limit with ⟨f_lim, hf_lim_meas, h_tendsto⟩,
exact ⟨hf_lim_meas.to_Lp f_lim, tendsto_Lp_of_tendsto_ℒp f_lim hf_lim_meas h_tendsto⟩, },
have hB : summable B, from summable_geometric_two,
cases hB with M hB,
let B1 := λ n, ennreal.of_real (B n),
have hB1_has : has_sum B1 (ennreal.of_real M),
{ have h_tsum_B1 : ∑' i, B1 i = (ennreal.of_real M),
{ change (∑' (n : ℕ), ennreal.of_real (B n)) = ennreal.of_real M,
rw ←hB.tsum_eq,
exact (ennreal.of_real_tsum_of_nonneg (λ n, le_of_lt (hB_pos n)) hB.summable).symm, },
have h_sum := (@ennreal.summable _ B1).has_sum,
rwa h_tsum_B1 at h_sum, },
have hB1 : ∑' i, B1 i < ∞, by {rw hB1_has.tsum_eq, exact ennreal.of_real_lt_top, },
let f1 : ℕ → α → E := λ n, f n,
refine H f1 (λ n, Lp.mem_ℒp (f n)) B1 hB1 (λ N n m hn hm, _),
specialize hf N n m hn hm,
rw dist_def at hf,
simp_rw [f1, B1],
rwa ennreal.lt_of_real_iff_to_real_lt,
rw snorm_congr_ae (Lp.coe_fn_sub _ _).symm,
exact Lp.snorm_ne_top _,
end
/-! ### Prove that controlled Cauchy sequences of `ℒp` have limits in `ℒp` -/
private lemma snorm'_sum_norm_sub_le_tsum_of_cauchy_snorm' {f : ℕ → α → E}
(hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p)
{B : ℕ → ℝ≥0∞} (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm' (f n - f m) p μ < B N) (n : ℕ) :
snorm' (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) p μ ≤ ∑' i, B i :=
begin
let f_norm_diff := λ i x, norm (f (i + 1) x - f i x),
have hgf_norm_diff : ∀ n, (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x))
= ∑ i in finset.range (n + 1), f_norm_diff i,
from λ n, funext (λ x, by simp [f_norm_diff]),
rw hgf_norm_diff,
refine (snorm'_sum_le (λ i _, ((hf (i+1)).sub (hf i)).norm) hp1).trans _,
simp_rw [←pi.sub_apply, snorm'_norm],
refine (finset.sum_le_sum _).trans (sum_le_tsum _ (λ m _, zero_le _) ennreal.summable),
exact λ m _, (h_cau m (m + 1) m (nat.le_succ m) (le_refl m)).le,
end
private lemma lintegral_rpow_sum_coe_nnnorm_sub_le_rpow_tsum {f : ℕ → α → E}
(hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (n : ℕ)
(hn : snorm' (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) p μ ≤ ∑' i, B i) :
∫⁻ a, (∑ i in finset.range (n + 1), nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ
≤ (∑' i, B i) ^ p :=
begin
have hp_pos : 0 < p := zero_lt_one.trans_le hp1,
rw [←one_div_one_div p, @ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [hp_pos]),
one_div_one_div p],
simp_rw snorm' at hn,
have h_nnnorm_nonneg :
(λ a, (nnnorm (∑ i in finset.range (n + 1), ∥f (i + 1) a - f i a∥) : ℝ≥0∞) ^ p)
= λ a, (∑ i in finset.range (n + 1), (nnnorm(f (i + 1) a - f i a) : ℝ≥0∞)) ^ p,
{ ext1 a,
congr,
simp_rw ←of_real_norm_eq_coe_nnnorm,
rw ←ennreal.of_real_sum_of_nonneg,
{ rw real.norm_of_nonneg _,
exact finset.sum_nonneg (λ x hx, norm_nonneg _), },
{ exact λ x hx, norm_nonneg _, }, },
change (∫⁻ a, (λ x, ↑(nnnorm (∑ i in finset.range (n + 1), ∥f (i+1) x - f i x∥))^p) a ∂μ)^(1/p)
≤ ∑' i, B i at hn,
rwa h_nnnorm_nonneg at hn,
end
private lemma lintegral_rpow_tsum_coe_nnnorm_sub_le_tsum {f : ℕ → α → E}
(hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞}
(h : ∀ n, ∫⁻ a, (∑ i in finset.range (n + 1), nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ
≤ (∑' i, B i) ^ p) :
(∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ) ^ (1/p) ≤ ∑' i, B i :=
begin
have hp_pos : 0 < p := zero_lt_one.trans_le hp1,
suffices h_pow : ∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ ≤ (∑' i, B i) ^ p,
by rwa [←ennreal.le_rpow_one_div_iff (by simp [hp_pos] : 0 < 1 / p), one_div_one_div],
have h_tsum_1 : ∀ g : ℕ → ℝ≥0∞,
∑' i, g i = at_top.liminf (λ n, ∑ i in finset.range (n + 1), g i),
by { intro g, rw [ennreal.tsum_eq_liminf_sum_nat, ← liminf_nat_add _ 1], },
simp_rw h_tsum_1 _,
rw ← h_tsum_1,
have h_liminf_pow : ∫⁻ a, at_top.liminf (λ n, ∑ i in finset.range (n + 1),
(nnnorm (f (i + 1) a - f i a)))^p ∂μ
= ∫⁻ a, at_top.liminf (λ n, (∑ i in finset.range (n + 1), (nnnorm (f (i + 1) a - f i a)))^p) ∂μ,
{ refine lintegral_congr (λ x, _),
have h_rpow_mono := ennreal.rpow_left_strict_mono_of_pos (zero_lt_one.trans_le hp1),
have h_rpow_surj := (ennreal.rpow_left_bijective hp_pos.ne.symm).2,
refine (h_rpow_mono.order_iso_of_surjective _ h_rpow_surj).liminf_apply _ _ _ _,
all_goals { is_bounded_default }, },
rw h_liminf_pow,
refine (lintegral_liminf_le' _).trans _,
{ exact λ n, (finset.ae_measurable_sum (finset.range (n+1))
(λ i _, ((hf (i+1)).sub (hf i)).ennnorm)).pow_const _, },
{ exact liminf_le_of_frequently_le' (frequently_of_forall h), },
end
private lemma tsum_nnnorm_sub_ae_lt_top
{f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞}
(hB : ∑' i, B i ≠ ∞)
(h : (∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ) ^ (1/p) ≤ ∑' i, B i) :
∀ᵐ x ∂μ, (∑' i, nnnorm (f (i + 1) x - f i x) : ℝ≥0∞) < ∞ :=
begin
have hp_pos : 0 < p := zero_lt_one.trans_le hp1,
have h_integral : ∫⁻ a, (∑' i, ∥f (i + 1) a - f i a∥₊ : ℝ≥0∞)^p ∂μ < ∞,
{ have h_tsum_lt_top : (∑' i, B i) ^ p < ∞,
from ennreal.rpow_lt_top_of_nonneg hp_pos.le hB,
refine lt_of_le_of_lt _ h_tsum_lt_top,
rwa [←ennreal.le_rpow_one_div_iff (by simp [hp_pos] : 0 < 1 / p), one_div_one_div] at h, },
have rpow_ae_lt_top : ∀ᵐ x ∂μ, (∑' i, nnnorm (f (i + 1) x - f i x) : ℝ≥0∞)^p < ∞,
{ refine ae_lt_top' (ae_measurable.pow_const _ _) h_integral.ne,
exact ae_measurable.ennreal_tsum (λ n, ((hf (n+1)).sub (hf n)).ennnorm), },
refine rpow_ae_lt_top.mono (λ x hx, _),
rwa [←ennreal.lt_rpow_one_div_iff hp_pos,
ennreal.top_rpow_of_pos (by simp [hp_pos] : 0 < 1 / p)] at hx,
end
lemma ae_tendsto_of_cauchy_snorm' [complete_space E] {f : ℕ → α → E} {p : ℝ}
(hf : ∀ n, ae_measurable (f n) μ) (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i ≠ ∞)
(h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm' (f n - f m) p μ < B N) :
∀ᵐ x ∂μ, ∃ l : E, at_top.tendsto (λ n, f n x) (𝓝 l) :=
begin
have h_summable : ∀ᵐ x ∂μ, summable (λ (i : ℕ), f (i + 1) x - f i x),
{ have h1 : ∀ n, snorm' (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) p μ
≤ ∑' i, B i,
from snorm'_sum_norm_sub_le_tsum_of_cauchy_snorm' hf hp1 h_cau,
have h2 : ∀ n, ∫⁻ a, (∑ i in finset.range (n + 1), nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ
≤ (∑' i, B i) ^ p,
from λ n, lintegral_rpow_sum_coe_nnnorm_sub_le_rpow_tsum hf hp1 n (h1 n),
have h3 : (∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ) ^ (1/p) ≤ ∑' i, B i,
from lintegral_rpow_tsum_coe_nnnorm_sub_le_tsum hf hp1 h2,
have h4 : ∀ᵐ x ∂μ, (∑' i, nnnorm (f (i + 1) x - f i x) : ℝ≥0∞) < ∞,
from tsum_nnnorm_sub_ae_lt_top hf hp1 hB h3,
exact h4.mono (λ x hx, summable_of_summable_nnnorm
(ennreal.tsum_coe_ne_top_iff_summable.mp (lt_top_iff_ne_top.mp hx))), },
have h : ∀ᵐ x ∂μ, ∃ l : E,
at_top.tendsto (λ n, ∑ i in finset.range n, (f (i + 1) x - f i x)) (𝓝 l),
{ refine h_summable.mono (λ x hx, _),
let hx_sum := hx.has_sum.tendsto_sum_nat,
exact ⟨∑' i, (f (i + 1) x - f i x), hx_sum⟩, },
refine h.mono (λ x hx, _),
cases hx with l hx,
have h_rw_sum : (λ n, ∑ i in finset.range n, (f (i + 1) x - f i x)) = λ n, f n x - f 0 x,
{ ext1 n,
change ∑ (i : ℕ) in finset.range n, ((λ m, f m x) (i + 1) - (λ m, f m x) i) = f n x - f 0 x,
rw finset.sum_range_sub, },
rw h_rw_sum at hx,
have hf_rw : (λ n, f n x) = λ n, f n x - f 0 x + f 0 x, by { ext1 n, abel, },
rw hf_rw,
exact ⟨l + f 0 x, tendsto.add_const _ hx⟩,
end
lemma ae_tendsto_of_cauchy_snorm [complete_space E] {f : ℕ → α → E}
(hf : ∀ n, ae_measurable (f n) μ) (hp : 1 ≤ p) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i ≠ ∞)
(h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N) :
∀ᵐ x ∂μ, ∃ l : E, at_top.tendsto (λ n, f n x) (𝓝 l) :=
begin
by_cases hp_top : p = ∞,
{ simp_rw [hp_top] at *,
have h_cau_ae : ∀ᵐ x ∂μ, ∀ N n m, N ≤ n → N ≤ m → (nnnorm ((f n - f m) x) : ℝ≥0∞) < B N,
{ simp_rw [ae_all_iff, ae_imp_iff],
exact λ N n m hnN hmN, ae_lt_of_ess_sup_lt (h_cau N n m hnN hmN), },
simp_rw [snorm_exponent_top, snorm_ess_sup] at h_cau,
refine h_cau_ae.mono (λ x hx, cauchy_seq_tendsto_of_complete _),
refine cauchy_seq_of_le_tendsto_0 (λ n, (B n).to_real) _ _,
{ intros n m N hnN hmN,
specialize hx N n m hnN hmN,
rw [dist_eq_norm, ←ennreal.to_real_of_real (norm_nonneg _),
ennreal.to_real_le_to_real ennreal.of_real_ne_top
(ennreal.ne_top_of_tsum_ne_top hB N)],
rw ←of_real_norm_eq_coe_nnnorm at hx,
exact hx.le, },
{ rw ← ennreal.zero_to_real,
exact tendsto.comp (ennreal.tendsto_to_real ennreal.zero_ne_top)
(ennreal.tendsto_at_top_zero_of_tsum_ne_top hB), }, },
have hp1 : 1 ≤ p.to_real,
{ rw [← ennreal.of_real_le_iff_le_to_real hp_top, ennreal.of_real_one],
exact hp, },
have h_cau' : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm' (f n - f m) (p.to_real) μ < B N,
{ intros N n m hn hm,
specialize h_cau N n m hn hm,
rwa snorm_eq_snorm' (ennreal.zero_lt_one.trans_le hp).ne.symm hp_top at h_cau, },
exact ae_tendsto_of_cauchy_snorm' hf hp1 hB h_cau',
end
lemma cauchy_tendsto_of_tendsto {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ)
(f_lim : α → E) {B : ℕ → ℝ≥0∞}
(hB : ∑' i, B i ≠ ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N)
(h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) :
at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) :=
begin
rw ennreal.tendsto_at_top_zero,
intros ε hε,
have h_B : ∃ (N : ℕ), B N ≤ ε,
{ suffices h_tendsto_zero : ∃ (N : ℕ), ∀ n : ℕ, N ≤ n → B n ≤ ε,
from ⟨h_tendsto_zero.some, h_tendsto_zero.some_spec _ (le_refl _)⟩,
exact (ennreal.tendsto_at_top_zero.mp (ennreal.tendsto_at_top_zero_of_tsum_ne_top hB))
ε hε, },
cases h_B with N h_B,
refine ⟨N, λ n hn, _⟩,
have h_sub : snorm (f n - f_lim) p μ ≤ at_top.liminf (λ m, snorm (f n - f m) p μ),
{ refine snorm_lim_le_liminf_snorm (λ m, (hf n).sub (hf m)) (f n - f_lim) _,
refine h_lim.mono (λ x hx, _),
simp_rw sub_eq_add_neg,
exact tendsto.add tendsto_const_nhds (tendsto.neg hx), },
refine h_sub.trans _,
refine liminf_le_of_frequently_le' (frequently_at_top.mpr _),
refine λ N1, ⟨max N N1, le_max_right _ _, _⟩,
exact (h_cau N n (max N N1) hn (le_max_left _ _)).le.trans h_B,
end
lemma mem_ℒp_of_cauchy_tendsto (hp : 1 ≤ p) {f : ℕ → α → E} (hf : ∀ n, mem_ℒp (f n) p μ)
(f_lim : α → E) (h_lim_meas : ae_measurable f_lim μ)
(h_tendsto : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0)) :
mem_ℒp f_lim p μ :=
begin
refine ⟨h_lim_meas, _⟩,
rw ennreal.tendsto_at_top_zero at h_tendsto,
cases (h_tendsto 1 ennreal.zero_lt_one) with N h_tendsto_1,
specialize h_tendsto_1 N (le_refl N),
have h_add : f_lim = f_lim - f N + f N, by abel,
rw h_add,
refine lt_of_le_of_lt (snorm_add_le (h_lim_meas.sub (hf N).1) (hf N).1 hp) _,
rw ennreal.add_lt_top,
split,
{ refine lt_of_le_of_lt _ ennreal.one_lt_top,
have h_neg : f_lim - f N = -(f N - f_lim), by simp,
rwa [h_neg, snorm_neg], },
{ exact (hf N).2, },
end
lemma cauchy_complete_ℒp [complete_space E] (hp : 1 ≤ p)
{f : ℕ → α → E} (hf : ∀ n, mem_ℒp (f n) p μ) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i ≠ ∞)
(h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N) :
∃ (f_lim : α → E) (hf_lim_meas : mem_ℒp f_lim p μ),
at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) :=
begin
obtain ⟨f_lim, h_f_lim_meas, h_lim⟩ : ∃ (f_lim : α → E) (hf_lim_meas : measurable f_lim),
∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (nhds (f_lim x)),
from measurable_limit_of_tendsto_metric_ae (λ n, (hf n).1)
(ae_tendsto_of_cauchy_snorm (λ n, (hf n).1) hp hB h_cau),
have h_tendsto' : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0),
from cauchy_tendsto_of_tendsto (λ m, (hf m).1) f_lim hB h_cau h_lim,
have h_ℒp_lim : mem_ℒp f_lim p μ,
from mem_ℒp_of_cauchy_tendsto hp hf f_lim h_f_lim_meas.ae_measurable h_tendsto',
exact ⟨f_lim, h_ℒp_lim, h_tendsto'⟩,
end
/-! ### `Lp` is complete for `1 ≤ p` -/
instance [complete_space E] [hp : fact (1 ≤ p)] : complete_space (Lp E p μ) :=
complete_space_Lp_of_cauchy_complete_ℒp $
λ f hf B hB h_cau, cauchy_complete_ℒp hp.elim hf hB.ne h_cau
end Lp
end measure_theory
end complete_space
/-! ### Continuous functions in `Lp` -/
open_locale bounded_continuous_function
open bounded_continuous_function
variables [borel_space E] [second_countable_topology E] [topological_space α] [borel_space α]
variables (E p μ)
/-- An additive subgroup of `Lp E p μ`, consisting of the equivalence classes which contain a
bounded continuous representative. -/
def measure_theory.Lp.bounded_continuous_function : add_subgroup (Lp E p μ) :=
add_subgroup.add_subgroup_of
((continuous_map.to_ae_eq_fun_add_hom μ).comp (forget_boundedness_add_hom α E)).range
(Lp E p μ)
variables {E p μ}
/-- By definition, the elements of `Lp.bounded_continuous_function E p μ` are the elements of
`Lp E p μ` which contain a bounded continuous representative. -/
lemma measure_theory.Lp.mem_bounded_continuous_function_iff {f : (Lp E p μ)} :
f ∈ measure_theory.Lp.bounded_continuous_function E p μ
↔ ∃ f₀ : (α →ᵇ E), f₀.to_continuous_map.to_ae_eq_fun μ = (f : α →ₘ[μ] E) :=
add_subgroup.mem_add_subgroup_of
namespace bounded_continuous_function
variables [is_finite_measure μ]
/-- A bounded continuous function on a finite-measure space is in `Lp`. -/
lemma mem_Lp (f : α →ᵇ E) :
f.to_continuous_map.to_ae_eq_fun μ ∈ Lp E p μ :=
begin
refine Lp.mem_Lp_of_ae_bound (∥f∥) _,
filter_upwards [f.to_continuous_map.coe_fn_to_ae_eq_fun μ],
intros x hx,
convert f.norm_coe_le_norm x
end
/-- The `Lp`-norm of a bounded continuous function is at most a constant (depending on the measure
of the whole space) times its sup-norm. -/
lemma Lp_norm_le (f : α →ᵇ E) :
∥(⟨f.to_continuous_map.to_ae_eq_fun μ, mem_Lp f⟩ : Lp E p μ)∥
≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ * ∥f∥ :=
begin
apply Lp.norm_le_of_ae_bound (norm_nonneg f),
{ refine (f.to_continuous_map.coe_fn_to_ae_eq_fun μ).mono _,
intros x hx,
convert f.norm_coe_le_norm x },
{ apply_instance }
end
variables (p μ)
/-- The normed group homomorphism of considering a bounded continuous function on a finite-measure
space as an element of `Lp`. -/
def to_Lp_hom [fact (1 ≤ p)] : normed_group_hom (α →ᵇ E) (Lp E p μ) :=
{ bound' := ⟨_, Lp_norm_le⟩,
.. add_monoid_hom.cod_restrict
((continuous_map.to_ae_eq_fun_add_hom μ).comp (forget_boundedness_add_hom α E))
(Lp E p μ)
mem_Lp }
lemma range_to_Lp_hom [fact (1 ≤ p)] :
((to_Lp_hom p μ).range : add_subgroup (Lp E p μ))
= measure_theory.Lp.bounded_continuous_function E p μ :=
begin
symmetry,
convert add_monoid_hom.add_subgroup_of_range_eq_of_le
((continuous_map.to_ae_eq_fun_add_hom μ).comp (forget_boundedness_add_hom α E))
(by { rintros - ⟨f, rfl⟩, exact mem_Lp f } : _ ≤ Lp E p μ),
end
variables (𝕜 : Type*) [measurable_space 𝕜]
/-- The bounded linear map of considering a bounded continuous function on a finite-measure space
as an element of `Lp`. -/
def to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] [fact (1 ≤ p)] :
(α →ᵇ E) →L[𝕜] (Lp E p μ) :=
linear_map.mk_continuous
(linear_map.cod_restrict
(Lp.Lp_submodule E p μ 𝕜)
((continuous_map.to_ae_eq_fun_linear_map μ).comp (forget_boundedness_linear_map α E 𝕜))
mem_Lp)
_
Lp_norm_le
variables {𝕜}
lemma range_to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] [fact (1 ≤ p)] :
((to_Lp p μ 𝕜).range.to_add_subgroup : add_subgroup (Lp E p μ))
= measure_theory.Lp.bounded_continuous_function E p μ :=
range_to_Lp_hom p μ
variables {p}
lemma coe_fn_to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] [fact (1 ≤ p)]
(f : α →ᵇ E) :
to_Lp p μ 𝕜 f =ᵐ[μ] f :=
ae_eq_fun.coe_fn_mk f _
lemma to_Lp_norm_le [nondiscrete_normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E]
[fact (1 ≤ p)] :
∥(to_Lp p μ 𝕜 : (α →ᵇ E) →L[𝕜] (Lp E p μ))∥ ≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ :=
linear_map.mk_continuous_norm_le _ ((measure_univ_nnreal μ) ^ (p.to_real)⁻¹).coe_nonneg _
end bounded_continuous_function
namespace continuous_map
variables [compact_space α] [is_finite_measure μ]
variables (𝕜 : Type*) [measurable_space 𝕜] (p μ) [fact (1 ≤ p)]
/-- The bounded linear map of considering a continuous function on a compact finite-measure
space `α` as an element of `Lp`. By definition, the norm on `C(α, E)` is the sup-norm, transferred
from the space `α →ᵇ E` of bounded continuous functions, so this construction is just a matter of
transferring the structure from `bounded_continuous_function.to_Lp` along the isometry. -/
def to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] :
C(α, E) →L[𝕜] (Lp E p μ) :=
(bounded_continuous_function.to_Lp p μ 𝕜).comp
(linear_isometry_bounded_of_compact α E 𝕜).to_linear_isometry.to_continuous_linear_map
variables {𝕜}
lemma range_to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] :
((to_Lp p μ 𝕜).range.to_add_subgroup : add_subgroup (Lp E p μ))
= measure_theory.Lp.bounded_continuous_function E p μ :=
begin
refine set_like.ext' _,
have := (linear_isometry_bounded_of_compact α E 𝕜).surjective,
convert function.surjective.range_comp this (bounded_continuous_function.to_Lp p μ 𝕜),
rw ← bounded_continuous_function.range_to_Lp p μ,
refl,
end
variables {p}
lemma coe_fn_to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] (f : C(α, E)) :
to_Lp p μ 𝕜 f =ᵐ[μ] f :=
ae_eq_fun.coe_fn_mk f _
lemma to_Lp_def [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] (f : C(α, E)) :
to_Lp p μ 𝕜 f
= bounded_continuous_function.to_Lp p μ 𝕜 (linear_isometry_bounded_of_compact α E 𝕜 f) :=
rfl
@[simp] lemma to_Lp_comp_forget_boundedness [normed_field 𝕜] [opens_measurable_space 𝕜]
[normed_space 𝕜 E] (f : α →ᵇ E) :
to_Lp p μ 𝕜 (bounded_continuous_function.forget_boundedness α E f)
= bounded_continuous_function.to_Lp p μ 𝕜 f :=
rfl
@[simp] lemma coe_to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E]
(f : C(α, E)) :
(to_Lp p μ 𝕜 f : α →ₘ[μ] E) = f.to_ae_eq_fun μ :=
rfl
variables [nondiscrete_normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E]
lemma to_Lp_norm_eq_to_Lp_norm_coe :
∥(to_Lp p μ 𝕜 : C(α, E) →L[𝕜] (Lp E p μ))∥
= ∥(bounded_continuous_function.to_Lp p μ 𝕜 : (α →ᵇ E) →L[𝕜] (Lp E p μ))∥ :=
continuous_linear_map.op_norm_comp_linear_isometry_equiv _ _
/-- Bound for the operator norm of `continuous_map.to_Lp`. -/
lemma to_Lp_norm_le :
∥(to_Lp p μ 𝕜 : C(α, E) →L[𝕜] (Lp E p μ))∥ ≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ :=
by { rw to_Lp_norm_eq_to_Lp_norm_coe, exact bounded_continuous_function.to_Lp_norm_le μ }
end continuous_map
--(to_Lp p μ 𝕜 : (α →ᵇ E) →L[𝕜] (Lp E p μ))
|
e5487ba5b622b97b4a2cb6847891b9475b1781df | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/ring/default.lean | 9e07db37e3ae3fd2a0671e23d8fad0955de57e15 | [
"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 | 247 | lean | /-
Copyright (c) 2020 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import algebra.ring.basic
/-!
# Default file for ring
This file imports `algebra.ring.basic`
-/
|
40c9ca05cb2f812645e9416713a7ce4417e9ee8e | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/algebra/pointwise.lean | 7a447d925a9e4a2340350a272b7dcb167a44dfb3 | [
"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 | 15,620 | 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
/-!
# 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_semigroup]
instance [semigroup α] : semigroup (set α) :=
{ mul_assoc := λ _ _ _, image2_assoc mul_assoc,
..set.has_mul }
@[to_additive set.add_monoid]
instance [monoid α] : monoid (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.semigroup,
..set.has_one }
@[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
@[to_additive]
lemma mul_subset_mul [has_mul α] (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ * s₂ ⊆ t₁ * t₂ :=
image2_subset h₁ h₂
@[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
/-! ### Properties about inversion -/
@[to_additive set.has_neg'] -- todo: remove prime once name becomes available
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] }
/-! ### 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.semiring [monoid α] : semiring (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,
zero_mul := λ s, empty_mul,
mul_zero := λ s, mul_empty,
left_distrib := λ _ _ _, mul_union,
right_distrib := λ _ _ _, union_mul,
..set.monoid }
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
section
open set
variables {α : Type*} {β : Type*}
/-- A nonempty set in a semimodule is scaled by zero to the singleton
containing 0 in the semimodule. -/
lemma zero_smul_set [semiring α] [add_comm_monoid β] [semimodule α β] {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] }
end finset
|
8e6a6735dda005410025ad99009d761403f94786 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/set_theory/game/impartial.lean | c361208cf43b65a63a0054f35a14afdf10ab69cf | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 7,012 | lean | /-
Copyright (c) 2020 Fox Thomson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Fox Thomson
-/
import set_theory.game.basic
import tactic.nth_rewrite
/-!
# Basic definitions about impartial (pre-)games
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We will define an impartial game, one in which left and right can make exactly the same moves.
Our definition differs slightly by saying that the game is always equivalent to its negative,
no matter what moves are played. This allows for games such as poker-nim to be classifed as
impartial.
-/
universe u
open_locale pgame
namespace pgame
/-- The definition for a impartial game, defined using Conway induction. -/
def impartial_aux : pgame → Prop
| G := G ≈ -G ∧ (∀ i, impartial_aux (G.move_left i)) ∧ ∀ j, impartial_aux (G.move_right j)
using_well_founded { dec_tac := pgame_wf_tac }
lemma impartial_aux_def {G : pgame} : G.impartial_aux ↔ G ≈ -G ∧
(∀ i, impartial_aux (G.move_left i)) ∧ ∀ j, impartial_aux (G.move_right j) :=
by rw impartial_aux
/-- A typeclass on impartial games. -/
class impartial (G : pgame) : Prop := (out : impartial_aux G)
lemma impartial_iff_aux {G : pgame} : G.impartial ↔ G.impartial_aux :=
⟨λ h, h.1, λ h, ⟨h⟩⟩
lemma impartial_def {G : pgame} : G.impartial ↔ G ≈ -G ∧
(∀ i, impartial (G.move_left i)) ∧ ∀ j, impartial (G.move_right j) :=
by simpa only [impartial_iff_aux] using impartial_aux_def
namespace impartial
instance impartial_zero : impartial 0 :=
by { rw impartial_def, dsimp, simp }
instance impartial_star : impartial star :=
by { rw impartial_def, simpa using impartial.impartial_zero }
lemma neg_equiv_self (G : pgame) [h : G.impartial] : G ≈ -G := (impartial_def.1 h).1
@[simp] lemma mk_neg_equiv_self (G : pgame) [h : G.impartial] : -⟦G⟧ = ⟦G⟧ :=
quot.sound (neg_equiv_self G).symm
instance move_left_impartial {G : pgame} [h : G.impartial] (i : G.left_moves) :
(G.move_left i).impartial :=
(impartial_def.1 h).2.1 i
instance move_right_impartial {G : pgame} [h : G.impartial] (j : G.right_moves) :
(G.move_right j).impartial :=
(impartial_def.1 h).2.2 j
theorem impartial_congr : ∀ {G H : pgame} (e : G ≡r H) [G.impartial], H.impartial
| G H := λ e, begin
introI h,
exact impartial_def.2
⟨e.symm.equiv.trans ((neg_equiv_self G).trans (neg_equiv_neg_iff.2 e.equiv)),
λ i, impartial_congr (e.move_left_symm i), λ j, impartial_congr (e.move_right_symm j)⟩
end
using_well_founded { dec_tac := pgame_wf_tac }
instance impartial_add : ∀ (G H : pgame) [G.impartial] [H.impartial], (G + H).impartial
| G H :=
begin
introsI hG hH,
rw impartial_def,
refine ⟨(add_congr (neg_equiv_self _) (neg_equiv_self _)).trans
(neg_add_relabelling _ _).equiv.symm, λ k, _, λ k, _⟩,
{ apply left_moves_add_cases k,
all_goals
{ intro i, simp only [add_move_left_inl, add_move_left_inr],
apply impartial_add } },
{ apply right_moves_add_cases k,
all_goals
{ intro i, simp only [add_move_right_inl, add_move_right_inr],
apply impartial_add } }
end
using_well_founded { dec_tac := pgame_wf_tac }
instance impartial_neg : ∀ (G : pgame) [G.impartial], (-G).impartial
| G :=
begin
introI hG,
rw impartial_def,
refine ⟨_, λ i, _, λ i, _⟩,
{ rw neg_neg,
exact (neg_equiv_self G).symm },
{ rw move_left_neg',
apply impartial_neg },
{ rw move_right_neg',
apply impartial_neg }
end
using_well_founded { dec_tac := pgame_wf_tac }
variables (G : pgame) [impartial G]
lemma nonpos : ¬ 0 < G :=
λ h, begin
have h' := neg_lt_neg_iff.2 h,
rw [neg_zero, lt_congr_left (neg_equiv_self G).symm] at h',
exact (h.trans h').false
end
lemma nonneg : ¬ G < 0 :=
λ h, begin
have h' := neg_lt_neg_iff.2 h,
rw [neg_zero, lt_congr_right (neg_equiv_self G).symm] at h',
exact (h.trans h').false
end
/-- In an impartial game, either the first player always wins, or the second player always wins. -/
lemma equiv_or_fuzzy_zero : G ≈ 0 ∨ G ‖ 0 :=
begin
rcases lt_or_equiv_or_gt_or_fuzzy G 0 with h | h | h | h,
{ exact ((nonneg G) h).elim },
{ exact or.inl h },
{ exact ((nonpos G) h).elim },
{ exact or.inr h }
end
@[simp] lemma not_equiv_zero_iff : ¬ G ≈ 0 ↔ G ‖ 0 :=
⟨(equiv_or_fuzzy_zero G).resolve_left, fuzzy.not_equiv⟩
@[simp] lemma not_fuzzy_zero_iff : ¬ G ‖ 0 ↔ G ≈ 0 :=
⟨(equiv_or_fuzzy_zero G).resolve_right, equiv.not_fuzzy⟩
lemma add_self : G + G ≈ 0 :=
(add_congr_left (neg_equiv_self G)).trans (add_left_neg_equiv G)
@[simp] lemma mk_add_self : ⟦G⟧ + ⟦G⟧ = 0 := quot.sound (add_self G)
/-- This lemma doesn't require `H` to be impartial. -/
lemma equiv_iff_add_equiv_zero (H : pgame) : H ≈ G ↔ H + G ≈ 0 :=
by { rw [equiv_iff_game_eq, equiv_iff_game_eq, ←@add_right_cancel_iff _ _ _ (-⟦G⟧)], simpa }
/-- This lemma doesn't require `H` to be impartial. -/
lemma equiv_iff_add_equiv_zero' (H : pgame) : G ≈ H ↔ G + H ≈ 0 :=
by { rw [equiv_iff_game_eq, equiv_iff_game_eq, ←@add_left_cancel_iff _ _ _ (-⟦G⟧), eq_comm], simpa }
lemma le_zero_iff {G : pgame} [G.impartial] : G ≤ 0 ↔ 0 ≤ G :=
by rw [←zero_le_neg_iff, le_congr_right (neg_equiv_self G)]
lemma lf_zero_iff {G : pgame} [G.impartial] : G ⧏ 0 ↔ 0 ⧏ G :=
by rw [←zero_lf_neg_iff, lf_congr_right (neg_equiv_self G)]
lemma equiv_zero_iff_le: G ≈ 0 ↔ G ≤ 0 := ⟨and.left, λ h, ⟨h, le_zero_iff.1 h⟩⟩
lemma fuzzy_zero_iff_lf : G ‖ 0 ↔ G ⧏ 0 := ⟨and.left, λ h, ⟨h, lf_zero_iff.1 h⟩⟩
lemma equiv_zero_iff_ge : G ≈ 0 ↔ 0 ≤ G := ⟨and.right, λ h, ⟨le_zero_iff.2 h, h⟩⟩
lemma fuzzy_zero_iff_gf : G ‖ 0 ↔ 0 ⧏ G := ⟨and.right, λ h, ⟨lf_zero_iff.2 h, h⟩⟩
lemma forall_left_moves_fuzzy_iff_equiv_zero : (∀ i, G.move_left i ‖ 0) ↔ G ≈ 0 :=
begin
refine ⟨λ hb, _, λ hp i, _⟩,
{ rw [equiv_zero_iff_le G, le_zero_lf],
exact λ i, (hb i).1 },
{ rw fuzzy_zero_iff_lf,
exact hp.1.move_left_lf i }
end
lemma forall_right_moves_fuzzy_iff_equiv_zero : (∀ j, G.move_right j ‖ 0) ↔ G ≈ 0 :=
begin
refine ⟨λ hb, _, λ hp i, _⟩,
{ rw [equiv_zero_iff_ge G, zero_le_lf],
exact λ i, (hb i).2 },
{ rw fuzzy_zero_iff_gf,
exact hp.2.lf_move_right i }
end
lemma exists_left_move_equiv_iff_fuzzy_zero : (∃ i, G.move_left i ≈ 0) ↔ G ‖ 0 :=
begin
refine ⟨λ ⟨i, hi⟩, (fuzzy_zero_iff_gf G).2 (lf_of_le_move_left hi.2), λ hn, _⟩,
rw [fuzzy_zero_iff_gf G, zero_lf_le] at hn,
cases hn with i hi,
exact ⟨i, (equiv_zero_iff_ge _).2 hi⟩
end
lemma exists_right_move_equiv_iff_fuzzy_zero : (∃ j, G.move_right j ≈ 0) ↔ G ‖ 0 :=
begin
refine ⟨λ ⟨i, hi⟩, (fuzzy_zero_iff_lf G).2 (lf_of_move_right_le hi.1), λ hn, _⟩,
rw [fuzzy_zero_iff_lf G, lf_zero_le] at hn,
cases hn with i hi,
exact ⟨i, (equiv_zero_iff_le _).2 hi⟩
end
end impartial
end pgame
|
06112b1ec8e3bc926d8234114fb5b552fc3729fd | efa51dd2edbbbbd6c34bd0ce436415eb405832e7 | /20170116_POPL/assoc/flat_assoc_trace.lean | 5a4320d83477309dcae75a785ecbb6a6a8633ffa | [
"Apache-2.0"
] | permissive | leanprover/presentations | dd031a05bcb12c8855676c77e52ed84246bd889a | 3ce2d132d299409f1de269fa8e95afa1333d644e | refs/heads/master | 1,688,703,388,796 | 1,686,838,383,000 | 1,687,465,742,000 | 29,750,158 | 12 | 9 | Apache-2.0 | 1,540,211,670,000 | 1,422,042,683,000 | Lean | UTF-8 | Lean | false | false | 4,040 | lean | /-
In this file, we add tracing capabilities to
the flattening tactics we have defined at flat_assoc.lean.
-/
import data.set
open tactic expr
/- The command `declare_trace` add a new trace.flat_assoc option to Lean -/
declare_trace flat_assoc
/--
Return `some (a, b)` iff `e` is of the form `(op a b)`
-/
meta def is_bin_app (op : expr) : expr → option (expr × expr)
| (app (app fn a1) a2) := if op = fn then some (a1, a2) else none
| _ := none
/--
The tactic (flat_with op assoc lhs rhs) returns the flattening of (op lhs rhs) and
proof that the resulting term is equal to (op lhs rhs).
- `op` is a binary operator
- `assoc` is a proof that it is associative
The tactic may fail if `op` is not a binary operator, if `assoc` is not a proof that
`op` is associative.
-/
meta def flat_with (op : expr) (assoc : expr) : expr → expr → tactic (expr × expr)
| lhs rhs :=
/- The tactic (when_tracing id tac) executes the tactic `tac` if
the option trace.id is set to true.
-/
when_tracing `flat_assoc (do
/- The tactic (pp e) pretty-prints the given expression.
It returns the formatting object for `e`. It will
format it with respect to the local context and environment associated
with the main goal. -/
lhs_fmt ← pp lhs,
rhs_fmt ← pp rhs,
trace (to_fmt "flattening " ++ lhs_fmt ++ " with " ++ rhs_fmt))
>>
match is_bin_app op lhs with
| (some (lhs₁, lhs₂)) := do
(rhs₁, h₁) ← flat_with lhs₂ rhs,
(rhs₂, h₂) ← flat_with lhs₁ rhs₁,
h₃ ← return $ assoc lhs₁ lhs₂ rhs,
h₄ ← mk_app `congr_arg [op lhs₁, h₁],
h ← to_expr `(eq.trans %%h₃ (eq.trans %%h₄ %%h₂)),
return (rhs₂, h)
| none := do
new_rhs ← return (op lhs rhs),
h ← mk_app `eq.refl [new_rhs],
return (new_rhs, h)
end
/--
The tactic (flat_core op assoc e) returns the flattening of `e` with respect to the binary operator `op`,
and proof that the resulting term is equal to `e`
- `op` is a binary operator
- `assoc` is a proof that it is associative
-/
meta def flat_core (op : expr) (assoc : expr) : expr → tactic (expr × expr)
| e :=
match is_bin_app op e with
| (some (lhs, rhs)) := do
(new_rhs, h₁) ← flat_core rhs,
(new_app, h₂) ← flat_with op assoc lhs new_rhs,
h ← to_expr `(eq.trans (congr_arg %%(op lhs) %%h₁) %%h₂),
return (new_app, h)
| none :=
do pr ← mk_app `eq.refl [e],
return (e, pr)
end
/--
The tactic a_refl closes the current goal iff it is of the form (lhs = rhs),
and the flattening of lhs and rhs, with respect to op, is the same term. -/
meta def a_refl_core (op : expr) (assoc : expr) : tactic unit :=
do
t ← target,
when_tracing `flat_assoc (do
t_fmt ← pp t,
trace $ to_fmt ">> a_refl_core " ++ t_fmt),
(lhs, rhs) ← match_eq t,
when_tracing `flat_assoc (trace ">>> flattening lhs"),
(flat_lhs, h₁) ← flat_core op assoc lhs,
when_tracing `flat_assoc (trace ">>> flattening rhs"),
(flat_rhs, h₂) ← flat_core op assoc rhs,
guard (flat_lhs = flat_rhs),
to_expr `(eq.trans %%h₁ (eq.symm %%h₂)) >>= exact
meta def is_assoc_bin_app : expr → tactic (expr × expr)
| (app (app op a1) a2) := do h ← to_expr `(is_associative.assoc %%op), return (op, h)
| _ := failed
meta def a_refl : tactic unit :=
do (lhs, rhs) ← target >>= match_eq,
(op, assoc) ← is_assoc_bin_app lhs,
a_refl_core op assoc
/- We can enable/disable the tracing messages
using the set_option command.
Later, we demonstrate how to use the Lean debugger and VM monitor. -/
set_option trace.flat_assoc true
example (a b c d e f g : nat) : ((a + b) + c) + ((d + e) + (f + g)) = a + (b + (c + (d + (e + (f + g))))) :=
by a_refl
set_option trace.flat_assoc false
example (s₁ s₂ s₃ s₄ : set nat) : (s₁ ∪ s₂) ∪ (s₃ ∪ s₄) = s₁ ∪ (s₂ ∪ (s₃ ∪ s₄)) :=
by a_refl
|
7fa55f37891e63e4f41d3c7bcfa1cc28b0988d4b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/locally_convex/weak_dual.lean | 7a93c7c14106ec223f7284f766d471855cebdfa6 | [
"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 | 5,551 | 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 topology.algebra.module.weak_dual
import analysis.normed.field.basic
import analysis.locally_convex.with_seminorms
/-!
# Weak Dual in Topological Vector Spaces
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We prove that the weak topology induced by a bilinear form `B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜` is locally
convex and we explicit give a neighborhood basis in terms of the family of seminorms `λ x, ‖B x y‖`
for `y : F`.
## Main definitions
* `linear_map.to_seminorm`: turn a linear form `f : E →ₗ[𝕜] 𝕜` into a seminorm `λ x, ‖f x‖`.
* `linear_map.to_seminorm_family`: turn a bilinear form `B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜` into a map
`F → seminorm 𝕜 E`.
## Main statements
* `linear_map.has_basis_weak_bilin`: the seminorm balls of `B.to_seminorm_family` form a
neighborhood basis of `0` in the weak topology.
* `linear_map.to_seminorm_family.with_seminorms`: the topology of a weak space is induced by the
family of seminorm `B.to_seminorm_family`.
* `weak_bilin.locally_convex_space`: a spaced endowed with a weak topology is locally convex.
## References
* [Bourbaki, *Topological Vector Spaces*][bourbaki1987]
## Tags
weak dual, seminorm
-/
variables {𝕜 E F ι : Type*}
open_locale topology
section bilin_form
namespace linear_map
variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [add_comm_group F] [module 𝕜 F]
/-- Construct a seminorm from a linear form `f : E →ₗ[𝕜] 𝕜` over a normed field `𝕜` by
`λ x, ‖f x‖` -/
def to_seminorm (f : E →ₗ[𝕜] 𝕜) : seminorm 𝕜 E :=
(norm_seminorm 𝕜 𝕜).comp f
lemma coe_to_seminorm {f : E →ₗ[𝕜] 𝕜} :
⇑f.to_seminorm = λ x, ‖f x‖ := rfl
@[simp] lemma to_seminorm_apply {f : E →ₗ[𝕜] 𝕜} {x : E} :
f.to_seminorm x = ‖f x‖ := rfl
lemma to_seminorm_ball_zero {f : E →ₗ[𝕜] 𝕜} {r : ℝ} :
seminorm.ball f.to_seminorm 0 r = { x : E | ‖f x‖ < r} :=
by simp only [seminorm.ball_zero_eq, to_seminorm_apply]
lemma to_seminorm_comp (f : F →ₗ[𝕜] 𝕜) (g : E →ₗ[𝕜] F) :
f.to_seminorm.comp g = (f.comp g).to_seminorm :=
by { ext, simp only [seminorm.comp_apply, to_seminorm_apply, coe_comp] }
/-- Construct a family of seminorms from a bilinear form. -/
def to_seminorm_family (B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜) : seminorm_family 𝕜 E F :=
λ y, (B.flip y).to_seminorm
@[simp] lemma to_seminorm_family_apply {B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜} {x y} :
(B.to_seminorm_family y) x = ‖B x y‖ := rfl
end linear_map
end bilin_form
section topology
variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [add_comm_group F] [module 𝕜 F]
variables [nonempty ι]
variables {B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜}
lemma linear_map.has_basis_weak_bilin (B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜) :
(𝓝 (0 : weak_bilin B)).has_basis B.to_seminorm_family.basis_sets id :=
begin
let p := B.to_seminorm_family,
rw [nhds_induced, nhds_pi],
simp only [map_zero, linear_map.zero_apply],
have h := @metric.nhds_basis_ball 𝕜 _ 0,
have h' := filter.has_basis_pi (λ (i : F), h),
have h'' := filter.has_basis.comap (λ x y, B x y) h',
refine h''.to_has_basis _ _,
{ rintros (U : set F × (F → ℝ)) hU,
cases hU with hU₁ hU₂,
simp only [id.def],
let U' := hU₁.to_finset,
by_cases hU₃ : U.fst.nonempty,
{ have hU₃' : U'.nonempty := hU₁.to_finset_nonempty.mpr hU₃,
refine ⟨(U'.sup p).ball 0 $ U'.inf' hU₃' U.snd, p.basis_sets_mem _ $
(finset.lt_inf'_iff _).2 $ λ y hy, hU₂ y $ (hU₁.mem_to_finset).mp hy, λ x hx y hy, _⟩,
simp only [set.mem_preimage, set.mem_pi, mem_ball_zero_iff],
rw seminorm.mem_ball_zero at hx,
rw ←linear_map.to_seminorm_family_apply,
have hyU' : y ∈ U' := (set.finite.mem_to_finset hU₁).mpr hy,
have hp : p y ≤ U'.sup p := finset.le_sup hyU',
refine lt_of_le_of_lt (hp x) (lt_of_lt_of_le hx _),
exact finset.inf'_le _ hyU' },
rw set.not_nonempty_iff_eq_empty.mp hU₃,
simp only [set.empty_pi, set.preimage_univ, set.subset_univ, and_true],
exact Exists.intro ((p 0).ball 0 1) (p.basis_sets_singleton_mem 0 one_pos) },
rintros U (hU : U ∈ p.basis_sets),
rw seminorm_family.basis_sets_iff at hU,
rcases hU with ⟨s, r, hr, hU⟩,
rw hU,
refine ⟨(s, λ _, r), ⟨by simp only [s.finite_to_set], λ y hy, hr⟩, λ x hx, _⟩,
simp only [set.mem_preimage, set.mem_pi, finset.mem_coe, mem_ball_zero_iff] at hx,
simp only [id.def, seminorm.mem_ball, sub_zero],
refine seminorm.finset_sup_apply_lt hr (λ y hy, _),
rw linear_map.to_seminorm_family_apply,
exact hx y hy,
end
lemma linear_map.weak_bilin_with_seminorms (B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜) :
with_seminorms (linear_map.to_seminorm_family B : F → seminorm 𝕜 (weak_bilin B)) :=
seminorm_family.with_seminorms_of_has_basis _ B.has_basis_weak_bilin
end topology
section locally_convex
variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [add_comm_group F] [module 𝕜 F]
variables [nonempty ι] [normed_space ℝ 𝕜] [module ℝ E] [is_scalar_tower ℝ 𝕜 E]
instance {B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜} : locally_convex_space ℝ (weak_bilin B) :=
(B.weak_bilin_with_seminorms).to_locally_convex_space
end locally_convex
|
cfa2d8b0bec0a85567ee10d8dcfe577e874bffaa | 4f643cce24b2d005aeeb5004c2316a8d6cc7f3b1 | /old/unification_hints.lean | 423874f39da92bf268f4a6ba38029e55f5927da6 | [] | no_license | rwbarton/lean-omin | da209ed061d64db65a8f7f71f198064986f30eb9 | fd733c6d95ef6f4743aae97de5e15df79877c00e | refs/heads/master | 1,674,408,673,325 | 1,607,343,535,000 | 1,607,343,535,000 | 285,150,399 | 9 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,680 | lean | -- Earlier experiments with bundled definable types and unification hints.
/-
@[unify] def Def_hint {X Y Z : Def S} : unification_hint :=
{ pattern := ↥Z ≟ (↥X × ↥Y),
constraints := [Z ≟ X.prod Y] }
This unification hint lets us write X × Y in place of X.prod Y
in simple situations but it fails when it would need to be applied recursively:
type mismatch at application
preimage q
term
q
has type
(↥X × ↥Z) × ↥Y → ↥X × ↥Y : Type u
but is expected to have type
↥?m_3 → ↥X × ↥Y : Type (max ? u)
state:
R : Type u,
S : struc R,
X Y Z : Def S,
g : ↥Y → ↥Z,
hg : def_fun g,
f : ↥X → ↥Y,
hf : def_fun f,
q : (↥X × ↥Z) × ↥Y → ↥X × ↥Y := λ (p : (↥X × ↥Z) × ↥Y), (p.fst.fst, p.snd),
this : is_reindexing R q
⊢ def_set {x : ↥((X.prod Z).prod Y) | f x.fst.fst = x.snd}
We need to solve ↥?m_3 = (↥X × ↥Z) × ↥Y
but it is not (yet) of the form ↥?m_3 = ↥A × ↥B
because first we need to figure out that
we should solve ↥A = ↥X × ↥Z by taking A = X.prod Z.
-/
/-
@[unify] def Def_hint {α β : Type u} {A B Z : Def.{u} S} : unification_hint :=
{ pattern := ↥Z ≟ (α × β),
constraints := [↥A ≟ α, ↥B ≟ β, Z ≟ A.prod B] }
This ought to solve the problem above:
↥?m_3 ≟ (↥X × ↥Z) × ↥Y
[↥?A ≟ ↥X × ↥Z, ↥?B ≟ ↥Y, ?m_3 ≟ ?A.prod ?B]
[↥?A₁ ≟ ↥X, ↥?A₂ = ↥Z, ?A = ?A₁.prod ?A₂, ↥?B ≟ ↥Y, ?m_3 ≟ ?A.prod ?B]
A₁ = X, A₂ = Z, A = X.prod Z, B = Y, ?m_3 = (X.prod Z).prod Y
For some reason it doesn't work;
maybe the elaborator doesn't want to introduce new metavariables?
How is this handled in Coq?
-/
|
b9db446a24d12e4724c969489567984deea0d4d1 | 5e42295de7f5bcdf224b94603a8ec29b17c2d367 | /interactive.lean | fe7fa5f629ccae62e432e21a5a79d2ecab146595 | [] | no_license | pnmadelaine/lean_polya | 9369e0d87dce773f91383bb58ac6fde0a00a1a40 | 1c62b0b3fa71044b0225ce28030627d251b08ebc | refs/heads/master | 1,590,161,172,243 | 1,515,010,019,000 | 1,515,010,019,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,038 | lean | import .control
open polya monad
meta structure polya_cache :=
(sum_cache : rb_set sum_form_comp_data)
(prod_cache : rb_set prod_form_comp_data)
(bb : blackboard)
meta def polya_tactic := state_t polya_cache tactic
namespace polya_tactic
meta instance : monad polya_tactic :=
state_t.monad _ _
private meta def lift_tactic (α) : tactic α → polya_tactic α :=
state_t.lift
private meta def lift_polya_state (α) : polya_state α → polya_tactic α :=
λ t s, let (a, bb') := t s.bb in return (a, ⟨s.sum_cache, s.prod_cache, bb'⟩)
meta instance polya_tactic.of_tactic : has_monad_lift tactic polya_tactic :=
⟨lift_tactic⟩
meta instance polya_tactic.of_polya_state : has_monad_lift polya_state polya_tactic :=
⟨lift_polya_state⟩
meta instance tpt (α) : has_coe (tactic α) (polya_tactic α) :=
⟨monad_lift⟩
meta instance pst (α) : has_coe (polya_state α) (polya_tactic α) :=
⟨monad_lift⟩
meta def polya_tactic_orelse {α} (t₁ t₂ : polya_tactic α) : polya_tactic α :=
λ ss ts, result.cases_on (t₁ ss ts)
result.success
(λ e₁ ref₁ s', result.cases_on (t₂ ss ts)
result.success
result.exception)
meta instance : monad_fail polya_tactic :=
{ polya_tactic.monad with fail := λ α s, (tactic.fail (to_fmt s) : polya_tactic α) }
meta instance : alternative polya_tactic :=
{ polya_tactic.monad with
failure := λ α, @tactic.failed α,
orelse := @polya_tactic_orelse }
meta def step {α} (c : polya_tactic α) : polya_tactic unit :=
c >> return ()
meta def save_info (p : pos) : polya_tactic unit :=
return ()
meta def execute (c : polya_tactic unit) : tactic unit :=
do bb ← add_proof_to_blackboard blackboard.mk_empty `(rat_one_gt_zero),
let pc : polya_cache := ⟨mk_rb_set, mk_rb_set, bb⟩ in
c pc >> return ()
/-meta def istep {α} (line0 col0 line col : ℕ) (c : polya_tactic α) : polya_tactic unit :=
tactic.istep line0 col0 line col c-/
meta def assert_claims_with_names : list expr → list name → tactic unit
| [] _ := tactic.skip
| (h::hs) (n::ns) := tactic.note n none h >> assert_claims_with_names hs ns
| (h::hs) [] := do n ← tactic.mk_fresh_name, tactic.note n none h, assert_claims_with_names hs []
namespace interactive
open lean lean.parser interactive interactive.types
meta def add_expr (e : parse texpr) : polya_tactic unit :=
λ ps, do bb' ← tactic.i_to_expr e >>= process_expr_tac ps.bb, return ((), ⟨ps.sum_cache, ps.prod_cache, bb'⟩)
meta def add_comparison (e : parse texpr) : polya_tactic unit :=
λ ps, do bb' ← tactic.i_to_expr e >>= add_proof_to_blackboard ps.bb, return ((), ⟨ps.sum_cache, ps.prod_cache, bb'⟩)
meta def add_hypotheses (ns : parse (many ident)) : polya_tactic unit :=
λ ps,
do exps ← ns.mmap tactic.get_local,
bb' ← add_proofs_to_blackboard ps.bb exps,
return ((), ⟨ps.sum_cache, ps.prod_cache, bb'⟩)
meta def additive : polya_tactic unit :=
λ ps,
let (nsc, bb') := sum_form.add_new_ineqs ps.sum_cache ps.bb in
return ((), ⟨nsc, ps.prod_cache, bb'⟩)
meta def multiplicative : polya_tactic unit :=
λ ps,
let (nsc, bb') := prod_form.add_new_ineqs ps.prod_cache ps.bb in
return ((), ⟨ps.sum_cache, nsc, bb'⟩)
meta def trace_exprs : polya_tactic unit :=
do ps ← state_t.read,
ps.bb.trace_exprs
meta def trace_state : polya_tactic unit :=
do ps ← state_t.read,
ps.bb.trace
meta def trace_contr : polya_tactic unit :=
do ps ← state_t.read,
match ps.bb.contr with
| contrad.none := tactic.trace "no contradiction found"
| _ := tactic.trace "contradiction found"
end
meta def reconstruct : polya_tactic unit :=
do ps ← state_t.read,
e ← ps.bb.contr.reconstruct,
tactic.apply e
meta def extract_comparisons_between (lhs rhs : parse parser.pexpr) (nms : parse with_ident_list) : polya_tactic unit :=
do lhs' ← tactic.i_to_expr lhs,
rhs' ← tactic.i_to_expr rhs,
iqs ← get_ineqs lhs' rhs',
iqse ← iqs.data.mmap (λ iq, iq.prf.reconstruct),
assert_claims_with_names iqse nms
end interactive
end polya_tactic
#exit
|
c0618d90127f414d499a39c18444265b936d7796 | c8af905dcd8475f414868d303b2eb0e9d3eb32f9 | /src/data/cpi/species/normalise.lean | 4f4f0331f182d72f1693c22d652d8b0de4f2f424 | [
"BSD-3-Clause"
] | permissive | continuouspi/lean-cpi | 81480a13842d67ff5f3698643210d8ed5dd08de4 | 443bf2cb236feadc45a01387099c236ab2b78237 | refs/heads/master | 1,650,307,316,582 | 1,587,033,364,000 | 1,587,033,364,000 | 207,499,661 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,312 | lean | import data.cpi.species.congruence
namespace cpi
namespace species
variables {ℍ : Type} {ω : context}
open_locale congruence
/-- Drop a binder from a species, assuming the binder is unused. -/
def drop {Γ} {k} {n} {A : whole ℍ ω k (context.extend n Γ)}
: level.zero ∉ A → whole ℍ ω k Γ
| free := rename_with A (name.drop_var (λ l, l ∈ A) free)
lemma drop_extend {Γ} {n} {A : species ℍ ω (context.extend n Γ)} (fr : level.zero ∉ A)
: rename name.extend (drop fr) = A
:= begin
unfold drop,
rw [rename_with_compose,
name.drop_var_compose (λ l, l ∈ A) fr,
rename_with_id]
end
namespace normalise
/-- A version of species.kind, but for atoms. -/
@[nolint has_inhabited_instance]
inductive kind' (ℍ : Type) : kind → Type
| atom {} : kind' kind.species
| in_choice {} : kind' kind.species
| in_nu {} : affinity ℍ → kind' kind.species
| choices {}: kind' kind.choices
/-- A more restrictive kind of species. -/
inductive atom :
∀ {sk : kind} (k : kind' ℍ sk) {Γ : context}
, whole ℍ ω sk Γ → Prop
| choice_one {Γ} {A : species ℍ ω Γ}
: atom kind'.atom A
→ atom kind'.in_choice A
| choice_cons {Γ} {A As : species ℍ ω Γ}
: atom kind'.atom A
→ atom kind'.in_choice As
→ atom kind'.in_choice (A |ₛ As)
| nu_one {Γ} (M : affinity ℍ) {A : species ℍ ω (context.extend M.arity Γ)}
: atom kind'.atom A → level.zero ∈ A
→ atom (kind'.in_nu M) A
| nu_cons {Γ} (M : affinity ℍ) {A As : species ℍ ω (context.extend M.arity Γ)}
: atom kind'.atom A → level.zero ∈ A
→ atom (kind'.in_nu M) As
→ atom (kind'.in_nu M) (A |ₛ As)
| apply {Γ} {n} (D : reference n ω) (as : vector (name Γ) n)
: atom kind'.atom (apply D as)
| choice {Γ} {As : choices ℍ ω Γ}
: atom kind'.choices As
→ atom kind'.atom (Σ# As)
| restriction {Γ} (M : affinity ℍ) {A : species ℍ ω (context.extend M.arity Γ)}
: atom (kind'.in_nu M) A
→ atom kind'.atom (ν(M) A)
| empty {} {Γ} : atom kind'.choices (@whole.empty ℍ ω Γ)
| cons_nil {Γ} {f} (π : prefix_expr ℍ Γ f) {As : choices ℍ ω Γ}
: atom kind'.choices As
→ atom kind'.choices (whole.cons π nil As)
| cons_species {Γ} {f} (π : prefix_expr ℍ Γ f) {A : species ℍ ω (f.apply Γ)} {As : choices ℍ ω Γ}
: atom kind'.in_choice A
→ atom kind'.choices As
→ atom kind'.choices (whole.cons π A As)
lemma mk_choice {Γ : context} {f} (π : prefix_expr ℍ Γ f) {As : choices ℍ ω Γ}:
∀ (Bs : list (species ℍ ω (f.apply Γ)))
, (∀ B ∈ Bs, atom kind'.atom B)
→ atom kind'.choices As
→ atom kind'.choices (whole.cons π (parallel.from_list Bs) As)
| [] _ atomAs := atom.cons_nil π atomAs
| (B::Bs) atomBs atomAs := begin
suffices : atom kind'.in_choice (parallel.from_list (B :: Bs)),
from atom.cons_species π this atomAs,
induction Bs generalizing B,
case list.nil { from atom.choice_one (atomBs B (list.mem_cons_self B _)) },
case list.cons : B' Bs ih {
refine atom.choice_cons (atomBs B (list.mem_cons_self B _)) _,
from ih B' (λ x mem, atomBs x (list.mem_cons_of_mem _ mem)),
}
end
/-- parallel.from_list is injective on atoms. -/
lemma atom_parallel_inj {Γ} :
∀ (As Bs : list (species ℍ ω Γ))
, parallel.from_list As = parallel.from_list Bs
→ (∀ (A : whole ℍ ω kind.species Γ), A ∈ As → atom kind'.atom A)
→ (∀ (A : whole ℍ ω kind.species Γ), A ∈ Bs → atom kind'.atom A)
→ As = Bs
| [] [] ⟨ _ ⟩ atomA atomB := rfl
| [] [_] ⟨ _ ⟩ atomA atomB := by cases atomB _ (list.mem_cons_self _ _)
| [] (B::B'::Bs) eq atomA atomB := by cases eq
| [_] [] ⟨ _ ⟩ atomA atomB := by cases atomA _ (list.mem_cons_self _ _)
| [A] [B] ⟨ _ ⟩ atomA atomB := rfl
| [A] (B::B'::Bs') ⟨ _ ⟩ atomA atomB := by cases atomA _ (list.mem_cons_self _ _)
| (A::A'::As) [] eq atomA atomB := by cases eq
| (A::A'::As) [B] ⟨ _ ⟩ atomA atomB := by cases atomB _ (list.mem_cons_self _ _)
| (A::A'::As) (B::B'::Bs) eq atomA atomB := begin
simp only [parallel.from_list] at eq,
have h := atom_parallel_inj (A'::As) (B'::Bs) eq.2
(λ x mem, atomA x (list.mem_cons_of_mem _ mem))
(λ x mem, atomB x (list.mem_cons_of_mem _ mem)),
rw [eq.1, h],
end
axiom drop_atom :
∀ {Γ} {sk} {k : kind' ℍ sk} {n} {A : whole ℍ ω sk (context.extend n Γ)} (h : level.zero ∉ A)
, atom k A → atom k (drop h)
end normalise
/-- Splits the parallel component of a restriction into two parts - those
which can be lifted out of it, and those which cannot. -/
def partition_restriction : ∀ {Γ}
(M : affinity ℍ)
(As : list (species ℍ ω (context.extend (M.arity) Γ)))
(C : species ℍ ω (context.extend (M.arity) Γ))
, (∀ A ∈ As, normalise.atom normalise.kind'.atom A)
→ Σ' (As' : list (species ℍ ω (context.extend (M.arity) Γ)))
(Bs : list (species ℍ ω Γ))
, (ν(M) C |ₛ parallel.from_list As)
≈ ((ν(M) C |ₛ parallel.from_list As') |ₛ parallel.from_list Bs)
∧ (∀ A ∈ As', normalise.atom normalise.kind'.atom A ∧ level.zero ∈ A)
∧ (∀ B ∈ Bs, normalise.atom normalise.kind'.atom B)
| Γ M [] C _ :=
⟨ [], [],
calc (ν(M) C |ₛ nil)
≈ (ν(M) (C |ₛ nil) |ₛ nil)
: equiv.ξ_restriction M equiv.parallel_nil₂
... ≈ ((ν(M) C |ₛ nil) |ₛ nil) : begin
suffices : (ν(M) (C |ₛ nil) |ₛ rename name.extend nil) ≈ ((ν(M) C |ₛ nil) |ₛ nil),
simpa only [rename.nil],
from equiv.ν_parallel' M
end,
λ x, false.elim,
λ x, false.elim ⟩
| Γ M (A :: As) C atomAs :=
let ⟨ As', Bs', eq, atomAs', atomBs' ⟩ := partition_restriction M As (C |ₛ A)
(λ x mem, atomAs x (list.mem_cons_of_mem _ mem))
in
let eq' :=
calc (ν(M) C |ₛ parallel.from_list (A :: As))
≈ (ν(M) C |ₛ A |ₛ parallel.from_list As)
: equiv.ξ_restriction M $ equiv.ξ_parallel₂ $ parallel.from_list_cons A As
... ≈ (ν(M) (C |ₛ A) |ₛ parallel.from_list As)
: equiv.ξ_restriction M $ equiv.parallel_assoc₂
... ≈ ((ν(M) (C |ₛ A) |ₛ parallel.from_list As') |ₛ parallel.from_list Bs')
: eq
in
if h : level.zero ∈ A then
-- The restriction is used within this term - keep it in.
⟨ A :: As', Bs',
calc (ν(M) C |ₛ parallel.from_list (A :: As))
≈ ((ν(M) (C |ₛ A) |ₛ parallel.from_list As') |ₛ parallel.from_list Bs')
: eq'
... ≈ ((ν(M) C |ₛ A |ₛ parallel.from_list As') |ₛ parallel.from_list Bs')
: equiv.ξ_parallel₁ $ equiv.ξ_restriction M $ equiv.parallel_assoc₁
... ≈ ((ν(M) C |ₛ parallel.from_list (A :: As')) |ₛ parallel.from_list Bs')
: equiv.ξ_parallel₁ $ equiv.ξ_restriction M
$ equiv.ξ_parallel₂ (symm (parallel.from_list_cons A As')),
λ x mem, begin
clear partition_restriction _let_match,
cases mem, case or.inr { from atomAs' x mem }, subst mem,
from ⟨ atomAs x (list.mem_cons_self _ _), h ⟩,
end,
atomBs' ⟩
else
⟨ As', drop h :: Bs',
-- The restriction is not within this term - lift it out.
calc (ν(M) C |ₛ parallel.from_list (A :: As))
≈ ((ν(M) (C |ₛ A) |ₛ parallel.from_list As') |ₛ parallel.from_list Bs')
: eq'
... ≈ ((ν(M) A |ₛ C |ₛ parallel.from_list As') |ₛ parallel.from_list Bs')
: equiv.ξ_parallel₁ $ equiv.ξ_restriction M
$ trans (equiv.ξ_parallel₁ equiv.parallel_symm) equiv.parallel_assoc₁
... ≈ (((ν(M) C |ₛ parallel.from_list As') |ₛ drop h) |ₛ parallel.from_list Bs')
: equiv.ξ_parallel₁ begin
suffices : (ν(M) rename name.extend (drop h) |ₛ C |ₛ parallel.from_list As')
≈ (drop h |ₛ (ν(M) C |ₛ parallel.from_list As')),
rw drop_extend h at this, from trans this equiv.parallel_symm,
from equiv.ν_parallel₁ M
end
... ≈ ((ν(M) C |ₛ parallel.from_list As') |ₛ drop h |ₛ parallel.from_list Bs')
: equiv.parallel_assoc₁
... ≈ ((ν(M) C |ₛ parallel.from_list As') |ₛ parallel.from_list (drop h :: Bs'))
: equiv.ξ_parallel₂ (symm (parallel.from_list_cons (drop h) Bs')),
atomAs',
λ x mem, begin
clear partition_restriction _let_match,
cases mem, case or.inr { from atomBs' x mem }, subst mem,
from normalise.drop_atom h (atomAs A (list.mem_cons_self _ _)),
end ⟩
/-- Build a restriction from a list of parallel components, or drop it if it is
empty. -/
def build_restriction {Γ} : ∀ (M : affinity ℍ)
(As : list (species ℍ ω (context.extend M.arity Γ)))
(Bs : list (species ℍ ω Γ))
, (∀ A ∈ As, normalise.atom normalise.kind'.atom A ∧ level.zero ∈ A)
→ (∀ B ∈ Bs, normalise.atom normalise.kind'.atom B)
→ Σ' (Cs : list (species ℍ ω Γ))
, parallel.from_list ((ν(M) parallel.from_list As) :: Bs)
≈ parallel.from_list Cs
∧ (∀ C ∈ Cs, normalise.atom normalise.kind'.atom C)
| M [] Bs atomAs atomBs :=
⟨ Bs,
calc parallel.from_list ((ν(M) nil) :: Bs)
≈ ((ν(M) nil) |ₛ parallel.from_list Bs) : parallel.from_list_cons _ Bs
... ≈ (nil |ₛ parallel.from_list Bs) : begin
suffices : equiv (ν(M) rename name.extend nil) nil,
{ simp only [rename.nil] at this, from equiv.ξ_parallel₁ this },
from equiv.ν_drop₁ M,
end
... ≈ parallel.from_list Bs : equiv.parallel_nil',
atomBs ⟩
| M (A::As) Bs atomAs atomBs :=
⟨ (ν(M) parallel.from_list (A::As)) :: Bs, equiv.rfl,
λ x mem, begin
cases mem,
case or.inr { from atomBs x mem },
subst mem,
suffices : normalise.atom (normalise.kind'.in_nu M) (parallel.from_list (A :: As)),
{ from normalise.atom.restriction M this },
induction As generalizing A,
case list.nil {
cases atomAs A (list.mem_cons_self A []) with atomA usesM,
from normalise.atom.nu_one M atomA usesM,
},
case list.cons : A' As ih {
cases atomAs A (list.mem_cons_self A _) with atomA usesM,
from normalise.atom.nu_cons M atomA usesM (ih A' (λ x mem, atomAs x (list.mem_cons_of_mem _ mem))),
}
end ⟩
/-- Simplifies a restriction as much as possible. This lifts any parallel
components out of it if possible, and removes the entire thing if possible. -/
def normalise_restriction {Γ} : ∀ (M : affinity ℍ)
(As : list (species ℍ ω (context.extend (M.arity) Γ)))
, (∀ A ∈ As, normalise.atom normalise.kind'.atom A)
→ Σ' (Bs : list (species ℍ ω Γ))
, (ν(M) parallel.from_list As) ≈ parallel.from_list Bs
∧ ∀ B ∈ Bs, normalise.atom normalise.kind'.atom B
| M As atomAs :=
let ⟨ As₁, Bs, eq, atomAs₁, atomBs ⟩ := partition_restriction M As nil atomAs in
let ⟨ As₂, eq₂, atomAs₂ ⟩ := build_restriction M As₁ Bs atomAs₁ atomBs in
⟨ As₂,
calc (ν(M) parallel.from_list As)
≈ (ν(M) nil |ₛ parallel.from_list As)
: equiv.ξ_restriction M (symm equiv.parallel_nil')
... ≈ ((ν(M) nil |ₛ parallel.from_list As₁) |ₛ parallel.from_list Bs) : eq
... ≈ ((ν(M) parallel.from_list As₁) |ₛ parallel.from_list Bs)
: equiv.ξ_parallel₁ $ equiv.ξ_restriction M equiv.parallel_nil'
... ≈ parallel.from_list As₂
: trans (symm (parallel.from_list_cons _ Bs)) eq₂,
atomAs₂ ⟩
/-- Wraps species.equiv to work on both species and lists of choices. -/
@[nolint has_inhabited_instance]
def equivalence_of : ∀ {k} {Γ}, whole ℍ ω k Γ → Type
| kind.species Γ A :=
Σ' (Bs : list (species ℍ ω Γ))
, A ≈ parallel.from_list Bs
∧ ∀ B ∈ Bs, normalise.atom normalise.kind'.atom B
| kind.choices Γ A :=
Σ' (B : choices ℍ ω Γ)
, (Σ# A) ≈ (Σ# B)
∧ normalise.atom normalise.kind'.choices B
/-- Reduce a term to some equivalent normal form. -/
def normalise_to : ∀ {k} {Γ} (A : whole ℍ ω k Γ), equivalence_of A
| ._ ._ nil := ⟨ [], refl _, λ x, false.elim ⟩
| ._ ._ (apply D as) := ⟨ [apply D as], refl _, λ x mem, begin
cases mem, case or.inr { cases mem }, subst mem,
from normalise.atom.apply D as,
end⟩
| ._ Γ (A |ₛ B) :=
let ⟨ A', ea, atomA ⟩ := normalise_to A in
let ⟨ B', eb, atomB ⟩ := normalise_to B in
⟨ A' ++ B',
calc (A |ₛ B)
≈ (parallel.from_list A' |ₛ parallel.from_list B')
: trans (equiv.ξ_parallel₁ ea) (equiv.ξ_parallel₂ eb)
... ≈ parallel.from_list (A' ++ B') : symm (parallel.from_append A' B'),
λ x mem, or.elim (list.mem_append.mp mem) (atomA x) (atomB x) ⟩
| ._ Γ (ν(M) A) :=
let ⟨ A', ea, atomA ⟩ := normalise_to A in
let ⟨ B, eb, atomB ⟩ := normalise_restriction M A' atomA in
⟨ B, trans (equiv.ξ_restriction M ea) eb, atomB ⟩
| ._ Γ (Σ# As) :=
let ⟨ As', eqa, atom ⟩ := normalise_to As in
⟨ [ Σ# As' ], eqa, λ x mem, begin
cases mem, case or.inr { cases mem }, subst mem,
from normalise.atom.choice atom,
end ⟩
| ._ Γ whole.empty := ⟨ whole.empty, refl _, normalise.atom.empty ⟩
| ._ Γ (whole.cons π A As) :=
let ⟨ A', eqa, atomA ⟩ := normalise_to A in
let ⟨ As', eqas, atomAs ⟩ := normalise_to As in
⟨ whole.cons π (parallel.from_list A') As',
trans (equiv.ξ_choice_here π eqa) (equiv.ξ_choice_there π eqas),
normalise.mk_choice π A' atomA atomAs ⟩
using_well_founded {
rel_tac := λ _ _,
`[exact ⟨_, measure_wf (λ x, whole.sizeof ℍ ω x.fst x.snd.fst x.snd.snd ) ⟩ ],
dec_tac := tactic.fst_dec_tac,
}
/-- Reduce a term to some equivalent normal form. -/
def normalise : ∀ {k} {Γ}, whole ℍ ω k Γ → whole ℍ ω k Γ
| kind.species Γ A := parallel.from_list (normalise_to A).fst
| kind.choices Γ A := (normalise_to A).fst
namespace normalise
/-- Two species are n-equivalent if they normalise to the same term. -/
def equiv {Γ : context} (A B : species ℍ ω Γ) : Prop := normalise A = normalise B
instance equiv.decide [decidable_eq ℍ] {Γ : context} : decidable_rel (@equiv ℍ ω Γ)
| A B := species.whole.decidable_eq ℍ ω kind.species Γ (normalise A) (normalise B)
lemma equiv.refl {Γ} : reflexive (@equiv ℍ ω Γ)
| A := rfl
lemma equiv.symm {Γ} : symmetric (@equiv ℍ ω Γ)
| A B eql := eq.symm eql
lemma equiv.trans {Γ} : transitive (@equiv ℍ ω Γ)
| A B C ab bc := eq.trans ab bc
/-- If two terms reduce to the same thing, then they are equivalent. -/
lemma equiv.imp_congruent {Γ} {A B : species ℍ ω Γ} : equiv A B → A ≈ B
| eq := begin
unfold equiv normalise at eq,
have : A ≈ parallel.from_list (normalise_to B).1 := eq ▸ (normalise_to A).2.1,
from trans this (symm (normalise_to B).2.1),
end
lemma equiv.normalise_to {Γ} {A B : species ℍ ω Γ} :
equiv A B → (normalise_to A).1 = (normalise_to B).1
| ab := begin
unfold equiv normalise at ab, clear equiv.normalise_to,
rcases normalise_to A with ⟨ As, eq, atomA ⟩, assume ab, simp only [] at ⊢ ab, clear eq,
rcases normalise_to B with ⟨ Bs, eq, atomB ⟩, assume ab, simp only [] at ⊢ ab, clear eq,
from atom_parallel_inj As Bs ab atomA atomB,
end
/-- Equivalence under normalisation. Namely, two species are equivalent if they
normalise to identical species. -/
def setoid {Γ} : setoid (species ℍ ω Γ) :=
⟨ equiv, ⟨ @equiv.refl ℍ ω Γ, @equiv.symm ℍ ω Γ, @equiv.trans ℍ ω Γ ⟩ ⟩
localized "attribute [instance] cpi.species.normalise.setoid" in normalise
instance species'.has_repr [has_repr ℍ] {Γ} : has_repr (species' ℍ ω Γ)
:= ⟨ λ x, quot.lift_on x (λ x, repr (normalise x))
(λ a b r, by { simp only [], from congr_arg repr r }) ⟩
end normalise
end species
end cpi
#lint-
|
4a9605b0e0f4868eb56cf061e5316a4cc2eb2b8f | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/analysis/normed_space/extr.lean | 603a1020ad2b37cbf78eec03c5c5732b27151264 | [
"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 | 4,001 | lean | /-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.normed_space.ray
import topology.local_extr
/-!
# (Local) maximums in a normed space
In this file we prove the following lemma, see `is_max_filter.norm_add_same_ray`. If `f : α → E` is
a function such that `norm ∘ f` has a maximum along a filter `l` at a point `c` and `y` is a vector
on the same ray as `f c`, then the function `λ x, ∥f x + y∥` has a maximul along `l` at `c`.
Then we specialize it to the case `y = f c` and to different special cases of `is_max_filter`:
`is_max_on`, `is_local_max_on`, and `is_local_max`.
## Tags
local maximum, normed space
-/
variables {α X E : Type*} [seminormed_add_comm_group E] [normed_space ℝ E] [topological_space X]
section
variables {f : α → E} {l : filter α} {s : set α} {c : α} {y : E}
/-- If `f : α → E` is a function such that `norm ∘ f` has a maximum along a filter `l` at a point
`c` and `y` is a vector on the same ray as `f c`, then the function `λ x, ∥f x + y∥` has a maximul
along `l` at `c`. -/
lemma is_max_filter.norm_add_same_ray (h : is_max_filter (norm ∘ f) l c) (hy : same_ray ℝ (f c) y) :
is_max_filter (λ x, ∥f x + y∥) l c :=
h.mono $ λ x hx,
calc ∥f x + y∥ ≤ ∥f x∥ + ∥y∥ : norm_add_le _ _
... ≤ ∥f c∥ + ∥y∥ : add_le_add_right hx _
... = ∥f c + y∥ : hy.norm_add.symm
/-- If `f : α → E` is a function such that `norm ∘ f` has a maximum along a filter `l` at a point
`c`, then the function `λ x, ∥f x + f c∥` has a maximul along `l` at `c`. -/
lemma is_max_filter.norm_add_self (h : is_max_filter (norm ∘ f) l c) :
is_max_filter (λ x, ∥f x + f c∥) l c :=
h.norm_add_same_ray same_ray.rfl
/-- If `f : α → E` is a function such that `norm ∘ f` has a maximum on a set `s` at a point `c` and
`y` is a vector on the same ray as `f c`, then the function `λ x, ∥f x + y∥` has a maximul on `s` at
`c`. -/
lemma is_max_on.norm_add_same_ray (h : is_max_on (norm ∘ f) s c) (hy : same_ray ℝ (f c) y) :
is_max_on (λ x, ∥f x + y∥) s c :=
h.norm_add_same_ray hy
/-- If `f : α → E` is a function such that `norm ∘ f` has a maximum on a set `s` at a point `c`,
then the function `λ x, ∥f x + f c∥` has a maximul on `s` at `c`. -/
lemma is_max_on.norm_add_self (h : is_max_on (norm ∘ f) s c) : is_max_on (λ x, ∥f x + f c∥) s c :=
h.norm_add_self
end
variables {f : X → E} {s : set X} {c : X} {y : E}
/-- If `f : α → E` is a function such that `norm ∘ f` has a local maximum on a set `s` at a point
`c` and `y` is a vector on the same ray as `f c`, then the function `λ x, ∥f x + y∥` has a local
maximul on `s` at `c`. -/
lemma is_local_max_on.norm_add_same_ray (h : is_local_max_on (norm ∘ f) s c)
(hy : same_ray ℝ (f c) y) : is_local_max_on (λ x, ∥f x + y∥) s c :=
h.norm_add_same_ray hy
/-- If `f : α → E` is a function such that `norm ∘ f` has a local maximum on a set `s` at a point
`c`, then the function `λ x, ∥f x + f c∥` has a local maximul on `s` at `c`. -/
lemma is_local_max_on.norm_add_self (h : is_local_max_on (norm ∘ f) s c) :
is_local_max_on (λ x, ∥f x + f c∥) s c :=
h.norm_add_self
/-- If `f : α → E` is a function such that `norm ∘ f` has a local maximum at a point `c` and `y` is
a vector on the same ray as `f c`, then the function `λ x, ∥f x + y∥` has a local maximul at `c`. -/
lemma is_local_max.norm_add_same_ray (h : is_local_max (norm ∘ f) c)
(hy : same_ray ℝ (f c) y) : is_local_max (λ x, ∥f x + y∥) c :=
h.norm_add_same_ray hy
/-- If `f : α → E` is a function such that `norm ∘ f` has a local maximum at a point `c`, then the
function `λ x, ∥f x + f c∥` has a local maximul at `c`. -/
lemma is_local_max.norm_add_self (h : is_local_max (norm ∘ f) c) :
is_local_max (λ x, ∥f x + f c∥) c :=
h.norm_add_self
|
7c3ddeb132a29b7eaf035ed8b3cf7f95706c0540 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/order/ord_continuous.lean | e334efbb4c920ef214ae1955f8589d6e31d1afc4 | [
"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 | 7,977 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov, Johannes Hölzl
-/
import order.conditionally_complete_lattice.basic
import order.rel_iso.basic
/-!
# Order continuity
We say that a function is *left order continuous* if it sends all least upper bounds
to least upper bounds. The order dual notion is called *right order continuity*.
For monotone functions `ℝ → ℝ` these notions correspond to the usual left and right continuity.
We prove some basic lemmas (`map_sup`, `map_Sup` etc) and prove that an `rel_iso` is both left
and right order continuous.
-/
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
open function order_dual set
/-!
### Definitions
-/
/-- A function `f` between preorders is left order continuous if it preserves all suprema. We
define it using `is_lub` instead of `Sup` so that the proof works both for complete lattices and
conditionally complete lattices. -/
def left_ord_continuous [preorder α] [preorder β] (f : α → β) :=
∀ ⦃s : set α⦄ ⦃x⦄, is_lub s x → is_lub (f '' s) (f x)
/-- A function `f` between preorders is right order continuous if it preserves all infima. We
define it using `is_glb` instead of `Inf` so that the proof works both for complete lattices and
conditionally complete lattices. -/
def right_ord_continuous [preorder α] [preorder β] (f : α → β) :=
∀ ⦃s : set α⦄ ⦃x⦄, is_glb s x → is_glb (f '' s) (f x)
namespace left_ord_continuous
section preorder
variables (α) [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β}
protected lemma id : left_ord_continuous (id : α → α) := λ s x h, by simpa only [image_id] using h
variable {α}
protected lemma order_dual : left_ord_continuous f → right_ord_continuous (to_dual ∘ f ∘ of_dual) :=
id
lemma map_is_greatest (hf : left_ord_continuous f) {s : set α} {x : α} (h : is_greatest s x):
is_greatest (f '' s) (f x) :=
⟨mem_image_of_mem f h.1, (hf h.is_lub).1⟩
lemma mono (hf : left_ord_continuous f) : monotone f :=
λ a₁ a₂ h,
have is_greatest {a₁, a₂} a₂ := ⟨or.inr rfl, by simp [*]⟩,
(hf.map_is_greatest this).2 $ mem_image_of_mem _ (or.inl rfl)
lemma comp (hg : left_ord_continuous g) (hf : left_ord_continuous f) :
left_ord_continuous (g ∘ f) :=
λ s x h, by simpa only [image_image] using hg (hf h)
protected lemma iterate {f : α → α} (hf : left_ord_continuous f) (n : ℕ) :
left_ord_continuous (f^[n]) :=
nat.rec_on n (left_ord_continuous.id α) $ λ n ihn, ihn.comp hf
end preorder
section semilattice_sup
variables [semilattice_sup α] [semilattice_sup β] {f : α → β}
lemma map_sup (hf : left_ord_continuous f) (x y : α) :
f (x ⊔ y) = f x ⊔ f y :=
(hf is_lub_pair).unique $ by simp only [image_pair, is_lub_pair]
lemma le_iff (hf : left_ord_continuous f) (h : injective f) {x y} :
f x ≤ f y ↔ x ≤ y :=
by simp only [← sup_eq_right, ← hf.map_sup, h.eq_iff]
lemma lt_iff (hf : left_ord_continuous f) (h : injective f) {x y} :
f x < f y ↔ x < y :=
by simp only [lt_iff_le_not_le, hf.le_iff h]
variable (f)
/-- Convert an injective left order continuous function to an order embedding. -/
def to_order_embedding (hf : left_ord_continuous f) (h : injective f) :
α ↪o β :=
⟨⟨f, h⟩, λ x y, hf.le_iff h⟩
variable {f}
@[simp] lemma coe_to_order_embedding (hf : left_ord_continuous f) (h : injective f) :
⇑(hf.to_order_embedding f h) = f := rfl
end semilattice_sup
section complete_lattice
variables [complete_lattice α] [complete_lattice β] {f : α → β}
lemma map_Sup' (hf : left_ord_continuous f) (s : set α) :
f (Sup s) = Sup (f '' s) :=
(hf $ is_lub_Sup s).Sup_eq.symm
lemma map_Sup (hf : left_ord_continuous f) (s : set α) :
f (Sup s) = ⨆ x ∈ s, f x :=
by rw [hf.map_Sup', Sup_image]
lemma map_supr (hf : left_ord_continuous f) (g : ι → α) :
f (⨆ i, g i) = ⨆ i, f (g i) :=
by simp only [supr, hf.map_Sup', ← range_comp]
end complete_lattice
section conditionally_complete_lattice
variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι]
{f : α → β}
lemma map_cSup (hf : left_ord_continuous f) {s : set α} (sne : s.nonempty) (sbdd : bdd_above s) :
f (Sup s) = Sup (f '' s) :=
((hf $ is_lub_cSup sne sbdd).cSup_eq $ sne.image f).symm
lemma map_csupr (hf : left_ord_continuous f) {g : ι → α} (hg : bdd_above (range g)) :
f (⨆ i, g i) = ⨆ i, f (g i) :=
by simp only [supr, hf.map_cSup (range_nonempty _) hg, ← range_comp]
end conditionally_complete_lattice
end left_ord_continuous
namespace right_ord_continuous
section preorder
variables (α) [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β}
protected lemma id : right_ord_continuous (id : α → α) := λ s x h, by simpa only [image_id] using h
variable {α}
protected lemma order_dual : right_ord_continuous f → left_ord_continuous (to_dual ∘ f ∘ of_dual) :=
id
lemma map_is_least (hf : right_ord_continuous f) {s : set α} {x : α} (h : is_least s x):
is_least (f '' s) (f x) :=
hf.order_dual.map_is_greatest h
lemma mono (hf : right_ord_continuous f) : monotone f :=
hf.order_dual.mono.dual
lemma comp (hg : right_ord_continuous g) (hf : right_ord_continuous f) :
right_ord_continuous (g ∘ f) :=
hg.order_dual.comp hf.order_dual
protected lemma iterate {f : α → α} (hf : right_ord_continuous f) (n : ℕ) :
right_ord_continuous (f^[n]) :=
hf.order_dual.iterate n
end preorder
section semilattice_inf
variables [semilattice_inf α] [semilattice_inf β] {f : α → β}
lemma map_inf (hf : right_ord_continuous f) (x y : α) :
f (x ⊓ y) = f x ⊓ f y :=
hf.order_dual.map_sup x y
lemma le_iff (hf : right_ord_continuous f) (h : injective f) {x y} :
f x ≤ f y ↔ x ≤ y :=
hf.order_dual.le_iff h
lemma lt_iff (hf : right_ord_continuous f) (h : injective f) {x y} :
f x < f y ↔ x < y :=
hf.order_dual.lt_iff h
variable (f)
/-- Convert an injective left order continuous function to a `order_embedding`. -/
def to_order_embedding (hf : right_ord_continuous f) (h : injective f) : α ↪o β :=
⟨⟨f, h⟩, λ x y, hf.le_iff h⟩
variable {f}
@[simp] lemma coe_to_order_embedding (hf : right_ord_continuous f) (h : injective f) :
⇑(hf.to_order_embedding f h) = f := rfl
end semilattice_inf
section complete_lattice
variables [complete_lattice α] [complete_lattice β] {f : α → β}
lemma map_Inf' (hf : right_ord_continuous f) (s : set α) :
f (Inf s) = Inf (f '' s) :=
hf.order_dual.map_Sup' s
lemma map_Inf (hf : right_ord_continuous f) (s : set α) :
f (Inf s) = ⨅ x ∈ s, f x :=
hf.order_dual.map_Sup s
lemma map_infi (hf : right_ord_continuous f) (g : ι → α) :
f (⨅ i, g i) = ⨅ i, f (g i) :=
hf.order_dual.map_supr g
end complete_lattice
section conditionally_complete_lattice
variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι]
{f : α → β}
lemma map_cInf (hf : right_ord_continuous f) {s : set α} (sne : s.nonempty) (sbdd : bdd_below s) :
f (Inf s) = Inf (f '' s) :=
hf.order_dual.map_cSup sne sbdd
lemma map_cinfi (hf : right_ord_continuous f) {g : ι → α} (hg : bdd_below (range g)) :
f (⨅ i, g i) = ⨅ i, f (g i) :=
hf.order_dual.map_csupr hg
end conditionally_complete_lattice
end right_ord_continuous
namespace order_iso
section preorder
variables [preorder α] [preorder β] (e : α ≃o β)
{s : set α} {x : α}
protected lemma left_ord_continuous : left_ord_continuous e :=
λ s x hx,
⟨monotone.mem_upper_bounds_image (λ x y, e.map_rel_iff.2) hx.1,
λ y hy, e.rel_symm_apply.1 $ (is_lub_le_iff hx).2 $ λ x' hx', e.rel_symm_apply.2 $ hy $
mem_image_of_mem _ hx'⟩
protected lemma right_ord_continuous : right_ord_continuous e :=
order_iso.left_ord_continuous e.dual
end preorder
end order_iso
|
8bbce1cc6b93b4ceb6aa55da58ed6fe02edbb9fe | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/real/conjugate_exponents.lean | e5ebd392e9434e380df452a45ca340f0178b2372 | [
"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 | 3,807 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Yury Kudryashov
-/
import data.real.ennreal
/-!
# Real conjugate exponents
`p.is_conjugate_exponent q` registers the fact that the real numbers `p` and `q` are `> 1` and
satisfy `1/p + 1/q = 1`. This property shows up often in analysis, especially when dealing with
`L^p` spaces.
We make several basic facts available through dot notation in this situation.
We also introduce `p.conjugate_exponent` for `p / (p-1)`. When `p > 1`, it is conjugate to `p`.
-/
noncomputable theory
namespace real
/-- Two real exponents `p, q` are conjugate if they are `> 1` and satisfy the equality
`1/p + 1/q = 1`. This condition shows up in many theorems in analysis, notably related to `L^p`
norms. -/
structure is_conjugate_exponent (p q : ℝ) : Prop :=
(one_lt : 1 < p)
(inv_add_inv_conj : 1/p + 1/q = 1)
/-- The conjugate exponent of `p` is `q = p/(p-1)`, so that `1/p + 1/q = 1`. -/
def conjugate_exponent (p : ℝ) : ℝ := p/(p-1)
namespace is_conjugate_exponent
variables {p q : ℝ} (h : p.is_conjugate_exponent q)
include h
/- Register several non-vanishing results following from the fact that `p` has a conjugate exponent
`q`: many computations using these exponents require clearing out denominators, which can be done
with `field_simp` given a proof that these denominators are non-zero, so we record the most usual
ones. -/
lemma pos : 0 < p :=
lt_trans zero_lt_one h.one_lt
lemma nonneg : 0 ≤ p := le_of_lt h.pos
lemma ne_zero : p ≠ 0 :=
ne_of_gt h.pos
lemma sub_one_pos : 0 < p - 1 :=
sub_pos.2 h.one_lt
lemma sub_one_ne_zero : p - 1 ≠ 0 :=
ne_of_gt h.sub_one_pos
lemma one_div_pos : 0 < 1/p :=
one_div_pos.2 h.pos
lemma one_div_nonneg : 0 ≤ 1/p :=
le_of_lt h.one_div_pos
lemma one_div_ne_zero : 1/p ≠ 0 :=
ne_of_gt (h.one_div_pos)
lemma conj_eq : q = p/(p-1) :=
begin
have := h.inv_add_inv_conj,
rw [← eq_sub_iff_add_eq', one_div, inv_eq_iff] at this,
field_simp [← this, h.ne_zero]
end
lemma conjugate_eq : conjugate_exponent p = q := h.conj_eq.symm
lemma sub_one_mul_conj : (p - 1) * q = p :=
mul_comm q (p - 1) ▸ (eq_div_iff h.sub_one_ne_zero).1 h.conj_eq
lemma mul_eq_add : p * q = p + q :=
by simpa only [sub_mul, sub_eq_iff_eq_add, one_mul] using h.sub_one_mul_conj
@[symm] protected lemma symm : q.is_conjugate_exponent p :=
{ one_lt := by { rw [h.conj_eq], exact (one_lt_div h.sub_one_pos).mpr (sub_one_lt p) },
inv_add_inv_conj := by simpa [add_comm] using h.inv_add_inv_conj }
lemma div_conj_eq_sub_one : p / q = p - 1 :=
begin
field_simp [h.symm.ne_zero],
rw h.sub_one_mul_conj
end
lemma one_lt_nnreal : 1 < real.to_nnreal p :=
begin
rw [←real.to_nnreal_one, real.to_nnreal_lt_to_nnreal_iff h.pos],
exact h.one_lt,
end
lemma inv_add_inv_conj_nnreal : 1 / real.to_nnreal p + 1 / real.to_nnreal q = 1 :=
by rw [← real.to_nnreal_one, ← real.to_nnreal_div' h.nonneg, ← real.to_nnreal_div' h.symm.nonneg,
← real.to_nnreal_add h.one_div_nonneg h.symm.one_div_nonneg, h.inv_add_inv_conj]
lemma inv_add_inv_conj_ennreal : 1 / ennreal.of_real p + 1 / ennreal.of_real q = 1 :=
by rw [← ennreal.of_real_one, ← ennreal.of_real_div_of_pos h.pos,
← ennreal.of_real_div_of_pos h.symm.pos,
← ennreal.of_real_add h.one_div_nonneg h.symm.one_div_nonneg, h.inv_add_inv_conj]
end is_conjugate_exponent
lemma is_conjugate_exponent_iff {p q : ℝ} (h : 1 < p) :
p.is_conjugate_exponent q ↔ q = p/(p-1) :=
⟨λ H, H.conj_eq, λ H, ⟨h, by field_simp [H, ne_of_gt (lt_trans zero_lt_one h)]⟩⟩
lemma is_conjugate_exponent_conjugate_exponent {p : ℝ} (h : 1 < p) :
p.is_conjugate_exponent (conjugate_exponent p) :=
(is_conjugate_exponent_iff h).2 rfl
end real
|
a5a7972458be1b994ef191d68feee18040f945af | c777c32c8e484e195053731103c5e52af26a25d1 | /src/analysis/convex/side.lean | a6941b8d4cc43fb05214f418fbee5693ad4e447d | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 39,286 | lean | /-
Copyright (c) 2022 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import analysis.convex.between
import analysis.convex.normed
import analysis.normed.group.add_torsor
/-!
# Sides of affine subspaces
This file defines notions of two points being on the same or opposite sides of an affine subspace.
## Main definitions
* `s.w_same_side x y`: The points `x` and `y` are weakly on the same side of the affine
subspace `s`.
* `s.s_same_side x y`: The points `x` and `y` are strictly on the same side of the affine
subspace `s`.
* `s.w_opp_side x y`: The points `x` and `y` are weakly on opposite sides of the affine
subspace `s`.
* `s.s_opp_side x y`: The points `x` and `y` are strictly on opposite sides of the affine
subspace `s`.
-/
variables {R V V' P P' : Type*}
open affine_equiv affine_map
namespace affine_subspace
section strict_ordered_comm_ring
variables [strict_ordered_comm_ring R] [add_comm_group V] [module R V] [add_torsor V P]
variables [add_comm_group V'] [module R V'] [add_torsor V' P']
include V
/-- The points `x` and `y` are weakly on the same side of `s`. -/
def w_same_side (s : affine_subspace R P) (x y : P) : Prop :=
∃ p₁ p₂ ∈ s, same_ray R (x -ᵥ p₁) (y -ᵥ p₂)
/-- The points `x` and `y` are strictly on the same side of `s`. -/
def s_same_side (s : affine_subspace R P) (x y : P) : Prop :=
s.w_same_side x y ∧ x ∉ s ∧ y ∉ s
/-- The points `x` and `y` are weakly on opposite sides of `s`. -/
def w_opp_side (s : affine_subspace R P) (x y : P) : Prop :=
∃ p₁ p₂ ∈ s, same_ray R (x -ᵥ p₁) (p₂ -ᵥ y)
/-- The points `x` and `y` are strictly on opposite sides of `s`. -/
def s_opp_side (s : affine_subspace R P) (x y : P) : Prop :=
s.w_opp_side x y ∧ x ∉ s ∧ y ∉ s
include V'
lemma w_same_side.map {s : affine_subspace R P} {x y : P} (h : s.w_same_side x y)
(f : P →ᵃ[R] P') : (s.map f).w_same_side (f x) (f y) :=
begin
rcases h with ⟨p₁, hp₁, p₂, hp₂, h⟩,
refine ⟨f p₁, mem_map_of_mem f hp₁, f p₂, mem_map_of_mem f hp₂, _⟩,
simp_rw [←linear_map_vsub],
exact h.map f.linear
end
lemma _root_.function.injective.w_same_side_map_iff {s : affine_subspace R P} {x y : P}
{f : P →ᵃ[R] P'} (hf : function.injective f) :
(s.map f).w_same_side (f x) (f y) ↔ s.w_same_side x y :=
begin
refine ⟨λ h, _, λ h, h.map _⟩,
rcases h with ⟨fp₁, hfp₁, fp₂, hfp₂, h⟩,
rw mem_map at hfp₁ hfp₂,
rcases hfp₁ with ⟨p₁, hp₁, rfl⟩,
rcases hfp₂ with ⟨p₂, hp₂, rfl⟩,
refine ⟨p₁, hp₁, p₂, hp₂, _⟩,
simp_rw [←linear_map_vsub, (f.linear_injective_iff.2 hf).same_ray_map_iff] at h,
exact h
end
lemma _root_.function.injective.s_same_side_map_iff {s : affine_subspace R P} {x y : P}
{f : P →ᵃ[R] P'} (hf : function.injective f) :
(s.map f).s_same_side (f x) (f y) ↔ s.s_same_side x y :=
by simp_rw [s_same_side, hf.w_same_side_map_iff, mem_map_iff_mem_of_injective hf]
@[simp] lemma _root_.affine_equiv.w_same_side_map_iff {s : affine_subspace R P} {x y : P}
(f : P ≃ᵃ[R] P') : (s.map ↑f).w_same_side (f x) (f y) ↔ s.w_same_side x y :=
(show function.injective f.to_affine_map, from f.injective).w_same_side_map_iff
@[simp] lemma _root_.affine_equiv.s_same_side_map_iff {s : affine_subspace R P} {x y : P}
(f : P ≃ᵃ[R] P') : (s.map ↑f).s_same_side (f x) (f y) ↔ s.s_same_side x y :=
(show function.injective f.to_affine_map, from f.injective).s_same_side_map_iff
lemma w_opp_side.map {s : affine_subspace R P} {x y : P} (h : s.w_opp_side x y)
(f : P →ᵃ[R] P') : (s.map f).w_opp_side (f x) (f y) :=
begin
rcases h with ⟨p₁, hp₁, p₂, hp₂, h⟩,
refine ⟨f p₁, mem_map_of_mem f hp₁, f p₂, mem_map_of_mem f hp₂, _⟩,
simp_rw [←linear_map_vsub],
exact h.map f.linear
end
lemma _root_.function.injective.w_opp_side_map_iff {s : affine_subspace R P} {x y : P}
{f : P →ᵃ[R] P'} (hf : function.injective f) :
(s.map f).w_opp_side (f x) (f y) ↔ s.w_opp_side x y :=
begin
refine ⟨λ h, _, λ h, h.map _⟩,
rcases h with ⟨fp₁, hfp₁, fp₂, hfp₂, h⟩,
rw mem_map at hfp₁ hfp₂,
rcases hfp₁ with ⟨p₁, hp₁, rfl⟩,
rcases hfp₂ with ⟨p₂, hp₂, rfl⟩,
refine ⟨p₁, hp₁, p₂, hp₂, _⟩,
simp_rw [←linear_map_vsub, (f.linear_injective_iff.2 hf).same_ray_map_iff] at h,
exact h
end
lemma _root_.function.injective.s_opp_side_map_iff {s : affine_subspace R P} {x y : P}
{f : P →ᵃ[R] P'} (hf : function.injective f) :
(s.map f).s_opp_side (f x) (f y) ↔ s.s_opp_side x y :=
by simp_rw [s_opp_side, hf.w_opp_side_map_iff, mem_map_iff_mem_of_injective hf]
@[simp] lemma _root_.affine_equiv.w_opp_side_map_iff {s : affine_subspace R P} {x y : P}
(f : P ≃ᵃ[R] P') : (s.map ↑f).w_opp_side (f x) (f y) ↔ s.w_opp_side x y :=
(show function.injective f.to_affine_map, from f.injective).w_opp_side_map_iff
@[simp] lemma _root_.affine_equiv.s_opp_side_map_iff {s : affine_subspace R P} {x y : P}
(f : P ≃ᵃ[R] P') : (s.map ↑f).s_opp_side (f x) (f y) ↔ s.s_opp_side x y :=
(show function.injective f.to_affine_map, from f.injective).s_opp_side_map_iff
omit V'
lemma w_same_side.nonempty {s : affine_subspace R P} {x y : P} (h : s.w_same_side x y) :
(s : set P).nonempty :=
⟨h.some, h.some_spec.some⟩
lemma s_same_side.nonempty {s : affine_subspace R P} {x y : P} (h : s.s_same_side x y) :
(s : set P).nonempty :=
⟨h.1.some, h.1.some_spec.some⟩
lemma w_opp_side.nonempty {s : affine_subspace R P} {x y : P} (h : s.w_opp_side x y) :
(s : set P).nonempty :=
⟨h.some, h.some_spec.some⟩
lemma s_opp_side.nonempty {s : affine_subspace R P} {x y : P} (h : s.s_opp_side x y) :
(s : set P).nonempty :=
⟨h.1.some, h.1.some_spec.some⟩
lemma s_same_side.w_same_side {s : affine_subspace R P} {x y : P} (h : s.s_same_side x y) :
s.w_same_side x y :=
h.1
lemma s_same_side.left_not_mem {s : affine_subspace R P} {x y : P} (h : s.s_same_side x y) :
x ∉ s :=
h.2.1
lemma s_same_side.right_not_mem {s : affine_subspace R P} {x y : P} (h : s.s_same_side x y) :
y ∉ s :=
h.2.2
lemma s_opp_side.w_opp_side {s : affine_subspace R P} {x y : P} (h : s.s_opp_side x y) :
s.w_opp_side x y :=
h.1
lemma s_opp_side.left_not_mem {s : affine_subspace R P} {x y : P} (h : s.s_opp_side x y) :
x ∉ s :=
h.2.1
lemma s_opp_side.right_not_mem {s : affine_subspace R P} {x y : P} (h : s.s_opp_side x y) :
y ∉ s :=
h.2.2
lemma w_same_side_comm {s : affine_subspace R P} {x y : P} :
s.w_same_side x y ↔ s.w_same_side y x :=
⟨λ ⟨p₁, hp₁, p₂, hp₂, h⟩, ⟨p₂, hp₂, p₁, hp₁, h.symm⟩,
λ ⟨p₁, hp₁, p₂, hp₂, h⟩, ⟨p₂, hp₂, p₁, hp₁, h.symm⟩⟩
alias w_same_side_comm ↔ w_same_side.symm _
lemma s_same_side_comm {s : affine_subspace R P} {x y : P} :
s.s_same_side x y ↔ s.s_same_side y x :=
by rw [s_same_side, s_same_side, w_same_side_comm, and_comm (x ∉ s)]
alias s_same_side_comm ↔ s_same_side.symm _
lemma w_opp_side_comm {s : affine_subspace R P} {x y : P} :
s.w_opp_side x y ↔ s.w_opp_side y x :=
begin
split,
{ rintro ⟨p₁, hp₁, p₂, hp₂, h⟩,
refine ⟨p₂, hp₂, p₁, hp₁, _⟩,
rwa [same_ray_comm, ←same_ray_neg_iff, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] },
{ rintro ⟨p₁, hp₁, p₂, hp₂, h⟩,
refine ⟨p₂, hp₂, p₁, hp₁, _⟩,
rwa [same_ray_comm, ←same_ray_neg_iff, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] }
end
alias w_opp_side_comm ↔ w_opp_side.symm _
lemma s_opp_side_comm {s : affine_subspace R P} {x y : P} :
s.s_opp_side x y ↔ s.s_opp_side y x :=
by rw [s_opp_side, s_opp_side, w_opp_side_comm, and_comm (x ∉ s)]
alias s_opp_side_comm ↔ s_opp_side.symm _
lemma not_w_same_side_bot (x y : P) : ¬ (⊥ : affine_subspace R P).w_same_side x y :=
by simp [w_same_side, not_mem_bot]
lemma not_s_same_side_bot (x y : P) : ¬ (⊥ : affine_subspace R P).s_same_side x y :=
λ h, not_w_same_side_bot x y h.w_same_side
lemma not_w_opp_side_bot (x y : P) : ¬ (⊥ : affine_subspace R P).w_opp_side x y :=
by simp [w_opp_side, not_mem_bot]
lemma not_s_opp_side_bot (x y : P) : ¬ (⊥ : affine_subspace R P).s_opp_side x y :=
λ h, not_w_opp_side_bot x y h.w_opp_side
@[simp] lemma w_same_side_self_iff {s : affine_subspace R P} {x : P} :
s.w_same_side x x ↔ (s : set P).nonempty :=
⟨λ h, h.nonempty, λ ⟨p, hp⟩, ⟨p, hp, p, hp, same_ray.rfl⟩⟩
lemma s_same_side_self_iff {s : affine_subspace R P} {x : P} :
s.s_same_side x x ↔ (s : set P).nonempty ∧ x ∉ s :=
⟨λ ⟨h, hx, _⟩, ⟨w_same_side_self_iff.1 h, hx⟩, λ ⟨h, hx⟩, ⟨w_same_side_self_iff.2 h, hx, hx⟩⟩
lemma w_same_side_of_left_mem {s : affine_subspace R P} {x : P} (y : P) (hx : x ∈ s) :
s.w_same_side x y :=
begin
refine ⟨x, hx, x, hx, _⟩,
simp
end
lemma w_same_side_of_right_mem {s : affine_subspace R P} (x : P) {y : P} (hy : y ∈ s) :
s.w_same_side x y :=
(w_same_side_of_left_mem x hy).symm
lemma w_opp_side_of_left_mem {s : affine_subspace R P} {x : P} (y : P) (hx : x ∈ s) :
s.w_opp_side x y :=
begin
refine ⟨x, hx, x, hx, _⟩,
simp
end
lemma w_opp_side_of_right_mem {s : affine_subspace R P} (x : P) {y : P} (hy : y ∈ s) :
s.w_opp_side x y :=
(w_opp_side_of_left_mem x hy).symm
lemma w_same_side_vadd_left_iff {s : affine_subspace R P} {x y : P} {v : V}
(hv : v ∈ s.direction) : s.w_same_side (v +ᵥ x) y ↔ s.w_same_side x y :=
begin
split,
{ rintro ⟨p₁, hp₁, p₂, hp₂, h⟩,
refine ⟨-v +ᵥ p₁,
affine_subspace.vadd_mem_of_mem_direction (submodule.neg_mem _ hv) hp₁, p₂, hp₂, _⟩,
rwa [vsub_vadd_eq_vsub_sub, sub_neg_eq_add, add_comm, ←vadd_vsub_assoc] },
{ rintro ⟨p₁, hp₁, p₂, hp₂, h⟩,
refine ⟨v +ᵥ p₁,
affine_subspace.vadd_mem_of_mem_direction hv hp₁, p₂, hp₂, _⟩,
rwa vadd_vsub_vadd_cancel_left }
end
lemma w_same_side_vadd_right_iff {s : affine_subspace R P} {x y : P} {v : V}
(hv : v ∈ s.direction) : s.w_same_side x (v +ᵥ y) ↔ s.w_same_side x y :=
by rw [w_same_side_comm, w_same_side_vadd_left_iff hv, w_same_side_comm]
lemma s_same_side_vadd_left_iff {s : affine_subspace R P} {x y : P} {v : V}
(hv : v ∈ s.direction) : s.s_same_side (v +ᵥ x) y ↔ s.s_same_side x y :=
by rw [s_same_side, s_same_side, w_same_side_vadd_left_iff hv,
vadd_mem_iff_mem_of_mem_direction hv]
lemma s_same_side_vadd_right_iff {s : affine_subspace R P} {x y : P} {v : V}
(hv : v ∈ s.direction) : s.s_same_side x (v +ᵥ y) ↔ s.s_same_side x y :=
by rw [s_same_side_comm, s_same_side_vadd_left_iff hv, s_same_side_comm]
lemma w_opp_side_vadd_left_iff {s : affine_subspace R P} {x y : P} {v : V}
(hv : v ∈ s.direction) : s.w_opp_side (v +ᵥ x) y ↔ s.w_opp_side x y :=
begin
split,
{ rintro ⟨p₁, hp₁, p₂, hp₂, h⟩,
refine ⟨-v +ᵥ p₁,
affine_subspace.vadd_mem_of_mem_direction (submodule.neg_mem _ hv) hp₁, p₂, hp₂, _⟩,
rwa [vsub_vadd_eq_vsub_sub, sub_neg_eq_add, add_comm, ←vadd_vsub_assoc] },
{ rintro ⟨p₁, hp₁, p₂, hp₂, h⟩,
refine ⟨v +ᵥ p₁,
affine_subspace.vadd_mem_of_mem_direction hv hp₁, p₂, hp₂, _⟩,
rwa vadd_vsub_vadd_cancel_left }
end
lemma w_opp_side_vadd_right_iff {s : affine_subspace R P} {x y : P} {v : V}
(hv : v ∈ s.direction) : s.w_opp_side x (v +ᵥ y) ↔ s.w_opp_side x y :=
by rw [w_opp_side_comm, w_opp_side_vadd_left_iff hv, w_opp_side_comm]
lemma s_opp_side_vadd_left_iff {s : affine_subspace R P} {x y : P} {v : V}
(hv : v ∈ s.direction) : s.s_opp_side (v +ᵥ x) y ↔ s.s_opp_side x y :=
by rw [s_opp_side, s_opp_side, w_opp_side_vadd_left_iff hv,
vadd_mem_iff_mem_of_mem_direction hv]
lemma s_opp_side_vadd_right_iff {s : affine_subspace R P} {x y : P} {v : V}
(hv : v ∈ s.direction) : s.s_opp_side x (v +ᵥ y) ↔ s.s_opp_side x y :=
by rw [s_opp_side_comm, s_opp_side_vadd_left_iff hv, s_opp_side_comm]
lemma w_same_side_smul_vsub_vadd_left {s : affine_subspace R P} {p₁ p₂ : P} (x : P)
(hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : 0 ≤ t) : s.w_same_side (t • (x -ᵥ p₁) +ᵥ p₂) x :=
begin
refine ⟨p₂, hp₂, p₁, hp₁, _⟩,
rw vadd_vsub,
exact same_ray_nonneg_smul_left _ ht
end
lemma w_same_side_smul_vsub_vadd_right {s : affine_subspace R P} {p₁ p₂ : P} (x : P)
(hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : 0 ≤ t) : s.w_same_side x (t • (x -ᵥ p₁) +ᵥ p₂) :=
(w_same_side_smul_vsub_vadd_left x hp₁ hp₂ ht).symm
lemma w_same_side_line_map_left {s : affine_subspace R P} {x : P} (y : P) (h : x ∈ s) {t : R}
(ht : 0 ≤ t) : s.w_same_side (line_map x y t) y :=
w_same_side_smul_vsub_vadd_left y h h ht
lemma w_same_side_line_map_right {s : affine_subspace R P} {x : P} (y : P) (h : x ∈ s) {t : R}
(ht : 0 ≤ t) : s.w_same_side y (line_map x y t) :=
(w_same_side_line_map_left y h ht).symm
lemma w_opp_side_smul_vsub_vadd_left {s : affine_subspace R P} {p₁ p₂ : P} (x : P)
(hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : t ≤ 0) : s.w_opp_side (t • (x -ᵥ p₁) +ᵥ p₂) x :=
begin
refine ⟨p₂, hp₂, p₁, hp₁, _⟩,
rw [vadd_vsub, ←neg_neg t, neg_smul, ←smul_neg, neg_vsub_eq_vsub_rev],
exact same_ray_nonneg_smul_left _ (neg_nonneg.2 ht)
end
lemma w_opp_side_smul_vsub_vadd_right {s : affine_subspace R P} {p₁ p₂ : P} (x : P)
(hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : t ≤ 0) : s.w_opp_side x (t • (x -ᵥ p₁) +ᵥ p₂) :=
(w_opp_side_smul_vsub_vadd_left x hp₁ hp₂ ht).symm
lemma w_opp_side_line_map_left {s : affine_subspace R P} {x : P} (y : P) (h : x ∈ s) {t : R}
(ht : t ≤ 0) : s.w_opp_side (line_map x y t) y :=
w_opp_side_smul_vsub_vadd_left y h h ht
lemma w_opp_side_line_map_right {s : affine_subspace R P} {x : P} (y : P) (h : x ∈ s) {t : R}
(ht : t ≤ 0) : s.w_opp_side y (line_map x y t) :=
(w_opp_side_line_map_left y h ht).symm
lemma _root_.wbtw.w_same_side₂₃ {s : affine_subspace R P} {x y z : P} (h : wbtw R x y z)
(hx : x ∈ s) : s.w_same_side y z :=
begin
rcases h with ⟨t, ⟨ht0, -⟩, rfl⟩,
exact w_same_side_line_map_left z hx ht0
end
lemma _root_.wbtw.w_same_side₃₂ {s : affine_subspace R P} {x y z : P} (h : wbtw R x y z)
(hx : x ∈ s) : s.w_same_side z y :=
(h.w_same_side₂₃ hx).symm
lemma _root_.wbtw.w_same_side₁₂ {s : affine_subspace R P} {x y z : P} (h : wbtw R x y z)
(hz : z ∈ s) : s.w_same_side x y :=
h.symm.w_same_side₃₂ hz
lemma _root_.wbtw.w_same_side₂₁ {s : affine_subspace R P} {x y z : P} (h : wbtw R x y z)
(hz : z ∈ s) : s.w_same_side y x :=
h.symm.w_same_side₂₃ hz
lemma _root_.wbtw.w_opp_side₁₃ {s : affine_subspace R P} {x y z : P} (h : wbtw R x y z)
(hy : y ∈ s) : s.w_opp_side x z :=
begin
rcases h with ⟨t, ⟨ht0, ht1⟩, rfl⟩,
refine ⟨_, hy, _, hy, _⟩,
rcases ht1.lt_or_eq with ht1' | rfl, swap, { simp },
rcases ht0.lt_or_eq with ht0' | rfl, swap, { simp },
refine or.inr (or.inr ⟨1 - t, t, sub_pos.2 ht1', ht0', _⟩),
simp_rw [line_map_apply, vadd_vsub_assoc, vsub_vadd_eq_vsub_sub, ←neg_vsub_eq_vsub_rev z x,
vsub_self, zero_sub, ←neg_one_smul R (z -ᵥ x), ←add_smul, smul_neg, ←neg_smul,
smul_smul],
ring_nf
end
lemma _root_.wbtw.w_opp_side₃₁ {s : affine_subspace R P} {x y z : P} (h : wbtw R x y z)
(hy : y ∈ s) : s.w_opp_side z x :=
h.symm.w_opp_side₁₃ hy
end strict_ordered_comm_ring
section linear_ordered_field
variables [linear_ordered_field R] [add_comm_group V] [module R V] [add_torsor V P]
variables [add_comm_group V'] [module R V'] [add_torsor V' P']
include V
variables {R}
@[simp] lemma w_opp_side_self_iff {s : affine_subspace R P} {x : P} : s.w_opp_side x x ↔ x ∈ s :=
begin
split,
{ rintro ⟨p₁, hp₁, p₂, hp₂, h⟩,
obtain ⟨a, -, -, -, -, h₁, -⟩ := h.exists_eq_smul_add,
rw [add_comm, vsub_add_vsub_cancel, ←eq_vadd_iff_vsub_eq] at h₁,
rw h₁,
exact s.smul_vsub_vadd_mem a hp₂ hp₁ hp₁ },
{ exact λ h, ⟨x, h, x, h, same_ray.rfl⟩ }
end
lemma not_s_opp_side_self (s : affine_subspace R P) (x : P) : ¬s.s_opp_side x x :=
by simp [s_opp_side]
lemma w_same_side_iff_exists_left {s : affine_subspace R P} {x y p₁ : P} (h : p₁ ∈ s) :
s.w_same_side x y ↔ x ∈ s ∨ ∃ p₂ ∈ s, same_ray R (x -ᵥ p₁) (y -ᵥ p₂) :=
begin
split,
{ rintro ⟨p₁', hp₁', p₂', hp₂', h0 | h0 | ⟨r₁, r₂, hr₁, hr₂, hr⟩⟩,
{ rw vsub_eq_zero_iff_eq at h0,
rw h0,
exact or.inl hp₁' },
{ refine or.inr ⟨p₂', hp₂', _⟩,
rw h0,
exact same_ray.zero_right _ },
{ refine or.inr ⟨(r₁ / r₂) • (p₁ -ᵥ p₁') +ᵥ p₂', s.smul_vsub_vadd_mem _ h hp₁' hp₂',
or.inr (or.inr ⟨r₁, r₂, hr₁, hr₂, _⟩)⟩,
rw [vsub_vadd_eq_vsub_sub, smul_sub, ←hr, smul_smul, mul_div_cancel' _ hr₂.ne.symm,
←smul_sub, vsub_sub_vsub_cancel_right] } },
{ rintro (h' | h'),
{ exact w_same_side_of_left_mem y h' },
{ exact ⟨p₁, h, h'⟩ } }
end
lemma w_same_side_iff_exists_right {s : affine_subspace R P} {x y p₂ : P} (h : p₂ ∈ s) :
s.w_same_side x y ↔ y ∈ s ∨ ∃ p₁ ∈ s, same_ray R (x -ᵥ p₁) (y -ᵥ p₂) :=
begin
rw [w_same_side_comm, w_same_side_iff_exists_left h],
simp_rw same_ray_comm
end
lemma s_same_side_iff_exists_left {s : affine_subspace R P} {x y p₁ : P} (h : p₁ ∈ s) :
s.s_same_side x y ↔ x ∉ s ∧ y ∉ s ∧ ∃ p₂ ∈ s, same_ray R (x -ᵥ p₁) (y -ᵥ p₂) :=
begin
rw [s_same_side, and_comm, w_same_side_iff_exists_left h, and_assoc, and.congr_right_iff],
intro hx,
rw or_iff_right hx
end
lemma s_same_side_iff_exists_right {s : affine_subspace R P} {x y p₂ : P} (h : p₂ ∈ s) :
s.s_same_side x y ↔ x ∉ s ∧ y ∉ s ∧ ∃ p₁ ∈ s, same_ray R (x -ᵥ p₁) (y -ᵥ p₂) :=
begin
rw [s_same_side_comm, s_same_side_iff_exists_left h, ←and_assoc, and_comm (y ∉ s), and_assoc],
simp_rw same_ray_comm
end
lemma w_opp_side_iff_exists_left {s : affine_subspace R P} {x y p₁ : P} (h : p₁ ∈ s) :
s.w_opp_side x y ↔ x ∈ s ∨ ∃ p₂ ∈ s, same_ray R (x -ᵥ p₁) (p₂ -ᵥ y) :=
begin
split,
{ rintro ⟨p₁', hp₁', p₂', hp₂', h0 | h0 | ⟨r₁, r₂, hr₁, hr₂, hr⟩⟩,
{ rw vsub_eq_zero_iff_eq at h0,
rw h0,
exact or.inl hp₁' },
{ refine or.inr ⟨p₂', hp₂', _⟩,
rw h0,
exact same_ray.zero_right _ },
{ refine or.inr ⟨(-r₁ / r₂) • (p₁ -ᵥ p₁') +ᵥ p₂', s.smul_vsub_vadd_mem _ h hp₁' hp₂',
or.inr (or.inr ⟨r₁, r₂, hr₁, hr₂, _⟩)⟩,
rw [vadd_vsub_assoc, smul_add, ←hr, smul_smul, neg_div, mul_neg,
mul_div_cancel' _ hr₂.ne.symm, neg_smul, neg_add_eq_sub, ←smul_sub,
vsub_sub_vsub_cancel_right] } },
{ rintro (h' | h'),
{ exact w_opp_side_of_left_mem y h' },
{ exact ⟨p₁, h, h'⟩ } }
end
lemma w_opp_side_iff_exists_right {s : affine_subspace R P} {x y p₂ : P} (h : p₂ ∈ s) :
s.w_opp_side x y ↔ y ∈ s ∨ ∃ p₁ ∈ s, same_ray R (x -ᵥ p₁) (p₂ -ᵥ y) :=
begin
rw [w_opp_side_comm, w_opp_side_iff_exists_left h],
split,
{ rintro (hy | ⟨p, hp, hr⟩), { exact or.inl hy },
refine or.inr ⟨p, hp, _⟩,
rwa [same_ray_comm, ←same_ray_neg_iff, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] },
{ rintro (hy | ⟨p, hp, hr⟩), { exact or.inl hy },
refine or.inr ⟨p, hp, _⟩,
rwa [same_ray_comm, ←same_ray_neg_iff, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] }
end
lemma s_opp_side_iff_exists_left {s : affine_subspace R P} {x y p₁ : P} (h : p₁ ∈ s) :
s.s_opp_side x y ↔ x ∉ s ∧ y ∉ s ∧ ∃ p₂ ∈ s, same_ray R (x -ᵥ p₁) (p₂ -ᵥ y) :=
begin
rw [s_opp_side, and_comm, w_opp_side_iff_exists_left h, and_assoc, and.congr_right_iff],
intro hx,
rw or_iff_right hx
end
lemma s_opp_side_iff_exists_right {s : affine_subspace R P} {x y p₂ : P} (h : p₂ ∈ s) :
s.s_opp_side x y ↔ x ∉ s ∧ y ∉ s ∧ ∃ p₁ ∈ s, same_ray R (x -ᵥ p₁) (p₂ -ᵥ y) :=
begin
rw [s_opp_side, and_comm, w_opp_side_iff_exists_right h, and_assoc, and.congr_right_iff,
and.congr_right_iff],
rintro hx hy,
rw or_iff_right hy
end
lemma w_same_side.trans {s : affine_subspace R P} {x y z : P} (hxy : s.w_same_side x y)
(hyz : s.w_same_side y z) (hy : y ∉ s) : s.w_same_side x z :=
begin
rcases hxy with ⟨p₁, hp₁, p₂, hp₂, hxy⟩,
rw [w_same_side_iff_exists_left hp₂, or_iff_right hy] at hyz,
rcases hyz with ⟨p₃, hp₃, hyz⟩,
refine ⟨p₁, hp₁, p₃, hp₃, hxy.trans hyz _⟩,
refine λ h, false.elim _,
rw vsub_eq_zero_iff_eq at h,
exact hy (h.symm ▸ hp₂)
end
lemma w_same_side.trans_s_same_side {s : affine_subspace R P} {x y z : P}
(hxy : s.w_same_side x y) (hyz : s.s_same_side y z) : s.w_same_side x z :=
hxy.trans hyz.1 hyz.2.1
lemma w_same_side.trans_w_opp_side {s : affine_subspace R P} {x y z : P} (hxy : s.w_same_side x y)
(hyz : s.w_opp_side y z) (hy : y ∉ s) : s.w_opp_side x z :=
begin
rcases hxy with ⟨p₁, hp₁, p₂, hp₂, hxy⟩,
rw [w_opp_side_iff_exists_left hp₂, or_iff_right hy] at hyz,
rcases hyz with ⟨p₃, hp₃, hyz⟩,
refine ⟨p₁, hp₁, p₃, hp₃, hxy.trans hyz _⟩,
refine λ h, false.elim _,
rw vsub_eq_zero_iff_eq at h,
exact hy (h.symm ▸ hp₂)
end
lemma w_same_side.trans_s_opp_side {s : affine_subspace R P} {x y z : P} (hxy : s.w_same_side x y)
(hyz : s.s_opp_side y z) : s.w_opp_side x z :=
hxy.trans_w_opp_side hyz.1 hyz.2.1
lemma s_same_side.trans_w_same_side {s : affine_subspace R P} {x y z : P}
(hxy : s.s_same_side x y) (hyz : s.w_same_side y z) : s.w_same_side x z :=
(hyz.symm.trans_s_same_side hxy.symm).symm
lemma s_same_side.trans {s : affine_subspace R P} {x y z : P} (hxy : s.s_same_side x y)
(hyz : s.s_same_side y z) : s.s_same_side x z :=
⟨hxy.w_same_side.trans_s_same_side hyz, hxy.2.1, hyz.2.2⟩
lemma s_same_side.trans_w_opp_side {s : affine_subspace R P} {x y z : P} (hxy : s.s_same_side x y)
(hyz : s.w_opp_side y z) : s.w_opp_side x z :=
hxy.w_same_side.trans_w_opp_side hyz hxy.2.2
lemma s_same_side.trans_s_opp_side {s : affine_subspace R P} {x y z : P} (hxy : s.s_same_side x y)
(hyz : s.s_opp_side y z) : s.s_opp_side x z :=
⟨hxy.trans_w_opp_side hyz.1, hxy.2.1, hyz.2.2⟩
lemma w_opp_side.trans_w_same_side {s : affine_subspace R P} {x y z : P} (hxy : s.w_opp_side x y)
(hyz : s.w_same_side y z) (hy : y ∉ s) : s.w_opp_side x z :=
(hyz.symm.trans_w_opp_side hxy.symm hy).symm
lemma w_opp_side.trans_s_same_side {s : affine_subspace R P} {x y z : P} (hxy : s.w_opp_side x y)
(hyz : s.s_same_side y z) : s.w_opp_side x z :=
hxy.trans_w_same_side hyz.1 hyz.2.1
lemma w_opp_side.trans {s : affine_subspace R P} {x y z : P} (hxy : s.w_opp_side x y)
(hyz : s.w_opp_side y z) (hy : y ∉ s) : s.w_same_side x z :=
begin
rcases hxy with ⟨p₁, hp₁, p₂, hp₂, hxy⟩,
rw [w_opp_side_iff_exists_left hp₂, or_iff_right hy] at hyz,
rcases hyz with ⟨p₃, hp₃, hyz⟩,
rw [←same_ray_neg_iff, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] at hyz,
refine ⟨p₁, hp₁, p₃, hp₃, hxy.trans hyz _⟩,
refine λ h, false.elim _,
rw vsub_eq_zero_iff_eq at h,
exact hy (h ▸ hp₂)
end
lemma w_opp_side.trans_s_opp_side {s : affine_subspace R P} {x y z : P} (hxy : s.w_opp_side x y)
(hyz : s.s_opp_side y z) : s.w_same_side x z :=
hxy.trans hyz.1 hyz.2.1
lemma s_opp_side.trans_w_same_side {s : affine_subspace R P} {x y z : P} (hxy : s.s_opp_side x y)
(hyz : s.w_same_side y z) : s.w_opp_side x z :=
(hyz.symm.trans_s_opp_side hxy.symm).symm
lemma s_opp_side.trans_s_same_side {s : affine_subspace R P} {x y z : P} (hxy : s.s_opp_side x y)
(hyz : s.s_same_side y z) : s.s_opp_side x z :=
(hyz.symm.trans_s_opp_side hxy.symm).symm
lemma s_opp_side.trans_w_opp_side {s : affine_subspace R P} {x y z : P} (hxy : s.s_opp_side x y)
(hyz : s.w_opp_side y z) : s.w_same_side x z :=
(hyz.symm.trans_s_opp_side hxy.symm).symm
lemma s_opp_side.trans {s : affine_subspace R P} {x y z : P} (hxy : s.s_opp_side x y)
(hyz : s.s_opp_side y z) : s.s_same_side x z :=
⟨hxy.trans_w_opp_side hyz.1, hxy.2.1, hyz.2.2⟩
lemma w_same_side_and_w_opp_side_iff {s : affine_subspace R P} {x y : P} :
(s.w_same_side x y ∧ s.w_opp_side x y) ↔ (x ∈ s ∨ y ∈ s) :=
begin
split,
{ rintro ⟨hs, ho⟩,
rw w_opp_side_comm at ho,
by_contra h,
rw not_or_distrib at h,
exact h.1 (w_opp_side_self_iff.1 (hs.trans_w_opp_side ho h.2)) },
{ rintro (h | h),
{ exact ⟨w_same_side_of_left_mem y h, w_opp_side_of_left_mem y h⟩ },
{ exact ⟨w_same_side_of_right_mem x h, w_opp_side_of_right_mem x h⟩ } }
end
lemma w_same_side.not_s_opp_side {s : affine_subspace R P} {x y : P} (h : s.w_same_side x y) :
¬s.s_opp_side x y :=
begin
intro ho,
have hxy := w_same_side_and_w_opp_side_iff.1 ⟨h, ho.1⟩,
rcases hxy with hx | hy,
{ exact ho.2.1 hx },
{ exact ho.2.2 hy }
end
lemma s_same_side.not_w_opp_side {s : affine_subspace R P} {x y : P} (h : s.s_same_side x y) :
¬s.w_opp_side x y :=
begin
intro ho,
have hxy := w_same_side_and_w_opp_side_iff.1 ⟨h.1, ho⟩,
rcases hxy with hx | hy,
{ exact h.2.1 hx },
{ exact h.2.2 hy }
end
lemma s_same_side.not_s_opp_side {s : affine_subspace R P} {x y : P} (h : s.s_same_side x y) :
¬s.s_opp_side x y :=
λ ho, h.not_w_opp_side ho.1
lemma w_opp_side.not_s_same_side {s : affine_subspace R P} {x y : P} (h : s.w_opp_side x y) :
¬s.s_same_side x y :=
λ hs, hs.not_w_opp_side h
lemma s_opp_side.not_w_same_side {s : affine_subspace R P} {x y : P} (h : s.s_opp_side x y) :
¬s.w_same_side x y :=
λ hs, hs.not_s_opp_side h
lemma s_opp_side.not_s_same_side {s : affine_subspace R P} {x y : P} (h : s.s_opp_side x y) :
¬s.s_same_side x y :=
λ hs, h.not_w_same_side hs.1
lemma w_opp_side_iff_exists_wbtw {s : affine_subspace R P} {x y : P} :
s.w_opp_side x y ↔ ∃ p ∈ s, wbtw R x p y :=
begin
refine ⟨λ h, _, λ ⟨p, hp, h⟩, h.w_opp_side₁₃ hp⟩,
rcases h with ⟨p₁, hp₁, p₂, hp₂, (h | h | ⟨r₁, r₂, hr₁, hr₂, h⟩)⟩,
{ rw vsub_eq_zero_iff_eq at h,
rw h,
exact ⟨p₁, hp₁, wbtw_self_left _ _ _⟩ },
{ rw vsub_eq_zero_iff_eq at h,
rw ←h,
exact ⟨p₂, hp₂, wbtw_self_right _ _ _⟩ },
{ refine ⟨line_map x y (r₂ / (r₁ + r₂)), _, _⟩,
{ rw [line_map_apply, ←vsub_vadd x p₁, ←vsub_vadd y p₂, vsub_vadd_eq_vsub_sub,
vadd_vsub_assoc, ←vadd_assoc, vadd_eq_add],
convert s.smul_vsub_vadd_mem (r₂ / (r₁ + r₂)) hp₂ hp₁ hp₁,
rw [add_comm (y -ᵥ p₂), smul_sub, smul_add, add_sub_assoc, add_assoc, add_right_eq_self,
div_eq_inv_mul, ←neg_vsub_eq_vsub_rev, smul_neg, ←smul_smul, ←h, smul_smul,
←neg_smul, ←sub_smul, ←div_eq_inv_mul, ←div_eq_inv_mul, ←neg_div, ←sub_div,
sub_eq_add_neg, ←neg_add, neg_div, div_self (left.add_pos hr₁ hr₂).ne.symm,
neg_one_smul, neg_add_self] },
{ exact set.mem_image_of_mem _ ⟨div_nonneg hr₂.le (left.add_pos hr₁ hr₂).le,
div_le_one_of_le (le_add_of_nonneg_left hr₁.le)
(left.add_pos hr₁ hr₂).le⟩ } }
end
lemma s_opp_side.exists_sbtw {s : affine_subspace R P} {x y : P} (h : s.s_opp_side x y) :
∃ p ∈ s, sbtw R x p y :=
begin
obtain ⟨p, hp, hw⟩ := w_opp_side_iff_exists_wbtw.1 h.w_opp_side,
refine ⟨p, hp, hw, _, _⟩,
{ rintro rfl,
exact h.2.1 hp },
{ rintro rfl,
exact h.2.2 hp },
end
lemma _root_.sbtw.s_opp_side_of_not_mem_of_mem {s : affine_subspace R P} {x y z : P}
(h : sbtw R x y z) (hx : x ∉ s) (hy : y ∈ s) : s.s_opp_side x z :=
begin
refine ⟨h.wbtw.w_opp_side₁₃ hy, hx, λ hz, hx _⟩,
rcases h with ⟨⟨t, ⟨ht0, ht1⟩, rfl⟩, hyx, hyz⟩,
rw line_map_apply at hy,
have ht : t ≠ 1, { rintro rfl, simpa [line_map_apply] using hyz },
have hy' := vsub_mem_direction hy hz,
rw [vadd_vsub_assoc, ←neg_vsub_eq_vsub_rev z, ←neg_one_smul R (z -ᵥ x), ←add_smul,
←sub_eq_add_neg, s.direction.smul_mem_iff (sub_ne_zero_of_ne ht)] at hy',
rwa vadd_mem_iff_mem_of_mem_direction (submodule.smul_mem _ _ hy') at hy
end
lemma s_same_side_smul_vsub_vadd_left {s : affine_subspace R P} {x p₁ p₂ : P} (hx : x ∉ s)
(hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : 0 < t) : s.s_same_side (t • (x -ᵥ p₁) +ᵥ p₂) x :=
begin
refine ⟨w_same_side_smul_vsub_vadd_left x hp₁ hp₂ ht.le, λ h, hx _, hx⟩,
rwa [vadd_mem_iff_mem_direction _ hp₂, s.direction.smul_mem_iff ht.ne.symm,
vsub_right_mem_direction_iff_mem hp₁] at h
end
lemma s_same_side_smul_vsub_vadd_right {s : affine_subspace R P} {x p₁ p₂ : P} (hx : x ∉ s)
(hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : 0 < t) : s.s_same_side x (t • (x -ᵥ p₁) +ᵥ p₂) :=
(s_same_side_smul_vsub_vadd_left hx hp₁ hp₂ ht).symm
lemma s_same_side_line_map_left {s : affine_subspace R P} {x y : P} (hx : x ∈ s) (hy : y ∉ s)
{t : R} (ht : 0 < t) : s.s_same_side (line_map x y t) y :=
s_same_side_smul_vsub_vadd_left hy hx hx ht
lemma s_same_side_line_map_right {s : affine_subspace R P} {x y : P} (hx : x ∈ s) (hy : y ∉ s)
{t : R} (ht : 0 < t) : s.s_same_side y (line_map x y t) :=
(s_same_side_line_map_left hx hy ht).symm
lemma s_opp_side_smul_vsub_vadd_left {s : affine_subspace R P} {x p₁ p₂ : P} (hx : x ∉ s)
(hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : t < 0) : s.s_opp_side (t • (x -ᵥ p₁) +ᵥ p₂) x :=
begin
refine ⟨w_opp_side_smul_vsub_vadd_left x hp₁ hp₂ ht.le, λ h, hx _, hx⟩,
rwa [vadd_mem_iff_mem_direction _ hp₂, s.direction.smul_mem_iff ht.ne,
vsub_right_mem_direction_iff_mem hp₁] at h
end
lemma s_opp_side_smul_vsub_vadd_right {s : affine_subspace R P} {x p₁ p₂ : P} (hx : x ∉ s)
(hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : t < 0) : s.s_opp_side x (t • (x -ᵥ p₁) +ᵥ p₂) :=
(s_opp_side_smul_vsub_vadd_left hx hp₁ hp₂ ht).symm
lemma s_opp_side_line_map_left {s : affine_subspace R P} {x y : P} (hx : x ∈ s) (hy : y ∉ s)
{t : R} (ht : t < 0) : s.s_opp_side (line_map x y t) y :=
s_opp_side_smul_vsub_vadd_left hy hx hx ht
lemma s_opp_side_line_map_right {s : affine_subspace R P} {x y : P} (hx : x ∈ s) (hy : y ∉ s)
{t : R} (ht : t < 0) : s.s_opp_side y (line_map x y t) :=
(s_opp_side_line_map_left hx hy ht).symm
lemma set_of_w_same_side_eq_image2 {s : affine_subspace R P} {x p : P} (hx : x ∉ s) (hp : p ∈ s) :
{y | s.w_same_side x y} = set.image2 (λ (t : R) q, t • (x -ᵥ p) +ᵥ q) (set.Ici 0) s :=
begin
ext y,
simp_rw [set.mem_set_of, set.mem_image2, set.mem_Ici, mem_coe],
split,
{ rw [w_same_side_iff_exists_left hp, or_iff_right hx],
rintro ⟨p₂, hp₂, h | h | ⟨r₁, r₂, hr₁, hr₂, h⟩⟩,
{ rw vsub_eq_zero_iff_eq at h,
exact false.elim (hx (h.symm ▸ hp)) },
{ rw vsub_eq_zero_iff_eq at h,
refine ⟨0, p₂, le_refl _, hp₂, _⟩,
simp [h] },
{ refine ⟨r₁ / r₂, p₂, (div_pos hr₁ hr₂).le, hp₂, _⟩,
rw [div_eq_inv_mul, ←smul_smul, h, smul_smul, inv_mul_cancel hr₂.ne.symm, one_smul,
vsub_vadd] } },
{ rintro ⟨t, p', ht, hp', rfl⟩,
exact w_same_side_smul_vsub_vadd_right x hp hp' ht }
end
lemma set_of_s_same_side_eq_image2 {s : affine_subspace R P} {x p : P} (hx : x ∉ s) (hp : p ∈ s) :
{y | s.s_same_side x y} = set.image2 (λ (t : R) q, t • (x -ᵥ p) +ᵥ q) (set.Ioi 0) s :=
begin
ext y,
simp_rw [set.mem_set_of, set.mem_image2, set.mem_Ioi, mem_coe],
split,
{ rw s_same_side_iff_exists_left hp,
rintro ⟨-, hy, p₂, hp₂, h | h | ⟨r₁, r₂, hr₁, hr₂, h⟩⟩,
{ rw vsub_eq_zero_iff_eq at h,
exact false.elim (hx (h.symm ▸ hp)) },
{ rw vsub_eq_zero_iff_eq at h,
exact false.elim (hy (h.symm ▸ hp₂)) },
{ refine ⟨r₁ / r₂, p₂, div_pos hr₁ hr₂, hp₂, _⟩,
rw [div_eq_inv_mul, ←smul_smul, h, smul_smul, inv_mul_cancel hr₂.ne.symm, one_smul,
vsub_vadd] } },
{ rintro ⟨t, p', ht, hp', rfl⟩,
exact s_same_side_smul_vsub_vadd_right hx hp hp' ht }
end
lemma set_of_w_opp_side_eq_image2 {s : affine_subspace R P} {x p : P} (hx : x ∉ s) (hp : p ∈ s) :
{y | s.w_opp_side x y} = set.image2 (λ (t : R) q, t • (x -ᵥ p) +ᵥ q) (set.Iic 0) s :=
begin
ext y,
simp_rw [set.mem_set_of, set.mem_image2, set.mem_Iic, mem_coe],
split,
{ rw [w_opp_side_iff_exists_left hp, or_iff_right hx],
rintro ⟨p₂, hp₂, h | h | ⟨r₁, r₂, hr₁, hr₂, h⟩⟩,
{ rw vsub_eq_zero_iff_eq at h,
exact false.elim (hx (h.symm ▸ hp)) },
{ rw vsub_eq_zero_iff_eq at h,
refine ⟨0, p₂, le_refl _, hp₂, _⟩,
simp [h] },
{ refine ⟨-r₁ / r₂, p₂, (div_neg_of_neg_of_pos (left.neg_neg_iff.2 hr₁) hr₂).le, hp₂, _⟩,
rw [div_eq_inv_mul, ←smul_smul, neg_smul, h, smul_neg, smul_smul,
inv_mul_cancel hr₂.ne.symm, one_smul, neg_vsub_eq_vsub_rev, vsub_vadd] } },
{ rintro ⟨t, p', ht, hp', rfl⟩,
exact w_opp_side_smul_vsub_vadd_right x hp hp' ht }
end
lemma set_of_s_opp_side_eq_image2 {s : affine_subspace R P} {x p : P} (hx : x ∉ s) (hp : p ∈ s) :
{y | s.s_opp_side x y} = set.image2 (λ (t : R) q, t • (x -ᵥ p) +ᵥ q) (set.Iio 0) s :=
begin
ext y,
simp_rw [set.mem_set_of, set.mem_image2, set.mem_Iio, mem_coe],
split,
{ rw s_opp_side_iff_exists_left hp,
rintro ⟨-, hy, p₂, hp₂, h | h | ⟨r₁, r₂, hr₁, hr₂, h⟩⟩,
{ rw vsub_eq_zero_iff_eq at h,
exact false.elim (hx (h.symm ▸ hp)) },
{ rw vsub_eq_zero_iff_eq at h,
exact false.elim (hy (h ▸ hp₂)) },
{ refine ⟨-r₁ / r₂, p₂, div_neg_of_neg_of_pos (left.neg_neg_iff.2 hr₁) hr₂, hp₂, _⟩,
rw [div_eq_inv_mul, ←smul_smul, neg_smul, h, smul_neg, smul_smul,
inv_mul_cancel hr₂.ne.symm, one_smul, neg_vsub_eq_vsub_rev, vsub_vadd] } },
{ rintro ⟨t, p', ht, hp', rfl⟩,
exact s_opp_side_smul_vsub_vadd_right hx hp hp' ht }
end
lemma w_opp_side_point_reflection {s : affine_subspace R P} {x : P} (y : P) (hx : x ∈ s) :
s.w_opp_side y (point_reflection R x y) :=
(wbtw_point_reflection R _ _).w_opp_side₁₃ hx
lemma s_opp_side_point_reflection {s : affine_subspace R P} {x y : P} (hx : x ∈ s) (hy : y ∉ s) :
s.s_opp_side y (point_reflection R x y) :=
begin
refine (sbtw_point_reflection_of_ne R (λ h, hy _)).s_opp_side_of_not_mem_of_mem hy hx,
rwa ←h
end
end linear_ordered_field
section normed
variables [seminormed_add_comm_group V] [normed_space ℝ V] [pseudo_metric_space P]
variables [normed_add_torsor V P]
include V
lemma is_connected_set_of_w_same_side {s : affine_subspace ℝ P} (x : P)
(h : (s : set P).nonempty) : is_connected {y | s.w_same_side x y} :=
begin
obtain ⟨p, hp⟩ := h,
haveI : nonempty s := ⟨⟨p, hp⟩⟩,
by_cases hx : x ∈ s,
{ convert is_connected_univ,
{ simp [w_same_side_of_left_mem, hx] },
{ exact add_torsor.connected_space V P } },
{ rw [set_of_w_same_side_eq_image2 hx hp, ←set.image_prod],
refine (is_connected_Ici.prod (is_connected_iff_connected_space.2 _)).image _
((continuous_fst.smul continuous_const).vadd continuous_snd).continuous_on,
convert add_torsor.connected_space s.direction s }
end
lemma is_preconnected_set_of_w_same_side (s : affine_subspace ℝ P) (x : P) :
is_preconnected {y | s.w_same_side x y} :=
begin
rcases set.eq_empty_or_nonempty (s : set P) with h | h,
{ convert is_preconnected_empty,
rw coe_eq_bot_iff at h,
simp only [h, not_w_same_side_bot],
refl },
{ exact (is_connected_set_of_w_same_side x h).is_preconnected }
end
lemma is_connected_set_of_s_same_side {s : affine_subspace ℝ P} {x : P} (hx : x ∉ s)
(h : (s : set P).nonempty) : is_connected {y | s.s_same_side x y} :=
begin
obtain ⟨p, hp⟩ := h,
haveI : nonempty s := ⟨⟨p, hp⟩⟩,
rw [set_of_s_same_side_eq_image2 hx hp, ←set.image_prod],
refine (is_connected_Ioi.prod (is_connected_iff_connected_space.2 _)).image _
((continuous_fst.smul continuous_const).vadd continuous_snd).continuous_on,
convert add_torsor.connected_space s.direction s
end
lemma is_preconnected_set_of_s_same_side (s : affine_subspace ℝ P) (x : P) :
is_preconnected {y | s.s_same_side x y} :=
begin
rcases set.eq_empty_or_nonempty (s : set P) with h | h,
{ convert is_preconnected_empty,
rw coe_eq_bot_iff at h,
simp only [h, not_s_same_side_bot],
refl },
{ by_cases hx : x ∈ s,
{ convert is_preconnected_empty,
simp only [hx, s_same_side, not_true, false_and, and_false],
refl },
{ exact (is_connected_set_of_s_same_side hx h).is_preconnected } }
end
lemma is_connected_set_of_w_opp_side {s : affine_subspace ℝ P} (x : P)
(h : (s : set P).nonempty) : is_connected {y | s.w_opp_side x y} :=
begin
obtain ⟨p, hp⟩ := h,
haveI : nonempty s := ⟨⟨p, hp⟩⟩,
by_cases hx : x ∈ s,
{ convert is_connected_univ,
{ simp [w_opp_side_of_left_mem, hx] },
{ exact add_torsor.connected_space V P } },
{ rw [set_of_w_opp_side_eq_image2 hx hp, ←set.image_prod],
refine (is_connected_Iic.prod (is_connected_iff_connected_space.2 _)).image _
((continuous_fst.smul continuous_const).vadd continuous_snd).continuous_on,
convert add_torsor.connected_space s.direction s }
end
lemma is_preconnected_set_of_w_opp_side (s : affine_subspace ℝ P) (x : P) :
is_preconnected {y | s.w_opp_side x y} :=
begin
rcases set.eq_empty_or_nonempty (s : set P) with h | h,
{ convert is_preconnected_empty,
rw coe_eq_bot_iff at h,
simp only [h, not_w_opp_side_bot],
refl },
{ exact (is_connected_set_of_w_opp_side x h).is_preconnected }
end
lemma is_connected_set_of_s_opp_side {s : affine_subspace ℝ P} {x : P} (hx : x ∉ s)
(h : (s : set P).nonempty) : is_connected {y | s.s_opp_side x y} :=
begin
obtain ⟨p, hp⟩ := h,
haveI : nonempty s := ⟨⟨p, hp⟩⟩,
rw [set_of_s_opp_side_eq_image2 hx hp, ←set.image_prod],
refine (is_connected_Iio.prod (is_connected_iff_connected_space.2 _)).image _
((continuous_fst.smul continuous_const).vadd continuous_snd).continuous_on,
convert add_torsor.connected_space s.direction s
end
lemma is_preconnected_set_of_s_opp_side (s : affine_subspace ℝ P) (x : P) :
is_preconnected {y | s.s_opp_side x y} :=
begin
rcases set.eq_empty_or_nonempty (s : set P) with h | h,
{ convert is_preconnected_empty,
rw coe_eq_bot_iff at h,
simp only [h, not_s_opp_side_bot],
refl },
{ by_cases hx : x ∈ s,
{ convert is_preconnected_empty,
simp only [hx, s_opp_side, not_true, false_and, and_false],
refl },
{ exact (is_connected_set_of_s_opp_side hx h).is_preconnected } }
end
end normed
end affine_subspace
|
1737fd32ec970d4981e2c2969eec46ad5cfc1f2e | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /tests/lean/implicit1.lean | c067ef04888d0ad3936bd2223ccfa5463273a80d | [
"Apache-2.0"
] | permissive | codyroux/lean0.1 | 1ce92751d664aacff0529e139083304a7bbc8a71 | 0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef | refs/heads/master | 1,610,830,535,062 | 1,402,150,480,000 | 1,402,150,480,000 | 19,588,851 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 745 | lean | import Int.
import Real.
variable f : Int -> Int -> Int
print forall a, f a a > 0
print forall a b, f a b > 0
variable g : Int -> Real -> Int
print forall a b, g a b > 0
print forall a b, g a (f a b) > 0
set_option pp::coercion true
print forall a b, g a (f a b) > 0
print fun a, a + 1
print fun a b, a + b
print fun (a b) (c : Int), a + c + b
-- The next example shows a limitation of the current elaborator.
-- The current elaborator resolves overloads before solving the implicit argument constraints.
-- So, it does not have enough information for deciding which overload to use.
print (fun a b, a + b) 10 20.
variable x : Int
-- The following one works because the type of x is used to decide which + should be used
print fun a b, a + x + b |
c8c921d7488b4c47c44e5a841450efec9d31e26b | 8c1d42979ad0e82bd7b1e39716fee7fbfe035fb0 | /hott/algebra/group_theory.hlean | 152bb50ea20dbcf7e837d62f1d6b17ff690927bf | [
"Apache-2.0"
] | permissive | pachugupta/lean2 | cb7513927669b0861fe26de46172f60799c55a5a | c2687310939f884d3fc78b2a56d736b470c779b2 | refs/heads/master | 1,611,083,498,962 | 1,490,236,465,000 | 1,490,907,111,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 19,298 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
Basic group theory
-/
import algebra.category.category algebra.bundled .homomorphism
open eq algebra pointed function is_trunc pi equiv is_equiv
set_option class.force_new true
namespace group
definition pointed_Group [instance] [constructor] (G : Group) : pointed G :=
pointed.mk 1
definition Group.struct' [instance] [reducible] (G : Group) : group G :=
Group.struct G
definition ab_group_Group_of_AbGroup [instance] [constructor] [priority 900]
(G : AbGroup) : ab_group (Group_of_AbGroup G) :=
begin esimp, exact _ end
definition ab_group_pSet_of_Group [instance] (G : AbGroup) : ab_group (pSet_of_Group G) :=
AbGroup.struct G
definition group_pSet_of_Group [instance] [priority 900] (G : Group) :
group (pSet_of_Group G) :=
Group.struct G
/- group homomorphisms -/
/-
definition is_homomorphism [class] [reducible]
{G₁ G₂ : Type} [has_mul G₁] [has_mul G₂] (φ : G₁ → G₂) : Type :=
Π(g h : G₁), φ (g * h) = φ g * φ h
section
variables {G G₁ G₂ G₃ : Type} {g h : G₁} (ψ : G₂ → G₃) {φ₁ φ₂ : G₁ → G₂} (φ : G₁ → G₂)
[group G] [group G₁] [group G₂] [group G₃]
[is_homomorphism ψ] [is_homomorphism φ₁] [is_homomorphism φ₂] [is_homomorphism φ]
definition respect_mul {G₁ G₂ : Type} [has_mul G₁] [has_mul G₂] (φ : G₁ → G₂)
[is_homomorphism φ] : Π(g h : G₁), φ (g * h) = φ g * φ h :=
by assumption
theorem respect_one /- φ -/ : φ 1 = 1 :=
mul.right_cancel
(calc
φ 1 * φ 1 = φ (1 * 1) : respect_mul φ
... = φ 1 : ap φ !one_mul
... = 1 * φ 1 : one_mul)
theorem respect_inv /- φ -/ (g : G₁) : φ g⁻¹ = (φ g)⁻¹ :=
eq_inv_of_mul_eq_one (!respect_mul⁻¹ ⬝ ap φ !mul.left_inv ⬝ !respect_one)
definition is_embedding_homomorphism /- φ -/ (H : Π{g}, φ g = 1 → g = 1) : is_embedding φ :=
begin
apply function.is_embedding_of_is_injective,
intro g g' p,
apply eq_of_mul_inv_eq_one,
apply H,
refine !respect_mul ⬝ _,
rewrite [respect_inv φ, p],
apply mul.right_inv
end
definition is_homomorphism_compose {ψ : G₂ → G₃} {φ : G₁ → G₂}
(H1 : is_homomorphism ψ) (H2 : is_homomorphism φ) : is_homomorphism (ψ ∘ φ) :=
λg h, ap ψ !respect_mul ⬝ !respect_mul
definition is_homomorphism_id (G : Type) [group G] : is_homomorphism (@id G) :=
λg h, idp
end
section additive
definition is_add_homomorphism [class] [reducible] {G₁ G₂ : Type} [has_add G₁] [has_add G₂]
(φ : G₁ → G₂) : Type :=
Π(g h : G₁), φ (g + h) = φ g + φ h
variables {G₁ G₂ : Type} (φ : G₁ → G₂) [add_group G₁] [add_group G₂] [is_add_homomorphism φ]
definition respect_add /- φ -/ : Π(g h : G₁), φ (g + h) = φ g + φ h :=
by assumption
theorem respect_zero /- φ -/ : φ 0 = 0 :=
add.right_cancel
(calc
φ 0 + φ 0 = φ (0 + 0) : respect_add φ
... = φ 0 : ap φ !zero_add
... = 0 + φ 0 : zero_add)
theorem respect_neg /- φ -/ (g : G₁) : φ (-g) = -(φ g) :=
eq_neg_of_add_eq_zero (!respect_add⁻¹ ⬝ ap φ !add.left_inv ⬝ !respect_zero)
end additive
-/
structure homomorphism (G₁ G₂ : Group) : Type :=
(φ : G₁ → G₂)
(p : is_mul_hom φ)
infix ` →g `:55 := homomorphism
definition group_fun [unfold 3] [coercion] := @homomorphism.φ
definition homomorphism.struct [unfold 3] [instance] [priority 900] {G₁ G₂ : Group}
(φ : G₁ →g G₂) : is_mul_hom φ :=
homomorphism.p φ
definition homomorphism.mulstruct [instance] [priority 2000] {G₁ G₂ : Group} (φ : G₁ →g G₂)
: is_mul_hom φ :=
homomorphism.p φ
definition homomorphism.addstruct [instance] [priority 2000] {G₁ G₂ : AddGroup} (φ : G₁ →g G₂)
: is_add_hom φ :=
homomorphism.p φ
variables {G G₁ G₂ G₃ : Group} {g h : G₁} {ψ : G₂ →g G₃} {φ₁ φ₂ : G₁ →g G₂} (φ : G₁ →g G₂)
definition to_respect_mul /- φ -/ (g h : G₁) : φ (g * h) = φ g * φ h :=
respect_mul φ g h
theorem to_respect_one /- φ -/ : φ 1 = 1 :=
respect_one φ
theorem to_respect_inv /- φ -/ (g : G₁) : φ g⁻¹ = (φ g)⁻¹ :=
respect_inv φ g
definition to_is_embedding_homomorphism /- φ -/ (H : Π{g}, φ g = 1 → g = 1) : is_embedding φ :=
is_embedding_of_is_mul_hom φ @H
variables (G₁ G₂)
definition is_set_homomorphism [instance] : is_set (G₁ →g G₂) :=
begin
have H : G₁ →g G₂ ≃ Σ(f : G₁ → G₂), Π(g₁ g₂ : G₁), f (g₁ * g₂) = f g₁ * f g₂,
begin
fapply equiv.MK,
{ intro φ, induction φ, constructor, exact (respect_mul φ)},
{ intro v, induction v with f H, constructor, exact H},
{ intro v, induction v, reflexivity},
{ intro φ, induction φ, reflexivity}
end,
apply is_trunc_equiv_closed_rev, exact H
end
variables {G₁ G₂}
definition pmap_of_homomorphism [constructor] /- φ -/ : G₁ →* G₂ :=
pmap.mk φ begin esimp, exact respect_one φ end
definition homomorphism_change_fun [constructor] {G₁ G₂ : Group}
(φ : G₁ →g G₂) (f : G₁ → G₂) (p : φ ~ f) : G₁ →g G₂ :=
homomorphism.mk f
(λg h, (p (g * h))⁻¹ ⬝ to_respect_mul φ g h ⬝ ap011 mul (p g) (p h))
definition homomorphism_eq (p : group_fun φ₁ ~ group_fun φ₂) : φ₁ = φ₂ :=
begin
induction φ₁ with φ₁ q₁, induction φ₂ with φ₂ q₂, esimp at p, induction p,
exact ap (homomorphism.mk φ₁) !is_prop.elim
end
section additive
variables {H₁ H₂ : AddGroup} (χ : H₁ →g H₂)
definition to_respect_add /- χ -/ (g h : H₁) : χ (g + h) = χ g + χ h :=
respect_add χ g h
theorem to_respect_zero /- χ -/ : χ 0 = 0 :=
respect_zero χ
theorem to_respect_neg /- χ -/ (g : H₁) : χ (-g) = -(χ g) :=
respect_neg χ g
end additive
section add_mul
variables {H₁ : AddGroup} {H₂ : Group} (χ : H₁ →g H₂)
definition to_respect_add_mul /- χ -/ (g h : H₁) : χ (g + h) = χ g * χ h :=
to_respect_mul χ g h
theorem to_respect_zero_one /- χ -/ : χ 0 = 1 :=
to_respect_one χ
theorem to_respect_neg_inv /- χ -/ (g : H₁) : χ (-g) = (χ g)⁻¹ :=
to_respect_inv χ g
end add_mul
section mul_add
variables {H₁ : Group} {H₂ : AddGroup} (χ : H₁ →g H₂)
definition to_respect_mul_add /- χ -/ (g h : H₁) : χ (g * h) = χ g + χ h :=
to_respect_mul χ g h
theorem to_respect_one_zero /- χ -/ : χ 1 = 0 :=
to_respect_one χ
theorem to_respect_inv_neg /- χ -/ (g : H₁) : χ g⁻¹ = -(χ g) :=
to_respect_inv χ g
end mul_add
/- categorical structure of groups + homomorphisms -/
definition homomorphism_compose [constructor] [trans] (ψ : G₂ →g G₃) (φ : G₁ →g G₂) : G₁ →g G₃ :=
homomorphism.mk (ψ ∘ φ) (is_mul_hom_compose _ _)
variable (G)
definition homomorphism_id [constructor] [refl] : G →g G :=
homomorphism.mk (@id G) (is_mul_hom_id G)
variable {G}
abbreviation gid [constructor] := @homomorphism_id
infixr ` ∘g `:75 := homomorphism_compose
notation 1 := homomorphism_id _
structure isomorphism (A B : Group) :=
(to_hom : A →g B)
(is_equiv_to_hom : is_equiv to_hom)
infix ` ≃g `:25 := isomorphism
attribute isomorphism.to_hom [coercion]
attribute isomorphism.is_equiv_to_hom [instance]
attribute isomorphism._trans_of_to_hom [unfold 3]
definition equiv_of_isomorphism [constructor] (φ : G₁ ≃g G₂) : G₁ ≃ G₂ :=
equiv.mk φ _
definition pequiv_of_isomorphism [constructor] (φ : G₁ ≃g G₂) :
G₁ ≃* G₂ :=
pequiv.mk φ begin esimp, exact _ end begin esimp, exact respect_one φ end
definition isomorphism_of_equiv [constructor] (φ : G₁ ≃ G₂)
(p : Πg₁ g₂, φ (g₁ * g₂) = φ g₁ * φ g₂) : G₁ ≃g G₂ :=
isomorphism.mk (homomorphism.mk φ p) !to_is_equiv
definition isomorphism_of_eq [constructor] {G₁ G₂ : Group} (φ : G₁ = G₂) : G₁ ≃g G₂ :=
isomorphism_of_equiv (equiv_of_eq (ap Group.carrier φ))
begin intros, induction φ, reflexivity end
definition pequiv_of_isomorphism_of_eq {G₁ G₂ : Group} (p : G₁ = G₂) :
pequiv_of_isomorphism (isomorphism_of_eq p) = pequiv_of_eq (ap pType_of_Group p) :=
begin
induction p,
apply pequiv_eq,
fapply pmap_eq,
{ intro g, reflexivity},
{ apply is_prop.elim}
end
definition to_ginv [constructor] (φ : G₁ ≃g G₂) : G₂ →g G₁ :=
homomorphism.mk φ⁻¹
abstract begin
intro g₁ g₂, apply eq_of_fn_eq_fn' φ,
rewrite [respect_mul φ, +right_inv φ]
end end
variable (G)
definition isomorphism.refl [refl] [constructor] : G ≃g G :=
isomorphism.mk 1 !is_equiv_id
variable {G}
definition isomorphism.symm [symm] [constructor] (φ : G₁ ≃g G₂) : G₂ ≃g G₁ :=
isomorphism.mk (to_ginv φ) !is_equiv_inv
definition isomorphism.trans [trans] [constructor] (φ : G₁ ≃g G₂) (ψ : G₂ ≃g G₃) : G₁ ≃g G₃ :=
isomorphism.mk (ψ ∘g φ) !is_equiv_compose
definition isomorphism.eq_trans [trans] [constructor]
{G₁ G₂ : Group} {G₃ : Group} (φ : G₁ = G₂) (ψ : G₂ ≃g G₃) : G₁ ≃g G₃ :=
proof isomorphism.trans (isomorphism_of_eq φ) ψ qed
definition isomorphism.trans_eq [trans] [constructor]
{G₁ : Group} {G₂ G₃ : Group} (φ : G₁ ≃g G₂) (ψ : G₂ = G₃) : G₁ ≃g G₃ :=
isomorphism.trans φ (isomorphism_of_eq ψ)
postfix `⁻¹ᵍ`:(max + 1) := isomorphism.symm
infixl ` ⬝g `:75 := isomorphism.trans
infixl ` ⬝gp `:75 := isomorphism.trans_eq
infixl ` ⬝pg `:75 := isomorphism.eq_trans
definition pmap_of_isomorphism [constructor] (φ : G₁ ≃g G₂) :
G₁ →* G₂ :=
pequiv_of_isomorphism φ
/- category of groups -/
section
open category
definition precategory_group [constructor] : precategory Group :=
precategory.mk homomorphism
@homomorphism_compose
@homomorphism_id
(λG₁ G₂ G₃ G₄ φ₃ φ₂ φ₁, homomorphism_eq (λg, idp))
(λG₁ G₂ φ, homomorphism_eq (λg, idp))
(λG₁ G₂ φ, homomorphism_eq (λg, idp))
end
-- TODO
-- definition category_group : category Group :=
-- category.mk precategory_group
-- begin
-- intro G₁ G₂,
-- fapply adjointify,
-- { intro φ, fapply Group_eq, },
-- { },
-- { }
-- end
/- given an equivalence A ≃ B we can transport a group structure on A to a group structure on B -/
section
parameters {A B : Type} (f : A ≃ B) [group A]
definition group_equiv_mul (b b' : B) : B := f (f⁻¹ᶠ b * f⁻¹ᶠ b')
definition group_equiv_one : B := f one
definition group_equiv_inv (b : B) : B := f (f⁻¹ᶠ b)⁻¹
local infix * := group_equiv_mul
local postfix ^ := group_equiv_inv
local notation 1 := group_equiv_one
theorem group_equiv_mul_assoc (b₁ b₂ b₃ : B) : (b₁ * b₂) * b₃ = b₁ * (b₂ * b₃) :=
by rewrite [↑group_equiv_mul, +left_inv f, mul.assoc]
theorem group_equiv_one_mul (b : B) : 1 * b = b :=
by rewrite [↑group_equiv_mul, ↑group_equiv_one, left_inv f, one_mul, right_inv f]
theorem group_equiv_mul_one (b : B) : b * 1 = b :=
by rewrite [↑group_equiv_mul, ↑group_equiv_one, left_inv f, mul_one, right_inv f]
theorem group_equiv_mul_left_inv (b : B) : b^ * b = 1 :=
by rewrite [↑group_equiv_mul, ↑group_equiv_one, ↑group_equiv_inv,
+left_inv f, mul.left_inv]
definition group_equiv_closed : group B :=
⦃group,
mul := group_equiv_mul,
mul_assoc := group_equiv_mul_assoc,
one := group_equiv_one,
one_mul := group_equiv_one_mul,
mul_one := group_equiv_mul_one,
inv := group_equiv_inv,
mul_left_inv := group_equiv_mul_left_inv,
is_set_carrier := is_trunc_equiv_closed 0 f⦄
end
variable (G)
/- the trivial group -/
open unit
definition trivial_group [constructor] : group unit :=
group.mk _ (λx y, star) (λx y z, idp) star (unit.rec idp) (unit.rec idp) (λx, star) (λx, idp)
definition Trivial_group [constructor] : Group :=
Group.mk _ trivial_group
abbreviation G0 := Trivial_group
definition trivial_group_of_is_contr [H : is_contr G] : G ≃g G0 :=
begin
fapply isomorphism_of_equiv,
{ apply equiv_unit_of_is_contr},
{ intros, reflexivity}
end
variable {G}
/-
A group where the point in the pointed type corresponds with 1 in the group.
We need this structure when we are given a pointed type, and want to say that there is a group
structure on it which is compatible with the point. This is used in chain complexes.
-/
structure pgroup [class] (X : Type*) extends semigroup X, has_inv X :=
(pt_mul : Πa, mul pt a = a)
(mul_pt : Πa, mul a pt = a)
(mul_left_inv_pt : Πa, mul (inv a) a = pt)
definition group_of_pgroup [reducible] [instance] (X : Type*) [H : pgroup X]
: group X :=
⦃group, H,
one := pt,
one_mul := pgroup.pt_mul ,
mul_one := pgroup.mul_pt,
mul_left_inv := pgroup.mul_left_inv_pt⦄
definition pgroup_of_group (X : Type*) [H : group X] (p : one = pt :> X) : pgroup X :=
begin
cases X with X x, esimp at *, induction p,
exact ⦃pgroup, H,
pt_mul := one_mul,
mul_pt := mul_one,
mul_left_inv_pt := mul.left_inv⦄
end
definition Group_of_pgroup (G : Type*) [pgroup G] : Group :=
Group.mk G _
definition pgroup_Group [instance] (G : Group) : pgroup G :=
⦃ pgroup, Group.struct G,
pt_mul := one_mul,
mul_pt := mul_one,
mul_left_inv_pt := mul.left_inv ⦄
-- infinity pgroups
structure inf_pgroup [class] (X : Type*) extends inf_semigroup X, has_inv X :=
(pt_mul : Πa, mul pt a = a)
(mul_pt : Πa, mul a pt = a)
(mul_left_inv_pt : Πa, mul (inv a) a = pt)
definition inf_group_of_inf_pgroup [reducible] [instance] (X : Type*) [H : inf_pgroup X]
: inf_group X :=
⦃inf_group, H,
one := pt,
one_mul := inf_pgroup.pt_mul ,
mul_one := inf_pgroup.mul_pt,
mul_left_inv := inf_pgroup.mul_left_inv_pt⦄
definition inf_pgroup_of_inf_group (X : Type*) [H : inf_group X] (p : one = pt :> X) : inf_pgroup X :=
begin
cases X with X x, esimp at *, induction p,
exact ⦃inf_pgroup, H,
pt_mul := one_mul,
mul_pt := mul_one,
mul_left_inv_pt := mul.left_inv⦄
end
definition inf_Group_of_inf_pgroup (G : Type*) [inf_pgroup G] : InfGroup :=
InfGroup.mk G _
definition inf_pgroup_InfGroup [instance] (G : InfGroup) : inf_pgroup G :=
⦃ inf_pgroup, InfGroup.struct G,
pt_mul := one_mul,
mul_pt := mul_one,
mul_left_inv_pt := mul.left_inv ⦄
/- equality of groups and abelian groups -/
definition group.to_has_mul {A : Type} (H : group A) : has_mul A := _
definition group.to_has_inv {A : Type} (H : group A) : has_inv A := _
definition group.to_has_one {A : Type} (H : group A) : has_one A := _
local attribute group.to_has_mul group.to_has_inv [coercion]
universe variable l
variables {A B : Type.{l}}
definition group_eq {G H : group A} (same_mul' : Π(g h : A), @mul A G g h = @mul A H g h)
: G = H :=
begin
have foo : Π(g : A), @inv A G g = (@inv A G g * g) * @inv A H g,
from λg, !mul_inv_cancel_right⁻¹,
cases G with Gs Gm Gh1 G1 Gh2 Gh3 Gi Gh4,
cases H with Hs Hm Hh1 H1 Hh2 Hh3 Hi Hh4,
have same_mul : Gm = Hm, from eq_of_homotopy2 same_mul',
cases same_mul,
have same_one : G1 = H1, from calc
G1 = Hm G1 H1 : Hh3
... = H1 : Gh2,
have same_inv : Gi = Hi, from eq_of_homotopy (take g, calc
Gi g = Hm (Hm (Gi g) g) (Hi g) : foo
... = Hm G1 (Hi g) : by rewrite Gh4
... = Hi g : Gh2),
cases same_one, cases same_inv,
have ps : Gs = Hs, from !is_prop.elim,
have ph1 : Gh1 = Hh1, from !is_prop.elim,
have ph2 : Gh2 = Hh2, from !is_prop.elim,
have ph3 : Gh3 = Hh3, from !is_prop.elim,
have ph4 : Gh4 = Hh4, from !is_prop.elim,
cases ps, cases ph1, cases ph2, cases ph3, cases ph4, reflexivity
end
definition group_pathover {G : group A} {H : group B} {p : A = B}
(resp_mul : Π(g h : A), cast p (g * h) = cast p g * cast p h) : G =[p] H :=
begin
induction p,
apply pathover_idp_of_eq, exact group_eq (resp_mul)
end
definition Group_eq_of_eq {G H : Group} (p : Group.carrier G = Group.carrier H)
(resp_mul : Π(g h : G), cast p (g * h) = cast p g * cast p h) : G = H :=
begin
cases G with Gc G, cases H with Hc H,
apply (apd011 Group.mk p),
exact group_pathover resp_mul
end
definition Group_eq {G H : Group} (f : Group.carrier G ≃ Group.carrier H)
(resp_mul : Π(g h : G), f (g * h) = f g * f h) : G = H :=
Group_eq_of_eq (ua f) (λg h, !cast_ua ⬝ resp_mul g h ⬝ ap011 mul !cast_ua⁻¹ !cast_ua⁻¹)
definition eq_of_isomorphism {G₁ G₂ : Group} (φ : G₁ ≃g G₂) : G₁ = G₂ :=
Group_eq (equiv_of_isomorphism φ) (respect_mul φ)
definition ab_group.to_has_mul {A : Type} (H : ab_group A) : has_mul A := _
local attribute ab_group.to_has_mul [coercion]
definition ab_group_eq {A : Type} {G H : ab_group A}
(same_mul : Π(g h : A), @mul A G g h = @mul A H g h)
: G = H :=
begin
have g_eq : @ab_group.to_group A G = @ab_group.to_group A H, from group_eq same_mul,
cases G with Gs Gm Gh1 G1 Gh2 Gh3 Gi Gh4 Gh5,
cases H with Hs Hm Hh1 H1 Hh2 Hh3 Hi Hh4 Hh5,
have pm : Gm = Hm, from ap (@mul _ ∘ group.to_has_mul) g_eq,
have pi : Gi = Hi, from ap (@inv _ ∘ group.to_has_inv) g_eq,
have p1 : G1 = H1, from ap (@one _ ∘ group.to_has_one) g_eq,
induction pm, induction pi, induction p1,
have ps : Gs = Hs, from !is_prop.elim,
have ph1 : Gh1 = Hh1, from !is_prop.elim,
have ph2 : Gh2 = Hh2, from !is_prop.elim,
have ph3 : Gh3 = Hh3, from !is_prop.elim,
have ph4 : Gh4 = Hh4, from !is_prop.elim,
have ph5 : Gh5 = Hh5, from !is_prop.elim,
induction ps, induction ph1, induction ph2, induction ph3, induction ph4, induction ph5,
reflexivity
end
definition ab_group_pathover {A B : Type} {G : ab_group A} {H : ab_group B} {p : A = B}
(resp_mul : Π(g h : A), cast p (g * h) = cast p g * cast p h) : G =[p] H :=
begin
induction p,
apply pathover_idp_of_eq, exact ab_group_eq (resp_mul)
end
definition AbGroup_eq_of_isomorphism {G₁ G₂ : AbGroup} (φ : G₁ ≃g G₂) : G₁ = G₂ :=
begin
induction G₁, induction G₂,
apply apd011 AbGroup.mk (ua (equiv_of_isomorphism φ)),
apply ab_group_pathover,
intro g h, exact !cast_ua ⬝ respect_mul φ g h ⬝ ap011 mul !cast_ua⁻¹ !cast_ua⁻¹
end
definition trivial_group_of_is_contr' (G : Group) [H : is_contr G] : G = G0 :=
eq_of_isomorphism (trivial_group_of_is_contr G)
end group
|
bcda3b05c2ac34f52cdf4cde49e2a58b137a3fb4 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/override1.lean | ba5cf06e59b376558a4577dedffbd823cb291a98 | [
"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 | 589 | lean | import data.finset data.set
open set
example (A : Type) (x : A) (S H : set A) (Pin : x ∈ S)
(Psub : S ⊆ H) : x ∈ H := Psub Pin
open finset
section
override set -- set notation overrides existing one
example (A : Type) (x : A) (S H : set A) (Pin : x ∈ S)
(Psub : S ⊆ H) : x ∈ H := Psub Pin
end
-- ⊆ is now overloaded
example (A : Type) (x : A) (S H : set A) (Pin : x ∈ S)
(Psub : S ⊆ H) : x ∈ H := Psub _ Pin
override set -- overrides existing notation
example (A : Type) (x : A) (S H : set A) (Pin : x ∈ S) (Psub : S ⊆ H) : x ∈ H := Psub Pin
|
f17a295ae3d655de917ceb1d1faf22948d1de00b | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/calculus/dslope.lean | 2f20481ada53d746612512abce85b8b1ff328b8f | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 6,308 | lean | /-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.calculus.deriv
import linear_algebra.affine_space.slope
/-!
# Slope of a differentiable function
Given a function `f : 𝕜 → E` from a nontrivially normed field to a normed space over this field,
`dslope f a b` is defined as `slope f a b = (b - a)⁻¹ • (f b - f a)` for `a ≠ b` and as `deriv f a`
for `a = b`.
In this file we define `dslope` and prove some basic lemmas about its continuity and
differentiability.
-/
open_locale classical topological_space filter
open function set filter
variables {𝕜 E : Type*} [nontrivially_normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E]
/-- `dslope f a b` is defined as `slope f a b = (b - a)⁻¹ • (f b - f a)` for `a ≠ b` and
`deriv f a` for `a = b`. -/
noncomputable def dslope (f : 𝕜 → E) (a : 𝕜) : 𝕜 → E := update (slope f a) a (deriv f a)
@[simp] lemma dslope_same (f : 𝕜 → E) (a : 𝕜) : dslope f a a = deriv f a := update_same _ _ _
variables {f : 𝕜 → E} {a b : 𝕜} {s : set 𝕜}
lemma dslope_of_ne (f : 𝕜 → E) (h : b ≠ a) : dslope f a b = slope f a b :=
update_noteq h _ _
lemma continuous_linear_map.dslope_comp {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F]
(f : E →L[𝕜] F) (g : 𝕜 → E) (a b : 𝕜) (H : a = b → differentiable_at 𝕜 g a) :
dslope (f ∘ g) a b = f (dslope g a b) :=
begin
rcases eq_or_ne b a with rfl|hne,
{ simp only [dslope_same],
exact (f.has_fderiv_at.comp_has_deriv_at b (H rfl).has_deriv_at).deriv },
{ simpa only [dslope_of_ne _ hne] using f.to_linear_map.slope_comp g a b }
end
lemma eq_on_dslope_slope (f : 𝕜 → E) (a : 𝕜) : eq_on (dslope f a) (slope f a) {a}ᶜ :=
λ b, dslope_of_ne f
lemma dslope_eventually_eq_slope_of_ne (f : 𝕜 → E) (h : b ≠ a) : dslope f a =ᶠ[𝓝 b] slope f a :=
(eq_on_dslope_slope f a).eventually_eq_of_mem (is_open_ne.mem_nhds h)
lemma dslope_eventually_eq_slope_punctured_nhds (f : 𝕜 → E) : dslope f a =ᶠ[𝓝[≠] a] slope f a :=
(eq_on_dslope_slope f a).eventually_eq_of_mem self_mem_nhds_within
@[simp] lemma sub_smul_dslope (f : 𝕜 → E) (a b : 𝕜) : (b - a) • dslope f a b = f b - f a :=
by rcases eq_or_ne b a with rfl | hne; simp [dslope_of_ne, *]
lemma dslope_sub_smul_of_ne (f : 𝕜 → E) (h : b ≠ a) : dslope (λ x, (x - a) • f x) a b = f b :=
by rw [dslope_of_ne _ h, slope_sub_smul _ h.symm]
lemma eq_on_dslope_sub_smul (f : 𝕜 → E) (a : 𝕜) : eq_on (dslope (λ x, (x - a) • f x) a) f {a}ᶜ :=
λ b, dslope_sub_smul_of_ne f
lemma dslope_sub_smul [decidable_eq 𝕜] (f : 𝕜 → E) (a : 𝕜) :
dslope (λ x, (x - a) • f x) a = update f a (deriv (λ x, (x - a) • f x) a) :=
eq_update_iff.2 ⟨dslope_same _ _, eq_on_dslope_sub_smul f a⟩
@[simp] lemma continuous_at_dslope_same : continuous_at (dslope f a) a ↔ differentiable_at 𝕜 f a :=
by simp only [dslope, continuous_at_update_same, ← has_deriv_at_deriv_iff,
has_deriv_at_iff_tendsto_slope]
lemma continuous_within_at.of_dslope (h : continuous_within_at (dslope f a) s b) :
continuous_within_at f s b :=
have continuous_within_at (λ x, (x - a) • dslope f a x + f a) s b,
from ((continuous_within_at_id.sub continuous_within_at_const).smul h).add
continuous_within_at_const,
by simpa only [sub_smul_dslope, sub_add_cancel] using this
lemma continuous_at.of_dslope (h : continuous_at (dslope f a) b) : continuous_at f b :=
(continuous_within_at_univ _ _).1 h.continuous_within_at.of_dslope
lemma continuous_on.of_dslope (h : continuous_on (dslope f a) s) : continuous_on f s :=
λ x hx, (h x hx).of_dslope
lemma continuous_within_at_dslope_of_ne (h : b ≠ a) :
continuous_within_at (dslope f a) s b ↔ continuous_within_at f s b :=
begin
refine ⟨continuous_within_at.of_dslope, λ hc, _⟩,
simp only [dslope, continuous_within_at_update_of_ne h],
exact ((continuous_within_at_id.sub continuous_within_at_const).inv₀
(sub_ne_zero.2 h)).smul (hc.sub continuous_within_at_const)
end
lemma continuous_at_dslope_of_ne (h : b ≠ a) : continuous_at (dslope f a) b ↔ continuous_at f b :=
by simp only [← continuous_within_at_univ, continuous_within_at_dslope_of_ne h]
lemma continuous_on_dslope (h : s ∈ 𝓝 a) :
continuous_on (dslope f a) s ↔ continuous_on f s ∧ differentiable_at 𝕜 f a :=
begin
refine ⟨λ hc, ⟨hc.of_dslope, continuous_at_dslope_same.1 $ hc.continuous_at h⟩, _⟩,
rintro ⟨hc, hd⟩ x hx,
rcases eq_or_ne x a with rfl | hne,
exacts [(continuous_at_dslope_same.2 hd).continuous_within_at,
(continuous_within_at_dslope_of_ne hne).2 (hc x hx)]
end
lemma differentiable_within_at.of_dslope (h : differentiable_within_at 𝕜 (dslope f a) s b) :
differentiable_within_at 𝕜 f s b :=
by simpa only [id, sub_smul_dslope f a, sub_add_cancel]
using ((differentiable_within_at_id.sub_const a).smul h).add_const (f a)
lemma differentiable_at.of_dslope (h : differentiable_at 𝕜 (dslope f a) b) :
differentiable_at 𝕜 f b :=
differentiable_within_at_univ.1 h.differentiable_within_at.of_dslope
lemma differentiable_on.of_dslope (h : differentiable_on 𝕜 (dslope f a) s) :
differentiable_on 𝕜 f s :=
λ x hx, (h x hx).of_dslope
lemma differentiable_within_at_dslope_of_ne (h : b ≠ a) :
differentiable_within_at 𝕜 (dslope f a) s b ↔ differentiable_within_at 𝕜 f s b :=
begin
refine ⟨differentiable_within_at.of_dslope, λ hd, _⟩,
refine (((differentiable_within_at_id.sub_const a).inv
(sub_ne_zero.2 h)).smul (hd.sub_const (f a))).congr_of_eventually_eq _ (dslope_of_ne _ h),
refine (eq_on_dslope_slope _ _).eventually_eq_of_mem _,
exact mem_nhds_within_of_mem_nhds (is_open_ne.mem_nhds h)
end
lemma differentiable_on_dslope_of_nmem (h : a ∉ s) :
differentiable_on 𝕜 (dslope f a) s ↔ differentiable_on 𝕜 f s :=
forall_congr $ λ x, forall_congr $ λ hx, differentiable_within_at_dslope_of_ne $
ne_of_mem_of_not_mem hx h
lemma differentiable_at_dslope_of_ne (h : b ≠ a) :
differentiable_at 𝕜 (dslope f a) b ↔ differentiable_at 𝕜 f b :=
by simp only [← differentiable_within_at_univ,
differentiable_within_at_dslope_of_ne h]
|
74cb9eac4ddd60b2b08223a6535a1f7c4fc1c76b | c777c32c8e484e195053731103c5e52af26a25d1 | /src/analysis/fourier/poisson_summation.lean | 17e5fae7dc9ccf1c79d480d052d19a756fc6ddb1 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 12,766 | lean | /-
Copyright (c) 2023 David Loeffler. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Loeffler
-/
import analysis.fourier.add_circle
import analysis.fourier.fourier_transform
import analysis.p_series
import analysis.schwartz_space
/-!
# Poisson's summation formula
We prove Poisson's summation formula `∑ (n : ℤ), f n = ∑ (n : ℤ), 𝓕 f n`, where `𝓕 f` is the
Fourier transform of `f`, under the following hypotheses:
* `f` is a continuous function `ℝ → ℂ`.
* The sum `∑ (n : ℤ), 𝓕 f n` is convergent.
* For all compacts `K ⊂ ℝ`, the sum `∑ (n : ℤ), sup { ‖f(x + n)‖ | x ∈ K }` is convergent.
See `real.tsum_eq_tsum_fourier_integral` for this formulation.
These hypotheses are potentially a little awkward to apply, so we also provide the less general but
easier-to-use result `real.tsum_eq_tsum_fourier_integral_of_rpow_decay`, in which we assume `f` and
`𝓕 f` both decay as `|x| ^ (-b)` for some `b > 1`, and the even more specific result
`schwartz_map.tsum_eq_tsum_fourier_integral`, where we assume that both `f` and `𝓕 f` are Schwartz
functions.
## TODO
At the moment `schwartz_map.tsum_eq_tsum_fourier_integral` requires separate proofs that both `f`
and `𝓕 f` are Schwartz functions. In fact, `𝓕 f` is automatically Schwartz if `f` is; and once
we have this lemma in the library, we should adjust the hypotheses here accordingly.
-/
noncomputable theory
open function (hiding comp_apply) complex (hiding abs_of_nonneg) real set (hiding restrict_apply)
topological_space filter measure_theory asymptotics
open_locale real big_operators filter fourier_transform
local attribute [instance] real.fact_zero_lt_one
open continuous_map
/-- The key lemma for Poisson summation: the `m`-th Fourier coefficient of the periodic function
`∑' n : ℤ, f (x + n)` is the value at `m` of the Fourier transform of `f`. -/
lemma real.fourier_coeff_tsum_comp_add {f : C(ℝ, ℂ)}
(hf : ∀ (K : compacts ℝ), summable (λ n : ℤ, ‖(f.comp (continuous_map.add_right n)).restrict K‖))
(m : ℤ) :
fourier_coeff (periodic.lift $ f.periodic_tsum_comp_add_zsmul 1) m = 𝓕 f m :=
begin
-- NB: This proof can be shortened somewhat by telescoping together some of the steps in the calc
-- block, but I think it's more legible this way. We start with preliminaries about the integrand.
let e : C(ℝ, ℂ) := (fourier (-m)).comp ⟨(coe : ℝ → unit_add_circle), continuous_quotient_mk⟩,
have neK : ∀ (K : compacts ℝ) (g : C(ℝ, ℂ)), ‖(e * g).restrict K‖ = ‖g.restrict K‖,
{ have : ∀ (x : ℝ), ‖e x‖ = 1, from λ x, abs_coe_circle _,
intros K g,
simp_rw [norm_eq_supr_norm, restrict_apply, mul_apply, norm_mul, this, one_mul] },
have eadd : ∀ (n : ℤ), e.comp (continuous_map.add_right n) = e,
{ intro n, ext1 x,
have : periodic e 1, from periodic.comp (λ x, add_circle.coe_add_period 1 x) _,
simpa only [mul_one] using this.int_mul n x },
-- Now the main argument. First unwind some definitions.
calc fourier_coeff (periodic.lift $ f.periodic_tsum_comp_add_zsmul 1) m
= ∫ x in 0..1, e x * (∑' n : ℤ, f.comp (continuous_map.add_right n)) x :
by simp_rw [fourier_coeff_eq_interval_integral _ m 0, div_one, one_smul, zero_add, comp_apply,
coe_mk, periodic.lift_coe, zsmul_one, smul_eq_mul]
-- Transform sum in C(ℝ, ℂ) evaluated at x into pointwise sum of values.
... = ∫ x in 0..1, (∑' n : ℤ, (e * f.comp (continuous_map.add_right n)) x) :
by simp_rw [coe_mul, pi.mul_apply, ←tsum_apply (summable_of_locally_summable_norm hf),
tsum_mul_left]
-- Swap sum and integral.
... = ∑' n : ℤ, ∫ x in 0..1, (e * f.comp (continuous_map.add_right n)) x :
begin
refine (interval_integral.tsum_interval_integral_eq_of_summable_norm _).symm,
convert hf ⟨uIcc 0 1, is_compact_uIcc⟩,
exact funext (λ n, neK _ _)
end
... = ∑' n : ℤ, ∫ x in 0..1, (e * f).comp (continuous_map.add_right n) x :
begin
simp only [continuous_map.comp_apply, mul_comp] at eadd ⊢,
simp_rw eadd,
end
-- Rearrange sum of interval integrals into an integral over `ℝ`.
... = ∫ x, e x * f x :
begin
suffices : integrable ⇑(e * f), from this.has_sum_interval_integral_comp_add_int.tsum_eq,
apply integrable_of_summable_norm_Icc,
convert hf ⟨Icc 0 1, is_compact_Icc⟩,
simp_rw [continuous_map.comp_apply, mul_comp] at eadd ⊢,
simp_rw eadd,
exact funext (λ n, neK ⟨Icc 0 1, is_compact_Icc⟩ _),
end
-- Minor tidying to finish
... = 𝓕 f m :
begin
rw fourier_integral_eq_integral_exp_smul,
congr' 1 with x : 1,
rw [smul_eq_mul, comp_apply, coe_mk, fourier_coe_apply],
congr' 2,
push_cast,
ring
end
end
/-- **Poisson's summation formula**, most general form. -/
theorem real.tsum_eq_tsum_fourier_integral {f : C(ℝ, ℂ)}
(h_norm : ∀ (K : compacts ℝ),
summable (λ n : ℤ, ‖(f.comp $ continuous_map.add_right n).restrict K‖))
(h_sum : summable (λ n : ℤ, 𝓕 f n)) :
∑' (n : ℤ), f n = ∑' (n : ℤ), 𝓕 f n :=
begin
let F : C(unit_add_circle, ℂ) := ⟨(f.periodic_tsum_comp_add_zsmul 1).lift,
continuous_coinduced_dom.mpr (map_continuous _)⟩,
have : summable (fourier_coeff F),
{ convert h_sum,
exact funext (λ n, real.fourier_coeff_tsum_comp_add h_norm n) },
convert (has_pointwise_sum_fourier_series_of_summable this 0).tsum_eq.symm using 1,
{ have := (has_sum_apply (summable_of_locally_summable_norm h_norm).has_sum 0).tsum_eq,
simpa only [coe_mk, ←quotient_add_group.coe_zero, periodic.lift_coe, zsmul_one, comp_apply,
coe_add_right, zero_add] using this },
{ congr' 1 with n : 1,
rw [←real.fourier_coeff_tsum_comp_add h_norm n, fourier_eval_zero, smul_eq_mul, mul_one],
refl },
end
section rpow_decay
variables {E : Type*} [normed_add_comm_group E]
/-- If `f` is `O(x ^ (-b))` at infinity, then so is the function
`λ x, ‖f.restrict (Icc (x + R) (x + S))‖` for any fixed `R` and `S`. -/
lemma is_O_norm_Icc_restrict_at_top {f : C(ℝ, E)} {b : ℝ} (hb : 0 < b)
(hf : is_O at_top f (λ x : ℝ, |x| ^ (-b))) (R S : ℝ) :
is_O at_top (λ x : ℝ, ‖f.restrict (Icc (x + R) (x + S))‖) (λ x : ℝ, |x| ^ (-b)) :=
begin
-- First establish an explicit estimate on decay of inverse powers.
-- This is logically independent of the rest of the proof, but of no mathematical interest in
-- itself, so it is proved using `async` rather than being formulated as a separate lemma.
have claim : ∀ (x : ℝ), max 0 (-2 * R) < x →
∀ (y : ℝ), x + R ≤ y → y ^ (-b) ≤ (1 / 2) ^ (-b) * x ^ (-b),
{ intros x hx y hy,
rw max_lt_iff at hx,
have hxR : 0 < x + R,
{ rcases le_or_lt 0 R with h|h,
{ exact add_pos_of_pos_of_nonneg hx.1 h },
{ rw [←sub_lt_iff_lt_add, zero_sub],
refine lt_trans _ hx.2,
rwa [neg_mul, neg_lt_neg_iff, two_mul, add_lt_iff_neg_left] } },
have hy' : 0 < y, from hxR.trans_le hy,
have : y ^ (-b) ≤ (x + R) ^ (-b),
{ rw [rpow_neg hy'.le, rpow_neg hxR.le,
inv_le_inv (rpow_pos_of_pos hy' _) (rpow_pos_of_pos hxR _)],
exact rpow_le_rpow hxR.le hy hb.le },
refine this.trans _,
rw [←mul_rpow one_half_pos.le hx.1.le, rpow_neg (mul_pos one_half_pos hx.1).le,
rpow_neg hxR.le],
refine inv_le_inv_of_le (rpow_pos_of_pos (mul_pos one_half_pos hx.1) _) _,
exact rpow_le_rpow (mul_pos one_half_pos hx.1).le (by linarith) hb.le },
-- Now the main proof.
obtain ⟨c, hc, hc'⟩ := hf.exists_pos,
simp only [is_O, is_O_with, eventually_at_top] at hc' ⊢,
obtain ⟨d, hd⟩ := hc',
refine ⟨c * (1 / 2) ^ (-b), ⟨max (1 + max 0 (-2 * R)) (d - R), λ x hx, _⟩⟩,
rw [ge_iff_le, max_le_iff] at hx,
have hx' : max 0 (-2 * R) < x, by linarith,
rw max_lt_iff at hx',
rw [norm_norm, continuous_map.norm_le _
(mul_nonneg (mul_nonneg hc.le $ rpow_nonneg_of_nonneg one_half_pos.le _) (norm_nonneg _))],
refine λ y, (hd y.1 (by linarith [hx.1, y.2.1])).trans _,
have A : ∀ (x : ℝ), 0 ≤ |x| ^ (-b), from λ x, by positivity,
rwa [mul_assoc, mul_le_mul_left hc, norm_of_nonneg (A _), norm_of_nonneg (A _)],
convert claim x (by linarith only [hx.1]) y.1 y.2.1,
{ apply abs_of_nonneg, linarith [y.2.1] },
{ exact abs_of_pos hx'.1 },
end
lemma is_O_norm_Icc_restrict_at_bot {f : C(ℝ, E)} {b : ℝ} (hb : 0 < b)
(hf : is_O at_bot f (λ x : ℝ, |x| ^ (-b))) (R S : ℝ) :
is_O at_bot (λ x : ℝ, ‖f.restrict (Icc (x + R) (x + S))‖) (λ x : ℝ, |x| ^ (-b)) :=
begin
have h1 : is_O at_top (f.comp (continuous_map.mk _ continuous_neg)) (λ x : ℝ, |x| ^ (-b)),
{ convert hf.comp_tendsto tendsto_neg_at_top_at_bot,
ext1 x, simp only [function.comp_app, abs_neg] },
have h2 := (is_O_norm_Icc_restrict_at_top hb h1 (-S) (-R)).comp_tendsto tendsto_neg_at_bot_at_top,
have : ((λ (x : ℝ), |x| ^ -b) ∘ has_neg.neg) = (λ (x : ℝ), |x| ^ -b),
{ ext1 x, simp only [function.comp_app, abs_neg] },
rw this at h2,
refine (is_O_of_le _ (λ x, _)).trans h2, -- equality holds, but less work to prove `≤` alone
rw [norm_norm, function.comp_app, norm_norm, continuous_map.norm_le _ (norm_nonneg _)],
rintro ⟨x, hx⟩,
rw [continuous_map.restrict_apply_mk],
refine (le_of_eq _).trans (continuous_map.norm_coe_le_norm _ ⟨-x, _⟩),
{ exact ⟨by linarith [hx.2], by linarith [hx.1]⟩ },
{ rw [continuous_map.restrict_apply_mk, continuous_map.comp_apply, continuous_map.coe_mk,
neg_neg] }
end
lemma is_O_norm_restrict_cocompact (f : C(ℝ, E)) {b : ℝ} (hb : 0 < b)
(hf : is_O (cocompact ℝ) f (λ x : ℝ, |x| ^ (-b))) (K : compacts ℝ) :
is_O (cocompact ℝ) (λ x, ‖(f.comp (continuous_map.add_right x)).restrict K‖) (λ x, |x| ^ (-b)) :=
begin
obtain ⟨r, hr⟩ := K.is_compact.bounded.subset_ball 0,
rw [closed_ball_eq_Icc, zero_add, zero_sub] at hr,
have : ∀ (x : ℝ), ‖(f.comp (continuous_map.add_right x)).restrict K‖ ≤
‖f.restrict (Icc (x - r) (x + r))‖,
{ intro x,
rw continuous_map.norm_le _ (norm_nonneg _),
rintro ⟨y, hy⟩,
refine (le_of_eq _).trans (continuous_map.norm_coe_le_norm _ ⟨y + x, _⟩),
exact ⟨by linarith [(hr hy).1], by linarith [(hr hy).2]⟩,
simp_rw [continuous_map.restrict_apply, continuous_map.comp_apply,
continuous_map.coe_add_right, subtype.coe_mk] },
simp_rw [cocompact_eq, is_O_sup] at hf ⊢,
split,
{ refine (is_O_of_le at_bot _).trans (is_O_norm_Icc_restrict_at_bot hb hf.1 (-r) r),
simp_rw norm_norm, exact this },
{ refine (is_O_of_le at_top _).trans (is_O_norm_Icc_restrict_at_top hb hf.2 (-r) r),
simp_rw norm_norm, exact this },
end
/-- **Poisson's summation formula**, assuming that `f` decays as
`|x| ^ (-b)` for some `1 < b` and its Fourier transform is summable. -/
lemma real.tsum_eq_tsum_fourier_integral_of_rpow_decay_of_summable {f : ℝ → ℂ} (hc : continuous f)
{b : ℝ} (hb : 1 < b) (hf : is_O (cocompact ℝ) f (λ x : ℝ, |x| ^ (-b)))
(hFf : summable (λ n : ℤ, 𝓕 f n)) :
∑' (n : ℤ), f n = ∑' (n : ℤ), 𝓕 f n :=
real.tsum_eq_tsum_fourier_integral
(λ K, summable_of_is_O (real.summable_abs_int_rpow hb)
((is_O_norm_restrict_cocompact (continuous_map.mk _ hc)
(zero_lt_one.trans hb) hf K).comp_tendsto int.tendsto_coe_cofinite)) hFf
/-- **Poisson's summation formula**, assuming that both `f` and its Fourier transform decay as
`|x| ^ (-b)` for some `1 < b`. (This is the one-dimensional case of Corollary VII.2.6 of Stein and
Weiss, *Introduction to Fourier analysis on Euclidean spaces*.) -/
lemma real.tsum_eq_tsum_fourier_integral_of_rpow_decay {f : ℝ → ℂ} (hc : continuous f)
{b : ℝ} (hb : 1 < b) (hf : is_O (cocompact ℝ) f (λ x : ℝ, |x| ^ (-b)))
(hFf : is_O (cocompact ℝ) (𝓕 f) (λ x : ℝ, |x| ^ (-b))) :
∑' (n : ℤ), f n = ∑' (n : ℤ), 𝓕 f n :=
real.tsum_eq_tsum_fourier_integral_of_rpow_decay_of_summable hc hb hf
(summable_of_is_O (real.summable_abs_int_rpow hb) (hFf.comp_tendsto int.tendsto_coe_cofinite))
end rpow_decay
section schwartz
/-- **Poisson's summation formula** for Schwartz functions. -/
lemma schwartz_map.tsum_eq_tsum_fourier_integral
(f g : schwartz_map ℝ ℂ) (hfg : 𝓕 f = g) :
∑' (n : ℤ), f n = ∑' (n : ℤ), g n :=
begin
-- We know that Schwartz functions are `O(‖x ^ (-b)‖)` for *every* `b`; for this argument we take
-- `b = 2` and work with that.
simp_rw ←hfg,
exact real.tsum_eq_tsum_fourier_integral_of_rpow_decay f.continuous one_lt_two
(f.is_O_cocompact_rpow (-2)) (by simpa only [hfg] using g.is_O_cocompact_rpow (-2))
end
end schwartz
|
b24a158ea8dbcd35e84e741a0d40b1850ed28e43 | c391c9c325aa6efef8b2b66f2de9b317e9d07740 | /src/internal_cat.lean | 25700dc89993252004c8651d61b74c5e1c7809c9 | [
"MIT"
] | permissive | goodlyrottenapple/lean-internal-cats | 96592a87f0c8cc03b2592c55098fdee86a25d1cf | fa9df99c2e852598b521b7b3ed8df3e4cb4853b6 | refs/heads/master | 1,601,182,654,282 | 1,578,409,845,000 | 1,578,409,845,000 | 226,436,434 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,925 | lean | import category_theory.category
import category_theory.limits.limits
import category_theory.limits.shapes
import w_pullback
open category_theory
open category_theory.limits
universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation
variables {C : Type u} [𝒞 : category.{v} C]
include 𝒞
class internal_category [category.{v} C] [limits.has_limits.{v} C] (obj_obj : C) : Type (max v u) :=
(obj_arr : C)
(i : obj_obj ⟶ obj_arr)
(dom : obj_arr ⟶ obj_obj)
(cod : obj_arr ⟶ obj_obj)
(notation `a2` := pullback cod dom)
(comp : a2 ⟶ obj_arr)
(notation `π1` := @pullback.fst _ _ _ _ _ cod dom _)
(notation `π2` := @pullback.snd _ _ _ _ _ cod dom _)
(dom_comp : comp ≫ dom = π1 ≫ dom)
(cod_comp : comp ≫ cod = π2 ≫ cod)
(dom_i_id : i ≫ dom = 𝟙 obj_obj)
(cod_i_id : i ≫ cod = 𝟙 obj_obj)
(comp_dom_id : (pullback.lift (dom ≫ i) (𝟙 obj_arr) (by simp [cod_i_id])) ≫ comp = 𝟙 obj_arr)
(comp_cod_id : (pullback.lift (𝟙 obj_arr) (cod ≫ i) (by simp [dom_i_id])) ≫ comp = 𝟙 obj_arr)
(notation `left` := @pullback.fst _ _ _ _ _ π2 π1 _)
(notation `right` := @pullback.snd _ _ _ _ _ π2 π1 _)
(notation `compl` := pullback.lift (left ≫ comp) (right ≫ π2)
(begin
simp [cod_comp, pullback.condition],
rw category.assoc_symm,
simp [pullback.condition]
end))
(notation `compr` := pullback.lift (left ≫ π1) (right ≫ comp)
(begin
simp [dom_comp, pullback.condition],
rw category.assoc_symm,
simp [pullback.condition]
end))
(comp_compl_compr : compl ≫ comp = compr ≫ comp)
set_option trace.check true
variables {X Y V W Z : C}
lemma pullback_one_eq_f_fst {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] :
(pullback.fst : pullback f g ⟶ X) ≫ f = ((limit.cone (cospan f g)).π).app walking_cospan.one := by apply (limit.w (cospan f g) walking_cospan.hom.inl)
lemma w_pullback_one_eq_f1_fst {f1 : X ⟶ W} {g1 : Y ⟶ W} {f2 : Y ⟶ Z} {g2 : V ⟶ Z} [has_limit (w_cospan f1 g1 f2 g2)] :
(w_pullback.fst : w_pullback f1 g1 f2 g2 ⟶ X) ≫ f1 = ((limit.cone (w_cospan f1 g1 f2 g2)).π).app walking_w.one := by apply (limit.w (w_cospan f1 g1 f2 g2) walking_w.hom.inl1)
lemma w_pullback_two_eq_f2_fst {f1 : X ⟶ W} {g1 : Y ⟶ W} {f2 : Y ⟶ Z} {g2 : V ⟶ Z} [has_limit (w_cospan f1 g1 f2 g2)] :
(w_pullback.mid : w_pullback f1 g1 f2 g2 ⟶ Y) ≫ f2 = ((limit.cone (w_cospan f1 g1 f2 g2)).π).app walking_w.two := by apply (limit.w (w_cospan f1 g1 f2 g2) walking_w.hom.inl2)
lemma pullback_unique_morphism {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)]
{h h' : W ⟶ pullback f g} (eq_left : h ≫ pullback.fst = h' ≫ pullback.fst) (eq_right : h ≫ pullback.snd = h' ≫ pullback.snd) : h = h' :=
begin
apply is_limit.hom_ext,
apply has_limit.is_limit,
intros w,
cases w,
simp[eq_left],
simp[eq_right],
rw ← pullback_one_eq_f_fst,
rw category.assoc_symm,
rw category.assoc_symm,
simp[eq_left]
end
lemma w_pullback_unique_morphism {P X Y V W Z : C} {f1 : X ⟶ W} {g1 : Y ⟶ W} {f2 : Y ⟶ Z} {g2 : V ⟶ Z} [has_limit (w_cospan f1 g1 f2 g2)]
{h h' : P ⟶ w_pullback f1 g1 f2 g2}
(eq_left : h ≫ w_pullback.fst = h' ≫ w_pullback.fst)
(eq_mid : h ≫ w_pullback.mid = h' ≫ w_pullback.mid)
(eq_right : h ≫ w_pullback.snd = h' ≫ w_pullback.snd) :
h = h' :=
begin
apply is_limit.hom_ext,
apply has_limit.is_limit,
intros w, cases w,
simp[eq_left],
simp[eq_mid],
simp[eq_right],
rw ← w_pullback_one_eq_f1_fst,
rw category.assoc_symm,
rw category.assoc_symm,
simp[eq_left],
rw ← w_pullback_two_eq_f2_fst,
rw category.assoc_symm,
rw category.assoc_symm,
simp[eq_mid]
end
lemma pullback.lift_fst {W X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_limit (cospan f g)] (l : W ⟶ X) (r : W ⟶ Y) (prf : l ≫ f = r ≫ g) :
(@pullback.lift C _ W X Y Z f g _ l r prf) ≫ pullback.fst = l := begin simp, apply rfl end
lemma pullback.lift_snd {W X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_limit (cospan f g)] (l : W ⟶ X) (r : W ⟶ Y) (prf : l ≫ f = r ≫ g) :
(@pullback.lift C _ W X Y Z f g _ l r prf) ≫ pullback.snd = r := begin simp, apply rfl end
lemma w_pullback.lift_fst {P X Y V W Z : C} {f1 : X ⟶ W} {g1 : Y ⟶ W} {f2 : Y ⟶ Z} {g2 : V ⟶ Z} [has_limit (w_cospan f1 g1 f2 g2)]
(h : P ⟶ X) (j : P ⟶ Y) (k : P ⟶ V) (w1 : h ≫ f1 = j ≫ g1) (w2 : j ≫ f2 = k ≫ g2) :
(@w_pullback.lift C _ P X Y V W Z f1 g1 f2 g2 _ h j k w1 w2) ≫ w_pullback.fst = h := begin simp, apply rfl end
lemma w_pullback.lift_mid {P X Y V W Z : C} {f1 : X ⟶ W} {g1 : Y ⟶ W} {f2 : Y ⟶ Z} {g2 : V ⟶ Z} [has_limit (w_cospan f1 g1 f2 g2)]
(h : P ⟶ X) (j : P ⟶ Y) (k : P ⟶ V) (w1 : h ≫ f1 = j ≫ g1) (w2 : j ≫ f2 = k ≫ g2) :
(@w_pullback.lift C _ P X Y V W Z f1 g1 f2 g2 _ h j k w1 w2) ≫ w_pullback.mid = j := begin simp, apply rfl end
lemma w_pullback.lift_snd {P X Y V W Z : C} {f1 : X ⟶ W} {g1 : Y ⟶ W} {f2 : Y ⟶ Z} {g2 : V ⟶ Z} [has_limit (w_cospan f1 g1 f2 g2)]
(h : P ⟶ X) (j : P ⟶ Y) (k : P ⟶ V) (w1 : h ≫ f1 = j ≫ g1) (w2 : j ≫ f2 = k ≫ g2) :
(@w_pullback.lift C _ P X Y V W Z f1 g1 f2 g2 _ h j k w1 w2) ≫ w_pullback.snd = k := begin simp, apply rfl end
lemma comp_left_cong {a b : X ⟶ Y} {c : Y ⟶ Z} {eq : a = b} : a ≫ c = b ≫ c := begin induction eq, refl end
lemma comp_right_cong {a b : Y ⟶ Z} {c : X ⟶ Y} {eq : a = b} : c ≫ a = c ≫ b := begin induction eq, refl end
abbreviation X₁ {X₀ C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] (j : X₀ ⟶ C₀) := w_pullback j iC.dom iC.cod j
abbreviation C₁ {C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] := iC.obj_arr
abbreviation domX {X₀ C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] (j : X₀ ⟶ C₀) : (X₁ j) ⟶ X₀ := w_pullback.fst
abbreviation codX {X₀ C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] (j : X₀ ⟶ C₀) : (X₁ j) ⟶ X₀ := w_pullback.snd
abbreviation j₁ {X₀ C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] (j : X₀ ⟶ C₀) : (X₁ j) ⟶ C₁ := w_pullback.mid
abbreviation X₂ {X₀ C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] (j : X₀ ⟶ C₀) := pullback (codX j) (domX j)
abbreviation C₂ {C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] := pullback iC.cod iC.dom
abbreviation πX₁ {X₀ C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] (j : X₀ ⟶ C₀) : (X₂ j) ⟶ (X₁ j) := pullback.fst
abbreviation πX₂ {X₀ C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] (j : X₀ ⟶ C₀) : (X₂ j) ⟶ (X₁ j) := pullback.snd
abbreviation j₂ {X₀ C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] (j : X₀ ⟶ C₀) : (X₂ j) ⟶ C₂ :=
pullback.lift (pullback.fst ≫ w_pullback.mid) (pullback.snd ≫ w_pullback.mid) (
begin
simp[w_pullback.condition2],
rw ← w_pullback.condition1,
rw category.assoc_symm,
rw pullback.condition,
simp
end)
abbreviation iX {X₀ C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] (j : X₀ ⟶ C₀) : X₀ ⟶ (X₁ j) :=
w_pullback.lift (𝟙 X₀) (j ≫ iC.i) (𝟙 X₀) (by simp[iC.dom_i_id]) (by simp[iC.cod_i_id])
abbreviation C₃ {C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] := pullback (@pullback.snd _ _ _ _ _ iC.cod iC.dom _) (@pullback.snd _ _ _ _ _ iC.cod iC.dom _)
abbreviation X₃ {X₀ C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] (j : X₀ ⟶ C₀) := pullback (πX₂ j) (πX₁ j)
abbreviation compX {X₀ C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] (j : X₀ ⟶ C₀) : (X₂ j) ⟶ (X₁ j) :=
@w_pullback.lift _ _ _ _ _ _ _ _ j iC.dom iC.cod j _
(πX₁ j ≫ domX j)
((j₂ j) ≫ iC.comp)
(πX₂ j ≫ codX j)
(begin
simp[w_pullback.condition1],
rw iC.dom_comp,
rw category.assoc_symm,
rw category.assoc_symm,
apply comp_left_cong,
rw (pullback.lift_fst iC.cod iC.dom (pullback.fst ≫ w_pullback.mid) (pullback.snd ≫ w_pullback.mid)),
end)
(begin
simp[w_pullback.condition2'],
rw iC.cod_comp,
rw category.assoc_symm,
rw category.assoc_symm,
apply comp_left_cong,
rw (pullback.lift_snd iC.cod iC.dom (pullback.fst ≫ w_pullback.mid) (pullback.snd ≫ w_pullback.mid))
end)
lemma lem_7_4 [has_lim : limits.has_limits.{v} C] {X₀ C₀ : C} [iC : internal_category C₀] (j : X₀ ⟶ C₀)
{T U : C} {f₁ f₂ : T ⟶ X₁ j} {f₁' f₂' : U ⟶ C₁}
{k : T ⟶ U}
(dom_cod_X : f₁ ≫ codX j = f₂ ≫ domX j)
(dom_cod_C : f₁' ≫ iC.cod = f₂' ≫ iC.dom)
(j_f_1 : f₁ ≫ j₁ j = k ≫ f₁')
(j_f_2 : f₂ ≫ j₁ j = k ≫ f₂') :
k ≫ (pullback.lift f₁' f₂' dom_cod_C) = (pullback.lift f₁ f₂ dom_cod_X) ≫ j₂ j :=
begin
apply pullback_unique_morphism,
rw ← category.assoc_symm,
rw pullback.lift_fst,
rw ← j_f_1,
rw ← category.assoc_symm,
rw pullback.lift_fst,
rw category.assoc_symm,
rw pullback.lift_fst,
rw ← category.assoc_symm,
rw pullback.lift_snd,
rw ← j_f_2,
rw ← category.assoc_symm,
rw pullback.lift_snd,
rw category.assoc_symm,
rw pullback.lift_snd
end
abbreviation complX {X₀ C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] (j : X₀ ⟶ C₀) : (X₃ j) ⟶ (X₂ j) :=
pullback.lift (pullback.fst ≫ compX j) (pullback.snd ≫ πX₂ j)
(begin
rw ← category.assoc_symm,
rw w_pullback.lift_snd,
rw category.assoc_symm,
simp [pullback.condition]
end)
abbreviation comprX {X₀ C₀ : C} [limits.has_limits.{v} C] [iC : internal_category C₀] (j : X₀ ⟶ C₀) : (X₃ j) ⟶ (X₂ j) :=
pullback.lift (pullback.fst ≫ πX₁ j) (pullback.snd ≫ compX j)
(begin
symmetry,
rw ← category.assoc_symm,
rw w_pullback.lift_fst,
rw category.assoc_symm,
rw ← pullback.condition,
rw ← category.assoc_symm,
rw ← category.assoc_symm,
apply comp_right_cong,
simp [pullback.condition]
end)
lemma lem_7_6 [has_lim : limits.has_limits.{v} C] {X₀ C₀ : C} [iC : internal_category C₀] (j : X₀ ⟶ C₀) :
complX j ≫ compX j = comprX j ≫ compX j :=
begin
apply w_pullback_unique_morphism,
-- dom𝕏 ⚬ comp𝕏 ⚬ compl𝕏 = dom𝕏 ⚬ comp𝕏 ⚬ compr𝕏
rw ← category.assoc_symm,
rw w_pullback.lift_fst,
rw category.assoc_symm,
rw pullback.lift_fst,
rw ← category.assoc_symm,
rw w_pullback.lift_fst,
rw ← category.assoc_symm,
rw w_pullback.lift_fst,
rw category.assoc_symm,
rw category.assoc_symm,
simp [pullback.lift_fst],
-- j₁ ⚬ comp𝕏 ⚬ compl𝕏 = j₁ ⚬ comp𝕏 ⚬ compr𝕏
rw ← category.assoc_symm,
rw w_pullback.lift_mid,
rw ← category.assoc_symm,
rw w_pullback.lift_mid,
rw category.assoc_symm,
rw category.assoc_symm,
transitivity pullback.lift (pullback.fst ≫ j₂ j) (pullback.snd ≫ j₂ j) _ ≫ _ ≫ iC.comp,
rw category.assoc_symm,
apply comp_left_cong,
symmetry,
apply (@lem_7_4 _ _ _ _ _ _ j _ _ (pullback.fst ≫ compX j) (pullback.snd ≫ πX₂ j) (pullback.fst ≫ iC.comp) ((@pullback.snd _ _ _ _ _ pullback.snd pullback.fst _) ≫ @pullback.snd _ _ _ _ _ iC.cod iC.dom _)),
rw ← category.assoc_symm,
rw iC.cod_comp,
rw ← category.assoc_symm,
rw ← pullback.condition,
rw category.assoc_symm,
simp[pullback.condition],
rw ← category.assoc_symm,
rw w_pullback.lift_mid,
rw category.assoc_symm,
rw category.assoc_symm,
apply comp_left_cong,
simp[pullback.lift_fst],
rw category.assoc_symm,
rw pullback.lift_snd,
rw ← category.assoc_symm,
rw ← category.assoc_symm,
rw pullback.lift_snd,
rw ← category.assoc_symm,
rw ← category.assoc_symm,
rw pullback.lift_snd,
rw pullback.lift_fst,
rw category.assoc_symm,
rw category.assoc_symm,
simp[pullback.condition],
symmetry,
transitivity (pullback.lift (pullback.fst ≫ j₂ j) (pullback.snd ≫ j₂ j) _ ≫ _) ≫ iC.comp,
apply comp_left_cong,
symmetry,
apply (@lem_7_4 _ _ _ _ _ _ j _ _ (pullback.fst ≫ πX₁ j) (pullback.snd ≫ compX j) ((@pullback.fst _ _ _ _ _ pullback.snd pullback.fst _) ≫ @pullback.fst _ _ _ _ _ iC.cod iC.dom _) (pullback.snd ≫ iC.comp) ),
rw ← category.assoc_symm,
rw ← category.assoc_symm,
rw iC.dom_comp,
rw pullback.condition,
rw category.assoc_symm,
simp[pullback.condition],
rw category.assoc_symm,
rw pullback.lift_fst,
rw ← category.assoc_symm,
rw ← category.assoc_symm,
apply comp_right_cong,
simp[pullback.lift_fst],
rw category.assoc_symm,
rw pullback.lift_snd,
rw ← category.assoc_symm,
rw ← category.assoc_symm,
rw w_pullback.lift_mid,
rw ← category.assoc_symm,
rw ← category.assoc_symm,
rw pullback.lift_snd,
rw pullback.lift_fst,
rw category.assoc_symm,
rw category.assoc_symm,
simp[pullback.condition],
rw ← category.assoc_symm,
apply comp_right_cong,
rw iC.comp_compl_compr,
-- cod𝕏 ⚬ comp𝕏 ⚬ compl𝕏 = cod𝕏 ⚬ comp𝕏 ⚬ compr𝕏
rw ← category.assoc_symm,
rw w_pullback.lift_snd,
rw category.assoc_symm,
rw pullback.lift_snd,
rw ← category.assoc_symm,
rw ← category.assoc_symm,
rw w_pullback.lift_snd,
rw category.assoc_symm,
rw category.assoc_symm,
rw pullback.lift_snd,
rw ← category.assoc_symm,
rw ← category.assoc_symm,
rw w_pullback.lift_snd
end
def pulled_back_of_internal_category [has_lim : limits.has_limits.{v} C] (obj_obj X : C) [iC : internal_category obj_obj] (j : X ⟶ obj_obj) :
internal_category X := {
obj_arr := X₁ j ,
dom := domX j,
cod := codX j,
comp := w_pullback.lift
(πX₁ j ≫ domX j)
((j₂ j) ≫ iC.comp)
(πX₂ j ≫ codX j)
(begin
simp[w_pullback.condition1],
rw iC.dom_comp,
rw category.assoc_symm,
rw category.assoc_symm,
apply comp_left_cong,
rw (pullback.lift_fst iC.cod iC.dom (pullback.fst ≫ w_pullback.mid) (pullback.snd ≫ w_pullback.mid)),
end)
(begin
simp[w_pullback.condition2'],
rw iC.cod_comp,
rw category.assoc_symm,
rw category.assoc_symm,
apply comp_left_cong,
rw (pullback.lift_snd iC.cod iC.dom (pullback.fst ≫ w_pullback.mid) (pullback.snd ≫ w_pullback.mid))
end),
i := iX j,
dom_comp := by simp[w_pullback.lift_fst],
cod_comp := by simp[w_pullback.lift_snd],
dom_i_id := by simp[w_pullback.lift_fst],
cod_i_id := by simp[w_pullback.lift_snd],
comp_dom_id := begin
apply w_pullback_unique_morphism,
work_on_goal 2 {
rw ← category.assoc_symm,
rw (w_pullback.lift_snd _ _ (pullback.snd ≫ w_pullback.snd)),
rw category.assoc_symm,
rw pullback.lift_snd
},
work_on_goal 0 {
rw ← category.assoc_symm,
rw w_pullback.lift_fst,
rw category.assoc_symm,
rw pullback.lift_fst,
rw ← category.assoc_symm,
rw w_pullback.lift_fst,
simp
},
rw ← category.assoc_symm,
rw w_pullback.lift_mid,
rw category.assoc_symm,
transitivity (j₁ j ≫ pullback.lift (iC.dom ≫ iC.i) (𝟙 C₁) _) ≫ iC.comp,
apply comp_left_cong,
symmetry,
apply lem_7_4,
rw ← category.assoc_symm,
rw w_pullback.lift_mid,
rw category.assoc_symm,
simp [w_pullback.condition1],
simp,
rw ← category.assoc_symm,
simp[iC.cod_i_id],
rw ← category.assoc_symm,
simp[iC.comp_dom_id]
end,
comp_cod_id := begin
apply w_pullback_unique_morphism,
work_on_goal 2 {
rw ← category.assoc_symm,
rw (w_pullback.lift_snd _ _ (pullback.snd ≫ w_pullback.snd)),
rw category.assoc_symm,
rw pullback.lift_snd,
simp[w_pullback.lift_snd]
},
work_on_goal 0 {
rw ← category.assoc_symm,
rw (w_pullback.lift_fst _ _ (pullback.snd ≫ w_pullback.snd)),
rw category.assoc_symm,
rw pullback.lift_fst
},
rw ← category.assoc_symm,
rw w_pullback.lift_mid,
rw category.assoc_symm,
transitivity (j₁ j ≫ pullback.lift (𝟙 C₁) (iC.cod ≫ iC.i) _) ≫ iC.comp,
apply comp_left_cong,
symmetry,
apply lem_7_4,
simp,
rw ← category.assoc_symm,
rw w_pullback.lift_mid,
rw category.assoc_symm,
simp [w_pullback.condition2'],
rw ← category.assoc_symm,
simp[iC.dom_i_id],
rw ← category.assoc_symm,
simp[iC.comp_cod_id]
end,
comp_compl_compr := by apply (lem_7_6 j)
}
|
bc8fd0e17cfa2504982800170296fd9ee0062b31 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/category_theory/category/Bipointed.lean | c426c8ed307fdcda33a487a2bcd00a2e7d683b3b | [
"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 | 6,049 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import category_theory.category.Pointed
/-!
# The category of bipointed types
This defines `Bipointed`, the category of bipointed types.
## TODO
Monoidal structure
-/
open category_theory
universes u
variables {α β : Type*}
/-- The category of bipointed types. -/
structure Bipointed : Type.{u + 1} :=
(X : Type.{u})
(to_prod : X × X)
namespace Bipointed
instance : has_coe_to_sort Bipointed Type* := ⟨X⟩
attribute [protected] Bipointed.X
/-- Turns a bipointing into a bipointed type. -/
def of {X : Type*} (to_prod : X × X) : Bipointed := ⟨X, to_prod⟩
alias of ← prod.Bipointed
instance : inhabited Bipointed := ⟨of ((), ())⟩
/-- Morphisms in `Bipointed`. -/
@[ext] protected structure hom (X Y : Bipointed.{u}) : Type u :=
(to_fun : X → Y)
(map_fst : to_fun X.to_prod.1 = Y.to_prod.1)
(map_snd : to_fun X.to_prod.2 = Y.to_prod.2)
namespace hom
/-- The identity morphism of `X : Bipointed`. -/
@[simps] def id (X : Bipointed) : hom X X := ⟨id, rfl, rfl⟩
instance (X : Bipointed) : inhabited (hom X X) := ⟨id X⟩
/-- Composition of morphisms of `Bipointed`. -/
@[simps] def comp {X Y Z : Bipointed.{u}} (f : hom X Y) (g : hom Y Z) : hom X Z :=
⟨g.to_fun ∘ f.to_fun, by rw [function.comp_apply, f.map_fst, g.map_fst],
by rw [function.comp_apply, f.map_snd, g.map_snd]⟩
end hom
instance large_category : large_category Bipointed :=
{ hom := hom,
id := hom.id,
comp := @hom.comp,
id_comp' := λ _ _ _, hom.ext _ _ rfl,
comp_id' := λ _ _ _, hom.ext _ _ rfl,
assoc' := λ _ _ _ _ _ _ _, hom.ext _ _ rfl }
instance concrete_category : concrete_category Bipointed :=
{ forget := { obj := Bipointed.X, map := @hom.to_fun },
forget_faithful := ⟨@hom.ext⟩ }
/-- Swaps the pointed elements of a bipointed type. `prod.swap` as a functor. -/
@[simps] def swap : Bipointed ⥤ Bipointed :=
{ obj := λ X, ⟨X, X.to_prod.swap⟩, map := λ X Y f, ⟨f.to_fun, f.map_snd, f.map_fst⟩ }
/-- The equivalence between `Bipointed` and itself induced by `prod.swap` both ways. -/
@[simps] def swap_equiv : Bipointed ≌ Bipointed :=
equivalence.mk swap swap
(nat_iso.of_components (λ X, { hom := ⟨id, rfl, rfl⟩, inv := ⟨id, rfl, rfl⟩ }) $ λ X Y f, rfl)
(nat_iso.of_components (λ X, { hom := ⟨id, rfl, rfl⟩, inv := ⟨id, rfl, rfl⟩ }) $ λ X Y f, rfl)
@[simp] lemma swap_equiv_symm : swap_equiv.symm = swap_equiv := rfl
end Bipointed
/-- The forgetful functor from `Bipointed` to `Pointed` which forgets about the second point. -/
def Bipointed_to_Pointed_fst : Bipointed ⥤ Pointed :=
{ obj := λ X, ⟨X, X.to_prod.1⟩, map := λ X Y f, ⟨f.to_fun, f.map_fst⟩ }
/-- The forgetful functor from `Bipointed` to `Pointed` which forgets about the first point. -/
def Bipointed_to_Pointed_snd : Bipointed ⥤ Pointed :=
{ obj := λ X, ⟨X, X.to_prod.2⟩, map := λ X Y f, ⟨f.to_fun, f.map_snd⟩ }
@[simp] lemma Bipointed_to_Pointed_fst_comp_forget :
Bipointed_to_Pointed_fst ⋙ forget Pointed = forget Bipointed := rfl
@[simp] lemma Bipointed_to_Pointed_snd_comp_forget :
Bipointed_to_Pointed_snd ⋙ forget Pointed = forget Bipointed := rfl
@[simp] lemma swap_comp_Bipointed_to_Pointed_fst :
Bipointed.swap ⋙ Bipointed_to_Pointed_fst = Bipointed_to_Pointed_snd := rfl
@[simp] lemma swap_comp_Bipointed_to_Pointed_snd :
Bipointed.swap ⋙ Bipointed_to_Pointed_snd = Bipointed_to_Pointed_fst := rfl
--TODO: This is actually an equivalence
/-- The functor from `Pointed` to `Bipointed` which adds a second point. -/
def Pointed_to_Bipointed_fst : Pointed.{u} ⥤ Bipointed :=
{ obj := λ X, ⟨option X, X.point, none⟩,
map := λ X Y f, ⟨option.map f.to_fun, congr_arg _ f.map_point, rfl⟩,
map_id' := λ X, Bipointed.hom.ext _ _ option.map_id,
map_comp' := λ X Y Z f g, Bipointed.hom.ext _ _ (option.map_comp_map _ _).symm }
--TODO: This is actually an equivalence
/-- The functor from `Pointed` to `Bipointed` which adds a first point. -/
def Pointed_to_Bipointed_snd : Pointed.{u} ⥤ Bipointed :=
{ obj := λ X, ⟨option X, none, X.point⟩,
map := λ X Y f, ⟨option.map f.to_fun, rfl, congr_arg _ f.map_point⟩,
map_id' := λ X, Bipointed.hom.ext _ _ option.map_id,
map_comp' := λ X Y Z f g, Bipointed.hom.ext _ _ (option.map_comp_map _ _).symm }
@[simp] lemma Pointed_to_Bipointed_fst_comp :
Pointed_to_Bipointed_fst ⋙ Bipointed.swap = Pointed_to_Bipointed_snd := rfl
@[simp] lemma Pointed_to_Bipointed_snd_comp :
Pointed_to_Bipointed_snd ⋙ Bipointed.swap = Pointed_to_Bipointed_fst := rfl
/-- The free/forgetful adjunction between `Pointed_to_Bipointed_fst` and `Bipointed_to_Pointed_fst`.
-/
def Pointed_to_Bipointed_fst_Bipointed_to_Pointed_fst_adjunction :
Pointed_to_Bipointed_fst ⊣ Bipointed_to_Pointed_fst :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X Y, { to_fun := λ f, ⟨f.to_fun ∘ option.some, f.map_fst⟩,
inv_fun := λ f, ⟨λ o, o.elim Y.to_prod.2 f.to_fun, f.map_point, rfl⟩,
left_inv := λ f, by { ext, cases x, exact f.map_snd.symm, refl },
right_inv := λ f, Pointed.hom.ext _ _ rfl },
hom_equiv_naturality_left_symm' := λ X' X Y f g, by { ext, cases x; refl } }
/-- The free/forgetful adjunction between `Pointed_to_Bipointed_snd` and `Bipointed_to_Pointed_snd`.
-/
def Pointed_to_Bipointed_snd_Bipointed_to_Pointed_snd_adjunction :
Pointed_to_Bipointed_snd ⊣ Bipointed_to_Pointed_snd :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X Y, { to_fun := λ f, ⟨f.to_fun ∘ option.some, f.map_snd⟩,
inv_fun := λ f, ⟨λ o, o.elim Y.to_prod.1 f.to_fun, rfl, f.map_point⟩,
left_inv := λ f, by { ext, cases x, exact f.map_fst.symm, refl },
right_inv := λ f, Pointed.hom.ext _ _ rfl },
hom_equiv_naturality_left_symm' := λ X' X Y f g, by { ext, cases x; refl } }
|
3f2573da79bcafe1bf66b6544ac309ecafda7519 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /tests/lean/run/letrecInProofs.lean | 73e7457fbbbb2dbe39b35a26839f7d079126901a | [
"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 | 2,730 | lean | import Lean
inductive Tree
| leaf : Tree
| node : Tree → Tree → Tree
abbrev notSubtree (x : Tree) (t : Tree) : Prop :=
Tree.ibelow (motive := fun z => x ≠ z) t
infix:50 "≮" => notSubtree
theorem Tree.acyclic (x t : Tree) : x = t → x ≮ t := by
let rec right (x s : Tree) (b : Tree) (h : x ≮ b) : node s x ≠ b ∧ node s x ≮ b := by
match b, h with
| leaf, h =>
apply And.intro _ trivial
intro h; injection h
| node l r, h =>
have ihl : x ≮ l → node s x ≠ l ∧ node s x ≮ l from right x s l
have ihr : x ≮ r → node s x ≠ r ∧ node s x ≮ r from right x s r
have hl : x ≠ l ∧ x ≮ l from h.1
have hr : x ≠ r ∧ x ≮ r from h.2.1
have ihl : node s x ≠ l ∧ node s x ≮ l from ihl hl.2
have ihr : node s x ≠ r ∧ node s x ≮ r from ihr hr.2
apply And.intro
focus
intro h
injection h with _ h
exact absurd h hr.1
done
focus
apply And.intro
apply ihl
apply And.intro _ trivial
apply ihr
let rec left (x t : Tree) (b : Tree) (h : x ≮ b) : node x t ≠ b ∧ node x t ≮ b := by
match b, h with
| leaf, h =>
apply And.intro _ trivial
intro h; injection h
| node l r, h =>
have ihl : x ≮ l → node x t ≠ l ∧ node x t ≮ l from left x t l
have ihr : x ≮ r → node x t ≠ r ∧ node x t ≮ r from left x t r
have hl : x ≠ l ∧ x ≮ l from h.1
have hr : x ≠ r ∧ x ≮ r from h.2.1
have ihl : node x t ≠ l ∧ node x t ≮ l from ihl hl.2
have ihr : node x t ≠ r ∧ node x t ≮ r from ihr hr.2
apply And.intro
focus
intro h
injection h with h _
exact absurd h hl.1
done
focus
apply And.intro
apply ihl
apply And.intro _ trivial
apply ihr
let rec aux : (x : Tree) → x ≮ x
| leaf => trivial
| node l r => by
have ih₁ : l ≮ l from aux l
have ih₂ : r ≮ r from aux r
show (node l r ≠ l ∧ node l r ≮ l) ∧ (node l r ≠ r ∧ node l r ≮ r) ∧ True
apply And.intro
focus
apply left
assumption
apply And.intro _ trivial
focus
apply right
assumption
intro h
subst h
apply aux
open Tree
theorem ex1 (x : Tree) : x ≠ node leaf (node x leaf) := by
intro h
exact absurd rfl $ Tree.acyclic _ _ h |>.2.1.2.1.1
theorem ex2 (x : Tree) : x ≠ node x leaf := by
intro h
exact absurd rfl $ Tree.acyclic _ _ h |>.1.1
theorem ex3 (x y : Tree) : x ≠ node y x := by
intro h
exact absurd rfl $ Tree.acyclic _ _ h |>.2.1.1
|
6ba3866914be7f7776fc36281551f60b520ba78c | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/ring_theory/polynomial/homogeneous.lean | ab381ab1a60fd517b9817f09743e6479b6ff3c75 | [] | 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 | 6,339 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.mv_polynomial.default
import Mathlib.data.fintype.card
import Mathlib.PostPort
universes u_1 u_3 u_2
namespace Mathlib
/-!
# 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_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
-/
namespace mv_polynomial
/-
TODO
* create definition for `∑ i in d.support, d i`
* define graded rings, and show that mv_polynomial is an example
-/
/-- A multivariate polynomial `φ` is homogeneous of degree `n`
if all monomials occuring in `φ` have degree `n`. -/
def is_homogeneous {σ : Type u_1} {R : Type u_3} [comm_semiring R] (φ : mv_polynomial σ R) (n : ℕ) :=
∀ {d : σ →₀ ℕ}, coeff d φ ≠ 0 → (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n
theorem is_homogeneous_monomial {σ : Type u_1} {R : Type u_3} [comm_semiring R] (d : σ →₀ ℕ) (r : R) (n : ℕ) (hn : (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n) : is_homogeneous (monomial d r) n := sorry
theorem is_homogeneous_C (σ : Type u_1) {R : Type u_3} [comm_semiring R] (r : R) : is_homogeneous (coe_fn C r) 0 := sorry
theorem is_homogeneous_zero (σ : Type u_1) (R : Type u_3) [comm_semiring R] (n : ℕ) : is_homogeneous 0 n :=
fun (d : σ →₀ ℕ) (hd : coeff d 0 ≠ 0) => false.elim (hd (coeff_zero d))
theorem is_homogeneous_one (σ : Type u_1) (R : Type u_3) [comm_semiring R] : is_homogeneous 1 0 :=
is_homogeneous_C σ 1
theorem is_homogeneous_X {σ : Type u_1} (R : Type u_3) [comm_semiring R] (i : σ) : is_homogeneous (X i) 1 := sorry
namespace is_homogeneous
theorem coeff_eq_zero {σ : Type u_1} {R : Type u_3} [comm_semiring R] {φ : mv_polynomial σ R} {n : ℕ} (hφ : is_homogeneous φ n) (d : σ →₀ ℕ) (hd : (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) ≠ n) : coeff d φ = 0 :=
eq.mp (Eq._oldrec (Eq.refl (¬coeff d φ ≠ 0)) (propext not_not)) (mt hφ hd)
theorem inj_right {σ : Type u_1} {R : Type u_3} [comm_semiring R] {φ : mv_polynomial σ R} {m : ℕ} {n : ℕ} (hm : is_homogeneous φ m) (hn : is_homogeneous φ n) (hφ : φ ≠ 0) : m = n := sorry
theorem add {σ : Type u_1} {R : Type u_3} [comm_semiring R] {φ : mv_polynomial σ R} {ψ : mv_polynomial σ R} {n : ℕ} (hφ : is_homogeneous φ n) (hψ : is_homogeneous ψ n) : is_homogeneous (φ + ψ) n := sorry
theorem sum {σ : Type u_1} {R : Type u_3} [comm_semiring R] {ι : Type u_2} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ℕ) (h : ∀ (i : ι), i ∈ s → is_homogeneous (φ i) n) : is_homogeneous (finset.sum s fun (i : ι) => φ i) n := sorry
theorem mul {σ : Type u_1} {R : Type u_3} [comm_semiring R] {φ : mv_polynomial σ R} {ψ : mv_polynomial σ R} {m : ℕ} {n : ℕ} (hφ : is_homogeneous φ m) (hψ : is_homogeneous ψ n) : is_homogeneous (φ * ψ) (m + n) := sorry
theorem prod {σ : Type u_1} {R : Type u_3} [comm_semiring R] {ι : Type u_2} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ι → ℕ) (h : ∀ (i : ι), i ∈ s → is_homogeneous (φ i) (n i)) : is_homogeneous (finset.prod s fun (i : ι) => φ i) (finset.sum s fun (i : ι) => n i) := sorry
theorem total_degree {σ : Type u_1} {R : Type u_3} [comm_semiring R] {φ : mv_polynomial σ R} {n : ℕ} (hφ : is_homogeneous φ n) (h : φ ≠ 0) : total_degree φ = n := sorry
end is_homogeneous
/-- `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 {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) : linear_map R (mv_polynomial σ R) (mv_polynomial σ R) :=
linear_map.comp
(submodule.subtype
(finsupp.supported R R (set_of fun (d : σ →₀ ℕ) => (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n)))
(finsupp.restrict_dom R R (set_of fun (d : σ →₀ ℕ) => (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n))
theorem coeff_homogeneous_component {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R) (d : σ →₀ ℕ) : coeff d (coe_fn (homogeneous_component n) φ) =
ite ((finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n) (coeff d φ) 0 := sorry
theorem homogeneous_component_apply {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R) : coe_fn (homogeneous_component n) φ =
finset.sum
(finset.filter (fun (d : σ →₀ ℕ) => (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) = n)
(finsupp.support φ))
fun (d : σ →₀ ℕ) => monomial d (coeff d φ) := sorry
theorem homogeneous_component_is_homogeneous {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R) : is_homogeneous (coe_fn (homogeneous_component n) φ) n := sorry
theorem homogeneous_component_zero {σ : Type u_1} {R : Type u_3} [comm_semiring R] (φ : mv_polynomial σ R) : coe_fn (homogeneous_component 0) φ = coe_fn C (coeff 0 φ) := sorry
theorem homogeneous_component_eq_zero' {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R) (h : ∀ (d : σ →₀ ℕ), d ∈ finsupp.support φ → (finset.sum (finsupp.support d) fun (i : σ) => coe_fn d i) ≠ n) : coe_fn (homogeneous_component n) φ = 0 := sorry
theorem homogeneous_component_eq_zero {σ : Type u_1} {R : Type u_3} [comm_semiring R] (n : ℕ) (φ : mv_polynomial σ R) (h : total_degree φ < n) : coe_fn (homogeneous_component n) φ = 0 := sorry
theorem sum_homogeneous_component {σ : Type u_1} {R : Type u_3} [comm_semiring R] (φ : mv_polynomial σ R) : (finset.sum (finset.range (total_degree φ + 1)) fun (i : ℕ) => coe_fn (homogeneous_component i) φ) = φ := sorry
|
f2c63d4051d79fbf9e66468a6109368299b6ed05 | 6214e13b31733dc9aeb4833db6a6466005763162 | /src/strengthening.lean | c8f675935f5a8eaa1a15164dd8031d27dbc05b92 | [] | no_license | joshua0pang/esverify-theory | 272a250445f3aeea49a7e72d1ab58c2da6618bbe | 8565b123c87b0113f83553d7732cd6696c9b5807 | refs/heads/master | 1,585,873,849,081 | 1,527,304,393,000 | 1,527,304,393,000 | 154,901,199 | 1 | 0 | null | 1,540,593,067,000 | 1,540,593,067,000 | null | UTF-8 | Lean | false | false | 14,279 | lean | import .definitions3 .logic
lemma strengthen_impl_with_dominating_instantiations {σ: env} {P P' Q: prop}:
(σ ⊨ vc.implies P'.to_vc P.to_vc) → (σ ⊨ (prop.implies P Q).to_vc) → (σ ⊨ (prop.implies P' Q).to_vc) :=
begin
assume h1,
assume h2,
apply valid_env.to_vc_implies.mpr,
apply valid_env.mpr,
assume h3,
have h4, from valid_env.mp h1 h3,
have h5, from valid_env.to_vc_implies.mp h2,
from valid_env.mp h5 h4
end
lemma strengthen_vc {P P' Q: prop} {σ: env}:
(σ ⊨ vc.implies P'.to_vc P.to_vc) → (FV P ⊆ FV P') →
(closed_subst σ (prop.implies P Q) → σ ⊨ (prop.implies P Q).to_vc) →
(closed_subst σ (prop.implies P' Q) → σ ⊨ (prop.implies P' Q).to_vc) :=
begin
assume h1,
assume h2,
assume h3,
assume h4,
apply @strengthen_impl_with_dominating_instantiations σ P P' Q,
from h1,
have h5: closed_subst σ (prop.implies P Q), by begin
assume x,
assume h6,
cases free_in_prop.implies.inv h6 with h7 h8,
have h9: x ∈ FV P, from h7,
have h10, from set.mem_of_mem_of_subset h9 h2,
have h12: free_in_prop x (prop.implies P' Q), from free_in_prop.implies₁ h10,
from h4 h12,
have h12: free_in_prop x (prop.implies P' Q), from free_in_prop.implies₂ h8,
from h4 h12
end,
from h3 h5
end
lemma strengthen_vc_with_q {P P' Q S: prop} {σ: env}:
(σ ⊨ vc.implies P'.to_vc P.to_vc) → (FV P ⊆ FV P') →
(closed_subst σ (prop.implies (P ⋀ Q) S) → σ ⊨ (prop.implies (P ⋀ Q) S).to_vc) →
(closed_subst σ (prop.implies (P' ⋀ Q) S) → σ ⊨ (prop.implies (P' ⋀ Q) S).to_vc) :=
begin
assume h1,
assume h2,
assume h3,
assume h4,
apply @strengthen_impl_with_dominating_instantiations σ (P ⋀ Q) (P' ⋀ Q) S,
from vc.implies.same_right (λ_, h1),
have h5: closed_subst σ (prop.implies (P⋀Q) S), by begin
assume x,
assume h6,
cases free_in_prop.implies.inv h6 with h7 h8,
cases free_in_prop.and.inv h7 with h8 h9,
have h9: x ∈ FV P, from h8,
have h10, from set.mem_of_mem_of_subset h9 h2,
have h11: free_in_prop x (P' ⋀ Q), from free_in_prop.and₁ h10,
have h12: free_in_prop x (prop.implies (P' ⋀ Q) S), from free_in_prop.implies₁ h11,
from h4 h12,
have h11: free_in_prop x (P' ⋀ Q), from free_in_prop.and₂ h9,
have h12: free_in_prop x (prop.implies (P' ⋀ Q) S), from free_in_prop.implies₁ h11,
from h4 h12,
have h12: free_in_prop x (prop.implies (P' ⋀ Q) S), from free_in_prop.implies₂ h8,
from h4 h12
end,
from h3 h5
end
lemma strengthen_exp {P: prop} {Q: propctx} {e: exp}:
(P ⊩ e : Q) → ∀P': prop, (FV P' = FV P) → (∀σ, σ ⊨ vc.implies P'.to_vc P.to_vc) → (P' ⊩ e: Q) :=
assume e_verified: (P ⊩ e : Q),
begin
induction e_verified,
case exp.dvcgen.tru x P e' Q x_not_free_in_P e'_verified ih { from (
assume P': prop,
assume free_P'_P: FV P' = FV P,
assume P'_dominates_p_P: (∀σ, σ ⊨ vc.implies P'.to_vc P.to_vc),
have h1: FV (P' ⋀ x ≡ value.true) = FV (P ⋀ x ≡ value.true),
from free_in_prop.same_right free_P'_P,
have h2: (∀σ, σ ⊨ vc.implies (P' ⋀ x ≡ value.true).to_vc (P ⋀ x ≡ value.true).to_vc),
from λσ, vc.implies.same_right (λ_, P'_dominates_p_P σ),
have e'_verified': P' ⋀ x ≡ value.true ⊩ e': Q, from ih (P' ⋀ x ≡ value.true) h1 h2,
have x_not_free_in_P': x ∉ FV P', from free_P'_P.symm ▸ x_not_free_in_P,
show P' ⊩ lett x = true in e' : propctx.exis x (x ≡ value.true ⋀ Q),
from exp.dvcgen.tru x_not_free_in_P' e'_verified'
)},
case exp.dvcgen.fals x P e' Q x_not_free_in_P e'_verified ih { from
assume P': prop,
assume free_P'_P: FV P' = FV P,
assume P'_dominates_p_P: (∀σ, σ ⊨ vc.implies P'.to_vc P.to_vc),
have h1: FV (P' ⋀ (x ≡ value.false)) = FV (P ⋀ x ≡ value.false),
from free_in_prop.same_right free_P'_P,
have h2: (∀σ, σ ⊨ vc.implies (P' ⋀ x ≡ value.false).to_vc (P ⋀ x ≡ value.false).to_vc),
from λσ, vc.implies.same_right (λ_, P'_dominates_p_P σ),
have e'_verified': P' ⋀ x ≡ value.false ⊩ e': Q, from ih (P' ⋀ x ≡ value.false) h1 h2,
have x_not_free_in_P': x ∉ FV P', from free_P'_P.symm ▸ x_not_free_in_P,
show P' ⊩ letf x = false in e' : propctx.exis x ((x ≡ value.false) ⋀ Q),
from exp.dvcgen.fals x_not_free_in_P' e'_verified'
},
case exp.dvcgen.num x n P e' Q x_not_free_in_P e'_verified ih { from
assume P': prop,
assume free_P'_P: FV P' = FV P,
assume P'_dominates_p_P: (∀σ, σ ⊨ vc.implies P'.to_vc P.to_vc),
have h1: FV (P' ⋀ x ≡ value.num n) = FV (P ⋀ x ≡ value.num n),
from free_in_prop.same_right free_P'_P,
have h2: (∀σ, σ ⊨ vc.implies (P' ⋀ x ≡ value.num n).to_vc (P ⋀ x ≡ value.num n).to_vc),
from λσ, vc.implies.same_right (λ_, P'_dominates_p_P σ),
have e'_verified': P' ⋀ (x ≡ value.num n) ⊩ e': Q, from ih (P' ⋀ (x ≡ value.num n)) h1 h2,
have x_not_free_in_P': x ∉ FV P', from free_P'_P.symm ▸ x_not_free_in_P,
show P' ⊩ letn x = n in e' : propctx.exis x ((x ≡ value.num n) ⋀ Q),
from exp.dvcgen.num x_not_free_in_P' e'_verified'
},
case exp.dvcgen.func f x R S e₁ e₂ P Q₁ Q₂ f_not_free_in_P x_not_free_in_P f_neq_x x_free_in_R fv_R fv_S
e₁_verified e₂_verified func_vc ih₁ ih₂ { from
assume P': prop,
assume free_P'_P: FV P' = FV P,
assume P'_dominates_p_P: (∀σ, σ ⊨ vc.implies P'.to_vc P.to_vc),
have f_not_free_in_P': f ∉ FV P', from free_P'_P.symm ▸ f_not_free_in_P,
have x_not_free_in_P': x ∉ FV P', from free_P'_P.symm ▸ x_not_free_in_P,
have fv_R': FV R.to_prop ⊆ FV P' ∪ { f, x }, from free_P'_P.symm ▸ fv_R,
have fv_S': FV S.to_prop ⊆ FV P' ∪ { f, x }, from free_P'_P.symm ▸ fv_S,
have h1: FV (P' ⋀ ((spec.func f x R S) ⋀ R)) = FV (P ⋀ ((spec.func f x R S) ⋀ R)),
from free_in_prop.same_right free_P'_P,
have h2: (∀σ, σ ⊨ vc.implies (P' ⋀ (spec.func f x R S) ⋀ R).to_vc (P ⋀ (spec.func f x R S) ⋀ R).to_vc),
from λσ, vc.implies.same_right (λ_, P'_dominates_p_P σ),
have e₁_verified': P' ⋀ (spec.func f x R S) ⋀ R ⊩ e₁ : Q₁,
from ih₁ (P' ⋀ (spec.func f x R S) ⋀ R) h1 h2,
have h3: FV (P' ⋀ (prop.func f x R (Q₁ (term.app ↑f ↑x) ⋀ ↑S)))
= FV (P ⋀ (prop.func f x R (Q₁ (term.app ↑f ↑x) ⋀ ↑S))),
from free_in_prop.same_right free_P'_P,
have h5: (∀σ, σ ⊨ vc.implies (P' ⋀ (prop.func f x R (Q₁ (term.app ↑f ↑x) ⋀ ↑S))).to_vc
(P ⋀ (prop.func f x R (Q₁ (term.app ↑f ↑x) ⋀ ↑S))).to_vc),
from (λσ, vc.implies.same_right (λ_, P'_dominates_p_P σ)),
have e₂_verified': P' ⋀ (prop.func f x R (Q₁ (term.app ↑f ↑x) ⋀ ↑S)) ⊩ e₂ : Q₂,
from ih₂ (P' ⋀ (prop.func f x R (Q₁ (term.app ↑f ↑x) ⋀ ↑S))) h3 h5,
have func_vc': ∀ (σ : env),
closed_subst σ (prop.implies (P'⋀↑(spec.func ↑f x R S) ⋀ R ⋀ Q₁ (term.app ↑f ↑x)) ↑S) →
σ ⊨ (prop.implies (P' ⋀ ↑(spec.func ↑f x R S) ⋀ R ⋀ Q₁ (term.app ↑f ↑x)) ↑S).to_vc,
from (λσ, strengthen_vc_with_q (P'_dominates_p_P σ) (set.subset_of_eq free_P'_P.symm) (func_vc σ)),
show P' ⊩ letf f[x] req R ens S {e₁} in e₂ : propctx.exis f (prop.func f x R (Q₁ (term.app ↑f ↑x) ⋀ ↑S) ⋀ Q₂),
from exp.dvcgen.func f_not_free_in_P' x_not_free_in_P' f_neq_x x_free_in_R fv_R' fv_S' e₁_verified'
e₂_verified' func_vc'
},
case exp.dvcgen.unop op x y P e' Q' x_free_in_P y_not_free_in_P e'_verified vc_valid ih { from
assume P': prop,
assume free_P'_P: FV P' = FV P,
assume P'_dominates_p_P: (∀σ, σ ⊨ vc.implies P'.to_vc P.to_vc),
have x_free_in_P': x ∈ FV P', from free_P'_P.symm ▸ x_free_in_P,
have y_not_free_in_P': y ∉ FV P', from free_P'_P.symm ▸ y_not_free_in_P,
have h1: FV (P' ⋀ y ≡ term.unop op x) = FV (P ⋀ y ≡ term.unop op x),
from free_in_prop.same_right free_P'_P,
have h2: (∀σ, σ ⊨ vc.implies (P' ⋀ y ≡ term.unop op x).to_vc (P ⋀ y ≡ term.unop op x).to_vc),
from (λσ, vc.implies.same_right (λ_, P'_dominates_p_P σ)),
have e'_verified': P' ⋀ y ≡ term.unop op x ⊩ e' : Q',
from ih (P' ⋀ y ≡ term.unop op x) h1 h2,
have FV P ⊆ FV P', from set.subset_of_eq free_P'_P.symm,
have vc_valid': ∀ (σ : env),
closed_subst σ (prop.implies P' (prop.pre₁ op x)) → σ ⊨ (prop.implies P' (prop.pre₁ op x)).to_vc,
from (λσ, strengthen_vc (P'_dominates_p_P σ) this (vc_valid σ)),
show P' ⊩ letop y = op [x] in e' : propctx.exis y (y ≡ term.unop op x ⋀ Q'),
from exp.dvcgen.unop x_free_in_P' y_not_free_in_P' e'_verified' vc_valid'
},
case exp.dvcgen.binop op x y z e' P Q' x_free_in_P y_free_in_P z_not_free_in_P e'_verified vc_valid ih { from
assume P': prop,
assume free_P'_P: FV P' = FV P,
assume P'_dominates_p_P: (∀σ, σ ⊨ vc.implies P'.to_vc P.to_vc),
have x_free_in_P': x ∈ FV P', from free_P'_P.symm ▸ x_free_in_P,
have y_free_in_P': y ∈ FV P', from free_P'_P.symm ▸ y_free_in_P,
have z_not_free_in_P': z ∉ FV P', from free_P'_P.symm ▸ z_not_free_in_P,
have h1: FV (P' ⋀ z ≡ term.binop op x y) = FV (P ⋀ z ≡ term.binop op x y),
from free_in_prop.same_right free_P'_P,
have h2: (∀σ, σ ⊨ vc.implies (P' ⋀ z ≡ term.binop op x y).to_vc (P ⋀ z ≡ term.binop op x y).to_vc),
from (λσ, vc.implies.same_right (λ_, P'_dominates_p_P σ)),
have e'_verified': P' ⋀ z ≡ term.binop op x y ⊩ e' : Q',
from ih (P' ⋀ z ≡ term.binop op x y) h1 h2,
have FV P ⊆ FV P', from set.subset_of_eq free_P'_P.symm,
have vc_valid': ∀ (σ : env),
closed_subst σ (prop.implies P' (prop.pre₂ op x y)) →
σ ⊨ (prop.implies P' (prop.pre₂ op x y)).to_vc,
from (λσ, strengthen_vc (P'_dominates_p_P σ) this (vc_valid σ)),
show P' ⊩ letop2 z = op [x, y] in e' : propctx.exis z (z ≡ term.binop op x y ⋀ Q'),
from exp.dvcgen.binop x_free_in_P' y_free_in_P' z_not_free_in_P' e'_verified' vc_valid'
},
case exp.dvcgen.app y f x e' P Q' f_free_in_P x_free_in_P y_not_free_in_P e'_verified vc_valid ih { from
assume P': prop,
assume free_P'_P: FV P' = FV P,
assume P'_dominates_p_P: (∀σ, σ ⊨ vc.implies P'.to_vc P.to_vc),
have f_free_in_P': f ∈ FV P', from free_P'_P.symm ▸ f_free_in_P,
have x_free_in_P': x ∈ FV P', from free_P'_P.symm ▸ x_free_in_P,
have y_not_free_in_P': y ∉ FV P', from free_P'_P.symm ▸ y_not_free_in_P,
have h1: FV (P' ⋀ prop.call x ⋀ prop.post f x ⋀ y ≡ term.app f x)
= FV (P ⋀ prop.call x ⋀ prop.post f x ⋀ y ≡ term.app f x),
from free_in_prop.same_right free_P'_P,
have h2: (∀σ, σ ⊨ vc.implies (P' ⋀ prop.call x ⋀ prop.post f x ⋀ y ≡ term.app f x).to_vc
(P ⋀ prop.call x ⋀ prop.post f x ⋀ y ≡ term.app f x).to_vc),
from (λσ, vc.implies.same_right (λ_, P'_dominates_p_P σ)),
have e'_verified': P' ⋀ prop.call x ⋀ prop.post f x ⋀ y ≡ term.app f x ⊩ e' : Q',
from ih (P' ⋀ prop.call x ⋀ prop.post f x ⋀ y ≡ term.app f x) h1 h2,
have vc_valid': ∀ (σ : env),
closed_subst σ (prop.implies (P' ⋀ prop.call x) (term.unop unop.isFunc f ⋀ prop.pre f x)) →
σ ⊨ (prop.implies (P' ⋀ prop.call x) (term.unop unop.isFunc f ⋀ prop.pre f x)).to_vc,
from (λσ, strengthen_vc_with_q (P'_dominates_p_P σ) (set.subset_of_eq free_P'_P.symm) (vc_valid σ)),
show P' ⊩ letapp y = f [x] in e' : propctx.exis y (prop.call x ⋀ prop.post f x ⋀ y ≡ term.app f x ⋀ Q'),
from exp.dvcgen.app f_free_in_P' x_free_in_P' y_not_free_in_P' e'_verified' vc_valid'
},
case exp.dvcgen.ite x e₂ e₁ P Q₁ Q₂ x_free_in_P e₁_verified e₂_verified vc_valid ih₁ ih₂ { from
assume P': prop,
assume free_P'_P: FV P' = FV P,
assume P'_dominates_p_P: (∀σ, σ ⊨ vc.implies P'.to_vc P.to_vc),
have x_free_in_P': x ∈ FV P', from free_P'_P.symm ▸ x_free_in_P,
have h1: FV (P' ⋀ x) = FV (P ⋀ x), from free_in_prop.same_right free_P'_P,
have h2: (∀σ, σ ⊨ vc.implies (P' ⋀ x).to_vc (P ⋀ x).to_vc),
from (λσ, vc.implies.same_right (λ_, P'_dominates_p_P σ)),
have e₁_verified': P' ⋀ x ⊩ e₁ : Q₁, from ih₁ (P' ⋀ x) h1 h2,
have h1: FV (P' ⋀ prop.not x) = FV (P ⋀ prop.not x), from free_in_prop.same_right free_P'_P,
have h2: (∀σ, σ ⊨ vc.implies (P' ⋀ prop.not x).to_vc (P ⋀ prop.not x).to_vc),
from (λσ, vc.implies.same_right (λ_, P'_dominates_p_P σ)),
have e₂_verified': P' ⋀ prop.not x ⊩ e₂ : Q₂, from ih₂ (P' ⋀ prop.not x) h1 h2,
have FV P ⊆ FV P', from set.subset_of_eq free_P'_P.symm,
have vc_valid': ∀ (σ : env),
closed_subst σ (prop.implies P' (term.unop unop.isBool x)) →
σ ⊨ (prop.implies P' (term.unop unop.isBool x)).to_vc,
from (λσ, strengthen_vc (P'_dominates_p_P σ) this (vc_valid σ)),
show P' ⊩ exp.ite x e₁ e₂ : propctx.implies x Q₁ ⋀ propctx.implies (prop.not x) Q₂,
from exp.dvcgen.ite x_free_in_P' e₁_verified' e₂_verified' vc_valid'
},
case exp.dvcgen.return x P x_free_in_P { from
assume P': prop,
assume free_P'_P: FV P' = FV P,
assume P'_dominates_p_P: (∀σ, σ ⊨ vc.implies P'.to_vc P.to_vc),
have x_free_in_P': x ∈ FV P', from free_P'_P.symm ▸ x_free_in_P,
show P' ⊩ exp.return x : (x ≣ •), from exp.dvcgen.return x_free_in_P'
}
end
|
96553d2a1bb80c8064cda5dc2b81a8c7fa5c7a0d | 6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b | /stage0/src/Lean/Elab/Tactic/Induction.lean | b819e39eaec4562f59ac080eca9156058cc45bdf | [
"Apache-2.0"
] | permissive | pbrinkmeier/lean4 | d31991fd64095e64490cb7157bcc6803f9c48af4 | 32fd82efc2eaf1232299e930ec16624b370eac39 | refs/heads/master | 1,681,364,001,662 | 1,618,425,427,000 | 1,618,425,427,000 | 358,314,562 | 0 | 0 | Apache-2.0 | 1,618,504,558,000 | 1,618,501,999,000 | null | UTF-8 | Lean | false | false | 20,364 | 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, Sebastian Ullrich
-/
import Lean.Util.CollectFVars
import Lean.Parser.Term
import Lean.Meta.RecursorInfo
import Lean.Meta.CollectMVars
import Lean.Meta.Tactic.ElimInfo
import Lean.Meta.Tactic.Induction
import Lean.Meta.Tactic.Cases
import Lean.Elab.App
import Lean.Elab.Tactic.ElabTerm
import Lean.Elab.Tactic.Generalize
namespace Lean.Elab.Tactic
open Meta
/-
Given an `inductionAlt` of the form
```
nodeWithAntiquot "inductionAlt" `Lean.Parser.Tactic.inductionAlt $ ident' >> many ident' >> darrow >> termParser
```
-/
private def getAltName (alt : Syntax) : Name :=
-- alt[1] is of the form (("@"? ident) <|> "_")
if alt[1].hasArgs then alt[1][1].getId.eraseMacroScopes else `_
private def altHasExplicitModifier (alt : Syntax) : Bool :=
alt[1].hasArgs && !alt[1][0].isNone
private def getAltVarNames (alt : Syntax) : Array Name :=
alt[2].getArgs.map getNameOfIdent'
private def getAltRHS (alt : Syntax) : Syntax :=
alt[4]
private def getAltDArrow (alt : Syntax) : Syntax :=
alt[3]
-- Return true if `stx` is a term occurring in the RHS of the induction/cases tactic
def isHoleRHS (rhs : Syntax) : Bool :=
rhs.isOfKind ``Parser.Term.syntheticHole || rhs.isOfKind ``Parser.Term.hole
def evalAlt (mvarId : MVarId) (alt : Syntax) (remainingGoals : Array MVarId) : TacticM (Array MVarId) :=
let rhs := getAltRHS alt
withCaseRef (getAltDArrow alt) rhs do
if isHoleRHS rhs then
let gs' ← withMVarContext mvarId $ withRef rhs do
let mvarDecl ← getMVarDecl mvarId
let val ← elabTermEnsuringType rhs mvarDecl.type
assignExprMVar mvarId val
let gs' ← getMVarsNoDelayed val
tagUntaggedGoals mvarDecl.userName `induction gs'.toList
pure gs'
return remainingGoals ++ gs'
else
setGoals [mvarId]
closeUsingOrAdmit rhs
return remainingGoals
/-
Helper method for creating an user-defined eliminator/recursor application.
-/
namespace ElimApp
structure Context where
elimInfo : ElimInfo
targets : Array Expr -- targets provided by the user
structure State where
argPos : Nat := 0 -- current argument position
targetPos : Nat := 0 -- current target at targetsStx
f : Expr
fType : Expr
alts : Array (Name × MVarId) := #[]
insts : Array MVarId := #[]
abbrev M := ReaderT Context $ StateRefT State TermElabM
private def addNewArg (arg : Expr) : M Unit :=
modify fun s => { s with argPos := s.argPos+1, f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg }
/- Return the binder name at `fType`. This method assumes `fType` is a function type. -/
private def getBindingName : M Name := return (← get).fType.bindingName!
/- Return the next argument expected type. This method assumes `fType` is a function type. -/
private def getArgExpectedType : M Expr := return (← get).fType.bindingDomain!
private def getFType : M Expr := do
let fType ← whnfForall (← get).fType
modify fun s => { s with fType := fType }
pure fType
structure Result where
elimApp : Expr
alts : Array (Name × MVarId) := #[]
others : Array MVarId := #[]
/--
Construct the an eliminator/recursor application. `targets` contains the explicit and implicit targets for
the eliminator. For example, the indices of builtin recursors are considered implicit targets.
Remark: the method `addImplicitTargets` may be used to compute the sequence of implicit and explicit targets
from the explicit ones.
-/
partial def mkElimApp (elimName : Name) (elimInfo : ElimInfo) (targets : Array Expr) (tag : Name) : TermElabM Result := do
let rec loop : M Unit := do
match (← getFType) with
| Expr.forallE binderName _ _ c =>
let ctx ← read
let argPos := (← get).argPos
if ctx.elimInfo.motivePos == argPos then
let motive ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.syntheticOpaque
addNewArg motive
else if ctx.elimInfo.targetsPos.contains argPos then
let s ← get
let ctx ← read
unless s.targetPos < ctx.targets.size do
throwError "insufficient number of targets for '{elimName}'"
let target := ctx.targets[s.targetPos]
let expectedType ← getArgExpectedType
let target ← Term.ensureHasType expectedType target
modify fun s => { s with targetPos := s.targetPos + 1 }
addNewArg target
else match c.binderInfo with
| BinderInfo.implicit =>
let arg ← mkFreshExprMVar (← getArgExpectedType)
addNewArg arg
| BinderInfo.instImplicit =>
let arg ← mkFreshExprMVar (← getArgExpectedType) (kind := MetavarKind.synthetic) (userName := appendTag tag binderName)
modify fun s => { s with insts := s.insts.push arg.mvarId! }
addNewArg arg
| _ =>
let arg ← mkFreshExprSyntheticOpaqueMVar (← getArgExpectedType) (tag := appendTag tag binderName)
modify fun s => { s with alts := s.alts.push (← getBindingName, arg.mvarId!) }
addNewArg arg
loop
| _ =>
pure ()
let f ← Term.mkConst elimName
let fType ← inferType f
let (_, s) ← loop.run { elimInfo := elimInfo, targets := targets } |>.run { f := f, fType := fType }
let mut others := #[]
for mvarId in s.insts do
try
unless (← Term.synthesizeInstMVarCore mvarId) do
setMVarKind mvarId MetavarKind.syntheticOpaque
others := others.push mvarId
catch _ =>
setMVarKind mvarId MetavarKind.syntheticOpaque
others := others.push mvarId
return { elimApp := (← instantiateMVars s.f), alts := s.alts, others := others }
/- Given a goal `... targets ... |- C[targets]` associated with `mvarId`, assign
`motiveArg := fun targets => C[targets]` -/
def setMotiveArg (mvarId : MVarId) (motiveArg : MVarId) (targets : Array FVarId) : MetaM Unit := do
let type ← inferType (mkMVar mvarId)
let motive ← mkLambdaFVars (targets.map mkFVar) type
let motiverInferredType ← inferType motive
let motiveType ← inferType (mkMVar motiveArg)
unless (← isDefEqGuarded motiverInferredType motiveType) do
throwError "type mismatch when assigning motive{indentExpr motive}\n{← mkHasTypeButIsExpectedMsg motiverInferredType motiveType}"
assignExprMVar motiveArg motive
private def getAltNumFields (elimInfo : ElimInfo) (altName : Name) : TermElabM Nat := do
for altInfo in elimInfo.altsInfo do
if altInfo.name == altName then
return altInfo.numFields
throwError "unknown alternative name '{altName}'"
private def checkAltNames (alts : Array (Name × MVarId)) (altsSyntax : Array Syntax) : TacticM Unit :=
for altStx in altsSyntax do
let altName := getAltName altStx
if altName != `_ then
unless alts.any fun (n, _) => n == altName do
throwErrorAt altStx "invalid alternative name '{altName}'"
def evalAlts (elimInfo : ElimInfo) (alts : Array (Name × MVarId)) (optPreTac : Syntax) (altsSyntax : Array Syntax)
(numEqs : Nat := 0) (numGeneralized : Nat := 0) (toClear : Array FVarId := #[]) : TacticM Unit := do
checkAltNames alts altsSyntax
let mut usedWildcard := false
let hasAlts := altsSyntax.size > 0
let mut subgoals := #[] -- when alternatives are not provided, we accumulate subgoals here
let mut altsSyntax := altsSyntax
for (altName, altMVarId) in alts do
let numFields ← getAltNumFields elimInfo altName
let altStx? ←
match altsSyntax.findIdx? (fun alt => getAltName alt == altName) with
| some idx =>
let altStx := altsSyntax[idx]
altsSyntax := altsSyntax.eraseIdx idx
pure (some altStx)
| none => match altsSyntax.findIdx? (fun alt => getAltName alt == `_) with
| some idx =>
usedWildcard := true
pure (some altsSyntax[idx])
| none =>
pure none
match altStx? with
| none =>
let mut (_, altMVarId) ← introN altMVarId numFields
match (← Cases.unifyEqs numEqs altMVarId {}) with
| none => pure () -- alternative is not reachable
| some (altMVarId, _) =>
let (_, altMVarId) ← introNP altMVarId numGeneralized
for fvarId in toClear do
altMVarId ← tryClear altMVarId fvarId
let altMVarIds ← applyPreTac altMVarId
if !hasAlts then
-- User did not provide alternatives using `|`
subgoals := subgoals ++ altMVarIds.toArray
else if altMVarIds.isEmpty then
pure ()
else
logError m!"alternative '{altName}' has not been provided"
altMVarIds.forM admitGoal
| some altStx =>
subgoals ← withRef altStx do
let altVarNames := getAltVarNames altStx
if altVarNames.size > numFields then
logError m!"too many variable names provided at alternative '{altName}', #{altVarNames.size} provided, but #{numFields} expected"
let mut (_, altMVarId) ← introN altMVarId numFields altVarNames.toList (useNamesForExplicitOnly := !altHasExplicitModifier altStx)
match (← Cases.unifyEqs numEqs altMVarId {}) with
| none => throwError "alternative '{altName}' is not needed"
| some (altMVarId, _) =>
let (_, altMVarId) ← introNP altMVarId numGeneralized
for fvarId in toClear do
altMVarId ← tryClear altMVarId fvarId
let altMVarIds ← applyPreTac altMVarId
if altMVarIds.isEmpty then
throwError "alternative '{altName}' is not needed"
else
altMVarIds.foldlM (init := subgoals) fun subgoal altMVarId =>
evalAlt altMVarId altStx subgoals
if usedWildcard then
altsSyntax := altsSyntax.filter fun alt => getAltName alt != `_
unless altsSyntax.isEmpty do
logErrorAt altsSyntax[0] "unused alternative"
setGoals subgoals.toList
where
applyPreTac (mvarId : MVarId) : TacticM (List MVarId) :=
if optPreTac.isNone then
return [mvarId]
else
evalTacticAt optPreTac[0] mvarId
end ElimApp
/--
Return a set of `FVarId`s containing `targets` and all variables they depend on.
Remark: this method assumes `targets` are free variables.
-/
private partial def mkForbiddenSet (targets : Array Expr) : MetaM NameSet := do
loop (targets.toList.map Expr.fvarId!) {}
where
visit (fvarId : FVarId) (todo : List FVarId) (s : NameSet) : MetaM (List FVarId × NameSet) := do
let localDecl ← getLocalDecl fvarId
let mut s' := collectFVars {} (← instantiateMVars localDecl.type)
if let some val := localDecl.value? then
s' := collectFVars s' (← instantiateMVars val)
let mut todo := todo
let mut s := s
for fvarId in s'.fvarSet do
unless s.contains fvarId do
todo := fvarId :: todo
s := s.insert fvarId
return (todo, s)
loop (todo : List FVarId) (s : NameSet) : MetaM NameSet := do
match todo with
| [] => return s
| fvarId::todo =>
if s.contains fvarId then
loop todo s
else
let (todo, s) ← visit fvarId todo <| s.insert fvarId
loop todo s
/--
Collect forward dependencies that are not in the forbidden set, and depend on some variable in `targets`.
Remark: this method assumes `targets` are free variables.
-/
private def collectForwardDeps (targets : Array Expr) (forbidden : NameSet) : MetaM NameSet := do
let mut s : NameSet := targets.foldl (init := {}) fun s target => s.insert target.fvarId!
let mut r : NameSet := {}
for localDecl in (← getLCtx) do
unless forbidden.contains localDecl.fvarId do
unless localDecl.isAuxDecl do
if (← getMCtx).findLocalDeclDependsOn localDecl fun fvarId => s.contains fvarId then
r := r.insert localDecl.fvarId
s := s.insert localDecl.fvarId
return r
/-
Recall that
```
generalizingVars := optional (" generalizing " >> many1 ident)
«induction» := leading_parser nonReservedSymbol "induction " >> majorPremise >> usingRec >> generalizingVars >> optional inductionAlts
```
`stx` is syntax for `induction`. -/
private def getGeneralizingFVarIds (stx : Syntax) : TacticM (Array FVarId) :=
withRef stx do
let generalizingStx := stx[3]
if generalizingStx.isNone then
pure #[]
else
trace[Elab.induction] "{generalizingStx}"
let vars := generalizingStx[1].getArgs
getFVarIds vars
-- process `generalizingVars` subterm of induction Syntax `stx`.
private def generalizeVars (mvarId : MVarId) (stx : Syntax) (targets : Array Expr) : TacticM (Nat × MVarId) :=
withMVarContext mvarId do
let userFVarIds ← getGeneralizingFVarIds stx
let forbidden ← mkForbiddenSet targets
let mut s ← collectForwardDeps targets forbidden
for userFVarId in userFVarIds do
if forbidden.contains userFVarId then
throwError "variable cannot be generalized because target depends on it{indentExpr (mkFVar userFVarId)}"
if s.contains userFVarId then
throwError "unnecessary 'generalizing' argument, variable '{mkFVar userFVarId}' is generalized automatically"
s := s.insert userFVarId
let fvarIds := s.fold (init := #[]) fun s fvarId => s.push fvarId
let lctx ← getLCtx
let fvarIds ← fvarIds.qsort fun x y => (lctx.get! x).index < (lctx.get! y).index
let (fvarIds, mvarId') ← Meta.revert mvarId fvarIds
return (fvarIds.size, mvarId')
-- syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+)
private def getAltsOfInductionAlts (inductionAlts : Syntax) : Array Syntax :=
inductionAlts[2].getArgs
private def getAltsOfOptInductionAlts (optInductionAlts : Syntax) : Array Syntax :=
if optInductionAlts.isNone then #[] else getAltsOfInductionAlts optInductionAlts[0]
private def getOptPreTacOfOptInductionAlts (optInductionAlts : Syntax) : Syntax :=
if optInductionAlts.isNone then mkNullNode else optInductionAlts[0][1]
/-
We may have at most one `| _ => ...` (wildcard alternative), and it must not set variable names.
The idea is to make sure users do not write unstructured tactics. -/
private def checkAltsOfOptInductionAlts (optInductionAlts : Syntax) : TacticM Unit :=
unless optInductionAlts.isNone do
let mut found := false
for alt in getAltsOfInductionAlts optInductionAlts[0] do
let n := getAltName alt
if n == `_ then
unless (getAltVarNames alt).isEmpty do
throwErrorAt alt "wildcard alternative must not specify variable names"
if found then
throwErrorAt alt "more than one wildcard alternative '| _ => ...' used"
found := true
def getInductiveValFromMajor (major : Expr) : TacticM InductiveVal :=
liftMetaMAtMain fun mvarId => do
let majorType ← inferType major
let majorType ← whnf majorType
matchConstInduct majorType.getAppFn
(fun _ => Meta.throwTacticEx `induction mvarId m!"major premise type is not an inductive type {indentExpr majorType}")
(fun val _ => pure val)
private def generalizeTerm (term : Expr) : TacticM Expr := do
match term with
| Expr.fvar .. => pure term
| _ =>
liftMetaTacticAux fun mvarId => do
let mvarId ← Meta.generalize mvarId term `x false
let (fvarId, mvarId) ← Meta.intro1 mvarId
pure (mkFVar fvarId, [mvarId])
-- `optElimId` is of the form `("using" ident)?`
private def getElimNameInfo (optElimId : Syntax) (targets : Array Expr) (induction : Bool): TacticM (Name × ElimInfo) := do
if optElimId.isNone then
unless targets.size == 1 do
throwError "eliminator must be provided when multiple targets are used (use 'using <eliminator-name>')"
let indVal ← getInductiveValFromMajor targets[0]
let elimName := if induction then mkRecName indVal.name else mkCasesOnName indVal.name
pure (elimName, ← getElimInfo elimName)
else
let elimId := optElimId[1]
let elimName ← withRef elimId do resolveGlobalConstNoOverloadWithInfo elimId elimId.getId.eraseMacroScopes
pure (elimName, ← withRef elimId do getElimInfo elimName)
@[builtinTactic Lean.Parser.Tactic.induction] def evalInduction : Tactic := fun stx => focus do
let targets ← stx[1].getSepArgs.mapM fun target => do
let target ← withMainContext <| elabTerm target none
generalizeTerm target
let (elimName, elimInfo) ← getElimNameInfo stx[2] targets (induction := true)
let mvarId ← getMainGoal
let tag ← getMVarTag mvarId
withMVarContext mvarId do
let targets ← addImplicitTargets elimInfo targets
checkTargets targets
let targetFVarIds := targets.map (·.fvarId!)
let (n, mvarId) ← generalizeVars mvarId stx targets
withMVarContext mvarId do
let result ← withRef stx[1] do -- use target position as reference
ElimApp.mkElimApp elimName elimInfo targets tag
let elimArgs := result.elimApp.getAppArgs
let motiveType ← inferType elimArgs[elimInfo.motivePos]
ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos].mvarId! targetFVarIds
let optInductionAlts := stx[4]
let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts
let alts := getAltsOfOptInductionAlts optInductionAlts
assignExprMVar mvarId result.elimApp
ElimApp.evalAlts elimInfo result.alts optPreTac alts (numGeneralized := n) (toClear := targetFVarIds)
appendGoals result.others.toList
where
checkTargets (targets : Array Expr) : MetaM Unit := do
let mut foundFVars : NameSet := {}
for target in targets do
unless target.isFVar do
throwError "index in target's type is not a variable (consider using the `cases` tactic instead){indentExpr target}"
if foundFVars.contains target.fvarId! then
throwError "target (or one of its indices) occurs more than once{indentExpr target}"
-- Recall that
-- majorPremise := leading_parser optional (try (ident >> " : ")) >> termParser
private def getTargetHypothesisName? (target : Syntax) : Option Name :=
if target[0].isNone then
none
else
some target[0][0].getId
private def getTargetTerm (target : Syntax) : Syntax :=
target[1]
private def elabTaggedTerm (h? : Option Name) (termStx : Syntax) : TacticM Expr :=
withMainContext <| withRef termStx do
let term ← elabTerm termStx none
match h? with
| none => pure term
| some h =>
let lctx ← getLCtx
let x ← mkFreshUserName `x
evalGeneralizeAux h? term x
withMainContext do
let lctx ← getLCtx
match lctx.findFromUserName? x with
| some decl => pure decl.toExpr
| none => throwError "failed to generalize"
def elabTargets (targets : Array Syntax) : TacticM (Array Expr) :=
targets.mapM fun target => do
let h? := getTargetHypothesisName? target
let term ← elabTaggedTerm h? (getTargetTerm target)
generalizeTerm term
builtin_initialize registerTraceClass `Elab.cases
@[builtinTactic Lean.Parser.Tactic.cases] def evalCases : Tactic := fun stx => focus do
-- leading_parser nonReservedSymbol "cases " >> sepBy1 (group majorPremise) ", " >> usingRec >> optInductionAlts
let targets ← elabTargets stx[1].getSepArgs
let optInductionAlts := stx[3]
let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts
let alts := getAltsOfOptInductionAlts optInductionAlts
let targetRef := stx[1]
let (elimName, elimInfo) ← getElimNameInfo stx[2] targets (induction := false)
let mvarId ← getMainGoal
let tag ← getMVarTag mvarId
withMVarContext mvarId do
let targets ← addImplicitTargets elimInfo targets
let result ← withRef targetRef <| ElimApp.mkElimApp elimName elimInfo targets tag
let elimArgs := result.elimApp.getAppArgs
let targets ← elimInfo.targetsPos.mapM fun i => instantiateMVars elimArgs[i]
let motiveType ← inferType elimArgs[elimInfo.motivePos]
let mvarId ← generalizeTargets mvarId motiveType targets
let (targetsNew, mvarId) ← introN mvarId targets.size
withMVarContext mvarId do
ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos].mvarId! targetsNew
assignExprMVar mvarId result.elimApp
ElimApp.evalAlts elimInfo result.alts optPreTac alts (numEqs := targets.size) (toClear := targetsNew)
end Lean.Elab.Tactic
|
b04f35a66ca7ffbb3e330b541b84dcc4778932af | 737dc4b96c97368cb66b925eeea3ab633ec3d702 | /tests/lean/run/PPTopDownAnalyze.lean | 99a7eea13b314466b8d81e8fa674743c79573f5a | [
"Apache-2.0"
] | permissive | Bioye97/lean4 | 1ace34638efd9913dc5991443777b01a08983289 | bc3900cbb9adda83eed7e6affeaade7cfd07716d | refs/heads/master | 1,690,589,820,211 | 1,631,051,000,000 | 1,631,067,598,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,315 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Daniel Selsam
-/
import Lean
import Std
open Lean Lean.Meta Lean.Elab Lean.Elab.Term Lean.Elab.Command
open Lean.PrettyPrinter
def checkDelab (e : Expr) (tgt? : Option Syntax) (name? : Option Name := none) : TermElabM Unit := do
if e.hasMVar then throwError "[checkDelab] original term has mvars, {e}"
let stx ← delab (← getCurrNamespace) (← getOpenDecls) e
match tgt? with
| some tgt =>
if toString (← PrettyPrinter.ppTerm stx) != toString (← PrettyPrinter.ppTerm tgt?.get!) then
throwError "[checkDelab] missed target\n{← PrettyPrinter.ppTerm stx}\n!=\n{← PrettyPrinter.ppTerm tgt}\n\nExpr: {e}\nType: {← inferType e}"
| _ => pure ()
let e' ←
try
let e' ← elabTerm stx (some (← inferType e))
synthesizeSyntheticMVarsNoPostponing
let e' ← instantiateMVars e'
-- let ⟨e', _⟩ ← levelMVarToParam e'
throwErrorIfErrors
e'
catch ex => throwError "[checkDelab] failed to re-elaborate,\n{stx}\n{← ex.toMessageData.toString}"
withTheReader Core.Context (fun ctx => { ctx with options := ctx.options.setBool `pp.all true }) do
if not (← isDefEq e e') then
println! "[checkDelab] {← inferType e} {← inferType e'}"
throwError "[checkDelab] roundtrip not structurally equal\n\nOriginal: {e}\n\nSyntax: {stx}\n\nNew: {e'}"
let e' ← instantiateMVars e'
if e'.hasMVar then throwError "[checkDelab] elaborated term still has mvars\n\nSyntax: {stx}\n\nExpression: {e'}"
syntax (name := testDelabTD) "#testDelab " term " expecting " term : command
@[commandElab testDelabTD] def elabTestDelabTD : CommandElab
| `(#testDelab $stx:term expecting $tgt:term) => liftTermElabM `delabTD do
let e ← elabTerm stx none
let ⟨e, _⟩ ← levelMVarToParam e
let e ← instantiateMVars e
checkDelab e (some tgt)
| _ => throwUnsupportedSyntax
syntax (name := testDelabTDN) "#testDelabN " ident : command
@[commandElab testDelabTDN] def elabTestDelabTDN : CommandElab
| `(#testDelabN $name:ident) => liftTermElabM `delabTD do
let name := name.getId
let [name] ← resolveGlobalConst (mkIdent name) | throwError "cannot resolve name"
let some cInfo ← (← getEnv).find? name | throwError "no decl for name"
let some value ← pure cInfo.value? | throwError "decl has no value"
modify fun s => { s with levelNames := cInfo.levelParams }
withTheReader Core.Context (fun ctx => { ctx with currNamespace := name.getPrefix, openDecls := [] }) do
checkDelab value none
| _ => throwUnsupportedSyntax
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
universe u v
set_option pp.analyze true
set_option pp.analyze.checkInstances true
set_option pp.proofs true
#testDelab @Nat.brecOn (fun x => Nat) 0 (fun x ih => x)
expecting Nat.brecOn (motive := fun x => Nat) 0 fun x ih => x
#testDelab @Nat.brecOn (fun x => Nat → Nat) 0 (fun x ih => fun y => y + x)
expecting Nat.brecOn (motive := fun x => Nat → Nat) 0 fun x ih y => y + x
#testDelab @Nat.brecOn (fun x => Nat → Nat) 0 (fun x ih => fun y => y + x) 0
expecting Nat.brecOn (motive := fun x => Nat → Nat) 0 (fun x ih y => y + x) 0
#testDelab let xs := #[]; xs.push (5 : Nat)
expecting let xs : Array Nat := #[]; Array.push xs 5
#testDelab let x := Nat.zero; x + Nat.zero
expecting let x := Nat.zero; x + Nat.zero
def fHole (α : Type) (x : α) : α := x
#testDelab fHole Nat Nat.zero
expecting fHole _ Nat.zero
def fPoly {α : Type u} (x : α) : α := x
#testDelab fPoly Nat.zero
expecting fPoly Nat.zero
#testDelab fPoly (id Nat.zero)
expecting fPoly (id Nat.zero)
def fPoly2 {α : Type u} {β : Type v} (x : α) : α := x
#testDelab @fPoly2 _ (Type 3) Nat.zero
expecting fPoly2 (β := Type 3) Nat.zero
def fPolyInst {α : Type u} [Add α] : α → α → α := Add.add
#testDelab @fPolyInst Nat ⟨Nat.add⟩
expecting fPolyInst
def fPolyNotInst {α : Type u} (inst : Add α) : α → α → α := Add.add
#testDelab @fPolyNotInst Nat ⟨Nat.add⟩
expecting fPolyNotInst { add := Nat.add }
#testDelab (fun (x : Nat) => x) Nat.zero
expecting (fun (x : Nat) => x) Nat.zero
#testDelab (fun (α : Type) (x : α) => x) Nat Nat.zero
expecting (fun (α : Type) (x : α) => x) _ Nat.zero
#testDelab (fun {α : Type} (x : α) => x) Nat.zero
expecting (fun {α : Type} (x : α) => x) Nat.zero
#testDelab ((@Add.mk Nat Nat.add).1 : Nat → Nat → Nat)
expecting Add.add
class Foo (α : Type v) where foo : α
instance : Foo Bool := ⟨true⟩
#testDelab @Foo.foo Bool ⟨true⟩
expecting Foo.foo
#testDelab @Foo.foo Bool ⟨false⟩
expecting Foo.foo (self := { foo := false })
axiom wild {α : Type u} {f : α → Type v} {x : α} [_inst_1 : Foo (f x)] : Nat
abbrev nat2bool : Nat → Type := fun _ => Bool
#testDelab @wild Nat nat2bool Nat.zero ⟨false⟩
expecting wild (f := nat2bool) (x := Nat.zero) (_inst_1 := { foo := false })
#testDelab @wild Nat (fun (n : Nat) => Bool) Nat.zero ⟨false⟩
expecting wild (f := fun n => Bool) (x := Nat.zero) (_inst_1 := { foo := false })
def takesFooUnnamed {Impl : Type} (Expl : Type) [Foo Nat] (x : Impl) (y : Expl) : Impl × Expl := (x, y)
#testDelab @takesFooUnnamed _ Nat (Foo.mk 7) false 5
expecting @takesFooUnnamed _ _ { foo := 7 } false 5
#testDelab (fun {α : Type u} (x : α) => x : ∀ {α : Type u}, α → α)
expecting fun {α} x => x
#testDelab (fun {α : Type} (x : α) => x) Nat.zero
expecting (fun {α : Type} (x : α) => x) Nat.zero
#testDelab (fun {α : Type} [Add α] (x : α) => x + x) (0 : Nat)
expecting (fun {α : Type} [Add α] (x : α) => x + x) 0
#testDelab (fun {α : Type} [Add α] (x : α) => x + x) Nat.zero
expecting (fun {α : Type} [Add α] (x : α) => x + x) Nat.zero
#testDelab id id id id Nat.zero
expecting id id id id Nat.zero
def zzz : Unit := ()
def Z1.zzz : Unit := ()
def Z1.Z2.zzz : Unit := ()
namespace Z1.Z2
#testDelab _root_.zzz
expecting _root_.zzz
#testDelab Z1.zzz
expecting Z1.zzz
#testDelab zzz
expecting zzz
end Z1.Z2
#testDelab fun {σ : Type u} {m : Type u → Type v} [Monad m] {α : Type u} (f : σ → α × σ) (s : σ) => pure (f := m) (f s)
expecting fun {σ} {m} [Monad m] {α} f s => pure (f s)
set_option pp.analyze.trustSubst false in
#testDelab (fun (x y z : Nat) (hxy : x = y) (hyz : x = z) => hxy ▸ hyz : ∀ (x y z : Nat), x = y → x = z → y = z)
expecting fun x y z hxy hyz => Eq.ndrec (a := x) (motive := fun x => x = z) hyz hxy
set_option pp.analyze.trustSubst true in
#testDelab (fun (x y z : Nat) (hxy : x = y) (hyz : x = z) => hxy ▸ hyz : ∀ (x y z : Nat), x = y → x = z → y = z)
expecting fun x y z hxy hyz => hxy ▸ hyz
set_option pp.analyze.trustId true in
#testDelab Sigma.mk (β := fun α => α) Bool true
expecting { fst := _, snd := true }
set_option pp.analyze.trustId false in
#testDelab Sigma.mk (β := fun α => α) Bool true
expecting Sigma.mk (β := fun α => α) _ true
#testDelab let xs := #[true]; xs
expecting let xs := #[true]; xs
def fooReadGetModify : ReaderT Unit (StateT Unit IO) Unit := do
let _ ← read
let _ ← get
modify fun s => s
#testDelab
(do discard read
pure () : ReaderT Bool IO Unit)
expecting
do discard read
pure ()
#testDelab
((do let ctx ← read
let s ← get
modify fun s => s : ReaderT Bool (StateT Bool IO) Unit))
expecting
do let _ ← read
let _ ← get
modify fun s => s
set_option pp.analyze.typeAscriptions true in
#testDelab (fun (x : Unit) => @id (ReaderT Bool IO Bool) (do read : ReaderT Bool IO Bool)) ()
expecting (fun (x : Unit) => (id read : ReaderT Bool IO Bool)) ()
set_option pp.analyze.typeAscriptions false in
#testDelab (fun (x : Unit) => @id (ReaderT Bool IO Bool) (do read : ReaderT Bool IO Bool)) ()
expecting (fun (x : Unit) => id read) ()
instance : CoeFun Bool (fun b => Bool → Bool) := { coe := fun b x => b && x }
set_option pp.analyze.trustCoe false in
#testDelab coeFun true false expecting coeFun (γ := fun b => Bool → Bool) true false
set_option pp.analyze.trustCoe true in
#testDelab coeFun true false expecting true false
#testDelab fun (xs : List Nat) => xs ≠ xs
expecting fun xs => xs ≠ xs
structure S1 where x : Unit
structure S2 where x : Unit
#testDelab { x := () : S1 }
expecting { x := () }
#testDelab (fun (u : Unit) => { x := () : S2 }) ()
expecting (fun (u : Unit) => { x := () : S2 }) ()
#testDelab Eq.refl True
expecting Eq.refl _
#testDelab (fun (u : Unit) => Eq.refl True) ()
expecting (fun (u : Unit) => Eq.refl True) ()
inductive NeedsAnalysis {α : Type} : Prop
| mk : NeedsAnalysis
set_option pp.proofs false in
#testDelab @NeedsAnalysis.mk Unit
expecting (_ : NeedsAnalysis (α := Unit))
set_option pp.proofs false in
set_option pp.proofs.withType false in
#testDelab @NeedsAnalysis.mk Unit
expecting _
#testDelab ∀ (α : Type u) (vals vals_1 : List α), { data := vals : Array α } = { data := vals_1 : Array α }
expecting ∀ (α : Type u) (vals vals_1 : List α), { data := vals : Array α } = { data := vals_1 }
#testDelab (do let ctxCore ← readThe Core.Context; ctxCore.currNamespace : MetaM Name)
expecting do
let ctxCore ← readThe Core.Context
pure ctxCore.currNamespace
structure SubtypeLike1 {α : Sort u} (p : α → Prop) where
#testDelab SubtypeLike1 fun (x : Nat) => x < 10
expecting SubtypeLike1 fun (x : Nat) => x < 10
#eval "prevent comment from parsing as part of previous expression"
--Note: currently we do not try "bottom-upping" inside lambdas
--(so we will always annotate the binder type)
#testDelab SubtypeLike1 fun (x : Nat) => Nat.succ x = x
expecting SubtypeLike1 fun (x : Nat) => Nat.succ x = x
structure SubtypeLike3 {α β γ : Sort u} (p : α → β → γ → Prop) where
#testDelab SubtypeLike3 fun (x y z : Nat) => x + y < z
expecting SubtypeLike3 fun (x y z : Nat) => x + y < z
structure SubtypeLike3Double {α β γ : Sort u} (p₁ : α → β → Prop) (p₂ : β → γ → Prop) where
#testDelab SubtypeLike3Double (fun (x y : Nat) => x = y) (fun (y z : Nat) => y = z)
expecting SubtypeLike3Double (fun (x y : Nat) => x = y) fun y (z : Nat) => y = z
def takesStricts ⦃α : Type⦄ {β : Type} ⦃γ : Type⦄ : Unit := ()
#testDelab takesStricts expecting takesStricts
#testDelab @takesStricts expecting takesStricts
#testDelab @takesStricts Unit Unit expecting takesStricts (α := Unit) (β := Unit)
#testDelab @takesStricts Unit Unit Unit expecting takesStricts (α := Unit) (β := Unit) (γ := Unit)
def takesStrictMotive ⦃motive : Nat → Type⦄ {n : Nat} (x : motive n) : motive n := x
#testDelab takesStrictMotive expecting takesStrictMotive
#testDelab @takesStrictMotive (fun x => Unit) 0 expecting takesStrictMotive (motive := fun x => Unit) (n := 0)
#testDelab @takesStrictMotive (fun x => Unit) 0 () expecting takesStrictMotive (motive := fun x => Unit) (n := 0) ()
def stackMkInjEqSnippet :=
fun {α : Type} (xs : Array α) => Eq.ndrec (motive := fun _ => (Std.Stack.mk xs = Std.Stack.mk xs)) (Eq.refl (Std.Stack.mk xs)) (rfl : xs = xs)
#testDelabN stackMkInjEqSnippet
def typeAs (α : Type u) (a : α) := ()
#testDelabN Nat.brecOn
#testDelabN Nat.below
#testDelabN Nat.mod_lt
#testDelabN Array.qsort
#testDelabN List.partition
#testDelabN List.partitionAux
#testDelabN StateT.modifyGet
#testDelabN Nat.gcd_one_left
#testDelabN List.hasDecidableLt
#testDelabN Lean.Xml.parse
#testDelabN Add.noConfusionType
#testDelabN List.filterMapM.loop
#testDelabN instMonadReaderOf
#testDelabN instInhabitedPUnit
#testDelabN Lean.Syntax.getOptionalIdent?
#testDelabN Lean.Meta.ppExpr
#testDelabN MonadLift.noConfusion
#testDelabN MonadLift.noConfusionType
#testDelabN MonadExcept.noConfusion
#testDelabN MonadFinally.noConfusion
#testDelabN Lean.Elab.InfoTree.goalsAt?.match_1
#testDelabN Std.ShareCommon.ObjectMap.find?
#testDelabN Std.ShareCommon.ObjectMap.insert
#testDelabN Std.Stack.mk.injEq
#testDelabN Lean.PrefixTree.empty
#testDelabN Std.PersistentHashMap.getCollisionNodeSize.match_1
#testDelabN Std.HashMap.size.match_1
-- TODO: for some reason this *only* works when trusting subst
set_option pp.analyze.trustSubst true in
#testDelabN and_false
-- TODO: this one prints out a structure instance with keyword field `end`
set_option pp.structureInstances false in
#testDelabN Lean.Server.FileWorker.handlePlainTermGoal
-- TODO: this one desugars to a `doLet` in an assignment
set_option pp.notation false in
#testDelabN Lean.Server.FileWorker.handlePlainGoal
-- TODO: this error occurs because we use a term's type to determine `blockImplicit` (@),
-- whereas we should actually use the expected type based on the function being applied.
-- #testDelabN HEq.subst
-- TODO: this error occurs because it cannot solve the universe constraints
-- (unclear if it is too few or too many annotations)
-- #testDelabN ExceptT.seqRight_eq
-- TODO: this error occurs because a function has explicit binders while its type has
-- implicit binders. This may be an issue in the elaborator.
-- #testDelabN Char.eqOfVeq
|
c6e26ff74a496f3ca5cc96ca909deab01fdd5032 | 43390109ab88557e6090f3245c47479c123ee500 | /src/M3P14/Arithmetic_functions/arithmetic_functions.lean | 286bca4c4c45659612256d86b6c113ff50541a6a | [
"Apache-2.0"
] | permissive | Ja1941/xena-UROP-2018 | 41f0956519f94d56b8bf6834a8d39473f4923200 | b111fb87f343cf79eca3b886f99ee15c1dd9884b | refs/heads/master | 1,662,355,955,139 | 1,590,577,325,000 | 1,590,577,325,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,332 | lean | import algebra.big_operators algebra.group_power chris_hughes_various.zmod data.fintype data.nat.gcd M3P14.order_zmodn_kmb M3P14.Arithmetic_functions.mobius
open nat
open fintype
--TODO: Add explicit formula for τ n
-- make the non-computable definition of mobius function work
-- add the mobius inversion formula
-- arithmetic functions and their properties
def is_mult (f : ℕ → ℕ) (m n : ℕ) (hp: gcd m n = 1) := f (m * n) = (f m) * (f n)
def is_strong_mult (f : ℕ → ℕ) (m n : ℕ) := f (m * n) = (f m) * (f n)
def is_add (f : ℕ → ℤ) (m n : ℕ) (hp: gcd m n = 1) := f (m + n) = (f m) + (f n)
def is_strong_add (f : ℕ → ℤ) (m n : ℕ) := f (m + n) = (f m) + (f n)
-- minor arithmetic functions that nobody cares about probably
--liouville function
def liouville_function (n : ℕ) : int := (-1)^(primes_div_dup n)
local notation `δ` := liouville_function
-- lambda was already taken up by lambda functions
theorem lio_strong_mul (n m : ℕ) : δ (m * n) = (δ m) * (δ n) := sorry
--number of divisors
def number_of_divisors_function (n : ℕ) := n.factors.erase_dup.length
local notation `τ` := number_of_divisors_function
theorem tau_is_mul (n m : ℕ) (hp: gcd n m = 1) : τ (n*m) = (τ n) * (τ m) := sorry
--theorem tau_formula (n α : ℕ)
-- ((range n.succ).filter (∣ n))
|
4d9de2b33274e77b50ad43c0714e9c4bc05c8152 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/topology/dense_embedding.lean | 8af6ad81a8bec350b5a08215ef8af3338fc227ad | [
"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 | 14,565 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot
-/
import topology.separation
/-!
# Dense embeddings
This file defines three properties of functions:
* `dense_range f` means `f` has dense image;
* `dense_inducing i` means `i` is also `inducing`;
* `dense_embedding e` means `e` is also an `embedding`.
The main theorem `continuous_extend` gives a criterion for a function
`f : X → Z` to a regular (T₃) space Z to extend along a dense embedding
`i : X → Y` to a continuous function `g : Y → Z`. Actually `i` only
has to be `dense_inducing` (not necessarily injective).
-/
noncomputable theory
open set filter
open_locale classical topological_space
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
section dense_range
variables [topological_space β] [topological_space γ] (f : α → β) (g : β → γ)
/-- `f : α → β` has dense range if its range (image) is a dense subset of β. -/
def dense_range := ∀ x, x ∈ closure (range f)
variables {f}
lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ :=
eq_univ_iff_forall.symm
lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ :=
eq_univ_iff_forall.mpr h
lemma dense_range.comp (hg : dense_range g) (hf : dense_range f) (cg : continuous g) :
dense_range (g ∘ f) :=
begin
have : g '' (closure $ range f) ⊆ closure (g '' range f),
from image_closure_subset_closure_image cg,
have : closure (g '' closure (range f)) ⊆ closure (g '' range f),
by simpa [closure_closure] using (closure_mono this),
intro c,
rw range_comp,
apply this,
rw [hf.closure_range, image_univ],
exact hg c
end
/-- If `f : α → β` has dense range and `β` contains some element, then `α` must too. -/
def dense_range.inhabited (df : dense_range f) (b : β) : inhabited α :=
⟨classical.choice $
by simpa only [univ_inter, range_nonempty_iff_nonempty] using
mem_closure_iff.1 (df b) _ is_open_univ trivial⟩
lemma dense_range.nonempty (hf : dense_range f) : nonempty α ↔ nonempty β :=
⟨nonempty.map f, λ ⟨b⟩, @nonempty_of_inhabited _ (hf.inhabited b)⟩
lemma dense_range.prod {ι : Type*} {κ : Type*} {f : ι → β} {g : κ → γ}
(hf : dense_range f) (hg : dense_range g) : dense_range (λ p : ι × κ, (f p.1, g p.2)) :=
have closure (range $ λ p : ι×κ, (f p.1, g p.2)) = set.prod (closure $ range f) (closure $ range g),
by rw [←closure_prod_eq, prod_range_range_eq],
assume ⟨b, d⟩, this.symm ▸ mem_prod.2 ⟨hf _, hg _⟩
end dense_range
/-- `i : α → β` is "dense inducing" if it has dense range and the topology on `α`
is the one induced by `i` from the topology on `β`. -/
structure dense_inducing [topological_space α] [topological_space β] (i : α → β)
extends inducing i : Prop :=
(dense : dense_range i)
namespace dense_inducing
variables [topological_space α] [topological_space β]
variables {i : α → β} (di : dense_inducing i)
lemma nhds_eq_comap (di : dense_inducing i) :
∀ a : α, 𝓝 a = comap i (𝓝 $ i a) :=
di.to_inducing.nhds_eq_comap
protected lemma continuous (di : dense_inducing i) : continuous i :=
di.to_inducing.continuous
lemma closure_range : closure (range i) = univ :=
di.dense.closure_range
lemma self_sub_closure_image_preimage_of_open {s : set β} (di : dense_inducing i) :
is_open s → s ⊆ closure (i '' (i ⁻¹' s)) :=
begin
intros s_op b b_in_s,
rw [image_preimage_eq_inter_range, mem_closure_iff],
intros U U_op b_in,
rw ←inter_assoc,
exact (dense_iff_inter_open.1 di.closure_range) _ (is_open_inter U_op s_op) ⟨b, b_in, b_in_s⟩
end
lemma closure_image_nhds_of_nhds {s : set α} {a : α} (di : dense_inducing i) :
s ∈ 𝓝 a → closure (i '' s) ∈ 𝓝 (i a) :=
begin
rw [di.nhds_eq_comap a, mem_comap_sets],
intro h,
rcases h with ⟨t, t_nhd, sub⟩,
rw mem_nhds_sets_iff at t_nhd,
rcases t_nhd with ⟨U, U_sub, ⟨U_op, e_a_in_U⟩⟩,
have := calc i ⁻¹' U ⊆ i⁻¹' t : preimage_mono U_sub
... ⊆ s : sub,
have := calc U ⊆ closure (i '' (i ⁻¹' U)) : self_sub_closure_image_preimage_of_open di U_op
... ⊆ closure (i '' s) : closure_mono (image_subset i this),
have U_nhd : U ∈ 𝓝 (i a) := mem_nhds_sets U_op e_a_in_U,
exact (𝓝 (i a)).sets_of_superset U_nhd this
end
/-- The product of two dense inducings is a dense inducing -/
protected lemma prod [topological_space γ] [topological_space δ]
{e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_inducing e₁) (de₂ : dense_inducing e₂) :
dense_inducing (λ(p : α × γ), (e₁ p.1, e₂ p.2)) :=
{ induced := (de₁.to_inducing.prod_mk de₂.to_inducing).induced,
dense := de₁.dense.prod de₂.dense }
variables [topological_space δ] {f : γ → α} {g : γ → δ} {h : δ → β}
/--
γ -f→ α
g↓ ↓e
δ -h→ β
-/
lemma tendsto_comap_nhds_nhds {d : δ} {a : α} (di : dense_inducing i) (H : tendsto h (𝓝 d) (𝓝 (i a)))
(comm : h ∘ g = i ∘ f) : tendsto f (comap g (𝓝 d)) (𝓝 a) :=
begin
have lim1 : map g (comap g (𝓝 d)) ≤ 𝓝 d := map_comap_le,
replace lim1 : map h (map g (comap g (𝓝 d))) ≤ map h (𝓝 d) := map_mono lim1,
rw [filter.map_map, comm, ← filter.map_map, map_le_iff_le_comap] at lim1,
have lim2 : comap i (map h (𝓝 d)) ≤ comap i (𝓝 (i a)) := comap_mono H,
rw ← di.nhds_eq_comap at lim2,
exact le_trans lim1 lim2,
end
protected lemma nhds_inf_ne_bot (di : dense_inducing i) {b : β} : 𝓝 b ⊓ principal (range i) ≠ ⊥ :=
begin
convert di.dense b,
simp [closure_eq_nhds]
end
lemma comap_nhds_ne_bot (di : dense_inducing i) {b : β} : comap i (𝓝 b) ≠ ⊥ :=
comap_ne_bot $ λ s hs,
let ⟨_, ⟨ha, a, rfl⟩⟩ := mem_closure_iff_nhds.1 (di.dense b) s hs in ⟨a, ha⟩
variables [topological_space γ]
/-- If `i : α → β` is a dense inducing, then any function `f : α → γ` "extends"
to a function `g = extend di f : β → γ`. If `γ` is Hausdorff and `f` has a
continuous extension, then `g` is the unique such extension. In general,
`g` might not be continuous or even extend `f`. -/
def extend (di : dense_inducing i) (f : α → γ) (b : β) : γ :=
@lim _ _ ⟨f (dense_range.inhabited di.dense b).default⟩ (map f (comap i (𝓝 b)))
lemma extend_eq [t2_space γ] {b : β} {c : γ} {f : α → γ} (hf : map f (comap i (𝓝 b)) ≤ 𝓝 c) :
di.extend f b = c :=
@lim_eq _ _ (id _) _ _ _ (by simp; exact comap_nhds_ne_bot di) hf
lemma extend_e_eq [t2_space γ] {f : α → γ} (a : α) (hf : continuous_at f a) :
di.extend f (i a) = f a :=
extend_eq _ $ di.nhds_eq_comap a ▸ hf
lemma extend_eq_of_cont [t2_space γ] {f : α → γ} (hf : continuous f) (a : α) :
di.extend f (i a) = f a :=
di.extend_e_eq a (continuous_iff_continuous_at.1 hf a)
lemma tendsto_extend [regular_space γ] {b : β} {f : α → γ} (di : dense_inducing i)
(hf : {b | ∃c, tendsto f (comap i $ 𝓝 b) (𝓝 c)} ∈ 𝓝 b) :
tendsto (di.extend f) (𝓝 b) (𝓝 (di.extend f b)) :=
let φ := {b | tendsto f (comap i $ 𝓝 b) (𝓝 $ di.extend f b)} in
have hφ : φ ∈ 𝓝 b,
from (𝓝 b).sets_of_superset hf $ assume b ⟨c, hc⟩,
show tendsto f (comap i (𝓝 b)) (𝓝 (di.extend f b)), from (di.extend_eq hc).symm ▸ hc,
assume s hs,
let ⟨s'', hs''₁, hs''₂, hs''₃⟩ := nhds_is_closed hs in
let ⟨s', hs'₁, (hs'₂ : i ⁻¹' s' ⊆ f ⁻¹' s'')⟩ := mem_of_nhds hφ hs''₁ in
let ⟨t, (ht₁ : t ⊆ φ ∩ s'), ht₂, ht₃⟩ := mem_nhds_sets_iff.mp $ inter_mem_sets hφ hs'₁ in
have h₁ : closure (f '' (i ⁻¹' s')) ⊆ s'',
by rw [closure_subset_iff_subset_of_is_closed hs''₃, image_subset_iff]; exact hs'₂,
have h₂ : t ⊆ di.extend f ⁻¹' closure (f '' (i ⁻¹' t)), from
assume b' hb',
have 𝓝 b' ≤ principal t, by simp; exact mem_nhds_sets ht₂ hb',
have map f (comap i (𝓝 b')) ≤ 𝓝 (di.extend f b') ⊓ principal (f '' (i ⁻¹' t)),
from calc _ ≤ map f (comap i (𝓝 b' ⊓ principal t)) : map_mono $ comap_mono $ le_inf (le_refl _) this
... ≤ map f (comap i (𝓝 b')) ⊓ map f (comap i (principal t)) :
le_inf (map_mono $ comap_mono $ inf_le_left) (map_mono $ comap_mono $ inf_le_right)
... ≤ map f (comap i (𝓝 b')) ⊓ principal (f '' (i ⁻¹' t)) : by simp [le_refl]
... ≤ _ : inf_le_inf ((ht₁ hb').left) (le_refl _),
show di.extend f b' ∈ closure (f '' (i ⁻¹' t)),
begin
rw [closure_eq_nhds],
apply ne_bot_of_le_ne_bot _ this,
simp,
exact di.comap_nhds_ne_bot
end,
(𝓝 b).sets_of_superset
(show t ∈ 𝓝 b, from mem_nhds_sets ht₂ ht₃)
(calc t ⊆ di.extend f ⁻¹' closure (f '' (i ⁻¹' t)) : h₂
... ⊆ di.extend f ⁻¹' closure (f '' (i ⁻¹' s')) :
preimage_mono $ closure_mono $ image_subset f $ preimage_mono $ subset.trans ht₁ $ inter_subset_right _ _
... ⊆ di.extend f ⁻¹' s'' : preimage_mono h₁
... ⊆ di.extend f ⁻¹' s : preimage_mono hs''₂)
lemma continuous_extend [regular_space γ] {f : α → γ} (di : dense_inducing i)
(hf : ∀b, ∃c, tendsto f (comap i (𝓝 b)) (𝓝 c)) : continuous (di.extend f) :=
continuous_iff_continuous_at.mpr $ assume b, di.tendsto_extend $ univ_mem_sets' hf
lemma mk'
(i : α → β)
(c : continuous i)
(dense : ∀x, x ∈ closure (range i))
(H : ∀ (a:α) s ∈ 𝓝 a,
∃t ∈ 𝓝 (i a), ∀ b, i b ∈ t → b ∈ s) :
dense_inducing i :=
{ induced := (induced_iff_nhds_eq i).2 $
λ a, le_antisymm (tendsto_iff_comap.1 $ c.tendsto _) (by simpa [le_def] using H a),
dense := dense }
end dense_inducing
/-- A dense embedding is an embedding with dense image. -/
structure dense_embedding [topological_space α] [topological_space β] (e : α → β)
extends dense_inducing e : Prop :=
(inj : function.injective e)
theorem dense_embedding.mk'
[topological_space α] [topological_space β] (e : α → β)
(c : continuous e)
(dense : ∀x, x ∈ closure (range e))
(inj : function.injective e)
(H : ∀ (a:α) s ∈ 𝓝 a,
∃t ∈ 𝓝 (e a), ∀ b, e b ∈ t → b ∈ s) :
dense_embedding e :=
{ inj := inj,
..dense_inducing.mk' e c dense H}
namespace dense_embedding
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
variables {e : α → β} (de : dense_embedding e)
lemma inj_iff {x y} : e x = e y ↔ x = y := de.inj.eq_iff
lemma to_embedding : embedding e :=
{ induced := de.induced,
inj := de.inj }
/-- The product of two dense embeddings is a dense embedding -/
protected lemma prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_embedding e₁) (de₂ : dense_embedding e₂) :
dense_embedding (λ(p : α × γ), (e₁ p.1, e₂ p.2)) :=
{ inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩,
by simp; exact assume h₁ h₂, ⟨de₁.inj h₁, de₂.inj h₂⟩,
..dense_inducing.prod de₁.to_dense_inducing de₂.to_dense_inducing }
/-- The dense embedding of a subtype inside its closure. -/
def subtype_emb {α : Type*} (p : α → Prop) (e : α → β) (x : {x // p x}) :
{x // x ∈ closure (e '' {x | p x})} :=
⟨e x.1, subset_closure $ mem_image_of_mem e x.2⟩
protected lemma subtype (p : α → Prop) : dense_embedding (subtype_emb p e) :=
{ dense_embedding .
dense := assume ⟨x, hx⟩, closure_subtype.mpr $
have (λ (x : {x // p x}), e (x.val)) = e ∘ subtype.val, from rfl,
begin
rw ← image_univ,
simp [(image_comp _ _ _).symm, (∘), subtype_emb, -image_univ],
rw [this, image_comp, subtype.val_image],
simp,
assumption
end,
inj := assume ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq $ de.inj $ @@congr_arg subtype.val h,
induced := (induced_iff_nhds_eq _).2 (assume ⟨x, hx⟩,
by simp [subtype_emb, nhds_subtype_eq_comap, de.to_inducing.nhds_eq_comap, comap_comap_comp, (∘)]) }
end dense_embedding
lemma is_closed_property [topological_space β] {e : α → β} {p : β → Prop}
(he : dense_range e) (hp : is_closed {x | p x}) (h : ∀a, p (e a)) :
∀b, p b :=
have univ ⊆ {b | p b},
from calc univ = closure (range e) : he.closure_range.symm
... ⊆ closure {b | p b} : closure_mono $ range_subset_iff.mpr h
... = _ : closure_eq_of_is_closed hp,
assume b, this trivial
lemma is_closed_property2 [topological_space β] {e : α → β} {p : β → β → Prop}
(he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) :
∀b₁ b₂, p b₁ b₂ :=
have ∀q:β×β, p q.1 q.2,
from is_closed_property (he.prod he) hp $ λ _, h _ _,
assume b₁ b₂, this ⟨b₁, b₂⟩
lemma is_closed_property3 [topological_space β] {e : α → β} {p : β → β → β → Prop}
(he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) :
∀b₁ b₂ b₃, p b₁ b₂ b₃ :=
have ∀q:β×β×β, p q.1 q.2.1 q.2.2,
from is_closed_property (he.prod $ he.prod he) hp $ λ _, h _ _ _,
assume b₁ b₂ b₃, this ⟨b₁, b₂, b₃⟩
@[elab_as_eliminator]
lemma dense_range.induction_on [topological_space β] {e : α → β} (he : dense_range e) {p : β → Prop}
(b₀ : β) (hp : is_closed {b | p b}) (ih : ∀a:α, p $ e a) : p b₀ :=
is_closed_property he hp ih b₀
@[elab_as_eliminator]
lemma dense_range.induction_on₂ [topological_space β] {e : α → β} {p : β → β → Prop}
(he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂))
(b₁ b₂ : β) : p b₁ b₂ := is_closed_property2 he hp h _ _
@[elab_as_eliminator]
lemma dense_range.induction_on₃ [topological_space β] {e : α → β} {p : β → β → β → Prop}
(he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃))
(b₁ b₂ b₃ : β) : p b₁ b₂ b₃ := is_closed_property3 he hp h _ _ _
section
variables [topological_space β] [topological_space γ] [t2_space γ]
variables {f : α → β}
/-- Two continuous functions to a t2-space that agree on the dense range of a function are equal. -/
lemma dense_range.equalizer (hfd : dense_range f)
{g h : β → γ} (hg : continuous g) (hh : continuous h) (H : g ∘ f = h ∘ f) :
g = h :=
funext $ λ y, hfd.induction_on y (is_closed_eq hg hh) $ congr_fun H
end
|
52f55230da0811e3597076bbd8b2896040b1e3c6 | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/tactic/lint/simp.lean | 243f521b889c7e64b70d0988a12f276bfb2a94b5 | [
"Apache-2.0"
] | permissive | hamdysalah1/mathlib | b915f86b2503feeae268de369f1b16932321f097 | 95454452f6b3569bf967d35aab8d852b1ddf8017 | refs/heads/master | 1,677,154,116,545 | 1,611,797,994,000 | 1,611,797,994,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,315 | lean | /-
Copyright (c) 2020 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import tactic.lint.basic
/-!
# Linter for simplification lemmas
This files defines several linters that prevent common mistakes when declaring simp lemmas:
* `simp_nf` checks that the left-hand side of a simp lemma is not simplified by a different lemma.
* `simp_var_head` checks that the head symbol of the left-hand side is not a variable.
* `simp_comm` checks that commutativity lemmas are not marked as simplification lemmas.
-/
open tactic expr
/-- `simp_lhs_rhs ty` returns the left-hand and right-hand side of a simp lemma with type `ty`. -/
private meta def simp_lhs_rhs : expr → tactic (expr × expr) | ty := do
ty ← head_beta ty,
-- We only detect a fixed set of simp relations here.
-- This is somewhat justified since for a custom simp relation R,
-- the simp lemma `R a b` is implicitly converted to `R a b ↔ true` as well.
match ty with
| `(¬ %%lhs) := pure (lhs, `(false))
| `(%%lhs = %%rhs) := pure (lhs, rhs)
| `(%%lhs ↔ %%rhs) := pure (lhs, rhs)
| (expr.pi n bi a b) := do
l ← mk_local' n bi a,
simp_lhs_rhs (b.instantiate_var l)
| ty := pure (ty, `(true))
end
/-- `simp_lhs ty` returns the left-hand side of a simp lemma with type `ty`. -/
private meta def simp_lhs (ty : expr): tactic expr :=
prod.fst <$> simp_lhs_rhs ty
/--
`simp_is_conditional_core ty` returns `none` if `ty` is a conditional simp
lemma, and `some lhs` otherwise.
-/
private meta def simp_is_conditional_core : expr → tactic (option expr) | ty := do
ty ← head_beta ty,
match ty with
| `(¬ %%lhs) := pure lhs
| `(%%lhs = _) := pure lhs
| `(%%lhs ↔ _) := pure lhs
| (expr.pi n bi a b) := do
l ← mk_local' n bi a,
some lhs ← simp_is_conditional_core (b.instantiate_var l) | pure none,
if bi ≠ binder_info.inst_implicit ∧
¬ (lhs.abstract_local l.local_uniq_name).has_var then
pure none
else
pure lhs
| ty := pure ty
end
/--
`simp_is_conditional ty` returns true iff the simp lemma with type `ty` is conditional.
-/
private meta def simp_is_conditional (ty : expr) : tactic bool :=
option.is_none <$> simp_is_conditional_core ty
private meta def heuristic_simp_lemma_extraction (prf : expr) : tactic (list name) :=
prf.list_constant.to_list.mfilter is_simp_lemma
/-- Checks whether two expressions are equal for the simplifier. That is,
they are reducibly-definitional equal, and they have the same head symbol. -/
meta def is_simp_eq (a b : expr) : tactic bool :=
if a.get_app_fn.const_name ≠ b.get_app_fn.const_name then pure ff else
succeeds $ is_def_eq a b transparency.reducible
/-- Reports declarations that are simp lemmas whose left-hand side is not in simp-normal form. -/
meta def simp_nf_linter (timeout := 200000) (d : declaration) : tactic (option string) := do
tt ← is_simp_lemma d.to_name | pure none,
-- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set.
-- In this case, ignore the declaration if it is not a valid simp lemma by itself.
tt ← is_valid_simp_lemma_cnst d.to_name | pure none,
[] ← get_eqn_lemmas_for ff d.to_name | pure none,
try_for timeout $
retrieve $ do
g ← mk_meta_var d.type,
set_goals [g],
unfreezing intros,
(lhs, rhs) ← target >>= simp_lhs_rhs,
sls ← simp_lemmas.mk_default,
let sls' := sls.erase [d.to_name],
(lhs', prf1, ns1) ← decorate_error "simplify fails on left-hand side:" $
simplify sls [] lhs {fail_if_unchanged := ff},
prf1_lems ← heuristic_simp_lemma_extraction prf1,
if d.to_name ∈ prf1_lems then pure none else do
is_cond ← simp_is_conditional d.type,
(rhs', prf2, ns2) ← decorate_error "simplify fails on right-hand side:" $
simplify sls [] rhs {fail_if_unchanged := ff},
lhs'_eq_rhs' ← is_simp_eq lhs' rhs',
lhs_in_nf ← is_simp_eq lhs' lhs,
if lhs'_eq_rhs' then do
used_lemmas ← heuristic_simp_lemma_extraction (prf1 prf2),
pure $ pure $ "simp can prove this:\n"
++ " by simp only " ++ to_string used_lemmas ++ "\n"
++ "One of the lemmas above could be a duplicate.\n"
++ "If that's not the case try reordering lemmas or adding @[priority].\n"
else if ¬ lhs_in_nf then do
lhs ← pp lhs,
lhs' ← pp lhs',
pure $ format.to_string $
to_fmt "Left-hand side simplifies from"
++ lhs.group.indent 2 ++ format.line
++ "to" ++ lhs'.group.indent 2 ++ format.line
++ "using " ++ (to_fmt prf1_lems).group.indent 2 ++ format.line
++ "Try to change the left-hand side to the simplified term!\n"
else if ¬ is_cond ∧ lhs = lhs' then do
pure "Left-hand side does not simplify.\nYou need to debug this yourself using `set_option trace.simplify.rewrite true`"
else
pure none
/--
This note gives you some tips to debug any errors that the simp-normal form linter raises
The reason that a lemma was considered faulty is because its left-hand side is not in simp-normal form.
These lemmas are hence never used by the simplifier.
This linter gives you a list of other simp lemmas, look at them!
Here are some tips depending on the error raised by the linter:
1. 'the left-hand side reduces to XYZ':
you should probably use XYZ as the left-hand side.
2. 'simp can prove this':
This typically means that lemma is a duplicate, or is shadowed by another lemma:
2a. Always put more general lemmas after specific ones:
@[simp] lemma zero_add_zero : 0 + 0 = 0 := rfl
@[simp] lemma add_zero : x + 0 = x := rfl
And not the other way around! The simplifier always picks the last matching lemma.
2b. You can also use @[priority] instead of moving simp-lemmas around in the file.
Tip: the default priority is 1000.
Use `@[priority 1100]` instead of moving a lemma down,
and `@[priority 900]` instead of moving a lemma up.
2c. Conditional simp lemmas are tried last, if they are shadowed
just remove the simp attribute.
2d. If two lemmas are duplicates, the linter will complain about the first one.
Try to fix the second one instead!
(You can find it among the other simp lemmas the linter prints out!)
3. 'try_for tactic failed, timeout':
This typically means that there is a loop of simp lemmas.
Try to apply squeeze_simp to the right-hand side (removing this lemma from the simp set) to see
what lemmas might be causing the loop.
Another trick is to `set_option trace.simplify.rewrite true` and
then apply `try_for 10000 { simp }` to the right-hand side. You will
see a periodic sequence of lemma applications in the trace message.
-/
library_note "simp-normal form"
/-- A linter for simp lemmas whose lhs is not in simp-normal form, and which hence never fire. -/
@[linter] meta def linter.simp_nf : linter :=
{ test := simp_nf_linter,
auto_decls := tt,
no_errors_found := "All left-hand sides of simp lemmas are in simp-normal form",
errors_found := "SOME SIMP LEMMAS ARE NOT IN SIMP-NORMAL FORM.
see note [simp-normal form] for tips how to debug this.
https://leanprover-community.github.io/mathlib_docs/notes.html#simp-normal%20form
" }
private meta def simp_var_head (d : declaration) : tactic (option string) := do
tt ← is_simp_lemma d.to_name | pure none,
-- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set.
-- In this case, ignore the declaration if it is not a valid simp lemma by itself.
tt ← is_valid_simp_lemma_cnst d.to_name | pure none,
lhs ← simp_lhs d.type,
head_sym@(expr.local_const _ _ _ _) ← pure lhs.get_app_fn | pure none,
head_sym ← pp head_sym,
pure $ format.to_string $ "Left-hand side has variable as head symbol: " ++ head_sym
/--
A linter for simp lemmas whose lhs has a variable as head symbol,
and which hence never fire.
-/
@[linter] meta def linter.simp_var_head : linter :=
{ test := simp_var_head,
auto_decls := tt,
no_errors_found :=
"No left-hand sides of a simp lemma has a variable as head symbol",
errors_found := "LEFT-HAND SIDE HAS VARIABLE AS HEAD SYMBOL.\n" ++
"Some simp lemmas have a variable as head symbol of the left-hand side" }
private meta def simp_comm (d : declaration) : tactic (option string) := do
tt ← is_simp_lemma d.to_name | pure none,
-- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set.
-- In this case, ignore the declaration if it is not a valid simp lemma by itself.
tt ← is_valid_simp_lemma_cnst d.to_name | pure none,
(lhs, rhs) ← simp_lhs_rhs d.type,
if lhs.get_app_fn.const_name ≠ rhs.get_app_fn.const_name then pure none else do
(lhs', rhs') ← (prod.snd <$> open_pis_metas d.type) >>= simp_lhs_rhs,
tt ← succeeds $ unify rhs lhs' transparency.reducible | pure none,
tt ← succeeds $ is_def_eq rhs lhs' transparency.reducible | pure none,
-- ensure that the second application makes progress:
ff ← succeeds $ unify lhs' rhs' transparency.reducible | pure none,
pure $ "should not be marked simp"
/-- A linter for commutativity lemmas that are marked simp. -/
@[linter] meta def linter.simp_comm : linter :=
{ test := simp_comm,
auto_decls := tt,
no_errors_found := "No commutativity lemma is marked simp",
errors_found := "COMMUTATIVITY LEMMA IS SIMP.\n" ++
"Some commutativity lemmas are simp lemmas" }
|
8dbe21e2772fb1c057a1df45ada6834d091de3c5 | 3b15c7b0b62d8ada1399c112ad88a529e6bfa115 | /stage0/src/Lean/Elab/Do.lean | c829509a011e987cbf33d5fc7bb689470cbfdf99 | [
"Apache-2.0"
] | permissive | stephenbrady/lean4 | 74bf5cae8a433e9c815708ce96c9e54a5caf2115 | b1bd3fc304d0f7bc6810ec78bfa4c51476d263f9 | refs/heads/master | 1,692,621,473,161 | 1,634,308,743,000 | 1,634,310,749,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 70,694 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Term
import Lean.Elab.BindersUtil
import Lean.Elab.PatternVar
import Lean.Elab.Quotation.Util
import Lean.Parser.Do
-- HACK: avoid code explosion until heuristics are improved
set_option compiler.reuse false
namespace Lean.Elab.Term
open Lean.Parser.Term
open Meta
private def getDoSeqElems (doSeq : Syntax) : List Syntax :=
if doSeq.getKind == ``Lean.Parser.Term.doSeqBracketed then
doSeq[1].getArgs.toList.map fun arg => arg[0]
else if doSeq.getKind == ``Lean.Parser.Term.doSeqIndent then
doSeq[0].getArgs.toList.map fun arg => arg[0]
else
[]
private def getDoSeq (doStx : Syntax) : Syntax :=
doStx[1]
@[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ =>
throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression"
/-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/
private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool :=
k == ``Lean.Parser.Term.do ||
k == ``Lean.Parser.Term.doSeqIndent ||
k == ``Lean.Parser.Term.doSeqBracketed ||
k == ``Lean.Parser.Term.termReturn ||
k == ``Lean.Parser.Term.termUnless ||
k == ``Lean.Parser.Term.termTry ||
k == ``Lean.Parser.Term.termFor
/-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/
private def letDeclArgHasBinders (letDeclArg : Syntax) : Bool :=
let k := letDeclArg.getKind
if k == ``Lean.Parser.Term.letPatDecl then
false
else if k == ``Lean.Parser.Term.letEqnsDecl then
true
else if k == ``Lean.Parser.Term.letIdDecl then
-- letIdLhs := ident >> checkWsBefore "expected space before binders" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType
let binders := letDeclArg[1]
binders.getNumArgs > 0
else
false
/-- Return `true` if the given `letDecl` contains binders. -/
private def letDeclHasBinders (letDecl : Syntax) : Bool :=
letDeclArgHasBinders letDecl[0]
/-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/
private def liftMethodForbiddenBinder (stx : Syntax) : Bool :=
let k := stx.getKind
if k == ``Lean.Parser.Term.fun || k == ``Lean.Parser.Term.matchAlts ||
k == ``Lean.Parser.Term.doLetRec || k == ``Lean.Parser.Term.letrec then
-- It is never ok to lift over this kind of binder
true
-- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not
else if k == ``Lean.Parser.Term.let then
letDeclHasBinders stx[1]
else if k == ``Lean.Parser.Term.doLet then
letDeclHasBinders stx[2]
else if k == ``Lean.Parser.Term.doLetArrow then
letDeclArgHasBinders stx[2]
else
false
private partial def hasLiftMethod : Syntax → Bool
| Syntax.node k args =>
if liftMethodDelimiter k then false
-- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a
-- bit slower
else if k == ``Lean.Parser.Term.liftMethod then true
else args.any hasLiftMethod
| _ => false
structure ExtractMonadResult where
m : Expr
α : Expr
hasBindInst : Expr
expectedType : Expr
isPure : Bool -- `true` when it is a pure `do` block. That is, Lean implicitly inserted the `Id` Monad.
private def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do
let u ← getDecLevel type
let id := Lean.mkConst ``Id [u]
let idBindVal := Lean.mkConst ``Id.hasBind [u]
pure { m := id, hasBindInst := idBindVal, α := type, expectedType := mkApp id type, isPure := true }
private partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do
match expectedType? with
| none => throwError "invalid 'do' notation, expected type is not available"
| some expectedType =>
let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do
match type with
| Expr.app m α _ =>
try
let bindInstType ← mkAppM ``Bind #[m]
let bindInstVal ← Meta.synthInstance bindInstType
return some { m := m, hasBindInst := bindInstVal, α := α, expectedType := expectedType, isPure := false }
catch _ =>
return none
| _ =>
return none
let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do
match (← extractStep? type) with
| some r => return r
| none =>
let typeNew ← whnfCore type
if typeNew != type then
extract? typeNew
else
if typeNew.getAppFn.isMVar then throwError "invalid 'do' notation, expected type is not available"
match (← unfoldDefinition? typeNew) with
| some typeNew => extract? typeNew
| none => return none
match (← extract? expectedType) with
| some r => return r
| none => mkIdBindFor expectedType
namespace Do
/- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/
structure Alt (σ : Type) where
ref : Syntax
vars : Array Name
patterns : Syntax
rhs : σ
deriving Inhabited
/-
Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`).
We convert `Code` into a `Syntax` term representing the:
- `do`-block, or
- the visitor argument for the `forIn` combinator.
We say the following constructors are terminals:
- `break`: for interrupting a `for x in s`
- `continue`: for interrupting the current iteration of a `for x in s`
- `return e`: for returning `e` as the result for the whole `do` computation block
- `action a`: for executing action `a` as a terminal
- `ite`: if-then-else
- `match`: pattern matching
- `jmp` a goto to a join-point
We say the terminals `break`, `continue`, `action`, and `return` are "exit points"
Note that, `return e` is not equivalent to `action (pure e)`. Here is an example:
```
def f (x : Nat) : IO Unit := do
if x == 0 then
return ()
IO.println "hello"
```
Executing `#eval f 0` will not print "hello". Now, consider
```
def g (x : Nat) : IO Unit := do
if x == 0 then
pure ()
IO.println "hello"
```
The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`.
- `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`).
The field `stx` is the actual `doElem`,
`vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block.
`vars` is an array since we have declarations such as `let (a, b) := s`.
- `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`).
- `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow.
- `seq a k` executes action `a`, ignores its result, and then executes `k`.
We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`.
A code block `C` is well-formed if
- For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and
`ps.size == as.size` -/
inductive Code where
| decl (xs : Array Name) (doElem : Syntax) (k : Code)
| reassign (xs : Array Name) (doElem : Syntax) (k : Code)
/- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/
| joinpoint (name : Name) (params : Array (Name × Bool)) (body : Code) (k : Code)
| seq (action : Syntax) (k : Code)
| action (action : Syntax)
| «break» (ref : Syntax)
| «continue» (ref : Syntax)
| «return» (ref : Syntax) (val : Syntax)
/- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/
| ite (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code)
| «match» (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code))
| jmp (ref : Syntax) (jpName : Name) (args : Array Syntax)
deriving Inhabited
/- A code block, and the collection of variables updated by it. -/
structure CodeBlock where
code : Code
uvars : NameSet := {} -- set of variables updated by `code`
private def nameSetToArray (s : NameSet) : Array Name :=
s.fold (fun (xs : Array Name) x => xs.push x) #[]
private def varsToMessageData (vars : Array Name) : MessageData :=
MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) " "
partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData :=
let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName
let rec loop : Code → MessageData
| Code.decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}"
| Code.reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}"
| Code.joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}"
| Code.seq e k => m!"{e}\n{loop k}"
| Code.action e => e
| Code.ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}"
| Code.jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}"
| Code.«break» _ => m!"break {us}"
| Code.«continue» _ => m!"continue {us}"
| Code.«return» _ v => m!"return {v} {us}"
| Code.«match» _ _ ds t alts =>
m!"match {ds} with"
++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}"
loop codeBlock.code
/- Return true if the give code contains an exit point that satisfies `p` -/
partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool :=
let rec loop : Code → Bool
| Code.decl _ _ k => loop k
| Code.reassign _ _ k => loop k
| Code.joinpoint _ _ b k => loop b || loop k
| Code.seq _ k => loop k
| Code.ite _ _ _ _ t e => loop t || loop e
| Code.«match» _ _ _ _ alts => alts.any (loop ·.rhs)
| Code.jmp _ _ _ => false
| c => p c
loop c
def hasExitPoint (c : Code) : Bool :=
hasExitPointPred c fun c => true
def hasReturn (c : Code) : Bool :=
hasExitPointPred c fun
| Code.«return» _ _ => true
| _ => false
def hasTerminalAction (c : Code) : Bool :=
hasExitPointPred c fun
| Code.«action» _ => true
| _ => false
def hasBreakContinue (c : Code) : Bool :=
hasExitPointPred c fun
| Code.«break» _ => true
| Code.«continue» _ => true
| _ => false
def hasBreakContinueReturn (c : Code) : Bool :=
hasExitPointPred c fun
| Code.«break» _ => true
| Code.«continue» _ => true
| Code.«return» _ _ => true
| _ => false
def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax → m Code) : m Code := withRef e <| withFreshMacroScope do
let y ← `(y)
let yName := y.getId
let doElem ← `(doElem| let y ← $e:term)
-- Add elaboration hint for producing sane error message
let y ← `(ensure_expected_type% "type mismatch, result value" $y)
let k ← mkCont y
pure $ Code.decl #[yName] doElem k
/- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/
partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code :=
let rec loop : Code → MacroM Code
| Code.decl xs stx k => do Code.decl xs stx (← loop k)
| Code.reassign xs stx k => do Code.reassign xs stx (← loop k)
| Code.joinpoint n ps b k => do Code.joinpoint n ps (← loop b) (← loop k)
| Code.seq e k => do Code.seq e (← loop k)
| Code.ite ref x? h c t e => do Code.ite ref x? h c (← loop t) (← loop e)
| Code.«match» ref g ds t alts => do Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) })
| Code.action e => mkAuxDeclFor e fun y =>
let ref := e
-- We jump to `jp` with xs **and** y
let jmpArgs := xs.map $ mkIdentFrom ref
let jmpArgs := jmpArgs.push y
pure $ Code.jmp ref jp jmpArgs
| c => pure c
loop code
structure JPDecl where
name : Name
params : Array (Name × Bool)
body : Code
def attachJP (jpDecl : JPDecl) (k : Code) : Code :=
Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k
def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code :=
jpDecls.foldr attachJP k
def mkFreshJP (ps : Array (Name × Bool)) (body : Code) : TermElabM JPDecl := do
let ps ←
if ps.isEmpty then
let y ← mkFreshUserName `y
pure #[(y, false)]
else
pure ps
-- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by
-- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp`
-- We will remove this hack when we re-implement the compiler frontend in Lean.
let name ← mkFreshUserName `_do_jp
pure { name := name, params := ps, body := body }
def mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl :=
mkFreshJP (xs.map fun x => (x, true)) body
def addFreshJP (ps : Array (Name × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do
let jp ← mkFreshJP ps body
modify fun (jps : Array JPDecl) => jps.push jp
pure jp.name
def insertVars (rs : NameSet) (xs : Array Name) : NameSet :=
xs.foldl (·.insert ·) rs
def eraseVars (rs : NameSet) (xs : Array Name) : NameSet :=
xs.foldl (·.erase ·) rs
def eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet :=
match x? with
| none => rs
| some x => rs.insert x
/- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/
def mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do
let xs := nameSetToArray rs
let jp ← addFreshJP (xs.map fun x => (x, true)) c
if xs.isEmpty then
let unit ← ``(Unit.unit)
return Code.jmp ref jp #[unit]
else
return Code.jmp ref jp (xs.map $ mkIdentFrom ref)
/- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value.
The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh`
is a fresh variable created by this method. -/
def mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do
let xs := nameSetToArray rs
let args := xs.map $ mkIdentFrom ref
let args := args.push val
let yFresh ← mkFreshUserName `y
let ps := xs.map fun x => (x, true)
let ps := ps.push (yFresh, false)
let jpBody ← liftMacroM $ mkJPBody (mkIdentFrom ref yFresh)
let jp ← addFreshJP ps jpBody
pure $ Code.jmp ref jp args
/- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/
partial def pullExitPointsAux : NameSet → Code → StateRefT (Array JPDecl) TermElabM Code
| rs, Code.decl xs stx k => do Code.decl xs stx (← pullExitPointsAux (eraseVars rs xs) k)
| rs, Code.reassign xs stx k => do Code.reassign xs stx (← pullExitPointsAux (insertVars rs xs) k)
| rs, Code.joinpoint j ps b k => do Code.joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k)
| rs, Code.seq e k => do Code.seq e (← pullExitPointsAux rs k)
| rs, Code.ite ref x? o c t e => do Code.ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e)
| rs, Code.«match» ref g ds t alts => do
Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) })
| rs, c@(Code.jmp _ _ _) => pure c
| rs, Code.«break» ref => mkSimpleJmp ref rs (Code.«break» ref)
| rs, Code.«continue» ref => mkSimpleJmp ref rs (Code.«continue» ref)
| rs, Code.«return» ref val => mkJmp ref rs val (fun y => pure $ Code.«return» ref y)
| rs, Code.action e =>
-- We use `mkAuxDeclFor` because `e` is not pure.
mkAuxDeclFor e fun y =>
let ref := e
mkJmp ref rs y (fun yFresh => do pure $ Code.action (← ``(Pure.pure $yFresh)))
/-
Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock.
When a new variable is not already in the collection, but is shadowed by some declaration in `c`,
we create auxiliary join points to make sure we preserve the semantics of the code block.
Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it
with the reassignment `x := x + 1`. We first use `pullExitPoints` to create
```
let jp (x!1) := return x!1;
print x;
let x := 10;
jmp jp x
```
and then we add the reassignment
```
x := x + 1
let jp (x!1) := return x!1;
print x;
let x := 10;
jmp jp x
```
Note that we created a fresh variable `x!1` to avoid accidental name capture.
As another example, consider
```
print x;
let x := 10
y := y + 1;
return x;
```
We transform it into
```
let jp (y x!1) := return x!1;
print x;
let x := 10
y := y + 1;
jmp jp y x
```
and then we add the reassignment as in the previous example.
We need to include `y` in the jump, because each exit point is implicitly returning the set of
update variables.
We implement the method as follows. Let `us` be `c.uvars`, then
1- for each `return _ y` in `c`, we create a join point
`let j (us y!1) := return y!1`
and replace the `return _ y` with `jmp us y`
2- for each `break`, we create a join point
`let j (us) := break`
and replace the `break` with `jmp us`.
3- Same as 2 for `continue`.
-/
def pullExitPoints (c : Code) : TermElabM Code := do
if hasExitPoint c then
let (c, jpDecls) ← (pullExitPointsAux {} c).run #[]
pure $ attachJPs jpDecls c
else
pure c
partial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code :=
let rec update : Code → TermElabM Code
| Code.joinpoint j ps b k => do Code.joinpoint j ps (← update b) (← update k)
| Code.seq e k => do Code.seq e (← update k)
| c@(Code.«match» ref g ds t alts) => do
if alts.any fun alt => alt.vars.any fun x => ws.contains x then
-- If a pattern variable is shadowing a variable in ws, we `pullExitPoints`
pullExitPoints c
else
Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) })
| Code.ite ref none o c t e => do Code.ite ref none o c (← update t) (← update e)
| c@(Code.ite ref (some h) o cond t e) => do
if ws.contains h then
-- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints`
pullExitPoints c
else
Code.ite ref (some h) o cond (← update t) (← update e)
| Code.reassign xs stx k => do Code.reassign xs stx (← update k)
| c@(Code.decl xs stx k) => do
if xs.any fun x => ws.contains x then
-- One the declared variables is shadowing a variable in `ws`
pullExitPoints c
else
Code.decl xs stx (← update k)
| c => pure c
update c
/-
Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`.
We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`.
See discussion at `pullExitPoints`.
-/
partial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do
if ws.any fun x => !c.uvars.contains x then
-- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed)
pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws }
else
pure { c with uvars := ws }
private def union (s₁ s₂ : NameSet) : NameSet :=
s₁.fold (·.insert ·) s₂
/-
Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables.
Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`.
We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws`
-/
def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do
let ws := union c₁.uvars c₂.uvars
let c₁ ← extendUpdatedVars c₁ ws
let c₂ ← extendUpdatedVars c₂ ws
pure (c₁, c₂)
/-
Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`.
We remove `x` from the collection of updated varibles.
Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables
declared by it. It is an array because we have let-declarations that declare multiple variables.
Example: `let (x, y) := t`
-/
def mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := {
code := Code.decl xs stx c.code,
uvars := eraseVars c.uvars xs
}
/-
Extending code blocks with reassignments: `x : t := v` and `x : t ← v`.
Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables
declared by it. It is an array because we have let-declarations that declare multiple variables.
Example: `(x, y) ← t`
-/
def mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do
let us := c.uvars
let ws := insertVars us xs
-- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`.
-- See discussion at `pullExitPoints`
let code ← if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code
pure { code := Code.reassign xs stx code, uvars := ws }
def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock :=
{ c with code := Code.seq action c.code }
def mkTerminalAction (action : Syntax) : CodeBlock :=
{ code := Code.action action }
def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock :=
{ code := Code.«return» ref val }
def mkBreak (ref : Syntax) : CodeBlock :=
{ code := Code.«break» ref }
def mkContinue (ref : Syntax) : CodeBlock :=
{ code := Code.«continue» ref }
def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do
let x? := if optIdent.isNone then none else some optIdent[0].getId
let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch
pure {
code := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code,
uvars := thenBranch.uvars,
}
private def mkUnit : MacroM Syntax :=
``((⟨⟩ : PUnit))
private def mkPureUnit : MacroM Syntax :=
``(pure PUnit.unit)
def mkPureUnitAction : MacroM CodeBlock := do
mkTerminalAction (← mkPureUnit)
def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do
let thenBranch ← mkPureUnitAction
pure { c with code := Code.ite (← getRef) none mkNullNode cond thenBranch.code c.code }
def mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do
-- nary version of homogenize
let ws := alts.foldl (union · ·.rhs.uvars) {}
let alts ← alts.mapM fun alt => do
let rhs ← extendUpdatedVars alt.rhs ws
pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code }
pure { code := Code.«match» ref genParam discrs optType alts, uvars := ws }
/- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`.
This method assumes `terminal` is a terminal -/
def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do
unless hasTerminalAction terminal.code do
throwErrorAt kRef "'do' element is unreachable"
let (terminal, k) ← homogenize terminal k
let xs := nameSetToArray k.uvars
let y ← match y? with | some y => pure y | none => mkFreshUserName `y
let ps := xs.map fun x => (x, true)
let ps := ps.push (y, false)
let jpDecl ← mkFreshJP ps k.code
let jp := jpDecl.name
let terminal ← liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs
pure { code := attachJP jpDecl terminal, uvars := k.uvars }
def getLetIdDeclVar (letIdDecl : Syntax) : Name :=
letIdDecl[0].getId
-- support both regular and syntax match
def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Name) :=
getPatternVarNames <$> getPatternVars pattern <|>
Array.map Syntax.getId <$> Quotation.getPatternVars pattern
def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Name) :=
getPatternVarNames <$> getPatternsVars patterns <|>
Array.map Syntax.getId <$> Quotation.getPatternsVars patterns
def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do
let pattern := letPatDecl[0]
getPatternVarsEx pattern
def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name :=
letEqnsDecl[0].getId
def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do
let arg := letDecl[0]
if arg.getKind == ``Lean.Parser.Term.letIdDecl then
pure #[getLetIdDeclVar arg]
else if arg.getKind == ``Lean.Parser.Term.letPatDecl then
getLetPatDeclVars arg
else if arg.getKind == ``Lean.Parser.Term.letEqnsDecl then
pure #[getLetEqnsDeclVar arg]
else
throwError "unexpected kind of let declaration"
def getDoLetVars (doLet : Syntax) : TermElabM (Array Name) :=
-- leading_parser "let " >> optional "mut " >> letDecl
getLetDeclVars doLet[2]
def getDoHaveVar (doHave : Syntax) : Name :=
/-
`leading_parser "have " >> Term.haveDecl`
where
```
haveDecl := leading_parser optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic)
optIdent := optional (try (ident >> " : "))
```
-/
let optIdent := doHave[1][0]
if optIdent.isNone then
`this
else
optIdent[0].getId
def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do
-- letRecDecls is an array of `(group (optional attributes >> letDecl))`
let letRecDecls := doLetRec[1][0].getSepArgs
let letDecls := letRecDecls.map fun p => p[2]
let mut allVars := #[]
for letDecl in letDecls do
let vars ← getLetDeclVars letDecl
allVars := allVars ++ vars
pure allVars
-- ident >> optType >> leftArrow >> termParser
def getDoIdDeclVar (doIdDecl : Syntax) : Name :=
doIdDecl[0].getId
-- termParser >> leftArrow >> termParser >> optional (" | " >> termParser)
def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do
let pattern := doPatDecl[0]
getPatternVarsEx pattern
-- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl)
def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do
let decl := doLetArrow[2]
if decl.getKind == ``Lean.Parser.Term.doIdDecl then
pure #[getDoIdDeclVar decl]
else if decl.getKind == ``Lean.Parser.Term.doPatDecl then
getDoPatDeclVars decl
else
throwError "unexpected kind of 'do' declaration"
def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do
let arg := doReassign[0]
if arg.getKind == ``Lean.Parser.Term.letIdDecl then
pure #[getLetIdDeclVar arg]
else if arg.getKind == ``Lean.Parser.Term.letPatDecl then
getLetPatDeclVars arg
else
throwError "unexpected kind of reassignment"
def mkDoSeq (doElems : Array Syntax) : Syntax :=
mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]]
def mkSingletonDoSeq (doElem : Syntax) : Syntax :=
mkDoSeq #[doElem]
/-
If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s. -/
private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with
| `(doElem|if $p:doIfProp then $t else $e) => pure none
| `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do
let mut e := e?.getD (← `(doSeq|pure PUnit.unit))
let mut eIsSeq := true
for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do
e ← if eIsSeq then e else `(doSeq|$e:doElem)
e ← withRef cond <| match cond with
| `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e)
| `(doIfCond|let $pat ← $d) => `(doElem| match%$i ← $d with | $pat:term => $t | _ => $e)
| `(doIfCond|$cond:doIfProp) => `(doElem| if%$i $cond:doIfProp then $t else $e)
| _ => `(doElem| if%$i $(Syntax.missing) then $t else $e)
eIsSeq := false
return some e
| _ => pure none
structure DoIfView where
ref : Syntax
optIdent : Syntax
cond : Syntax
thenBranch : Syntax
elseBranch : Syntax
/- This method assumes `expandDoIf?` is not applicable. -/
private def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do
pure {
ref := doIf,
optIdent := doIf[1][0],
cond := doIf[1][1],
thenBranch := doIf[3],
elseBranch := doIf[5][1]
}
/-
We use `MProd` instead of `Prod` to group values when expanding the
`do` notation. `MProd` is a universe monomorphic product.
The motivation is to generate simpler universe constraints in code
that was not written by the user.
Note that we are not restricting the macro power since the
`Bind.bind` combinator already forces values computed by monadic
actions to be in the same universe.
-/
private def mkTuple (elems : Array Syntax) : MacroM Syntax := do
if elems.size == 0 then
mkUnit
else if elems.size == 1 then
pure elems[0]
else
(elems.extract 0 (elems.size - 1)).foldrM
(fun elem tuple => ``(MProd.mk $elem $tuple))
(elems.back)
/- Return `some action` if `doElem` is a `doExpr <action>`-/
def isDoExpr? (doElem : Syntax) : Option Syntax :=
if doElem.getKind == ``Lean.Parser.Term.doExpr then
some doElem[0]
else
none
/--
Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term
```
let a_1 := x.1
let x := x.2
let a_2 := x.1
let x := x.2
...
let a_n := x.1
let a_{n+1} := x.2
body
```
Special cases
- `uvars := #[]` => `body`
- `uvars := #[a]` => `let a := x; body`
We use this method when expanding the `for-in` notation.
-/
private def destructTuple (uvars : Array Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do
if uvars.size == 0 then
return body
else if uvars.size == 1 then
`(let $(← mkIdentFromRef uvars[0]):ident := $x; $body)
else
destruct uvars.toList x body
where
destruct (as : List Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do
match as with
| [a, b] => `(let $(← mkIdentFromRef a):ident := $x.1; let $(← mkIdentFromRef b):ident := $x.2; $body)
| a :: as => withFreshMacroScope do
let rest ← destruct as (← `(x)) body
`(let $(← mkIdentFromRef a):ident := $x.1; let x := $x.2; $rest)
| _ => unreachable!
/-
The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term.
We use this method to convert
1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of
`CodeBlock` never contains `break` nor `continue`. Moreover, the collection
of updated variables is not packed into the result.
Thus, we have two kinds of exit points
- `Code.action e` which is converted into `e`
- `Code.return _ e` which is converted into `pure e`
We use `Kind.regular` for this case.
2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate
a `Syntax` term representing a function for the `xs.forIn` combinator.
a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term
has type `m (ForInStep (Option α × σ))`, where `a : α`, and the `σ` is the type
of the tuple of variables reassigned by `b`.
We use `Kind.forInWithReturn` for this case
b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated
`Syntax` term has type `m (ForInStep σ)`.
We use `Kind.forIn` for this case.
3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`).
The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`,
`Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information.
For example, the auxiliary type `DoResultPBC α σ` is used for a code block that exits with `Code.action`,
**and** `Code.break`/`Code.continue`, `α` is the type of values produced by the exit `action`, and
`σ` is the type of the tuple of reassigned variables.
The type `DoResult α β σ` is usedf for code blocks that exit with
`Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `β` is the type of the returned values.
We don't use `DoResult α β σ` for all cases because:
a) The elaborator would not be able to infer all type parameters without extra annotations. For example,
if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `β`.
b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`),
but we don't want to consider "unreachable" cases.
We do not distinguish between cases that contain `break`, but not `continue`, and vice versa.
When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`,
and `b/c` for a code block that contains `Code.break _` or `Code.continue _`.
- `a`: `Kind.regular`, type `m (α × σ)`
- `r`: `Kind.regular`, type `m (α × σ)`
Note that the code that pattern matches on the result will behave differently in this case.
It produces `return a` for this case, and `pure a` for the previous one.
- `b/c`: `Kind.nestedBC`, type `m (DoResultBC σ)`
- `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR α β σ)`
- `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)`
- `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)`
Again the code that pattern matches on the result will behave differently in this case and
the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for
this case, and `pure a` for the previous case.
- `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC α β σ)`
Here is the recipe for adding new combinators with nested `do`s.
Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m α → m α`
1- Convert `doSeq` into `codeBlock : CodeBlock`
2- Create term `term` using `mkNestedTerm code m uvars a r bc` where
`code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`,
`m` is a `Syntax` representing the Monad, and
`a` is true if `code` contains `Code.action _`,
`r` is true if `code` contains `Code.return _ _`,
`bc` is true if `code` contains `Code.break _` or `Code.continue _`.
Remark: for combinators such as `repeat` that take a single `doSeq`, all
arguments, but `m`, are extracted from `codeBlock`.
3- Create the term `repeat $term`
4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc`
-/
namespace ToTerm
inductive Kind where
| regular
| forIn
| forInWithReturn
| nestedBC
| nestedPR
| nestedSBC
| nestedPRBC
instance : Inhabited Kind := ⟨Kind.regular⟩
def Kind.isRegular : Kind → Bool
| Kind.regular => true
| _ => false
structure Context where
m : Syntax -- Syntax to reference the monad associated with the do notation.
uvars : Array Name
kind : Kind
abbrev M := ReaderT Context MacroM
def mkUVarTuple : M Syntax := do
let ctx ← read
let uvarIdents ← ctx.uvars.mapM mkIdentFromRef
mkTuple uvarIdents
def returnToTerm (val : Syntax) : M Syntax := do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| Kind.regular => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u))
| Kind.forIn => ``(Pure.pure (ForInStep.done $u))
| Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u)))
| Kind.nestedBC => unreachable!
| Kind.nestedPR => ``(Pure.pure (DoResultPR.«return» $val $u))
| Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«pureReturn» $val $u))
| Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«return» $val $u))
def continueToTerm : M Syntax := do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| Kind.regular => unreachable!
| Kind.forIn => ``(Pure.pure (ForInStep.yield $u))
| Kind.forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u)))
| Kind.nestedBC => ``(Pure.pure (DoResultBC.«continue» $u))
| Kind.nestedPR => unreachable!
| Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«continue» $u))
| Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«continue» $u))
def breakToTerm : M Syntax := do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| Kind.regular => unreachable!
| Kind.forIn => ``(Pure.pure (ForInStep.done $u))
| Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u)))
| Kind.nestedBC => ``(Pure.pure (DoResultBC.«break» $u))
| Kind.nestedPR => unreachable!
| Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«break» $u))
| Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«break» $u))
def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do
let ctx ← read
let u ← mkUVarTuple
match ctx.kind with
| Kind.regular => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u))
| Kind.forIn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u))
| Kind.forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u)))
| Kind.nestedBC => unreachable!
| Kind.nestedPR => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u)))
| Kind.nestedSBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u)))
| Kind.nestedPRBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.«pure» y $u)))
def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do
if action.getKind == ``Lean.Parser.Term.doDbgTrace then
let msg := action[1]
`(dbg_trace $msg; $k)
else if action.getKind == ``Lean.Parser.Term.doAssert then
let cond := action[1]
`(assert! $cond; $k)
else
let action ← withRef action ``(($action : $((←read).m) PUnit))
``(Bind.bind $action (fun (_ : PUnit) => $k))
def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do
let kind := decl.getKind
if kind == ``Lean.Parser.Term.doLet then
let letDecl := decl[2]
`(let $letDecl:letDecl; $k)
else if kind == ``Lean.Parser.Term.doLetRec then
let letRecToken := decl[0]
let letRecDecls := decl[1]
pure $ mkNode ``Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k]
else if kind == ``Lean.Parser.Term.doLetArrow then
let arg := decl[2]
let ref := arg
if arg.getKind == ``Lean.Parser.Term.doIdDecl then
let id := arg[0]
let type := expandOptType id arg[1]
let doElem := arg[3]
-- `doElem` must be a `doExpr action`. See `doLetArrowToCode`
match isDoExpr? doElem with
| some action =>
let action ← withRef action `(($action : $((← read).m) $type))
``(Bind.bind $action (fun ($id:ident : $type) => $k))
| none => Macro.throwErrorAt decl "unexpected kind of 'do' declaration"
else
Macro.throwErrorAt decl "unexpected kind of 'do' declaration"
else if kind == ``Lean.Parser.Term.doHave then
-- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser`
let args := decl.getArgs
let args := args ++ #[mkNullNode /- optional ';' -/, k]
pure $ mkNode `Lean.Parser.Term.«have» args
else
Macro.throwErrorAt decl "unexpected kind of 'do' declaration"
def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do
let kind := reassign.getKind
if kind == ``Lean.Parser.Term.doReassign then
-- doReassign := leading_parser (letIdDecl <|> letPatDecl)
let arg := reassign[0]
if arg.getKind == ``Lean.Parser.Term.letIdDecl then
-- letIdDecl := leading_parser ident >> many (ppSpace >> bracketedBinder) >> optType >> " := " >> termParser
let x := arg[0]
let val := arg[4]
let newVal ← `(ensure_type_of% $x $(quote "invalid reassignment, value") $val)
let arg := arg.setArg 4 newVal
let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]
`(let $letDecl:letDecl; $k)
else
-- TODO: ensure the types did not change
let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg]
`(let $letDecl:letDecl; $k)
else
-- Note that `doReassignArrow` is expanded by `doReassignArrowToCode
Macro.throwErrorAt reassign "unexpected kind of 'do' reassignment"
def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do
if optIdent.isNone then
``(if $cond then $thenBranch else $elseBranch)
else
let h := optIdent[0]
``(if $h:ident : $cond then $thenBranch else $elseBranch)
def mkJoinPoint (j : Name) (ps : Array (Name × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do
let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(type_of% $(← mkIdentFromRef id)) else `(_)
let ps ← ps.mapM fun ⟨id, useTypeOf⟩ => mkIdentFromRef id
/-
We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`.
By elaborating `$k` first, we "learn" more about `$body`'s type.
For example, consider the following example `do` expression
```
def f (x : Nat) : IO Unit := do
if x > 0 then
IO.println "x is not zero" -- Error is here
IO.mkRef true
```
it is expanded into
```
def f (x : Nat) : IO Unit := do
let jp (u : Unit) : IO _ :=
IO.mkRef true;
if x > 0 then
IO.println "not zero"
jp ()
else
jp ()
```
If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit → IO (IO.Ref Bool)`.
Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit → IO Unit`.
Then, we get the expected type mismatch error at `IO.mkRef true`. -/
`(let_delayed $(← mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((← read).m) _ := $body; $k)
def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax :=
Syntax.mkApp (mkIdentFrom ref j) args
partial def toTerm : Code → M Syntax
| Code.«return» ref val => withRef ref <| returnToTerm val
| Code.«continue» ref => withRef ref continueToTerm
| Code.«break» ref => withRef ref breakToTerm
| Code.action e => actionTerminalToTerm e
| Code.joinpoint j ps b k => do mkJoinPoint j ps (← toTerm b) (← toTerm k)
| Code.jmp ref j args => pure $ mkJmp ref j args
| Code.decl _ stx k => do declToTerm stx (← toTerm k)
| Code.reassign _ stx k => do reassignToTerm stx (← toTerm k)
| Code.seq stx k => do seqToTerm stx (← toTerm k)
| Code.ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e)
| Code.«match» ref genParam discrs optType alts => do
let mut termAlts := #[]
for alt in alts do
let rhs ← toTerm alt.rhs
let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", alt.patterns, mkAtomFrom alt.ref "=>", rhs]
termAlts := termAlts.push termAlt
let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts]
pure $ mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", genParam, discrs, optType, mkAtomFrom ref "with", termMatchAlts]
def run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do
let term ← toTerm code { m := m, kind := kind, uvars := uvars }
pure term
/- Given
- `a` is true if the code block has a `Code.action _` exit point
- `r` is true if the code block has a `Code.return _ _` exit point
- `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point
generate Kind. See comment at the beginning of the `ToTerm` namespace. -/
def mkNestedKind (a r bc : Bool) : Kind :=
match a, r, bc with
| true, false, false => Kind.regular
| false, true, false => Kind.regular
| false, false, true => Kind.nestedBC
| true, true, false => Kind.nestedPR
| true, false, true => Kind.nestedSBC
| false, true, true => Kind.nestedSBC
| true, true, true => Kind.nestedPRBC
| false, false, false => unreachable!
def mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do
ToTerm.run code m uvars (mkNestedKind a r bc)
/- Given a term `term` produced by `ToTerm.run`, pattern match on its result.
See comment at the beginning of the `ToTerm` namespace.
- `a` is true if the code block has a `Code.action _` exit point
- `r` is true if the code block has a `Code.return _ _` exit point
- `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point
The result is a sequence of `doElem` -/
def matchNestedTermResult (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do
let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo)
let u ← mkTuple (← uvars.mapM mkIdentFromRef)
match a, r, bc with
| true, false, false =>
if uvars.isEmpty then
toDoElems (← `(do $term:term))
else
toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1))
| false, true, false =>
if uvars.isEmpty then
toDoElems (← `(do let r ← $term:term; return r))
else
toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1))
| false, false, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| DoResultBC.«break» u => $u:term := u; break
| DoResultBC.«continue» u => $u:term := u; continue)
| true, true, false => toDoElems <$>
`(do let r ← $term:term;
match r with
| DoResultPR.«pure» a u => $u:term := u; pure a
| DoResultPR.«return» b u => $u:term := u; return b)
| true, false, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| DoResultSBC.«pureReturn» a u => $u:term := u; pure a
| DoResultSBC.«break» u => $u:term := u; break
| DoResultSBC.«continue» u => $u:term := u; continue)
| false, true, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| DoResultSBC.«pureReturn» a u => $u:term := u; return a
| DoResultSBC.«break» u => $u:term := u; break
| DoResultSBC.«continue» u => $u:term := u; continue)
| true, true, true => toDoElems <$>
`(do let r ← $term:term;
match r with
| DoResultPRBC.«pure» a u => $u:term := u; pure a
| DoResultPRBC.«return» a u => $u:term := u; return a
| DoResultPRBC.«break» u => $u:term := u; break
| DoResultPRBC.«continue» u => $u:term := u; continue)
| false, false, false => unreachable!
end ToTerm
def isMutableLet (doElem : Syntax) : Bool :=
let kind := doElem.getKind
(kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet)
&&
!doElem[1].isNone
namespace ToCodeBlock
structure Context where
ref : Syntax
m : Syntax -- Syntax representing the monad associated with the do notation.
mutableVars : NameSet := {}
insideFor : Bool := false
abbrev M := ReaderT Context TermElabM
def withNewMutableVars {α} (newVars : Array Name) (mutable : Bool) (x : M α) : M α :=
withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x
def checkReassignable (xs : Array Name) : M Unit := do
let throwInvalidReassignment (x : Name) : M Unit :=
throwError "'{x.simpMacroScopes}' cannot be reassigned"
let ctx ← read
for x in xs do
unless ctx.mutableVars.contains x do
throwInvalidReassignment x
def checkNotShadowingMutable (xs : Array Name) : M Unit := do
let throwInvalidShadowing (x : Name) : M Unit :=
throwError "mutable variable '{x.simpMacroScopes}' cannot be shadowed"
let ctx ← read
for x in xs do
if ctx.mutableVars.contains x then
throwInvalidShadowing x
def withFor {α} (x : M α) : M α :=
withReader (fun ctx => { ctx with insideFor := true }) x
structure ToForInTermResult where
uvars : Array Name
term : Syntax
def mkForInBody (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do
let ctx ← read
let uvars := forInBody.uvars
let uvars := nameSetToArray uvars
let term ← liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn)
pure ⟨uvars, term⟩
def ensureInsideFor : M Unit :=
unless (← read).insideFor do
throwError "invalid 'do' element, it must be inside 'for'"
def ensureEOS (doElems : List Syntax) : M Unit :=
unless doElems.isEmpty do
throwError "must be last element in a 'do' sequence"
private partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax → StateT (List Syntax) M Syntax
| stx@(Syntax.node k args) =>
if liftMethodDelimiter k then
return stx
else if k == ``Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do
if inBinder then
throwErrorAt stx "cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`"
let term := args[1]
let term ← expandLiftMethodAux inQuot inBinder term
let auxDoElem ← `(doElem| let a ← $term:term)
modify fun s => s ++ [auxDoElem]
`(a)
else do
let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot
let inBinder := inBinder || (!inQuot && liftMethodForbiddenBinder stx)
let args ← args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder)
return Syntax.node k args
| stx => pure stx
def expandLiftMethod (doElem : Syntax) : M (List Syntax × Syntax) := do
if !hasLiftMethod doElem then
pure ([], doElem)
else
let (doElem, doElemsNew) ← (expandLiftMethodAux false false doElem).run []
pure (doElemsNew, doElem)
def checkLetArrowRHS (doElem : Syntax) : M Unit := do
let kind := doElem.getKind
if kind == ``Lean.Parser.Term.doLetArrow ||
kind == ``Lean.Parser.Term.doLet ||
kind == ``Lean.Parser.Term.doLetRec ||
kind == ``Lean.Parser.Term.doHave ||
kind == ``Lean.Parser.Term.doReassign ||
kind == ``Lean.Parser.Term.doReassignArrow then
throwErrorAt doElem "invalid kind of value '{kind}' in an assignment"
/- Generate `CodeBlock` for `doReturn` which is of the form
```
"return " >> optional termParser
```
`doElems` is only used for sanity checking. -/
def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do
ensureEOS doElems
let argOpt := doReturn[1]
let arg ← if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0]
return mkReturn (← getRef) arg
structure Catch where
x : Syntax
optType : Syntax
codeBlock : CodeBlock
def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet :=
let ws := tryCode.uvars
let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws
let ws := match finallyCode? with
| none => ws
| some c => union c.uvars ws
ws
def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code → Bool) : Bool :=
p tryCode.code ||
catches.any (fun «catch» => p «catch».codeBlock.code) ||
match finallyCode? with
| none => false
| some finallyCode => p finallyCode.code
mutual
/- "Concatenate" `c` with `doSeqToCode doElems` -/
partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock :=
match doElems with
| [] => pure c
| nextDoElem :: _ => do
let k ← doSeqToCode doElems
let ref := nextDoElem
concat c ref none k
/- Generate `CodeBlock` for `doLetArrow; doElems`
`doLetArrow` is of the form
```
"let " >> optional "mut " >> (doIdDecl <|> doPatDecl)
```
where
```
def doIdDecl := leading_parser ident >> optType >> leftArrow >> doElemParser
def doPatDecl := leading_parser termParser >> leftArrow >> doElemParser >> optional (" | " >> doElemParser)
```
-/
partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do
let ref := doLetArrow
let decl := doLetArrow[2]
if decl.getKind == ``Lean.Parser.Term.doIdDecl then
let y := decl[0].getId
checkNotShadowingMutable #[y]
let doElem := decl[3]
let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems)
match isDoExpr? doElem with
| some action => pure $ mkVarDeclCore #[y] doLetArrow k
| none =>
checkLetArrowRHS doElem
let c ← doSeqToCode [doElem]
match doElems with
| [] => pure c
| kRef::_ => concat c kRef y k
else if decl.getKind == ``Lean.Parser.Term.doPatDecl then
let pattern := decl[0]
let doElem := decl[2]
let optElse := decl[3]
if optElse.isNone then withFreshMacroScope do
let auxDo ←
if isMutableLet doLetArrow then
`(do let discr ← $doElem; let mut $pattern:term := discr)
else
`(do let discr ← $doElem; let $pattern:term := discr)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else
if isMutableLet doLetArrow then
throwError "'mut' is currently not supported in let-decls with 'else' case"
let contSeq := mkDoSeq doElems.toArray
let elseSeq := mkSingletonDoSeq optElse[1]
let auxDo ← `(do let discr ← $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo)
else
throwError "unexpected kind of 'do' declaration"
/- Generate `CodeBlock` for `doReassignArrow; doElems`
`doReassignArrow` is of the form
```
(doIdDecl <|> doPatDecl)
```
-/
partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do
let ref := doReassignArrow
let decl := doReassignArrow[0]
if decl.getKind == ``Lean.Parser.Term.doIdDecl then
let doElem := decl[3]
let y := decl[0]
let auxDo ← `(do let r ← $doElem; $y:ident := r)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else if decl.getKind == ``Lean.Parser.Term.doPatDecl then
let pattern := decl[0]
let doElem := decl[2]
let optElse := decl[3]
if optElse.isNone then withFreshMacroScope do
let auxDo ← `(do let discr ← $doElem; $pattern:term := discr)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
else
throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported"
else
throwError "unexpected kind of 'do' reassignment"
/- Generate `CodeBlock` for `doIf; doElems`
`doIf` is of the form
```
"if " >> optIdent >> termParser >> " then " >> doSeq
>> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq))
>> optional (" else " >> doSeq)
``` -/
partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do
let view ← liftMacroM $ mkDoIfView doIf
let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch)
let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch)
let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch
concatWith ite doElems
/- Generate `CodeBlock` for `doUnless; doElems`
`doUnless` is of the form
```
"unless " >> termParser >> "do " >> doSeq
``` -/
partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do
let ref := doUnless
let cond := doUnless[1]
let doSeq := doUnless[3]
let body ← doSeqToCode (getDoSeqElems doSeq)
let unlessCode ← liftMacroM <| mkUnless cond body
concatWith unlessCode doElems
/- Generate `CodeBlock` for `doFor; doElems`
`doFor` is of the form
```
def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser
def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq
```
-/
partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do
let doForDecls := doFor[1].getSepArgs
if doForDecls.size > 1 then
/-
Expand
```
for x in xs, y in ys do
body
```
into
```
let s := toStream ys
for x in xs do
match Stream.next? s with
| none => break
| some (y, s') =>
s := s'
body
```
-/
-- Extract second element
let doForDecl := doForDecls[1]
let y := doForDecl[0]
let ys := doForDecl[2]
let doForDecls := doForDecls.eraseIdx 1
let body := doFor[3]
withFreshMacroScope do
let toStreamFn ← withRef ys ``(toStream)
let auxDo ←
`(do let mut s := $toStreamFn:ident $ys
for $doForDecls:doForDecl,* do
match Stream.next? s with
| none => break
| some ($y, s') =>
s := s'
do $body)
doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)
else withRef doFor do
let x := doForDecls[0][0]
withRef x <| checkNotShadowingMutable (← getPatternVarsEx x)
let xs := doForDecls[0][2]
let forElems := getDoSeqElems doFor[3]
let forInBodyCodeBlock ← withFor (doSeqToCode forElems)
let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock
let uvarsTuple ← liftMacroM do mkTuple (← uvars.mapM mkIdentFromRef)
if hasReturn forInBodyCodeBlock.code then
let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody
let forInTerm ← `(for_in% $(xs) (MProd.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody)
let auxDo ← `(do let r ← $forInTerm:term;
$uvarsTuple:term := r.2;
match r.1 with
| none => Pure.pure (ensure_expected_type% "type mismatch, 'for'" PUnit.unit)
| some a => return ensure_expected_type% "type mismatch, 'for'" a)
doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)
else
let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody
let forInTerm ← `(for_in% $(xs) $uvarsTuple fun $x r => $forInBody)
if doElems.isEmpty then
let auxDo ← `(do let r ← $forInTerm:term;
$uvarsTuple:term := r;
Pure.pure (ensure_expected_type% "type mismatch, 'for'" PUnit.unit))
doSeqToCode <| getDoSeqElems (getDoSeq auxDo)
else
let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r)
doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems
/-- Generate `CodeBlock` for `doMatch; doElems` -/
partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do
let ref := doMatch
let genParam := doMatch[1]
let discrs := doMatch[2]
let optType := doMatch[3]
let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt`
let alts ← matchAlts.mapM fun matchAlt => do
let patterns := matchAlt[1]
let vars ← getPatternsVarsEx patterns.getSepArgs
withRef patterns <| checkNotShadowingMutable vars
let rhs := matchAlt[3]
let rhs ← doSeqToCode (getDoSeqElems rhs)
pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock }
let matchCode ← mkMatch ref genParam discrs optType alts
concatWith matchCode doElems
/--
Generate `CodeBlock` for `doTry; doElems`
```
def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally
def doCatch := leading_parser "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq
def doCatchMatch := leading_parser "catch " >> doMatchAlts
def doFinally := leading_parser "finally " >> doSeq
```
-/
partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do
let ref := doTry
let tryCode ← doSeqToCode (getDoSeqElems doTry[1])
let optFinally := doTry[3]
let catches ← doTry[2].getArgs.mapM fun catchStx => do
if catchStx.getKind == ``Lean.Parser.Term.doCatch then
let x := catchStx[1]
if x.isIdent then
withRef x <| checkNotShadowingMutable #[x.getId]
let optType := catchStx[2]
let c ← doSeqToCode (getDoSeqElems catchStx[4])
pure { x := x, optType := optType, codeBlock := c : Catch }
else if catchStx.getKind == ``Lean.Parser.Term.doCatchMatch then
let matchAlts := catchStx[1]
let x ← `(ex)
let auxDo ← `(do match ex with $matchAlts)
let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo))
pure { x := x, codeBlock := c, optType := mkNullNode : Catch }
else
throwError "unexpected kind of 'catch'"
let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1])
if catches.isEmpty && finallyCode?.isNone then
throwError "invalid 'try', it must have a 'catch' or 'finally'"
let ctx ← read
let ws := getTryCatchUpdatedVars tryCode catches finallyCode?
let uvars := nameSetToArray ws
let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction
let r := tryCatchPred tryCode catches finallyCode? hasReturn
let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue
let toTerm (codeBlock : CodeBlock) : M Syntax := do
let codeBlock ← liftM $ extendUpdatedVars codeBlock ws
liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc
let term ← toTerm tryCode
let term ← catches.foldlM
(fun term «catch» => do
let catchTerm ← toTerm «catch».codeBlock
if catch.optType.isNone then
``(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm))
else
let type := «catch».optType[1]
``(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm)))
term
let term ← match finallyCode? with
| none => pure term
| some finallyCode => withRef optFinally do
unless finallyCode.uvars.isEmpty do
throwError "'finally' currently does not support reassignments"
if hasBreakContinueReturn finallyCode.code then
throwError "'finally' currently does 'return', 'break', nor 'continue'"
let finallyTerm ← liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular
``(tryFinally $term $finallyTerm)
let doElemsNew ← liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc
doSeqToCode (doElemsNew ++ doElems)
partial def doSeqToCode : List Syntax → M CodeBlock
| [] => do liftMacroM mkPureUnitAction
| doElem::doElems => withIncRecDepth <| withRef doElem do
checkMaxHeartbeats "'do'-expander"
match (← liftMacroM <| expandMacro? doElem) with
| some doElem => doSeqToCode (doElem::doElems)
| none =>
match (← liftMacroM <| expandDoIf? doElem) with
| some doElem => doSeqToCode (doElem::doElems)
| none =>
let (liftedDoElems, doElem) ← expandLiftMethod doElem
if !liftedDoElems.isEmpty then
doSeqToCode (liftedDoElems ++ [doElem] ++ doElems)
else
let ref := doElem
let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems
let k := doElem.getKind
if k == ``Lean.Parser.Term.doLet then
let vars ← getDoLetVars doElem
checkNotShadowingMutable vars
mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems)
else if k == ``Lean.Parser.Term.doHave then
let var := getDoHaveVar doElem
checkNotShadowingMutable #[var]
mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems)
else if k == ``Lean.Parser.Term.doLetRec then
let vars ← getDoLetRecVars doElem
checkNotShadowingMutable vars
mkVarDeclCore vars doElem <$> (doSeqToCode doElems)
else if k == ``Lean.Parser.Term.doReassign then
let vars ← getDoReassignVars doElem
checkReassignable vars
let k ← doSeqToCode doElems
mkReassignCore vars doElem k
else if k == ``Lean.Parser.Term.doLetArrow then
doLetArrowToCode doElem doElems
else if k == ``Lean.Parser.Term.doReassignArrow then
doReassignArrowToCode doElem doElems
else if k == ``Lean.Parser.Term.doIf then
doIfToCode doElem doElems
else if k == ``Lean.Parser.Term.doUnless then
doUnlessToCode doElem doElems
else if k == ``Lean.Parser.Term.doFor then withFreshMacroScope do
doForToCode doElem doElems
else if k == ``Lean.Parser.Term.doMatch then
doMatchToCode doElem doElems
else if k == ``Lean.Parser.Term.doTry then
doTryToCode doElem doElems
else if k == ``Lean.Parser.Term.doBreak then
ensureInsideFor
ensureEOS doElems
return mkBreak ref
else if k == ``Lean.Parser.Term.doContinue then
ensureInsideFor
ensureEOS doElems
return mkContinue ref
else if k == ``Lean.Parser.Term.doReturn then
doReturnToCode doElem doElems
else if k == ``Lean.Parser.Term.doDbgTrace then
return mkSeq doElem (← doSeqToCode doElems)
else if k == ``Lean.Parser.Term.doAssert then
return mkSeq doElem (← doSeqToCode doElems)
else if k == ``Lean.Parser.Term.doNested then
let nestedDoSeq := doElem[1]
doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems)
else if k == ``Lean.Parser.Term.doExpr then
let term := doElem[0]
if doElems.isEmpty then
return mkTerminalAction term
else
return mkSeq term (← doSeqToCode doElems)
else
throwError "unexpected do-element of kind {doElem.getKind}:\n{doElem}"
end
def run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock :=
(doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m }
end ToCodeBlock
/- Create a synthetic metavariable `?m` and assign `m` to it.
We use `?m` to refer to `m` when expanding the `do` notation. -/
private def mkMonadAlias (m : Expr) : TermElabM Syntax := do
let result ← `(?m)
let mType ← inferType m
let mvar ← elabTerm result mType
assignExprMVar mvar.mvarId! m
pure result
private partial def ensureArrowNotUsed (stx : Syntax) : MacroM Unit := do
/- We expand macros here because we stop the search at nested `do`s
So, we also want to stop the search at macros that expand `do ...`.
Hopefully this is not a performance bottleneck in practice. -/
let stx ← expandMacros stx
stx.getArgs.forM go
where
go (stx : Syntax) : MacroM Unit :=
match stx with
| Syntax.node k args => do
if k == ``Parser.Term.liftMethod || k == ``Parser.Term.doLetArrow || k == ``Parser.Term.doReassignArrow || k == ``Parser.Term.doIfLetBind then
Macro.throwErrorAt stx "`←` and `<-` are not allowed in pure `do` blocks, i.e., blocks where Lean implicitly used the `Id` monad"
unless k == ``Parser.Term.do do
args.forM go
| _ => pure ()
@[builtinTermElab «do»] def elabDo : TermElab := fun stx expectedType? => do
tryPostponeIfNoneOrMVar expectedType?
let bindInfo ← extractBind expectedType?
if bindInfo.isPure then
liftMacroM <| ensureArrowNotUsed stx
let m ← mkMonadAlias bindInfo.m
let codeBlock ← ToCodeBlock.run stx m
let stxNew ← liftMacroM $ ToTerm.run codeBlock.code m
trace[Elab.do] stxNew
withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType
end Do
builtin_initialize registerTraceClass `Elab.do
private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do
let stx := stx.setKind newKind
withRef stx `(do $stx:doElem)
@[builtinMacro Lean.Parser.Term.termFor]
def expandTermFor : Macro := toDoElem ``Lean.Parser.Term.doFor
@[builtinMacro Lean.Parser.Term.termTry]
def expandTermTry : Macro := toDoElem ``Lean.Parser.Term.doTry
@[builtinMacro Lean.Parser.Term.termUnless]
def expandTermUnless : Macro := toDoElem ``Lean.Parser.Term.doUnless
@[builtinMacro Lean.Parser.Term.termReturn]
def expandTermReturn : Macro := toDoElem ``Lean.Parser.Term.doReturn
end Lean.Elab.Term
|
39a405bc46af035aaaee920d95b72bb9978b8027 | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /tests/lean/run/uni.lean | 311e866eb9abe25427cb804626e1cfb17377d096 | [
"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 | 1,346 | lean | import logic
namespace experiment
inductive nat : Type :=
| zero : nat
| succ : nat → nat
check @nat.rec
(*
local env = get_env()
local nat_rec = Const({"nat", "rec"}, {1})
local nat = Const("nat")
local n = Local("n", nat)
local C = Fun(n, Prop)
local p = Local("p", Prop)
local ff = Const("false")
local tt = Const("true")
local t = nat_rec(C, ff, Fun(n, p, tt))
local zero = Const("zero")
local succ = Const("succ")
local one = succ(zero)
local tc = type_checker(env)
print(env:whnf(t(one)))
print(env:whnf(t(zero)))
local m = mk_metavar("m", nat)
print(env:whnf(t(m)))
function test_unify(env, lhs, rhs, num_s)
print(tostring(lhs) .. " =?= " .. tostring(rhs) .. ", expected: " .. tostring(num_s))
local ss = unify(env, lhs, rhs, name_generator(), true, substitution(), options())
local n = 0
for s in ss do
print("solution: ")
s:for_each_expr(function(n, v, j)
print(" " .. tostring(n) .. " := " .. tostring(v))
end)
s:for_each_level(function(n, v, j)
print(" " .. tostring(n) .. " := " .. tostring(v))
end)
n = n + 1
end
if num_s ~= n then print("n: " .. n) end
assert(num_s == n)
end
test_unify(env, t(m), tt, 1)
test_unify(env, t(m), ff, 1)
*)
end experiment
|
7e0ec5a723f6f0b971b0e21eb32649c1022be20c | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/topology/category/Top/basic.lean | 6d17e05487c85bbea46c186fefe36442533689ff | [
"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 | 2,873 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Scott Morrison, Mario Carneiro
-/
import category_theory.concrete_category.unbundled_hom
import topology.continuous_function.basic
import topology.opens
/-!
# Category instance for topological spaces
We introduce the bundled category `Top` of topological spaces together with the functors `discrete`
and `trivial` from the category of types to `Top` which equip a type with the corresponding
discrete, resp. trivial, topology. For a proof that these functors are left, resp. right adjoint
to the forgetful functor, see `topology.category.Top.adjunctions`.
-/
open category_theory
open topological_space
universe u
/-- The category of topological spaces and continuous maps. -/
def Top : Type (u+1) := bundled topological_space
namespace Top
instance bundled_hom : bundled_hom @continuous_map :=
⟨@continuous_map.to_fun, @continuous_map.id, @continuous_map.comp, @continuous_map.coe_inj⟩
attribute [derive [large_category, concrete_category]] Top
instance : has_coe_to_sort Top Type* := bundled.has_coe_to_sort
instance topological_space_unbundled (x : Top) : topological_space x := x.str
@[simp] lemma id_app (X : Top.{u}) (x : X) :
(𝟙 X : X → X) x = x := rfl
@[simp] lemma comp_app {X Y Z : Top.{u}} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) :
(f ≫ g : X → Z) x = g (f x) := rfl
/-- Construct a bundled `Top` from the underlying type and the typeclass. -/
def of (X : Type u) [topological_space X] : Top := ⟨X⟩
instance (X : Top) : topological_space X := X.str
@[simp] lemma coe_of (X : Type u) [topological_space X] : (of X : Type u) = X := rfl
instance : inhabited Top := ⟨Top.of empty⟩
/-- The discrete topology on any type. -/
def discrete : Type u ⥤ Top.{u} :=
{ obj := λ X, ⟨X, ⊥⟩,
map := λ X Y f, { to_fun := f, continuous_to_fun := continuous_bot } }
/-- The trivial topology on any type. -/
def trivial : Type u ⥤ Top.{u} :=
{ obj := λ X, ⟨X, ⊤⟩,
map := λ X Y f, { to_fun := f, continuous_to_fun := continuous_top } }
/-- Any homeomorphisms induces an isomorphism in `Top`. -/
@[simps] def iso_of_homeo {X Y : Top.{u}} (f : X ≃ₜ Y) : X ≅ Y :=
{ hom := ⟨f⟩,
inv := ⟨f.symm⟩ }
/-- Any isomorphism in `Top` induces a homeomorphism. -/
@[simps] def homeo_of_iso {X Y : Top.{u}} (f : X ≅ Y) : X ≃ₜ Y :=
{ to_fun := f.hom,
inv_fun := f.inv,
left_inv := λ x, by simp,
right_inv := λ x, by simp,
continuous_to_fun := f.hom.continuous,
continuous_inv_fun := f.inv.continuous }
@[simp] lemma of_iso_of_homeo {X Y : Top.{u}} (f : X ≃ₜ Y) : homeo_of_iso (iso_of_homeo f) = f :=
by { ext, refl }
@[simp] lemma of_homeo_of_iso {X Y : Top.{u}} (f : X ≅ Y) : iso_of_homeo (homeo_of_iso f) = f :=
by { ext, refl }
end Top
|
bfbe36534001d1b45d2e3e6ecef064790aa1d53a | f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58 | /order/zorn.lean | 442b58236681ab9f114239b8043fd21116f53892 | [
"Apache-2.0"
] | permissive | semorrison/mathlib | 1be6f11086e0d24180fec4b9696d3ec58b439d10 | 20b4143976dad48e664c4847b75a85237dca0a89 | refs/heads/master | 1,583,799,212,170 | 1,535,634,130,000 | 1,535,730,505,000 | 129,076,205 | 0 | 0 | Apache-2.0 | 1,551,697,998,000 | 1,523,442,265,000 | Lean | UTF-8 | Lean | false | false | 9,179 | 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
Zorn's lemmas.
Ported from Isabelle/HOL (written by Jacques D. Fleuriot, Tobias Nipkow, and Christian Sternagel).
-/
import data.set.lattice
noncomputable theory
universes u
open set classical
local attribute [instance] prop_decidable
namespace zorn
section chain
parameters {α : Type u} (r : α → α → Prop)
local infix ` ≺ `:50 := r
/-- A chain is a subset `c` satisfying
`x ≺ y ∨ x = y ∨ y ≺ x` for all `x y ∈ c`. -/
def chain (c : set α) := pairwise_on c (λx y, x ≺ y ∨ y ≺ x)
parameters {r}
theorem chain.total_of_refl [is_refl α r]
{c} (H : chain c) {x y} (hx : x ∈ c) (hy : y ∈ c) :
x ≺ y ∨ y ≺ x :=
if e : x = y then or.inl (e ▸ refl _) else H _ hx _ hy e
theorem chain.directed [is_refl α r]
{c} (H : chain c) {x y} (hx : x ∈ c) (hy : y ∈ c) :
∃ z, z ∈ c ∧ x ≺ z ∧ y ≺ z :=
match H.total_of_refl hx hy with
| or.inl h := ⟨y, hy, h, refl _⟩
| or.inr h := ⟨x, hx, refl _, h⟩
end
theorem chain_insert {c : set α} {a : α} (hc : chain c) (ha : ∀b∈c, b ≠ a → a ≺ b ∨ b ≺ a) :
chain (insert a c) :=
forall_insert_of_forall
(assume x hx, forall_insert_of_forall (hc x hx) (assume hneq, (ha x hx hneq).symm))
(forall_insert_of_forall (assume x hx hneq, ha x hx $ assume h', hneq h'.symm) (assume h, (h rfl).rec _))
def super_chain (c₁ c₂ : set α) := chain c₂ ∧ c₁ ⊂ c₂
def is_max_chain (c : set α) := chain c ∧ ¬ (∃c', super_chain c c')
def succ_chain (c : set α) :=
if h : ∃c', chain c ∧ super_chain c c' then some h else c
theorem succ_spec {c : set α} (h : ∃c', chain c ∧ super_chain c c') :
super_chain c (succ_chain c) :=
let ⟨c', hc'⟩ := h in
have chain c ∧ super_chain c (some h),
from @some_spec _ (λc', chain c ∧ super_chain c c') _,
by simp [succ_chain, dif_pos, h, this.right]
theorem chain_succ {c : set α} (hc : chain c) : chain (succ_chain c) :=
if h : ∃c', chain c ∧ super_chain c c' then
(succ_spec h).left
else
by simp [succ_chain, dif_neg, h]; exact hc
theorem super_of_not_max {c : set α} (hc₁ : chain c) (hc₂ : ¬ is_max_chain c) :
super_chain c (succ_chain c) :=
begin
simp [is_max_chain, not_and_distrib, not_forall_not] at hc₂,
cases hc₂.neg_resolve_left hc₁ with c' hc',
exact succ_spec ⟨c', hc₁, hc'⟩
end
theorem succ_increasing {c : set α} : c ⊆ succ_chain c :=
if h : ∃c', chain c ∧ super_chain c c' then
have super_chain c (succ_chain c), from succ_spec h,
this.right.left
else by simp [succ_chain, dif_neg, h, subset.refl]
inductive chain_closure : set α → Prop
| succ : ∀{s}, chain_closure s → chain_closure (succ_chain s)
| union : ∀{s}, (∀a∈s, chain_closure a) → chain_closure (⋃₀ s)
theorem chain_closure_empty : chain_closure ∅ :=
have chain_closure (⋃₀ ∅),
from chain_closure.union $ assume a h, h.rec _,
by simp at this; assumption
theorem chain_closure_closure : chain_closure (⋃₀ chain_closure) :=
chain_closure.union $ assume s hs, hs
variables {c c₁ c₂ c₃ : set α}
private lemma chain_closure_succ_total_aux (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂)
(h : ∀{c₃}, chain_closure c₃ → c₃ ⊆ c₂ → c₂ = c₃ ∨ succ_chain c₃ ⊆ c₂) :
c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁ :=
begin
induction hc₁,
case _root_.zorn.chain_closure.succ : c₃ hc₃ ih {
cases ih with ih ih,
{ have h := h hc₃ ih,
cases h with h h,
{ exact or.inr (h ▸ subset.refl _) },
{ exact or.inl h } },
{ exact or.inr (subset.trans ih succ_increasing) } },
case _root_.zorn.chain_closure.union : s hs ih {
refine (classical.or_iff_not_imp_right.2 $ λ hn, sUnion_subset $ λ a ha, _),
apply (ih a ha).resolve_right,
apply mt (λ h, _) hn,
exact subset.trans h (subset_sUnion_of_mem ha) }
end
private lemma chain_closure_succ_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : c₁ ⊆ c₂) :
c₂ = c₁ ∨ succ_chain c₁ ⊆ c₂ :=
begin
induction hc₂ generalizing c₁ hc₁ h,
case _root_.zorn.chain_closure.succ : c₂ hc₂ ih {
have h₁ : c₁ ⊆ c₂ ∨ @succ_chain α r c₂ ⊆ c₁ :=
(chain_closure_succ_total_aux hc₁ hc₂ $ assume c₁, ih),
cases h₁ with h₁ h₁,
{ have h₂ := ih hc₁ h₁,
cases h₂ with h₂ h₂,
{ exact (or.inr $ h₂ ▸ subset.refl _) },
{ exact (or.inr $ subset.trans h₂ succ_increasing) } },
{ exact (or.inl $ subset.antisymm h₁ h) } },
case _root_.zorn.chain_closure.union : s hs ih {
apply or.imp_left (assume h', subset.antisymm h' h),
apply classical.by_contradiction,
simp [not_or_distrib, sUnion_subset_iff, classical.not_forall],
intros c₃ hc₃ h₁ h₂,
have h := chain_closure_succ_total_aux hc₁ (hs c₃ hc₃) (assume c₄, ih _ hc₃),
cases h with h h,
{ have h' := ih c₃ hc₃ hc₁ h,
cases h' with h' h',
{ exact (h₁ $ h' ▸ subset.refl _) },
{ exact (h₂ $ subset.trans h' $ subset_sUnion_of_mem hc₃) } },
{ exact (h₁ $ subset.trans succ_increasing h) } }
end
theorem chain_closure_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) : c₁ ⊆ c₂ ∨ c₂ ⊆ c₁ :=
have c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁,
from chain_closure_succ_total_aux hc₁ hc₂ $ assume c₃ hc₃, chain_closure_succ_total hc₃ hc₂,
or.imp_right (assume : succ_chain c₂ ⊆ c₁, subset.trans succ_increasing this) this
theorem chain_closure_succ_fixpoint (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂)
(h_eq : succ_chain c₂ = c₂) : c₁ ⊆ c₂ :=
begin
induction hc₁,
case _root_.zorn.chain_closure.succ : c₁ hc₁ h {
exact or.elim (chain_closure_succ_total hc₁ hc₂ h)
(assume h, h ▸ h_eq.symm ▸ subset.refl c₂) id },
case _root_.zorn.chain_closure.union : s hs ih {
exact (sUnion_subset $ assume c₁ hc₁, ih c₁ hc₁) }
end
theorem chain_closure_succ_fixpoint_iff (hc : chain_closure c) :
succ_chain c = c ↔ c = ⋃₀ chain_closure :=
⟨assume h, subset.antisymm
(subset_sUnion_of_mem hc)
(chain_closure_succ_fixpoint chain_closure_closure hc h),
assume : c = ⋃₀{c : set α | chain_closure c},
subset.antisymm
(calc succ_chain c ⊆ ⋃₀{c : set α | chain_closure c} :
subset_sUnion_of_mem $ chain_closure.succ hc
... = c : this.symm)
succ_increasing⟩
theorem chain_chain_closure (hc : chain_closure c) : chain c :=
begin
induction hc,
case _root_.zorn.chain_closure.succ : c hc h {
exact chain_succ h },
case _root_.zorn.chain_closure.union : s hs h {
have h : ∀c∈s, zorn.chain c := h,
exact assume c₁ ⟨t₁, ht₁, (hc₁ : c₁ ∈ t₁)⟩ c₂ ⟨t₂, ht₂, (hc₂ : c₂ ∈ t₂)⟩ hneq,
have t₁ ⊆ t₂ ∨ t₂ ⊆ t₁, from chain_closure_total (hs _ ht₁) (hs _ ht₂),
or.elim this
(assume : t₁ ⊆ t₂, h t₂ ht₂ c₁ (this hc₁) c₂ hc₂ hneq)
(assume : t₂ ⊆ t₁, h t₁ ht₁ c₁ hc₁ c₂ (this hc₂) hneq) }
end
def max_chain := ⋃₀ chain_closure
/-- Hausdorff's maximality principle
There exists a maximal totally ordered subset of `α`.
Note that we do not require `α` to be partially ordered by `r`. -/
theorem max_chain_spec : is_max_chain max_chain :=
classical.by_contradiction $
assume : ¬ is_max_chain (⋃₀ chain_closure),
have super_chain (⋃₀ chain_closure) (succ_chain (⋃₀ chain_closure)),
from super_of_not_max (chain_chain_closure chain_closure_closure) this,
let ⟨h₁, h₂, (h₃ : (⋃₀ chain_closure) ≠ succ_chain (⋃₀ chain_closure))⟩ := this in
have succ_chain (⋃₀ chain_closure) = (⋃₀ chain_closure),
from (chain_closure_succ_fixpoint_iff chain_closure_closure).mpr rfl,
h₃ this.symm
/-- Zorn's lemma
If every chain has an upper bound, then there is a maximal element -/
theorem zorn (h : ∀c, chain c → ∃ub, ∀a∈c, a ≺ ub) (trans : ∀{a b c}, a ≺ b → b ≺ c → a ≺ c) :
∃m, ∀a, m ≺ a → a ≺ m :=
have ∃ub, ∀a∈max_chain, a ≺ ub,
from h _ $ max_chain_spec.left,
let ⟨ub, (hub : ∀a∈max_chain, a ≺ ub)⟩ := this in
⟨ub, assume a ha,
have chain (insert a max_chain),
from chain_insert max_chain_spec.left $ assume b hb _, or.inr $ trans (hub b hb) ha,
have a ∈ max_chain, from
classical.by_contradiction $ assume h : a ∉ max_chain,
max_chain_spec.right $ ⟨insert a max_chain, this, ssubset_insert h⟩,
hub a this⟩
end chain
theorem zorn_partial_order {α : Type u} [partial_order α]
(h : ∀c:set α, @chain α (≤) c → ∃ub, ∀a∈c, a ≤ ub) : ∃m:α, ∀a, m ≤ a → a = m :=
let ⟨m, hm⟩ := @zorn α (≤) h (assume a b c, le_trans) in
⟨m, assume a ha, le_antisymm (hm a ha) ha⟩
theorem chain.total {α : Type u} [preorder α]
{c} (H : @chain α (≤) c) :
∀ {x y}, x ∈ c → y ∈ c → x ≤ y ∨ y ≤ x :=
@chain.total_of_refl _ (≤) ⟨le_refl⟩ _ H
end zorn
|
2f40687cf36556bbfc7817fb8a67328fec6d718d | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/1576.lean | bfa141a069d15408ec3009eb9159db263d1513f5 | [
"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 | 51 | lean | example : True := by rw (config := non / sense) []
|
0c12c5ffc67c3c8fc2f69a2e62e7b4455d3010a1 | 50b3917f95cf9fe84639812ea0461b38f8f0dbe1 | /canonical_isomorphism/johan_challenge.lean | ae71c816751ff8c1e9e60e0c923bddb553881be9 | [] | no_license | roro47/xena | 6389bcd7dcf395656a2c85cfc90a4366e9b825bb | 237910190de38d6ff43694ffe3a9b68f79363e6c | refs/heads/master | 1,598,570,061,948 | 1,570,052,567,000 | 1,570,052,567,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,696 | lean | -- Questions by Johan Commelin
-- Solutions by Kenny Lau, with minor additions and tinkering by Kevin Buzzard
import data.equiv
universes u v w
class transportable (f : Type u → Type v) :=
(on_equiv : Π {α β : Type u} (e : equiv α β), equiv (f α) (f β))
(on_refl : Π (α : Type u), on_equiv (equiv.refl α) = equiv.refl (f α))
(on_trans : Π {α β γ : Type u} (d : equiv α β) (e : equiv β γ), on_equiv (equiv.trans d e) = equiv.trans (on_equiv d) (on_equiv e))
local attribute [simp] transportable.on_refl transportable.on_trans
-- Our goal is an automagic proof of the following (level 20)
theorem group.transportable : transportable group := sorry
-- cool transportable fact
def transportable.trans (f : Type u → Type v) (g : Type v → Type w)
[transportable f] [transportable g] : transportable (g ∘ f) :=
{ on_equiv := λ α β e, show g (f α) ≃ g (f β), from transportable.on_equiv g (transportable.on_equiv f e),
on_refl := λ α, by simp,
on_trans := λ α β γ e₁ e₂, by simp }
-- Basic instances which we prove by hand
def Const : Type u → Type v := λ α, punit
lemma Const.transportable : (transportable Const) :=
{ on_equiv := λ α β e, equiv.punit_equiv_punit,
on_refl := λ α, equiv.ext _ _ $ λ ⟨⟩, rfl,
on_trans := λ α β γ e1 e2, equiv.ext _ _ $ λ ⟨⟩, rfl }
def Fun : Type u → Type v → Type (max u v) := λ α β, α → β
lemma Fun.transportable (α : Type u) : (transportable (Fun α)) :=
{ on_equiv := λ β γ e, equiv.arrow_congr (equiv.refl α) e,
on_refl := λ β, equiv.ext _ _ $ λ f, rfl,
on_trans := λ β γ δ e1 e2, equiv.ext _ _ $ λ f, funext $ λ x,
by cases e1; cases e2; refl }
theorem prod.ext' {α β : Type*} {p q : α × β} (H1 : p.1 = q.1) (H2 : p.2 = q.2) : p = q :=
prod.ext.2 ⟨H1, H2⟩
def Prod : Type u → Type v → Type (max u v) := λ α β, α × β
lemma Prod.transportable (α : Type u) : (transportable (Prod α)) :=
{ on_equiv := λ β γ e, equiv.prod_congr (equiv.refl α) e,
on_refl := λ β, equiv.ext _ _ $ λ ⟨x, y⟩, by simp,
on_trans := λ β γ δ e1 e2, equiv.ext _ _ $ λ ⟨x, y⟩, by simp }
def Swap : Type u → Type v → Type (max u v) := λ α β, β × α
lemma Swap.transportable (α : Type u) : (transportable (Swap α)) :=
{ on_equiv := λ β γ e, equiv.prod_congr e (equiv.refl α),
on_refl := λ β, equiv.ext _ _ $ λ ⟨x, y⟩, by simp,
on_trans := λ β γ δ e1 e2, equiv.ext _ _ $ λ ⟨x, y⟩, by simp }
-- And then we can define
def Hom1 (α : Type u) : Type v → Type (max u v) := λ β, α → β
def Hom2 (β : Type v) : Type u → Type (max u v) := λ α, α → β
def Aut : Type u → Type u := λ α, α → α
-- And hopefully automagically derive
lemma Hom1.transportable (α : Type u) : (transportable (Hom1 α)) :=
Fun.transportable α
lemma Hom2.transportable (β : Type v) : (transportable (Hom2 β)) :=
{ on_equiv := λ α γ e, equiv.arrow_congr e (equiv.refl β),
on_refl := λ β, equiv.ext _ _ $ λ f, rfl,
on_trans := λ β γ δ e1 e2, equiv.ext _ _ $ λ f, funext $ λ x,
by cases e1; cases e2; refl }
lemma Aut.transportable : (transportable Aut) :=
{ on_equiv := λ α β e, equiv.arrow_congr e e,
on_refl := λ α, equiv.ext _ _ $ λ f, funext $ λ x, rfl,
on_trans := λ α β γ e1 e2, equiv.ext _ _ $ λ f, funext $ λ x,
by cases e1; cases e2; refl }
-- If we have all these in place...
-- A bit of magic might actually be able to derive `group.transportable`
-- After all, a group just is a type plus some functions... and we can now transport functions.
--theorem group.transportable : transportable group := sorry
-- other goals -- ring, topological_ring
-- These we might need to define and prove by hand
-- level 1
def Const' : Type u → Type v := λ α, punit
lemma Const'.transportable : (transportable Const) := {
on_equiv := λ α β H,⟨λ _,punit.star,λ _,punit.star,λ ⟨⟩,rfl,λ ⟨⟩,rfl⟩,
on_refl := λ α, equiv.ext _ _ (λ ⟨⟩,rfl),
on_trans := λ α β γ Hαβ Hβγ,by congr
}
-- level 2
def Fun : Type u → Type v → Type (max u v) := λ α β, α → β
lemma Fun.transportable (α : Type u) : (transportable (Fun α)) := {
on_equiv := λ β γ Hβγ,⟨
λ f a,Hβγ (f a),
λ f a,Hβγ.symm (f a),
λ f, funext $ λ x, by simp,
λ g,by funext a;simp
⟩,
on_refl := λ β,by congr,
on_trans := λ β γ δ Hβγ Hγδ,by congr
}
-- level 3
def Prod : Type u → Type v → Type (max u v) := λ α β, α × β
lemma Prod.transportable (α : Type u) : (transportable (Prod α)) := {
on_equiv := λ β γ Hβγ,⟨λ ⟨a,b⟩,⟨a,Hβγ b⟩,λ ⟨a,c⟩,⟨a,Hβγ.symm c⟩,λ f,begin funext,simp,end,sorry⟩,
on_refl := λ α,sorry,
on_trans := λ α β γ Hαβ Hβγ,sorry
}
lemma Swap.transportable (α : Type u) : (transportable (Swap α)) := sorry
-- And then we can define
def Hom1 (α : Type u) : Type v → Type (max u v) := λ β, α → β
def Hom2 (β : Type v) : Type u → Type (max u v) := λ α, α → β
def Aut : Type u → Type u := λ α, α → α
-- And hopefully automagically derive
lemma Hom1.transportable (α : Type u) : (transportable (Hom1 α)) := sorry
lemma Hom2.transportable (β : Type v) : (transportable (Hom1 β)) := sorry
lemma Aut.transportable (α : Type u) : (transportable Aut) := sorry
-- If we have all these in place...
-- A bit of magic might actually be able to derive `group.transportable` on line 11.
-- After all, a group just is a type plus some functions... and we can now transport functions.
lemma distrib.transportable : transportable distrib := {
on_equiv := sorry,
on_refl := sorry,
} |
6cd8fda7a4c1d49764f4e0aee807ede685f49ac2 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /04_Quantifiers_and_Equality.org.31.lean | 6232620f78a97d74b3a04d335e829f355a1de858 | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 397 | lean | /- page 59 -/
import standard
import data.nat
open nat
variable f : ℕ → ℕ
premise H : ∀ x : ℕ, f x ≤ f (x + 1)
-- BEGIN
example : f 0 ≥ f 1 → f 1 ≥ f 2 → f 0 = f 2 :=
suppose f 0 ≥ f 1,
suppose f 1 ≥ f 2,
have f 0 ≥ f 2, from le.trans `f 2 ≤ f 1` `f 1 ≤ f 0`,
have f 0 ≤ f 2, from le.trans (H 0) (H 1),
show f 0 = f 2, from le.antisymm this `f 0 ≥ f 2`
-- END
|
0673b899393b8f982ecf4ad25d964b1c9e249ed3 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/order/complete_boolean_algebra.lean | 544d8b81aa27a9984d92c2631dd81bb07a0cbf85 | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 4,686 | 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
Theory of complete Boolean algebras.
-/
import order.complete_lattice order.boolean_algebra data.set.basic
set_option old_structure_cmd true
universes u v w
variables {α : Type u} {β : Type v} {ι : Sort w}
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A complete distributive lattice is a bit stronger than the name might
suggest; perhaps completely distributive lattice is more descriptive,
as this class includes a requirement that the lattice join
distribute over *arbitrary* infima, and similarly for the dual. -/
class complete_distrib_lattice α extends complete_lattice α :=
(infi_sup_le_sup_Inf : ∀a s, (⨅ b ∈ s, a ⊔ b) ≤ a ⊔ Inf s)
(inf_Sup_le_supr_inf : ∀a s, a ⊓ Sup s ≤ (⨆ b ∈ s, a ⊓ b))
end prio
section complete_distrib_lattice
variables [complete_distrib_lattice α] {a b : α} {s t : set α}
theorem sup_Inf_eq : a ⊔ Inf s = (⨅ b ∈ s, a ⊔ b) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume h, sup_le_sup (le_refl _) (Inf_le h))
(complete_distrib_lattice.infi_sup_le_sup_Inf _ _)
theorem Inf_sup_eq : Inf s ⊔ b = (⨅ a ∈ s, a ⊔ b) :=
by simpa [sup_comm] using @sup_Inf_eq α _ b s
theorem inf_Sup_eq : a ⊓ Sup s = (⨆ b ∈ s, a ⊓ b) :=
le_antisymm
(complete_distrib_lattice.inf_Sup_le_supr_inf _ _)
(supr_le $ assume i, supr_le $ assume h, inf_le_inf (le_refl _) (le_Sup h))
theorem Sup_inf_eq : Sup s ⊓ b = (⨆ a ∈ s, a ⊓ b) :=
by simpa [inf_comm] using @inf_Sup_eq α _ b s
theorem Inf_sup_Inf : Inf s ⊔ Inf t = (⨅p ∈ set.prod s t, (p : α × α).1 ⊔ p.2) :=
begin
apply le_antisymm,
{ finish },
{ have : ∀ a ∈ s, (⨅p ∈ set.prod s t, (p : α × α).1 ⊔ p.2) ≤ a ⊔ Inf t,
{ assume a ha,
have : (⨅p ∈ set.prod s t, ((p : α × α).1 : α) ⊔ p.2) ≤
(⨅p ∈ prod.mk a '' t, (p : α × α).1 ⊔ p.2),
{ apply infi_le_infi_of_subset,
rintros ⟨x, y⟩,
simp only [and_imp, set.mem_image, prod.mk.inj_iff, set.prod_mk_mem_set_prod_eq,
exists_imp_distrib],
assume x' x't ax x'y,
rw [← x'y, ← ax],
simp [ha, x't] },
rw [infi_image] at this,
simp only [] at this,
rwa ← sup_Inf_eq at this },
calc (⨅p ∈ set.prod s t, (p : α × α).1 ⊔ p.2) ≤ (⨅a∈s, a ⊔ Inf t) : by simp; exact this
... = Inf s ⊔ Inf t : Inf_sup_eq.symm }
end
theorem Sup_inf_Sup : Sup s ⊓ Sup t = (⨆p ∈ set.prod s t, (p : α × α).1 ⊓ p.2) :=
begin
apply le_antisymm,
{ have : ∀ a ∈ s, a ⊓ Sup t ≤ (⨆p ∈ set.prod s t, (p : α × α).1 ⊓ p.2),
{ assume a ha,
have : (⨆p ∈ prod.mk a '' t, (p : α × α).1 ⊓ p.2)
≤ (⨆p ∈ set.prod s t, ((p : α × α).1 : α) ⊓ p.2),
{ apply supr_le_supr_of_subset,
rintros ⟨x, y⟩,
simp only [and_imp, set.mem_image, prod.mk.inj_iff, set.prod_mk_mem_set_prod_eq,
exists_imp_distrib],
assume x' x't ax x'y,
rw [← x'y, ← ax],
simp [ha, x't] },
rw [supr_image] at this,
simp only [] at this,
rwa ← inf_Sup_eq at this },
calc Sup s ⊓ Sup t = (⨆a∈s, a ⊓ Sup t) : Sup_inf_eq
... ≤ (⨆p ∈ set.prod s t, (p : α × α).1 ⊓ p.2) : by simp; exact this },
{ finish }
end
end complete_distrib_lattice
@[priority 100] -- see Note [lower instance priority]
instance complete_distrib_lattice.bounded_distrib_lattice [d : complete_distrib_lattice α] :
bounded_distrib_lattice α :=
{ le_sup_inf := λ x y z, by rw [← Inf_pair, ← Inf_pair, sup_Inf_eq, ← Inf_image, set.image_pair],
..d }
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A complete boolean algebra is a completely distributive boolean algebra. -/
class complete_boolean_algebra α extends boolean_algebra α, complete_distrib_lattice α
end prio
section complete_boolean_algebra
variables [complete_boolean_algebra α] {a b : α} {s : set α} {f : ι → α}
theorem compl_infi : - infi f = (⨆i, - f i) :=
le_antisymm
(compl_le_of_compl_le $ le_infi $ assume i, compl_le_of_compl_le $ le_supr (λi, - f i) i)
(supr_le $ assume i, compl_le_compl $ infi_le _ _)
theorem compl_supr : - supr f = (⨅i, - f i) :=
compl_inj (by simp [compl_infi])
theorem compl_Inf : - Inf s = (⨆i∈s, - i) :=
by simp [Inf_eq_infi, compl_infi]
theorem compl_Sup : - Sup s = (⨅i∈s, - i) :=
by simp [Sup_eq_supr, compl_supr]
end complete_boolean_algebra
|
302c4255fe9c9fdd65442ea8e9f86f548a3e77b1 | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/data/set/intervals/unordered_interval.lean | d6b7981ceb8589d418f74c457b2e6aa12dbc4b6c | [
"Apache-2.0"
] | permissive | vaibhavkarve/mathlib | a574aaf68c0a431a47fa82ce0637f0f769826bfe | 17f8340912468f49bdc30acdb9a9fa02eeb0473a | refs/heads/master | 1,621,263,802,637 | 1,585,399,588,000 | 1,585,399,588,000 | 250,833,447 | 0 | 0 | Apache-2.0 | 1,585,410,341,000 | 1,585,410,341,000 | null | UTF-8 | Lean | false | false | 5,104 | lean | /-
Copyright (c) 2020 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import data.set.intervals.basic order.bounds
/-!
# Intervals without endpoints ordering
In any decidable linear order `α`, we define the set of elements lying between two elements `a` and
`b` as `Icc (min a b) (max a b)`.
`Icc a b` requires the assumption `a ≤ b` to be meaningful, which is sometimes inconvenient. The
interval as defined in this file is always the set of things lying between `a` and `b`, regardless
of the relative order of `a` and `b`.
For real numbers, `Icc (min a b) (max a b)` is the same as `segment a b`.
## Notation
We use the localized notation `[a, b]` for `interval a b`. One can open the locale `interval` to
make the notation available.
-/
universe u
namespace set
section decidable_linear_order
variables {α : Type u} [decidable_linear_order α] {a a₁ a₂ b b₁ b₂ x : α}
/-- `interval a b` is the set of elements lying between `a` and `b`, with `a` and `b` included. -/
def interval (a b : α) := Icc (min a b) (max a b)
localized "notation `[`a `, ` b `]` := interval a b" in interval
@[simp] lemma interval_of_le (h : a ≤ b) : [a, b] = Icc a b :=
by rw [interval, min_eq_left h, max_eq_right h]
@[simp] lemma interval_of_ge (h : b ≤ a) : [a, b] = Icc b a :=
by { rw [interval, min_eq_right h, max_eq_left h] }
lemma interval_swap (a b : α) : [a, b] = [b, a] :=
or.elim (le_total a b) (by simp {contextual := tt}) (by simp {contextual := tt})
lemma interval_of_lt (h : a < b) : [a, b] = Icc a b :=
interval_of_le (le_of_lt h)
lemma interval_of_gt (h : b < a) : [a, b] = Icc b a :=
interval_of_ge (le_of_lt h)
lemma interval_of_not_le (h : ¬ a ≤ b) : [a, b] = Icc b a :=
interval_of_gt (lt_of_not_ge h)
lemma interval_of_not_ge (h : ¬ b ≤ a) : [a, b] = Icc a b :=
interval_of_lt (lt_of_not_ge h)
@[simp] lemma interval_self : [a, a] = {a} :=
set.ext $ by simp [le_antisymm_iff, and_comm]
@[simp] lemma nonempty_interval : set.nonempty [a, b] :=
by { simp only [interval, min_le_iff, le_max_iff, nonempty_Icc], left, left, refl }
@[simp] lemma left_mem_interval : a ∈ [a, b] :=
by { rw [interval, mem_Icc], exact ⟨min_le_left _ _, le_max_left _ _⟩ }
@[simp] lemma right_mem_interval : b ∈ [a, b] :=
by { rw interval_swap, exact left_mem_interval }
lemma Icc_subset_interval : Icc a b ⊆ [a, b] :=
by { assume x h, rwa interval_of_le, exact le_trans h.1 h.2 }
lemma Icc_subset_interval' : Icc b a ⊆ [a, b] :=
by { rw interval_swap, apply Icc_subset_interval }
lemma mem_interval_of_le (ha : a ≤ x) (hb : x ≤ b) : x ∈ [a, b] :=
Icc_subset_interval ⟨ha, hb⟩
lemma mem_interval_of_ge (hb : b ≤ x) (ha : x ≤ a) : x ∈ [a, b] :=
Icc_subset_interval' ⟨hb, ha⟩
lemma interval_subset_interval (h₁ : a₁ ∈ [a₂, b₂]) (h₂ : b₁ ∈ [a₂, b₂]) : [a₁, b₁] ⊆ [a₂, b₂] :=
Icc_subset_Icc (le_min h₁.1 h₂.1) (max_le h₁.2 h₂.2)
lemma interval_subset_interval_iff_mem : [a₁, b₁] ⊆ [a₂, b₂] ↔ a₁ ∈ [a₂, b₂] ∧ b₁ ∈ [a₂, b₂] :=
iff.intro (λh, ⟨h left_mem_interval, h right_mem_interval⟩) (λ h, interval_subset_interval h.1 h.2)
lemma interval_subset_interval_iff_le :
[a₁, b₁] ⊆ [a₂, b₂] ↔ min a₂ b₂ ≤ min a₁ b₁ ∧ max a₁ b₁ ≤ max a₂ b₂ :=
by { rw [interval, interval, Icc_subset_Icc_iff], exact min_le_max }
lemma interval_subset_interval_right (h : x ∈ [a, b]) : [x, b] ⊆ [a, b] :=
interval_subset_interval h right_mem_interval
lemma interval_subset_interval_left (h : x ∈ [a, b]) : [a, x] ⊆ [a, b] :=
interval_subset_interval left_mem_interval h
lemma bdd_below_bdd_above_iff_subset_interval (s : set α) :
bdd_below s ∧ bdd_above s ↔ ∃ a b, s ⊆ [a, b] :=
begin
rw [bdd_below_bdd_above_iff_subset_Icc],
split,
{ rintro ⟨a, b, h⟩, exact ⟨a, b, λ x hx, Icc_subset_interval (h hx)⟩ },
{ rintro ⟨a, b, h⟩, exact ⟨min a b, max a b, h⟩ }
end
end decidable_linear_order
open_locale interval
section ordered_comm_group
variables {α : Type u} [decidable_linear_ordered_comm_group α] {a b x y : α}
/-- If `[x, y]` is a subinterval of `[a, b]`, then the distance between `x` and `y`
is less than or equal to that of `a` and `b` -/
lemma abs_sub_le_of_subinterval (h : [x, y] ⊆ [a, b]) : abs (y - x) ≤ abs (b - a) :=
begin
rw [← max_sub_min_eq_abs, ← max_sub_min_eq_abs],
rw [interval_subset_interval_iff_le] at h,
exact sub_le_sub h.2 h.1,
end
/-- If `x ∈ [a, b]`, then the distance between `a` and `x` is less than or equal to
that of `a` and `b` -/
lemma abs_sub_left_of_mem_interval (h : x ∈ [a, b]) : abs (x - a) ≤ abs (b - a) :=
abs_sub_le_of_subinterval (interval_subset_interval_left h)
/-- If `x ∈ [a, b]`, then the distance between `x` and `b` is less than or equal to
that of `a` and `b` -/
lemma abs_sub_right_of_mem_interval (h : x ∈ [a, b]) : abs (b - x) ≤ abs (b - a) :=
abs_sub_le_of_subinterval (interval_subset_interval_right h)
end ordered_comm_group
end set
|
3ea4451040499df475b7fe808c0927afd37d0d31 | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /src/geometry/euclidean.lean | ed86989f93abd371d3ea7a824952812e95b50c96 | [
"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 | 29,395 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Joseph Myers.
-/
import analysis.normed_space.real_inner_product
import analysis.normed_space.add_torsor
import linear_algebra.affine_space
import tactic.interval_cases
noncomputable theory
open_locale big_operators
open_locale classical
open_locale real
/-!
# Euclidean spaces
This file defines Euclidean affine spaces.
## Implementation notes
Rather than requiring Euclidean affine spaces to be finite-dimensional
(as in the definition on Wikipedia), this is specified only for those
theorems that need it.
## References
* https://en.wikipedia.org/wiki/Euclidean_space
-/
/-- A `euclidean_affine_space V P` is an affine space with points `P`
over an `inner_product_space V`. -/
abbreviation euclidean_affine_space (V : Type*) (P : Type*) [inner_product_space V]
[metric_space P] :=
normed_add_torsor V P
example (n : Type*) [fintype n] : euclidean_affine_space (euclidean_space n) (euclidean_space n) :=
by apply_instance
namespace inner_product_geometry
/-!
### Geometrical results on real inner product spaces
This section develops some geometrical definitions and results on real
inner product spaces, where those definitions and results can most
conveniently be developed in terms of vectors and then used to deduce
corresponding results for Euclidean affine spaces.
-/
variables {V : Type*} [inner_product_space V]
/-- The undirected angle between two vectors. If either vector is 0,
this is π/2. -/
def angle (x y : V) : ℝ := real.arccos (inner x y / (∥x∥ * ∥y∥))
/-- The cosine of the angle between two vectors. -/
lemma cos_angle (x y : V) : real.cos (angle x y) = inner x y / (∥x∥ * ∥y∥) :=
real.cos_arccos (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).1
(abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).2
/-- The angle between two vectors does not depend on their order. -/
lemma angle_comm (x y : V) : angle x y = angle y x :=
begin
unfold angle,
rw [inner_comm, mul_comm]
end
/-- The angle between the negation of two vectors. -/
@[simp] lemma angle_neg_neg (x y : V) : angle (-x) (-y) = angle x y :=
begin
unfold angle,
rw [inner_neg_neg, norm_neg, norm_neg]
end
/-- The angle between two vectors is nonnegative. -/
lemma angle_nonneg (x y : V) : 0 ≤ angle x y :=
real.arccos_nonneg _
/-- The angle between two vectors is at most π. -/
lemma angle_le_pi (x y : V) : angle x y ≤ π :=
real.arccos_le_pi _
/-- The angle between a vector and the negation of another vector. -/
lemma angle_neg_right (x y : V) : angle x (-y) = π - angle x y :=
begin
unfold angle,
rw [←real.arccos_neg, norm_neg, inner_neg_right, neg_div]
end
/-- The angle between the negation of a vector and another vector. -/
lemma angle_neg_left (x y : V) : angle (-x) y = π - angle x y :=
by rw [←angle_neg_neg, neg_neg, angle_neg_right]
/-- The angle between the zero vector and a vector. -/
@[simp] lemma angle_zero_left (x : V) : angle 0 x = π / 2 :=
begin
unfold angle,
rw [inner_zero_left, zero_div, real.arccos_zero]
end
/-- The angle between a vector and the zero vector. -/
@[simp] lemma angle_zero_right (x : V) : angle x 0 = π / 2 :=
begin
unfold angle,
rw [inner_zero_right, zero_div, real.arccos_zero]
end
/-- The angle between a nonzero vector and itself. -/
@[simp] lemma angle_self {x : V} (hx : x ≠ 0) : angle x x = 0 :=
begin
unfold angle,
rw [←inner_self_eq_norm_square, div_self (λ h, hx (inner_self_eq_zero.1 h)),
real.arccos_one]
end
/-- The angle between a nonzero vector and its negation. -/
@[simp] lemma angle_self_neg_of_nonzero {x : V} (hx : x ≠ 0) : angle x (-x) = π :=
by rw [angle_neg_right, angle_self hx, sub_zero]
/-- The angle between the negation of a nonzero vector and that
vector. -/
@[simp] lemma angle_neg_self_of_nonzero {x : V} (hx : x ≠ 0) : angle (-x) x = π :=
by rw [angle_comm, angle_self_neg_of_nonzero hx]
/-- The angle between a vector and a positive multiple of a vector. -/
@[simp] lemma angle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) :
angle x (r • y) = angle x y :=
begin
unfold angle,
rw [inner_smul_right, norm_smul, real.norm_eq_abs, abs_of_nonneg (le_of_lt hr), ←mul_assoc,
mul_comm _ r, mul_assoc, mul_div_mul_left _ _ (ne_of_gt hr)]
end
/-- The angle between a positive multiple of a vector and a vector. -/
@[simp] lemma angle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) :
angle (r • x) y = angle x y :=
by rw [angle_comm, angle_smul_right_of_pos y x hr, angle_comm]
/-- The angle between a vector and a negative multiple of a vector. -/
@[simp] lemma angle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) :
angle x (r • y) = angle x (-y) :=
by rw [←neg_neg r, neg_smul, angle_neg_right, angle_smul_right_of_pos x y (neg_pos_of_neg hr),
angle_neg_right]
/-- The angle between a negative multiple of a vector and a vector. -/
@[simp] lemma angle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) :
angle (r • x) y = angle (-x) y :=
by rw [angle_comm, angle_smul_right_of_neg y x hr, angle_comm]
/-- The cosine of the angle between two vectors, multiplied by the
product of their norms. -/
lemma cos_angle_mul_norm_mul_norm (x y : V) : real.cos (angle x y) * (∥x∥ * ∥y∥) = inner x y :=
begin
rw cos_angle,
by_cases h : (∥x∥ * ∥y∥) = 0,
{ rw [h, mul_zero],
cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy,
{ rw norm_eq_zero at hx,
rw [hx, inner_zero_left] },
{ rw norm_eq_zero at hy,
rw [hy, inner_zero_right] } },
{ exact div_mul_cancel _ h }
end
/-- The sine of the angle between two vectors, multiplied by the
product of their norms. -/
lemma sin_angle_mul_norm_mul_norm (x y : V) : real.sin (angle x y) * (∥x∥ * ∥y∥) =
real.sqrt (inner x x * inner y y - inner x y * inner x y) :=
begin
unfold angle,
rw [real.sin_arccos (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).1
(abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).2,
←real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)),
←real.sqrt_mul' _ (mul_self_nonneg _), pow_two,
real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), inner_self_eq_norm_square,
inner_self_eq_norm_square],
by_cases h : (∥x∥ * ∥y∥) = 0,
{ rw [(show ∥x∥ * ∥x∥ * (∥y∥ * ∥y∥) = (∥x∥ * ∥y∥) * (∥x∥ * ∥y∥), by ring), h, mul_zero, mul_zero,
zero_sub],
cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy,
{ rw norm_eq_zero at hx,
rw [hx, inner_zero_left, zero_mul, neg_zero] },
{ rw norm_eq_zero at hy,
rw [hy, inner_zero_right, zero_mul, neg_zero] } },
{ field_simp [h],
ring }
end
/-- The angle between two vectors is zero if and only if they are
nonzero and one is a positive multiple of the other. -/
lemma angle_eq_zero_iff (x y : V) : angle x y = 0 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) :=
begin
unfold angle,
rw [←inner_div_norm_mul_norm_eq_one_iff, ←real.arccos_one],
split,
{ intro h,
exact real.arccos_inj (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).1
(abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).2
(by norm_num)
(by norm_num)
h },
{ intro h,
rw h }
end
/-- The angle between two vectors is π if and only if they are nonzero
and one is a negative multiple of the other. -/
lemma angle_eq_pi_iff (x y : V) : angle x y = π ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) :=
begin
unfold angle,
rw [←inner_div_norm_mul_norm_eq_neg_one_iff, ←real.arccos_neg_one],
split,
{ intro h,
exact real.arccos_inj (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).1
(abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).2
(by norm_num)
(by norm_num)
h },
{ intro h,
rw h }
end
/-- If the angle between two vectors is π, the angles between those
vectors and a third vector add to π. -/
lemma angle_add_angle_eq_pi_of_angle_eq_pi {x y : V} (z : V) (h : angle x y = π) :
angle x z + angle y z = π :=
begin
rw angle_eq_pi_iff at h,
rcases h with ⟨hx, ⟨r, ⟨hr, hxy⟩⟩⟩,
rw [hxy, angle_smul_left_of_neg x z hr, angle_neg_left,
add_sub_cancel'_right]
end
/-- Two vectors have inner product 0 if and only if the angle between
them is π/2. -/
lemma inner_eq_zero_iff_angle_eq_pi_div_two (x y : V) : inner x y = 0 ↔ angle x y = π / 2 :=
begin
split,
{ intro h,
unfold angle,
rw [h, zero_div, real.arccos_zero] },
{ intro h,
unfold angle at h,
rw ←real.arccos_zero at h,
have h2 : inner x y / (∥x∥ * ∥y∥) = 0 :=
real.arccos_inj (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).1
(abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).2
(by norm_num)
(by norm_num)
h,
by_cases h : (∥x∥ * ∥y∥) = 0,
{ cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy,
{ rw norm_eq_zero at hx,
rw [hx, inner_zero_left] },
{ rw norm_eq_zero at hy,
rw [hy, inner_zero_right] } },
{ simpa [h, div_eq_zero_iff] using h2 } },
end
/-- Pythagorean theorem, if-and-only-if vector angle form. -/
lemma norm_add_square_eq_norm_square_add_norm_square_iff_angle_eq_pi_div_two (x y : V) :
∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ angle x y = π / 2 :=
begin
rw norm_add_square_eq_norm_square_add_norm_square_iff_inner_eq_zero,
exact inner_eq_zero_iff_angle_eq_pi_div_two x y
end
/-- Pythagorean theorem, vector angle form. -/
lemma norm_add_square_eq_norm_square_add_norm_square' (x y : V) (h : angle x y = π / 2) :
∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ :=
(norm_add_square_eq_norm_square_add_norm_square_iff_angle_eq_pi_div_two x y).2 h
/-- Pythagorean theorem, subtracting vectors, if-and-only-if vector angle form. -/
lemma norm_sub_square_eq_norm_square_add_norm_square_iff_angle_eq_pi_div_two (x y : V) :
∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ angle x y = π / 2 :=
begin
rw norm_sub_square_eq_norm_square_add_norm_square_iff_inner_eq_zero,
exact inner_eq_zero_iff_angle_eq_pi_div_two x y
end
/-- Pythagorean theorem, subtracting vectors, vector angle form. -/
lemma norm_sub_square_eq_norm_square_add_norm_square' (x y : V) (h : angle x y = π / 2) :
∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ :=
(norm_sub_square_eq_norm_square_add_norm_square_iff_angle_eq_pi_div_two x y).2 h
/-- Law of cosines (cosine rule), vector angle form. -/
lemma norm_sub_square_eq_norm_square_add_norm_square_sub_two_mul_norm_mul_norm_mul_cos_angle
(x y : V) :
∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - 2 * ∥x∥ * ∥y∥ * real.cos (angle x y) :=
by rw [(show 2 * ∥x∥ * ∥y∥ * real.cos (angle x y) =
2 * (real.cos (angle x y) * (∥x∥ * ∥y∥)), by ring),
cos_angle_mul_norm_mul_norm, ←inner_self_eq_norm_square,
←inner_self_eq_norm_square, ←inner_self_eq_norm_square, inner_sub_sub_self,
sub_add_eq_add_sub]
/-- Pons asinorum, vector angle form. -/
lemma angle_sub_eq_angle_sub_rev_of_norm_eq {x y : V} (h : ∥x∥ = ∥y∥) :
angle x (x - y) = angle y (y - x) :=
begin
refine real.cos_inj_of_nonneg_of_le_pi (angle_nonneg _ _)
(angle_le_pi _ _)
(angle_nonneg _ _)
(angle_le_pi _ _) _,
rw [cos_angle, cos_angle, h, ←neg_sub, norm_neg, neg_sub,
inner_sub_right, inner_sub_right, inner_self_eq_norm_square, inner_self_eq_norm_square, h,
inner_comm x y]
end
/-- Converse of pons asinorum, vector angle form. -/
lemma norm_eq_of_angle_sub_eq_angle_sub_rev_of_angle_ne_pi {x y : V}
(h : angle x (x - y) = angle y (y - x)) (hpi : angle x y ≠ π) : ∥x∥ = ∥y∥ :=
begin
replace h := real.arccos_inj
(abs_le.mp (abs_inner_div_norm_mul_norm_le_one x (x - y))).1
(abs_le.mp (abs_inner_div_norm_mul_norm_le_one x (x - y))).2
(abs_le.mp (abs_inner_div_norm_mul_norm_le_one y (y - x))).1
(abs_le.mp (abs_inner_div_norm_mul_norm_le_one y (y - x))).2
h,
by_cases hxy : x = y,
{ rw hxy },
{ rw [←norm_neg (y - x), neg_sub, mul_comm, mul_comm ∥y∥, div_eq_mul_inv, div_eq_mul_inv,
mul_inv', mul_inv', ←mul_assoc, ←mul_assoc] at h,
replace h :=
mul_right_cancel' (inv_ne_zero (λ hz, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 hz)))) h,
rw [inner_sub_right, inner_sub_right, inner_comm y x, inner_self_eq_norm_square,
inner_self_eq_norm_square, mul_sub_right_distrib, mul_sub_right_distrib,
mul_self_mul_inv, mul_self_mul_inv, sub_eq_sub_iff_sub_eq_sub,
←mul_sub_left_distrib] at h,
by_cases hx0 : x = 0,
{ rw [hx0, norm_zero, inner_zero_left, zero_mul, zero_sub, neg_eq_zero] at h,
rw [hx0, norm_zero, h] },
{ by_cases hy0 : y = 0,
{ rw [hy0, norm_zero, inner_zero_right, zero_mul, sub_zero] at h,
rw [hy0, norm_zero, h] },
{ rw [inv_sub_inv (λ hz, hx0 (norm_eq_zero.1 hz)) (λ hz, hy0 (norm_eq_zero.1 hz)),
←neg_sub, ←mul_div_assoc, mul_comm, mul_div_assoc, ←mul_neg_one] at h,
symmetry,
by_contradiction hyx,
replace h := (mul_left_cancel' (sub_ne_zero_of_ne hyx) h).symm,
rw [inner_div_norm_mul_norm_eq_neg_one_iff, ←angle_eq_pi_iff] at h,
exact hpi h } } }
end
/-- The cosine of the sum of two angles in a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
real.cos (angle x (x - y) + angle y (y - x)) = -real.cos (angle x y) :=
begin
by_cases hxy : x = y,
{ rw [hxy, angle_self hy],
simp },
{ rw [real.cos_add, cos_angle, cos_angle, cos_angle],
have hxn : ∥x∥ ≠ 0 := (λ h, hx (norm_eq_zero.1 h)),
have hyn : ∥y∥ ≠ 0 := (λ h, hy (norm_eq_zero.1 h)),
have hxyn : ∥x - y∥ ≠ 0 := (λ h, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 h))),
apply mul_right_cancel' hxn,
apply mul_right_cancel' hyn,
apply mul_right_cancel' hxyn,
apply mul_right_cancel' hxyn,
have H1 : real.sin (angle x (x - y)) * real.sin (angle y (y - x)) *
∥x∥ * ∥y∥ * ∥x - y∥ * ∥x - y∥ =
(real.sin (angle x (x - y)) * (∥x∥ * ∥x - y∥)) *
(real.sin (angle y (y - x)) * (∥y∥ * ∥x - y∥)), { ring },
have H2 : inner x x * (inner x x - inner x y - (inner x y - inner y y)) -
(inner x x - inner x y) * (inner x x - inner x y) =
inner x x * inner y y - inner x y * inner x y, { ring },
have H3 : inner y y * (inner y y - inner x y - (inner x y - inner x x)) -
(inner y y - inner x y) * (inner y y - inner x y) =
inner x x * inner y y - inner x y * inner x y, { ring },
rw [mul_sub_right_distrib, mul_sub_right_distrib, mul_sub_right_distrib,
mul_sub_right_distrib, H1, sin_angle_mul_norm_mul_norm, norm_sub_rev x y,
sin_angle_mul_norm_mul_norm, norm_sub_rev y x, inner_sub_left, inner_sub_left,
inner_sub_right, inner_sub_right, inner_sub_right, inner_sub_right, inner_comm y x, H2,
H3, real.mul_self_sqrt (sub_nonneg_of_le (inner_mul_inner_self_le x y)),
inner_self_eq_norm_square, inner_self_eq_norm_square,
inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two],
field_simp [hxn, hyn, hxyn],
ring }
end
/-- The sine of the sum of two angles in a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma sin_angle_sub_add_angle_sub_rev_eq_sin_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
real.sin (angle x (x - y) + angle y (y - x)) = real.sin (angle x y) :=
begin
by_cases hxy : x = y,
{ rw [hxy, angle_self hy],
simp },
{ rw [real.sin_add, cos_angle, cos_angle],
have hxn : ∥x∥ ≠ 0 := (λ h, hx (norm_eq_zero.1 h)),
have hyn : ∥y∥ ≠ 0 := (λ h, hy (norm_eq_zero.1 h)),
have hxyn : ∥x - y∥ ≠ 0 := (λ h, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 h))),
apply mul_right_cancel' hxn,
apply mul_right_cancel' hyn,
apply mul_right_cancel' hxyn,
apply mul_right_cancel' hxyn,
have H1 : real.sin (angle x (x - y)) * (inner y (y - x) / (∥y∥ * ∥y - x∥)) * ∥x∥ * ∥y∥ * ∥x - y∥ =
real.sin (angle x (x - y)) * (∥x∥ * ∥x - y∥) *
(inner y (y - x) / (∥y∥ * ∥y - x∥)) * ∥y∥, { ring },
have H2 : inner x (x - y) / (∥x∥ * ∥y - x∥) * real.sin (angle y (y - x)) * ∥x∥ * ∥y∥ * ∥y - x∥ =
inner x (x - y) / (∥x∥ * ∥y - x∥) *
(real.sin (angle y (y - x)) * (∥y∥ * ∥y - x∥)) * ∥x∥, { ring },
have H3 : inner x x * (inner x x - inner x y - (inner x y - inner y y)) -
(inner x x - inner x y) * (inner x x - inner x y) =
inner x x * inner y y - inner x y * inner x y, { ring },
have H4 : inner y y * (inner y y - inner x y - (inner x y - inner x x)) -
(inner y y - inner x y) * (inner y y - inner x y) =
inner x x * inner y y - inner x y * inner x y, { ring },
rw [right_distrib, right_distrib, right_distrib, right_distrib, H1,
sin_angle_mul_norm_mul_norm, norm_sub_rev x y, H2, sin_angle_mul_norm_mul_norm,
norm_sub_rev y x, mul_assoc (real.sin (angle x y)), sin_angle_mul_norm_mul_norm,
inner_sub_left, inner_sub_left, inner_sub_right, inner_sub_right, inner_sub_right,
inner_sub_right, inner_comm y x, H3, H4, inner_self_eq_norm_square,
inner_self_eq_norm_square,
inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two],
field_simp [hxn, hyn, hxyn],
ring }
end
/-- The cosine of the sum of the angles of a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma cos_angle_add_angle_sub_add_angle_sub_eq_neg_one {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
real.cos (angle x y + angle x (x - y) + angle y (y - x)) = -1 :=
by rw [add_assoc, real.cos_add, cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle hx hy,
sin_angle_sub_add_angle_sub_rev_eq_sin_angle hx hy, ←neg_mul_eq_mul_neg, ←neg_add',
add_comm, ←pow_two, ←pow_two, real.sin_sq_add_cos_sq]
/-- The sine of the sum of the angles of a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma sin_angle_add_angle_sub_add_angle_sub_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
real.sin (angle x y + angle x (x - y) + angle y (y - x)) = 0 :=
begin
rw [add_assoc, real.sin_add, cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle hx hy,
sin_angle_sub_add_angle_sub_rev_eq_sin_angle hx hy],
ring
end
/-- The sum of the angles of a possibly degenerate triangle (where the
two given sides are nonzero), vector angle form. -/
lemma angle_add_angle_sub_add_angle_sub_eq_pi {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
angle x y + angle x (x - y) + angle y (y - x) = π :=
begin
have hcos := cos_angle_add_angle_sub_add_angle_sub_eq_neg_one hx hy,
have hsin := sin_angle_add_angle_sub_add_angle_sub_eq_zero hx hy,
rw real.sin_eq_zero_iff at hsin,
cases hsin with n hn,
symmetry' at hn,
have h0 : 0 ≤ angle x y + angle x (x - y) + angle y (y - x) :=
add_nonneg (add_nonneg (angle_nonneg _ _) (angle_nonneg _ _)) (angle_nonneg _ _),
have h3 : angle x y + angle x (x - y) + angle y (y - x) ≤ π + π + π :=
add_le_add (add_le_add (angle_le_pi _ _) (angle_le_pi _ _)) (angle_le_pi _ _),
have h3lt : angle x y + angle x (x - y) + angle y (y - x) < π + π + π,
{ by_contradiction hnlt,
have hxy : angle x y = π,
{ by_contradiction hxy,
exact hnlt (add_lt_add_of_lt_of_le (add_lt_add_of_lt_of_le
(lt_of_le_of_ne (angle_le_pi _ _) hxy)
(angle_le_pi _ _)) (angle_le_pi _ _)) },
rw hxy at hnlt,
rw angle_eq_pi_iff at hxy,
rcases hxy with ⟨hx, ⟨r, ⟨hr, hxr⟩⟩⟩,
rw [hxr, ←one_smul ℝ x, ←mul_smul, mul_one, ←sub_smul, one_smul, sub_eq_add_neg,
angle_smul_right_of_pos _ _ (add_pos' zero_lt_one (neg_pos_of_neg hr)), angle_self hx,
add_zero] at hnlt,
apply hnlt,
rw add_assoc,
exact add_lt_add_left (lt_of_le_of_lt (angle_le_pi _ _)
(lt_add_of_pos_right π real.pi_pos)) _ },
have hn0 : 0 ≤ n,
{ rw [hn, mul_nonneg_iff_right_nonneg_of_pos real.pi_pos] at h0,
norm_cast at h0,
exact h0 },
have hn3 : n < 3,
{ rw [hn, (show π + π + π = 3 * π, by ring)] at h3lt,
replace h3lt := lt_of_mul_lt_mul_right h3lt (le_of_lt real.pi_pos),
norm_cast at h3lt,
exact h3lt },
interval_cases n,
{ rw hn at hcos,
simp at hcos,
norm_num at hcos },
{ rw hn,
norm_num },
{ rw hn at hcos,
simp at hcos,
norm_num at hcos },
end
end inner_product_geometry
namespace euclidean_geometry
/-!
### Geometrical results on Euclidean affine spaces
This section develops some geometrical definitions and results on
Euclidean affine spaces.
-/
open add_torsor inner_product_geometry
variables (V : Type*) {P : Type*} [inner_product_space V] [metric_space P]
[euclidean_affine_space V P]
include V
/-- The undirected angle at `p2` between the line segments to `p1` and
`p3`. If either of those points equals `p2`, this is π/2. Use
`open_locale euclidean_geometry` to access the `∠ V p1 p2 p3`
notation. -/
def angle (p1 p2 p3 : P) : ℝ := angle (p1 -ᵥ p2 : V) (p3 -ᵥ p2)
localized "notation `∠` := euclidean_geometry.angle" in euclidean_geometry
/-- The angle at a point does not depend on the order of the other two
points. -/
lemma angle_comm (p1 p2 p3 : P) : ∠ V p1 p2 p3 = ∠ V p3 p2 p1 :=
angle_comm _ _
/-- The angle at a point is nonnegative. -/
lemma angle_nonneg (p1 p2 p3 : P) : 0 ≤ ∠ V p1 p2 p3 :=
angle_nonneg _ _
/-- The angle at a point is at most π. -/
lemma angle_le_pi (p1 p2 p3 : P) : ∠ V p1 p2 p3 ≤ π :=
angle_le_pi _ _
/-- The angle ∠AAB at a point. -/
lemma angle_eq_left (p1 p2 : P) : ∠ V p1 p1 p2 = π / 2 :=
begin
unfold angle,
rw vsub_self,
exact angle_zero_left _
end
/-- The angle ∠ABB at a point. -/
lemma angle_eq_right (p1 p2 : P) : ∠ V p1 p2 p2 = π / 2 :=
by rw [angle_comm, angle_eq_left]
/-- The angle ∠ABA at a point. -/
lemma angle_eq_of_ne {p1 p2 : P} (h : p1 ≠ p2) : ∠ V p1 p2 p1 = 0 :=
angle_self (λ he, h ((vsub_eq_zero_iff_eq V).1 he))
/-- If the angle ∠ABC at a point is π, the angle ∠BAC is 0. -/
lemma angle_eq_zero_of_angle_eq_pi_left {p1 p2 p3 : P} (h : ∠ V p1 p2 p3 = π) :
∠ V p2 p1 p3 = 0 :=
begin
unfold angle at h,
rw angle_eq_pi_iff at h,
rcases h with ⟨hp1p2, ⟨r, ⟨hr, hpr⟩⟩⟩,
unfold angle,
rw angle_eq_zero_iff,
rw [←neg_vsub_eq_vsub_rev, neg_ne_zero] at hp1p2,
use [hp1p2, -r + 1, add_pos' (neg_pos_of_neg hr) zero_lt_one],
rw [add_smul, ←neg_vsub_eq_vsub_rev V p1 p2, smul_neg],
simp [←hpr]
end
/-- If the angle ∠ABC at a point is π, the angle ∠BCA is 0. -/
lemma angle_eq_zero_of_angle_eq_pi_right {p1 p2 p3 : P} (h : ∠ V p1 p2 p3 = π) :
∠ V p2 p3 p1 = 0 :=
begin
rw angle_comm at h,
exact angle_eq_zero_of_angle_eq_pi_left V h
end
/-- If ∠BCD = π, then ∠ABC = ∠ABD. -/
lemma angle_eq_angle_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ V p2 p3 p4 = π) :
∠ V p1 p2 p3 = ∠ V p1 p2 p4 :=
begin
unfold angle at h,
rw angle_eq_pi_iff at h,
rcases h with ⟨hp2p3, ⟨r, ⟨hr, hpr⟩⟩⟩,
unfold angle,
symmetry,
convert angle_smul_right_of_pos _ _ (add_pos' (neg_pos_of_neg hr) zero_lt_one),
rw [add_smul, ←neg_vsub_eq_vsub_rev V p2 p3, smul_neg],
simp [←hpr]
end
/-- If ∠BCD = π, then ∠ACB + ∠ACD = π. -/
lemma angle_add_angle_eq_pi_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ V p2 p3 p4 = π) :
∠ V p1 p3 p2 + ∠ V p1 p3 p4 = π :=
begin
unfold angle at h,
rw [angle_comm V p1 p3 p2, angle_comm V p1 p3 p4],
unfold angle,
exact angle_add_angle_eq_pi_of_angle_eq_pi _ h
end
/-- Pythagorean theorem, if-and-only-if angle-at-point form. -/
lemma dist_square_eq_dist_square_add_dist_square_iff_angle_eq_pi_div_two (p1 p2 p3 : P) :
dist p1 p3 * dist p1 p3 = dist p1 p2 * dist p1 p2 + dist p3 p2 * dist p3 p2 ↔
∠ V p1 p2 p3 = π / 2 :=
by erw [metric_space.dist_comm p3 p2, dist_eq_norm V p1 p3, dist_eq_norm V p1 p2,
dist_eq_norm V p2 p3,
←norm_sub_square_eq_norm_square_add_norm_square_iff_angle_eq_pi_div_two,
vsub_sub_vsub_cancel_right V p1, ←neg_vsub_eq_vsub_rev V p2 p3, norm_neg]
/-- Law of cosines (cosine rule), angle-at-point form. -/
lemma dist_square_eq_dist_square_add_dist_square_sub_two_mul_dist_mul_dist_mul_cos_angle
(p1 p2 p3 : P) :
dist p1 p3 * dist p1 p3 =
dist p1 p2 * dist p1 p2 + dist p3 p2 * dist p3 p2 -
2 * dist p1 p2 * dist p3 p2 * real.cos (∠ V p1 p2 p3) :=
begin
rw [dist_eq_norm V p1 p3, dist_eq_norm V p1 p2, dist_eq_norm V p3 p2],
unfold angle,
convert norm_sub_square_eq_norm_square_add_norm_square_sub_two_mul_norm_mul_norm_mul_cos_angle
(p1 -ᵥ p2 : V) (p3 -ᵥ p2 : V),
{ exact (vsub_sub_vsub_cancel_right V p1 p3 p2).symm },
{ exact (vsub_sub_vsub_cancel_right V p1 p3 p2).symm }
end
/-- Pons asinorum, angle-at-point form. -/
lemma angle_eq_angle_of_dist_eq {p1 p2 p3 : P} (h : dist p1 p2 = dist p1 p3) :
∠ V p1 p2 p3 = ∠ V p1 p3 p2 :=
begin
rw [dist_eq_norm V p1 p2, dist_eq_norm V p1 p3] at h,
unfold angle,
convert angle_sub_eq_angle_sub_rev_of_norm_eq h,
{ exact (vsub_sub_vsub_cancel_left V p3 p2 p1).symm },
{ exact (vsub_sub_vsub_cancel_left V p2 p3 p1).symm }
end
/-- Converse of pons asinorum, angle-at-point form. -/
lemma dist_eq_of_angle_eq_angle_of_angle_ne_pi {p1 p2 p3 : P} (h : ∠ V p1 p2 p3 = ∠ V p1 p3 p2)
(hpi : ∠ V p2 p1 p3 ≠ π) : dist p1 p2 = dist p1 p3 :=
begin
unfold angle at h hpi,
rw [dist_eq_norm V p1 p2, dist_eq_norm V p1 p3],
rw [←angle_neg_neg, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] at hpi,
rw [←vsub_sub_vsub_cancel_left V p3 p2 p1, ←vsub_sub_vsub_cancel_left V p2 p3 p1] at h,
exact norm_eq_of_angle_sub_eq_angle_sub_rev_of_angle_ne_pi h hpi
end
/-- The sum of the angles of a possibly degenerate triangle (where the
given vertex is distinct from the others), angle-at-point. -/
lemma angle_add_angle_add_angle_eq_pi {p1 p2 p3 : P} (h2 : p2 ≠ p1) (h3 : p3 ≠ p1) :
∠ V p1 p2 p3 + ∠ V p2 p3 p1 + ∠ V p3 p1 p2 = π :=
begin
rw [add_assoc, add_comm, add_comm (∠ V p2 p3 p1), angle_comm V p2 p3 p1],
unfold angle,
rw [←angle_neg_neg (p1 -ᵥ p3), ←angle_neg_neg (p1 -ᵥ p2), neg_vsub_eq_vsub_rev,
neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev,
←vsub_sub_vsub_cancel_right V p3 p2 p1, ←vsub_sub_vsub_cancel_right V p2 p3 p1],
exact angle_add_angle_sub_add_angle_sub_eq_pi (λ he, h3 ((vsub_eq_zero_iff_eq V).1 he))
(λ he, h2 ((vsub_eq_zero_iff_eq V).1 he))
end
/-- The inner product of two vectors given with `weighted_vsub`, in
terms of the pairwise distances. -/
lemma inner_weighted_vsub {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (p₁ : ι₁ → P)
(h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (p₂ : ι₂ → P)
(h₂ : ∑ i in s₂, w₂ i = 0) :
inner (s₁.weighted_vsub V p₁ w₁) (s₂.weighted_vsub V p₂ w₂) =
(-∑ i₁ in s₁, ∑ i₂ in s₂,
w₁ i₁ * w₂ i₂ * (dist (p₁ i₁) (p₂ i₂) * dist (p₁ i₁) (p₂ i₂))) / 2 :=
begin
rw [finset.weighted_vsub_apply, finset.weighted_vsub_apply,
inner_sum_smul_sum_smul_of_sum_eq_zero _ h₁ _ h₂],
simp_rw [vsub_sub_vsub_cancel_right],
congr,
ext i₁,
congr,
ext i₂,
rw dist_eq_norm V (p₁ i₁) (p₂ i₂)
end
/-- The distance between two points given with `affine_combination`,
in terms of the pairwise distances between the points in that
combination. -/
lemma dist_affine_combination {ι : Type*} {s : finset ι} {w₁ w₂ : ι → ℝ} (p : ι → P)
(h₁ : ∑ i in s, w₁ i = 1) (h₂ : ∑ i in s, w₂ i = 1) :
dist (s.affine_combination V w₁ p) (s.affine_combination V w₂ p) *
dist (s.affine_combination V w₁ p) (s.affine_combination V w₂ p) =
(-∑ i₁ in s, ∑ i₂ in s,
(w₁ - w₂) i₁ * (w₁ - w₂) i₂ * (dist (p i₁) (p i₂) * dist (p i₁) (p i₂))) / 2 :=
begin
rw [dist_eq_norm V (s.affine_combination V w₁ p) (s.affine_combination V w₂ p),
←inner_self_eq_norm_square, finset.affine_combination_vsub],
have h : ∑ i in s, (w₁ - w₂) i = 0,
{ simp_rw [pi.sub_apply, finset.sum_sub_distrib, h₁, h₂, sub_self] },
exact inner_weighted_vsub V p h p h
end
end euclidean_geometry
|
3d266057c906299c11f71b7dd4bd0f705842b408 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1419.lean | a91dbc9e49bed0e7d50704bb5325af7aeb91a1a0 | [
"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 | 216 | lean | def Foo := Nat
def Foo.pow (x : Nat) (k : Nat) : Foo :=
match k with
| 0 => x
| k+1 => pow x k
instance : Pow Foo Nat := ⟨Foo.pow⟩
example (x : Foo) : x ^ 2048 = x := by
show Foo.pow x 2048 = x
sorry
|
edd79fa47c507ece70ae04564960fdf19eb5c36f | c6c5cca3fa72d1c84a604dfd343c976fa72ab6a4 | /test.lean | 1ac43f8392d87ec791cfa2eccf51bee76c620202 | [] | no_license | gebner/demopkg | f838547959c680735f320f3a28a4b49d127727db | ca772819a87cfad01e565d72a65b87d8b4bd8831 | refs/heads/master | 1,611,066,989,285 | 1,492,092,931,000 | 1,492,092,931,000 | 88,172,383 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 49 | lean | import data.list.sort
#eval list.sort [3,1,5,2]
|
3235c6f4c569cae0841dff7605f32f316857ba04 | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/dynamics/ergodic/conservative.lean | 37724a41d6c148029c222b4c1c1194e0cdfb144b | [
"Apache-2.0"
] | permissive | troyjlee/mathlib | e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5 | 45e7eb8447555247246e3fe91c87066506c14875 | refs/heads/master | 1,689,248,035,046 | 1,629,470,528,000 | 1,629,470,528,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,010 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import dynamics.ergodic.measure_preserving
import combinatorics.pigeonhole
/-!
# Conservative systems
In this file we define `f : α → α` to be a *conservative* system w.r.t a measure `μ` if `f` is
non-singular (`measure_theory.quasi_measure_preserving`) and for every measurable set `s` of
positive measure at least one point `x ∈ s` returns back to `s` after some number of iterations of
`f`. There are several properties that look like they are stronger than this one but actually follow
from it:
* `measure_theory.conservative.frequently_measure_inter_ne_zero`,
`measure_theory.conservative.exists_gt_measure_inter_ne_zero`: if `μ s ≠ 0`, then for infinitely
many `n`, the measure of `s ∩ (f^[n]) ⁻¹' s` is positive.
* `measure_theory.conservative.measure_mem_forall_ge_image_not_mem_eq_zero`,
`measure_theory.conservative.ae_mem_imp_frequently_image_mem`: a.e. every point of `s` visits `s`
infinitely many times (Poincaré recurrence theorem).
We also prove the topological Poincaré recurrence theorem
`measure_theory.conservative.ae_frequently_mem_of_mem_nhds`. Let `f : α → α` be a conservative
dynamical system on a topological space with second countable topology and measurable open
sets. Then almost every point `x : α` is recurrent: it visits every neighborhood `s ∈ 𝓝 x`
infinitely many times.
## Tags
conservative dynamical system, Poincare recurrence theorem
-/
noncomputable theory
open classical set filter measure_theory finset function topological_space
open_locale classical topological_space
variables {ι : Type*} {α : Type*} [measurable_space α] {f : α → α} {s : set α} {μ : measure α}
namespace measure_theory
open measure
/-- We say that a non-singular (`measure_theory.quasi_measure_preserving`) self-map is
*conservative* if for any measurable set `s` of positive measure there exists `x ∈ s` such that `x`
returns back to `s` under some iteration of `f`. -/
structure conservative (f : α → α) (μ : measure α . volume_tac)
extends quasi_measure_preserving f μ μ : Prop :=
(exists_mem_image_mem : ∀ ⦃s⦄, measurable_set s → μ s ≠ 0 → ∃ (x ∈ s) (m ≠ 0), f^[m] x ∈ s)
/-- A self-map preserving a finite measure is conservative. -/
protected lemma measure_preserving.conservative [finite_measure μ] (h : measure_preserving f μ μ) :
conservative f μ :=
⟨h.quasi_measure_preserving, λ s hsm h0, h.exists_mem_image_mem hsm h0⟩
namespace conservative
/-- The identity map is conservative w.r.t. any measure. -/
protected lemma id (μ : measure α) : conservative id μ :=
{ to_quasi_measure_preserving := quasi_measure_preserving.id μ,
exists_mem_image_mem := λ s hs h0, let ⟨x, hx⟩ := nonempty_of_measure_ne_zero h0 in
⟨x, hx, 1, one_ne_zero, hx⟩ }
/-- If `f` is a conservative map and `s` is a measurable set of nonzero measure, then
for infinitely many values of `m` a positive measure of points `x ∈ s` returns back to `s`
after `m` iterations of `f`. -/
lemma frequently_measure_inter_ne_zero (hf : conservative f μ) (hs : measurable_set s)
(h0 : μ s ≠ 0) :
∃ᶠ m in at_top, μ (s ∩ (f^[m]) ⁻¹' s) ≠ 0 :=
begin
by_contra H, simp only [not_frequently, eventually_at_top, ne.def, not_not] at H,
rcases H with ⟨N, hN⟩,
induction N with N ihN,
{ apply h0, simpa using hN 0 le_rfl },
rw [imp_false] at ihN, push_neg at ihN,
rcases ihN with ⟨n, hn, hμn⟩,
set T := s ∩ ⋃ n ≥ N + 1, (f^[n]) ⁻¹' s,
have hT : measurable_set T,
from hs.inter (measurable_set.bUnion (countable_encodable _)
(λ _ _, hf.measurable.iterate _ hs)),
have hμT : μ T = 0,
{ convert (measure_bUnion_null_iff $ countable_encodable _).2 hN,
rw ← set.inter_bUnion, refl },
have : μ ((s ∩ (f^[n]) ⁻¹' s) \ T) ≠ 0, by rwa [measure_diff_null hμT],
rcases hf.exists_mem_image_mem ((hs.inter (hf.measurable.iterate n hs)).diff hT) this
with ⟨x, ⟨⟨hxs, hxn⟩, hxT⟩, m, hm0, ⟨hxms, hxm⟩, hxx⟩,
refine hxT ⟨hxs, mem_bUnion_iff.2 ⟨n + m, _, _⟩⟩,
{ exact add_le_add hn (nat.one_le_of_lt $ pos_iff_ne_zero.2 hm0) },
{ rwa [set.mem_preimage, ← iterate_add_apply] at hxm }
end
/-- If `f` is a conservative map and `s` is a measurable set of nonzero measure, then
for an arbitrarily large `m` a positive measure of points `x ∈ s` returns back to `s`
after `m` iterations of `f`. -/
lemma exists_gt_measure_inter_ne_zero (hf : conservative f μ) (hs : measurable_set s) (h0 : μ s ≠ 0)
(N : ℕ) :
∃ m > N, μ (s ∩ (f^[m]) ⁻¹' s) ≠ 0 :=
let ⟨m, hm, hmN⟩ :=
((hf.frequently_measure_inter_ne_zero hs h0).and_eventually (eventually_gt_at_top N)).exists
in ⟨m, hmN, hm⟩
/-- Poincaré recurrence theorem: given a conservative map `f` and a measurable set `s`, the set
of points `x ∈ s` such that `x` does not return to `s` after `≥ n` iterations has measure zero. -/
lemma measure_mem_forall_ge_image_not_mem_eq_zero (hf : conservative f μ) (hs : measurable_set s)
(n : ℕ) :
μ {x ∈ s | ∀ m ≥ n, f^[m] x ∉ s} = 0 :=
begin
by_contradiction H,
have : measurable_set (s ∩ {x | ∀ m ≥ n, f^[m] x ∉ s}),
{ simp only [set_of_forall, ← compl_set_of],
exact hs.inter (measurable_set.bInter (countable_encodable _)
(λ m _, hf.measurable.iterate m hs.compl)) },
rcases (hf.exists_gt_measure_inter_ne_zero this H) n with ⟨m, hmn, hm⟩,
rcases nonempty_of_measure_ne_zero hm with ⟨x, ⟨hxs, hxn⟩, hxm, -⟩,
exact hxn m hmn.lt.le hxm
end
/-- Poincaré recurrence theorem: given a conservative map `f` and a measurable set `s`,
almost every point `x ∈ s` returns back to `s` infinitely many times. -/
lemma ae_mem_imp_frequently_image_mem (hf : conservative f μ) (hs : measurable_set s) :
∀ᵐ x ∂μ, x ∈ s → ∃ᶠ n in at_top, (f^[n] x) ∈ s :=
begin
simp only [frequently_at_top, @forall_swap (_ ∈ s), ae_all_iff],
intro n,
filter_upwards [measure_zero_iff_ae_nmem.1 (hf.measure_mem_forall_ge_image_not_mem_eq_zero hs n)],
simp
end
lemma inter_frequently_image_mem_ae_eq (hf : conservative f μ) (hs : measurable_set s) :
(s ∩ {x | ∃ᶠ n in at_top, f^[n] x ∈ s} : set α) =ᵐ[μ] s :=
inter_eventually_eq_left.2 $ hf.ae_mem_imp_frequently_image_mem hs
lemma measure_inter_frequently_image_mem_eq (hf : conservative f μ) (hs : measurable_set s) :
μ (s ∩ {x | ∃ᶠ n in at_top, f^[n] x ∈ s}) = μ s :=
measure_congr (hf.inter_frequently_image_mem_ae_eq hs)
/-- Poincaré recurrence theorem: if `f` is a conservative dynamical system and `s` is a measurable
set, then for `μ`-a.e. `x`, if the orbit of `x` visits `s` at least once, then it visits `s`
infinitely many times. -/
lemma ae_forall_image_mem_imp_frequently_image_mem (hf : conservative f μ) (hs : measurable_set s) :
∀ᵐ x ∂μ, ∀ k, f^[k] x ∈ s → ∃ᶠ n in at_top, (f^[n] x) ∈ s :=
begin
refine ae_all_iff.2 (λ k, _),
refine (hf.ae_mem_imp_frequently_image_mem (hf.measurable.iterate k hs)).mono (λ x hx hk, _),
rw [← map_add_at_top_eq_nat k, frequently_map],
refine (hx hk).mono (λ n hn, _),
rwa [add_comm, iterate_add_apply]
end
/-- If `f` is a conservative self-map and `s` is a measurable set of positive measure, then
`μ.ae`-frequently we have `x ∈ s` and `s` returns to `s` under infinitely many iterations of `f`. -/
lemma frequently_ae_mem_and_frequently_image_mem (hf : conservative f μ) (hs : measurable_set s)
(h0 : μ s ≠ 0) :
∃ᵐ x ∂μ, x ∈ s ∧ ∃ᶠ n in at_top, (f^[n] x) ∈ s :=
((frequently_ae_mem_iff.2 h0).and_eventually (hf.ae_mem_imp_frequently_image_mem hs)).mono $ λ x hx,
⟨hx.1, hx.2 hx.1⟩
/-- Poincaré recurrence theorem. Let `f : α → α` be a conservative dynamical system on a topological
space with second countable topology and measurable open sets. Then almost every point `x : α`
is recurrent: it visits every neighborhood `s ∈ 𝓝 x` infinitely many times. -/
lemma ae_frequently_mem_of_mem_nhds [topological_space α] [second_countable_topology α]
[opens_measurable_space α] {f : α → α} {μ : measure α} (h : conservative f μ) :
∀ᵐ x ∂μ, ∀ s ∈ 𝓝 x, ∃ᶠ n in at_top, f^[n] x ∈ s :=
begin
have : ∀ s ∈ countable_basis α, ∀ᵐ x ∂μ, x ∈ s → ∃ᶠ n in at_top, (f^[n] x) ∈ s,
from λ s hs, h.ae_mem_imp_frequently_image_mem
(is_open_of_mem_countable_basis hs).measurable_set,
refine ((ae_ball_iff $ countable_countable_basis α).2 this).mono (λ x hx s hs, _),
rcases (is_basis_countable_basis α).mem_nhds_iff.1 hs with ⟨o, hoS, hxo, hos⟩,
exact (hx o hoS hxo).mono (λ n hn, hos hn)
end
/-- Iteration of a conservative system is a conservative system. -/
protected lemma iterate (hf : conservative f μ) (n : ℕ) : conservative (f^[n]) μ :=
begin
cases n, { exact conservative.id μ }, -- Discharge the trivial case `n = 0`
refine ⟨hf.1.iterate _, λ s hs hs0, _⟩,
rcases (hf.frequently_ae_mem_and_frequently_image_mem hs hs0).exists with ⟨x, hxs, hx⟩,
/- We take a point `x ∈ s` such that `f^[k] x ∈ s` for infinitely many values of `k`,
then we choose two of these values `k < l` such that `k ≡ l [MOD (n + 1)]`.
Then `f^[k] x ∈ s` and `(f^[n + 1])^[(l - k) / (n + 1)] (f^[k] x) = f^[l] x ∈ s`. -/
rw nat.frequently_at_top_iff_infinite at hx,
rcases nat.exists_lt_modeq_of_infinite hx n.succ_pos with ⟨k, hk, l, hl, hkl, hn⟩,
set m := (l - k) / (n + 1),
have : (n + 1) * m = l - k,
{ apply nat.mul_div_cancel',
exact (nat.modeq_iff_dvd' hkl.le).1 hn },
refine ⟨f^[k] x, hk, m, _, _⟩,
{ intro hm,
rw [hm, mul_zero, eq_comm, nat.sub_eq_zero_iff_le] at this,
exact this.not_lt hkl },
{ rwa [← iterate_mul, this, ← iterate_add_apply, nat.sub_add_cancel],
exact hkl.le }
end
end conservative
end measure_theory
|
7a59f6db57e78404ebf80c68b9da53ec88014ebd | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/data/setoid/partition.lean | dd9093e8ab14c2cccd4967218b59481828d314bd | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,898 | lean | /-
Copyright (c) 2019 Amelia Livingston. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Amelia Livingston, Bryan Gin-ge Chen, Patrick Massot
-/
import data.setoid.basic
import data.set.pairwise
/-!
# Equivalence relations: partitions
This file comprises properties of equivalence relations viewed as partitions.
There are two implementations of partitions here:
* A collection `c : set (set α)` of sets is a partition of `α` if `∅ ∉ c` and each element `a : α`
belongs to a unique set `b ∈ c`. This is expressed as `is_partition c`
* An indexed partition is a map `s : ι → α` whose image is a partition. This is
expressed as `indexed_partition s`.
Of course both implementations are related to `quotient` and `setoid`.
## Tags
setoid, equivalence, iseqv, relation, equivalence relation, partition, equivalence class
-/
namespace setoid
variables {α : Type*}
/-- If x ∈ α is in 2 elements of a set of sets partitioning α, those 2 sets are equal. -/
lemma eq_of_mem_eqv_class {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b)
{x b b'} (hc : b ∈ c) (hb : x ∈ b) (hc' : b' ∈ c) (hb' : x ∈ b') :
b = b' :=
(H x).unique2 hc hb hc' hb'
/-- Makes an equivalence relation from a set of sets partitioning α. -/
def mk_classes (c : set (set α)) (H : ∀ a, ∃! b ∈ c, a ∈ b) :
setoid α :=
⟨λ x y, ∀ s ∈ c, x ∈ s → y ∈ s, ⟨λ _ _ _ hx, hx,
λ x y h s hs hy, (H x).elim2 $ λ t ht hx _,
have s = t, from eq_of_mem_eqv_class H hs hy ht (h t ht hx),
this.symm ▸ hx,
λ x y z h1 h2 s hs hx, (H y).elim2 $ λ t ht hy _, (H z).elim2 $ λ t' ht' hz _,
have hst : s = t, from eq_of_mem_eqv_class H hs (h1 _ hs hx) ht hy,
have htt' : t = t', from eq_of_mem_eqv_class H ht (h2 _ ht hy) ht' hz,
(hst.trans htt').symm ▸ hz⟩⟩
/-- Makes the equivalence classes of an equivalence relation. -/
def classes (r : setoid α) : set (set α) :=
{s | ∃ y, s = {x | r.rel x y}}
lemma mem_classes (r : setoid α) (y) : {x | r.rel x y} ∈ r.classes := ⟨y, rfl⟩
/-- Two equivalence relations are equal iff all their equivalence classes are equal. -/
lemma eq_iff_classes_eq {r₁ r₂ : setoid α} :
r₁ = r₂ ↔ ∀ x, {y | r₁.rel x y} = {y | r₂.rel x y} :=
⟨λ h x, h ▸ rfl, λ h, ext' $ λ x, set.ext_iff.1 $ h x⟩
lemma rel_iff_exists_classes (r : setoid α) {x y} :
r.rel x y ↔ ∃ c ∈ r.classes, x ∈ c ∧ y ∈ c :=
⟨λ h, ⟨_, r.mem_classes y, h, r.refl' y⟩,
λ ⟨c, ⟨z, hz⟩, hx, hy⟩, by { subst c, exact r.trans' hx (r.symm' hy) }⟩
/-- Two equivalence relations are equal iff their equivalence classes are equal. -/
lemma classes_inj {r₁ r₂ : setoid α} :
r₁ = r₂ ↔ r₁.classes = r₂.classes :=
⟨λ h, h ▸ rfl, λ h, ext' $ λ a b, by simp only [rel_iff_exists_classes, exists_prop, h] ⟩
/-- The empty set is not an equivalence class. -/
lemma empty_not_mem_classes {r : setoid α} : ∅ ∉ r.classes :=
λ ⟨y, hy⟩, set.not_mem_empty y $ hy.symm ▸ r.refl' y
/-- Equivalence classes partition the type. -/
lemma classes_eqv_classes {r : setoid α} (a) : ∃! b ∈ r.classes, a ∈ b :=
exists_unique.intro2 {x | r.rel x a} (r.mem_classes a) (r.refl' _) $
begin
rintros _ ⟨y, rfl⟩ ha,
ext x,
exact ⟨λ hx, r.trans' hx (r.symm' ha), λ hx, r.trans' hx ha⟩
end
/-- If x ∈ α is in 2 equivalence classes, the equivalence classes are equal. -/
lemma eq_of_mem_classes {r : setoid α} {x b} (hc : b ∈ r.classes)
(hb : x ∈ b) {b'} (hc' : b' ∈ r.classes) (hb' : x ∈ b') : b = b' :=
eq_of_mem_eqv_class classes_eqv_classes hc hb hc' hb'
/-- The elements of a set of sets partitioning α are the equivalence classes of the
equivalence relation defined by the set of sets. -/
lemma eq_eqv_class_of_mem {c : set (set α)}
(H : ∀ a, ∃! b ∈ c, a ∈ b) {s y} (hs : s ∈ c) (hy : y ∈ s) :
s = {x | (mk_classes c H).rel x y} :=
set.ext $ λ x,
⟨λ hs', symm' (mk_classes c H) $ λ b' hb' h', eq_of_mem_eqv_class H hs hy hb' h' ▸ hs',
λ hx, (H x).elim2 $ λ b' hc' hb' h',
(eq_of_mem_eqv_class H hs hy hc' $ hx b' hc' hb').symm ▸ hb'⟩
/-- The equivalence classes of the equivalence relation defined by a set of sets
partitioning α are elements of the set of sets. -/
lemma eqv_class_mem {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {y} :
{x | (mk_classes c H).rel x y} ∈ c :=
(H y).elim2 $ λ b hc hy hb, eq_eqv_class_of_mem H hc hy ▸ hc
lemma eqv_class_mem' {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {x} :
{y : α | (mk_classes c H).rel x y} ∈ c :=
by { convert setoid.eqv_class_mem H, ext, rw setoid.comm' }
/-- Distinct elements of a set of sets partitioning α are disjoint. -/
lemma eqv_classes_disjoint {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) :
c.pairwise_disjoint :=
λ b₁ h₁ b₂ h₂ h, set.disjoint_left.2 $
λ x hx1 hx2, (H x).elim2 $ λ b hc hx hb, h $ eq_of_mem_eqv_class H h₁ hx1 h₂ hx2
/-- A set of disjoint sets covering α partition α (classical). -/
lemma eqv_classes_of_disjoint_union {c : set (set α)}
(hu : set.sUnion c = @set.univ α) (H : c.pairwise_disjoint) (a) :
∃! b ∈ c, a ∈ b :=
let ⟨b, hc, ha⟩ := set.mem_sUnion.1 $ show a ∈ _, by rw hu; exact set.mem_univ a in
exists_unique.intro2 b hc ha $ λ b' hc' ha', H.elim_set hc' hc a ha' ha
/-- Makes an equivalence relation from a set of disjoints sets covering α. -/
def setoid_of_disjoint_union {c : set (set α)} (hu : set.sUnion c = @set.univ α)
(H : c.pairwise_disjoint) : setoid α :=
setoid.mk_classes c $ eqv_classes_of_disjoint_union hu H
/-- The equivalence relation made from the equivalence classes of an equivalence
relation r equals r. -/
theorem mk_classes_classes (r : setoid α) :
mk_classes r.classes classes_eqv_classes = r :=
ext' $ λ x y, ⟨λ h, r.symm' (h {z | r.rel z x} (r.mem_classes x) $ r.refl' x),
λ h b hb hx, eq_of_mem_classes (r.mem_classes x) (r.refl' x) hb hx ▸ r.symm' h⟩
@[simp] theorem sUnion_classes (r : setoid α) : ⋃₀ r.classes = set.univ :=
set.eq_univ_of_forall $ λ x, set.mem_sUnion.2 ⟨{ y | r.rel y x }, ⟨x, rfl⟩, setoid.refl _⟩
section partition
/-- A collection `c : set (set α)` of sets is a partition of `α` into pairwise
disjoint sets if `∅ ∉ c` and each element `a : α` belongs to a unique set `b ∈ c`. -/
def is_partition (c : set (set α)) :=
∅ ∉ c ∧ ∀ a, ∃! b ∈ c, a ∈ b
/-- A partition of `α` does not contain the empty set. -/
lemma nonempty_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (h : s ∈ c) :
s.nonempty :=
set.ne_empty_iff_nonempty.1 $ λ hs0, hc.1 $ hs0 ▸ h
lemma is_partition_classes (r : setoid α) : is_partition r.classes :=
⟨empty_not_mem_classes, classes_eqv_classes⟩
lemma is_partition.pairwise_disjoint {c : set (set α)} (hc : is_partition c) :
c.pairwise_disjoint :=
eqv_classes_disjoint hc.2
lemma is_partition.sUnion_eq_univ {c : set (set α)} (hc : is_partition c) :
⋃₀ c = set.univ :=
set.eq_univ_of_forall $ λ x, set.mem_sUnion.2 $
let ⟨t, ht⟩ := hc.2 x in ⟨t, by clear_aux_decl; finish⟩
/-- All elements of a partition of α are the equivalence class of some y ∈ α. -/
lemma exists_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (hs : s ∈ c) :
∃ y, s = {x | (mk_classes c hc.2).rel x y} :=
let ⟨y, hy⟩ := nonempty_of_mem_partition hc hs in
⟨y, eq_eqv_class_of_mem hc.2 hs hy⟩
/-- The equivalence classes of the equivalence relation defined by a partition of α equal
the original partition. -/
theorem classes_mk_classes (c : set (set α)) (hc : is_partition c) :
(mk_classes c hc.2).classes = c :=
set.ext $ λ s,
⟨λ ⟨y, hs⟩, (hc.2 y).elim2 $ λ b hm hb hy,
by rwa (show s = b, from hs.symm ▸ set.ext
(λ x, ⟨λ hx, symm' (mk_classes c hc.2) hx b hm hb,
λ hx b' hc' hx', eq_of_mem_eqv_class hc.2 hm hx hc' hx' ▸ hb⟩)),
exists_of_mem_partition hc⟩
/-- Defining `≤` on partitions as the `≤` defined on their induced equivalence relations. -/
instance partition.le : has_le (subtype (@is_partition α)) :=
⟨λ x y, mk_classes x.1 x.2.2 ≤ mk_classes y.1 y.2.2⟩
/-- Defining a partial order on partitions as the partial order on their induced
equivalence relations. -/
instance partition.partial_order : partial_order (subtype (@is_partition α)) :=
{ le := (≤),
lt := λ x y, x ≤ y ∧ ¬y ≤ x,
le_refl := λ _, @le_refl (setoid α) _ _,
le_trans := λ _ _ _, @le_trans (setoid α) _ _ _ _,
lt_iff_le_not_le := λ _ _, iff.rfl,
le_antisymm := λ x y hx hy, let h := @le_antisymm (setoid α) _ _ _ hx hy in by
rw [subtype.ext_iff_val, ←classes_mk_classes x.1 x.2, ←classes_mk_classes y.1 y.2, h] }
variables (α)
/-- The order-preserving bijection between equivalence relations on a type `α`, and
partitions of `α` into subsets. -/
protected def partition.order_iso :
setoid α ≃o {C : set (set α) // is_partition C} :=
{ to_fun := λ r, ⟨r.classes, empty_not_mem_classes, classes_eqv_classes⟩,
inv_fun := λ C, mk_classes C.1 C.2.2,
left_inv := mk_classes_classes,
right_inv := λ C, by rw [subtype.ext_iff_val, ←classes_mk_classes C.1 C.2],
map_rel_iff' := λ r s,
by { conv_rhs { rw [←mk_classes_classes r, ←mk_classes_classes s] }, refl } }
variables {α}
/-- A complete lattice instance for partitions; there is more infrastructure for the
equivalent complete lattice on equivalence relations. -/
instance partition.complete_lattice : complete_lattice (subtype (@is_partition α)) :=
galois_insertion.lift_complete_lattice $ @order_iso.to_galois_insertion
_ (subtype (@is_partition α)) _ (partial_order.to_preorder _) $ partition.order_iso α
end partition
end setoid
/-- Constructive information associated with a partition of a type `α` indexed by another type `ι`,
`s : ι → set α`.
`indexed_partition.index` sends an element to its index, while `indexed_partition.some` sends
an index to an element of the corresponding set.
This type is primarily useful for definitional control of `s` - if this is not needed, then
`setoid.ker index` by itself may be sufficient. -/
structure indexed_partition {ι α : Type*} (s : ι → set α) :=
(eq_of_mem : ∀ {x i j}, x ∈ s i → x ∈ s j → i = j)
(some : ι → α)
(some_mem : ∀ i, some i ∈ s i)
(index : α → ι)
(mem_index : ∀ x, x ∈ s (index x))
/-- The non-constructive constructor for `indexed_partition`. -/
noncomputable
def indexed_partition.mk' {ι α : Type*} (s : ι → set α) (dis : ∀ i j, i ≠ j → disjoint (s i) (s j))
(nonempty : ∀ i, (s i).nonempty) (ex : ∀ x, ∃ i, x ∈ s i) : indexed_partition s :=
{ eq_of_mem := λ x i j hxi hxj, classical.by_contradiction $ λ h, dis _ _ h ⟨hxi, hxj⟩,
some := λ i, (nonempty i).some,
some_mem := λ i, (nonempty i).some_spec,
index := λ x, (ex x).some,
mem_index := λ x, (ex x).some_spec }
namespace indexed_partition
open set
variables {ι α : Type*} {s : ι → set α} (hs : indexed_partition s)
/-- On a unique index set there is the obvious trivial partition -/
instance [unique ι] [inhabited α] :
inhabited (indexed_partition (λ i : ι, (set.univ : set α))) :=
⟨{ eq_of_mem := λ x i j hi hj, subsingleton.elim _ _,
some := λ i, default α,
some_mem := set.mem_univ,
index := λ a, default ι,
mem_index := set.mem_univ }⟩
attribute [simp] some_mem mem_index
include hs
lemma exists_mem (x : α) : ∃ i, x ∈ s i := ⟨hs.index x, hs.mem_index x⟩
lemma Union : (⋃ i, s i) = univ :=
by { ext x, simp [hs.exists_mem x] }
lemma disjoint : ∀ {i j}, i ≠ j → disjoint (s i) (s j) :=
λ i j h x ⟨hxi, hxj⟩, h (hs.eq_of_mem hxi hxj)
lemma mem_iff_index_eq {x i} : x ∈ s i ↔ hs.index x = i :=
⟨λ hxi, (hs.eq_of_mem hxi (hs.mem_index x)).symm, λ h, h ▸ hs.mem_index _⟩
lemma eq (i) : s i = {x | hs.index x = i} :=
set.ext $ λ _, hs.mem_iff_index_eq
/-- The equivalence relation associated to an indexed partition. Two
elements are equivalent if they belong to the same set of the partition. -/
protected abbreviation setoid (hs : indexed_partition s) : setoid α :=
setoid.ker hs.index
@[simp] lemma index_some (i : ι) : hs.index (hs.some i) = i :=
(mem_iff_index_eq _).1 $ hs.some_mem i
lemma some_index (x : α) : hs.setoid.rel (hs.some (hs.index x)) x :=
hs.index_some (hs.index x)
/-- The quotient associated to an indexed partition. -/
protected def quotient := quotient hs.setoid
/-- The projection onto the quotient associated to an indexed partition. -/
def proj : α → hs.quotient := quotient.mk'
instance [inhabited α] : inhabited (hs.quotient) := ⟨hs.proj (default α)⟩
lemma proj_eq_iff {x y : α} : hs.proj x = hs.proj y ↔ hs.index x = hs.index y :=
quotient.eq_rel
@[simp] lemma proj_some_index (x : α) : hs.proj (hs.some (hs.index x)) = hs.proj x :=
quotient.eq'.2 (hs.some_index x)
/-- The obvious equivalence between the quotient associated to an indexed partition and
the indexing type. -/
def equiv_quotient : ι ≃ hs.quotient :=
(setoid.quotient_ker_equiv_of_right_inverse hs.index hs.some $ hs.index_some).symm
@[simp] lemma equiv_quotient_index_apply (x : α) : hs.equiv_quotient (hs.index x) = hs.proj x :=
hs.proj_eq_iff.mpr (some_index hs x)
@[simp] lemma equiv_quotient_symm_proj_apply (x : α) :
hs.equiv_quotient.symm (hs.proj x) = hs.index x :=
rfl
lemma equiv_quotient_index : hs.equiv_quotient ∘ hs.index = hs.proj :=
funext hs.equiv_quotient_index_apply
/-- A map choosing a representative for each element of the quotient associated to an indexed
partition. This is a computable version of `quotient.out'` using `indexed_partition.some`. -/
def out : hs.quotient ↪ α :=
hs.equiv_quotient.symm.to_embedding.trans ⟨hs.some, function.left_inverse.injective hs.index_some⟩
/-- This lemma is analogous to `quotient.mk_out'`. -/
@[simp]
lemma out_proj (x : α) : hs.out (hs.proj x) = hs.some (hs.index x) :=
rfl
/-- The indices of `quotient.out'` and `indexed_partition.out` are equal. -/
lemma index_out' (x : hs.quotient) : hs.index (x.out') = hs.index (hs.out x) :=
quotient.induction_on' x $ λ x, (setoid.ker_apply_mk_out' x).trans (hs.index_some _).symm
/-- This lemma is analogous to `quotient.out_eq'`. -/
@[simp] lemma proj_out (x : hs.quotient) : hs.proj (hs.out x) = x :=
quotient.induction_on' x $ λ x, quotient.sound' $ hs.some_index x
lemma class_of {x : α} : set_of (hs.setoid.rel x) = s (hs.index x) :=
set.ext $ λ y, eq_comm.trans hs.mem_iff_index_eq.symm
lemma proj_fiber (x : hs.quotient) : hs.proj ⁻¹' {x} = s (hs.equiv_quotient.symm x) :=
quotient.induction_on' x $ λ x, begin
ext y,
simp only [set.mem_preimage, set.mem_singleton_iff, hs.mem_iff_index_eq],
exact quotient.eq',
end
end indexed_partition
|
eeb642e94257c2fedd692a6a4b28965fecd3abef | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/ind5.lean | abf0251f520fc3fb3adeed3a2489996ecb75b5b8 | [
"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 | 174 | lean | prelude
definition Prop : Type.{1} := Type.{0}
inductive or (A B : Prop) : Prop
| intro_left : A → or
| intro_right : B → or
check or
check or.intro_left
check or.rec
|
2b81926e2329765560891174a976bc3243917def | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/simpPartialApp.lean | 12a8be78a08321fc8eb70d99730619250adb200b | [
"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 | 205 | lean | variable {U V}
def f : (U → V) → (U → U) := sorry
def add {U} : U → U → U := sorry
@[simp] theorem foo (u : U) : f (add u) = id := sorry
def bar (u v : U) : f (add u) v = id v := by
simp
|
47a721c828f0976fe195a3dad6a0bfdc6e058424 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/control/random.lean | d5e327be1af5c73e3e521948295cb186fdf965cd | [
"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,771 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import control.monad.basic
import data.int.basic
import data.stream.defs
import control.uliftable
import tactic.norm_num
import data.bitvec.basic
/-!
# Rand Monad and Random Class
This module provides tools for formulating computations guided by randomness and for
defining objects that can be created randomly.
## Main definitions
* `rand` monad for computations guided by randomness;
* `random` class for objects that can be generated randomly;
* `random` to generate one object;
* `random_r` to generate one object inside a range;
* `random_series` to generate an infinite series of objects;
* `random_series_r` to generate an infinite series of objects inside a range;
* `io.mk_generator` to create a new random number generator;
* `io.run_rand` to run a randomized computation inside the `io` monad;
* `tactic.run_rand` to run a randomized computation inside the `tactic` monad
## Local notation
* `i .. j` : `Icc i j`, the set of values between `i` and `j` inclusively;
## Tags
random monad io
## References
* Similar library in Haskell: https://hackage.haskell.org/package/MonadRandom
-/
open list io applicative
universes u v w
/-- A monad to generate random objects using the generator type `g` -/
@[reducible]
def rand_g (g : Type) (α : Type u) : Type u := state (ulift.{u} g) α
/-- A monad to generate random objects using the generator type `std_gen` -/
@[reducible]
def rand := rand_g std_gen
instance (g : Type) : uliftable (rand_g.{u} g) (rand_g.{v} g) :=
@state_t.uliftable' _ _ _ _ _ (equiv.ulift.trans.{u u u u u} equiv.ulift.symm)
open ulift (hiding inhabited)
/-- Generate one more `ℕ` -/
def rand_g.next {g : Type} [random_gen g] : rand_g g ℕ :=
⟨ prod.map id up ∘ random_gen.next ∘ down ⟩
local infix ` .. `:41 := set.Icc
open stream
/-- `bounded_random α` gives us machinery to generate values of type `α` between certain bounds -/
class bounded_random (α : Type u) [preorder α] :=
(random_r : Π g [random_gen g] (x y : α),
(x ≤ y) → rand_g g (x .. y))
/-- `random α` gives us machinery to generate values of type `α` -/
class random (α : Type u) :=
(random [] : Π (g : Type) [random_gen g], rand_g g α)
/-- shift_31_left = 2^31; multiplying by it shifts the binary
representation of a number left by 31 bits, dividing by it shifts it
right by 31 bits -/
def shift_31_left : ℕ :=
by apply_normed 2^31
namespace rand
open stream
variables (α : Type u)
variables (g : Type) [random_gen g]
/-- create a new random number generator distinct from the one stored in the state -/
def split : rand_g g g := ⟨ prod.map id up ∘ random_gen.split ∘ down ⟩
variables {g}
section random
variables [random α]
export random (random)
/-- Generate a random value of type `α`. -/
def random : rand_g g α :=
random.random α g
/-- generate an infinite series of random values of type `α` -/
def random_series : rand_g g (stream α) :=
do gen ← uliftable.up (split g),
pure $ stream.corec_state (random.random α g) gen
end random
variables {α}
/-- Generate a random value between `x` and `y` inclusive. -/
def random_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) : rand_g g (x .. y) :=
bounded_random.random_r g x y h
/-- generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/
def random_series_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) :
rand_g g (stream (x .. y)) :=
do gen ← uliftable.up (split g),
pure $ corec_state (bounded_random.random_r g x y h) gen
end rand
namespace io
private def accum_char (w : ℕ) (c : char) : ℕ :=
c.to_nat + 256 * w
/-- create and a seed a random number generator -/
def mk_generator : io std_gen := do
seed ← io.rand 0 shift_31_left,
return $ mk_std_gen seed
variables {α : Type}
/-- Run `cmd` using a randomly seeded random number generator -/
def run_rand (cmd : _root_.rand α) : io α :=
do g ← io.mk_generator,
return $ (cmd.run ⟨g⟩).1
/-- Run `cmd` using the provided seed. -/
def run_rand_with (seed : ℕ) (cmd : _root_.rand α) : io α :=
return $ (cmd.run ⟨mk_std_gen seed⟩).1
section random
variables [random α]
/-- randomly generate a value of type α -/
def random : io α :=
io.run_rand (rand.random α)
/-- randomly generate an infinite series of value of type α -/
def random_series : io (stream α) :=
io.run_rand (rand.random_series α)
end random
section bounded_random
variables [preorder α] [bounded_random α]
/-- randomly generate a value of type α between `x` and `y` -/
def random_r (x y : α) (p : x ≤ y) : io (x .. y) :=
io.run_rand (bounded_random.random_r _ x y p)
/-- randomly generate an infinite series of value of type α between `x` and `y` -/
def random_series_r (x y : α) (h : x ≤ y) : io (stream $ x .. y) :=
io.run_rand (rand.random_series_r x y h)
end bounded_random
end io
namespace tactic
/-- create a seeded random number generator in the `tactic` monad -/
meta def mk_generator : tactic std_gen := do
tactic.unsafe_run_io @io.mk_generator
/-- run `cmd` using the a randomly seeded random number generator
in the tactic monad -/
meta def run_rand {α : Type u} (cmd : rand α) : tactic α := do
⟨g⟩ ← tactic.up mk_generator,
return (cmd.run ⟨g⟩).1
variables {α : Type u}
section bounded_random
variables [preorder α] [bounded_random α]
/-- Generate a random value between `x` and `y` inclusive. -/
meta def random_r (x y : α) (h : x ≤ y) : tactic (x .. y) :=
run_rand (rand.random_r x y h)
/-- Generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/
meta def random_series_r (x y : α) (h : x ≤ y) : tactic (stream $ x .. y) :=
run_rand (rand.random_series_r x y h)
end bounded_random
section random
variables [random α]
/-- randomly generate a value of type α -/
meta def random : tactic α :=
run_rand (rand.random α)
/-- randomly generate an infinite series of value of type α -/
meta def random_series : tactic (stream α) :=
run_rand (rand.random_series α)
end random
end tactic
open nat (succ one_add mod_eq_of_lt zero_lt_succ add_one succ_le_succ)
variables {g : Type} [random_gen g]
open nat
namespace fin
variables {n : ℕ} [fact (0 < n)]
/-- generate a `fin` randomly -/
protected def random : rand_g g (fin n) :=
⟨ λ ⟨g⟩, prod.map of_nat' up $ rand_nat g 0 n ⟩
end fin
open nat
instance nat_bounded_random : bounded_random ℕ :=
{ random_r := λ g inst x y hxy,
do z ← @fin.random g inst (succ $ y - x) _,
pure ⟨z.val + x, nat.le_add_left _ _,
by rw ← le_tsub_iff_right hxy; apply le_of_succ_le_succ z.is_lt⟩ }
/-- This `bounded_random` interval generates integers between `x` and
`y` by first generating a natural number between `0` and `y - x` and
shifting the result appropriately. -/
instance int_bounded_random : bounded_random ℤ :=
{ random_r := λ g inst x y hxy,
do ⟨z,h₀,h₁⟩ ← @bounded_random.random_r ℕ _ _ g inst 0 (int.nat_abs $ y - x) dec_trivial,
pure ⟨z + x,
int.le_add_of_nonneg_left (int.coe_nat_nonneg _),
int.add_le_of_le_sub_right $ le_trans
(int.coe_nat_le_coe_nat_of_le h₁)
(le_of_eq $ int.of_nat_nat_abs_eq_of_nonneg (int.sub_nonneg_of_le hxy)) ⟩ }
instance fin_random (n : ℕ) [fact (0 < n)] : random (fin n) :=
{ random := λ g inst, @fin.random g inst _ _ }
instance fin_bounded_random (n : ℕ) : bounded_random (fin n) :=
{ random_r := λ g inst (x y : fin n) p,
do ⟨r, h, h'⟩ ← @rand.random_r ℕ g inst _ _ x.val y.val p,
pure ⟨⟨r,lt_of_le_of_lt h' y.is_lt⟩, h, h'⟩ }
/-- A shortcut for creating a `random (fin n)` instance from
a proof that `0 < n` rather than on matching on `fin (succ n)` -/
def random_fin_of_pos : ∀ {n : ℕ} (h : 0 < n), random (fin n)
| (succ n) _ := fin_random _
| 0 h := false.elim (nat.not_lt_zero _ h)
lemma bool_of_nat_mem_Icc_of_mem_Icc_to_nat (x y : bool) (n : ℕ) :
n ∈ (x.to_nat .. y.to_nat) → bool.of_nat n ∈ (x .. y) :=
begin
simp only [and_imp, set.mem_Icc], intros h₀ h₁,
split;
[ have h₂ := bool.of_nat_le_of_nat h₀, have h₂ := bool.of_nat_le_of_nat h₁ ];
rw bool.of_nat_to_nat at h₂; exact h₂,
end
instance : random bool :=
{ random := λ g inst,
(bool.of_nat ∘ subtype.val) <$> @bounded_random.random_r ℕ _ _ g inst 0 1 (nat.zero_le _) }
instance : bounded_random bool :=
{ random_r := λ g _inst x y p,
subtype.map bool.of_nat (bool_of_nat_mem_Icc_of_mem_Icc_to_nat x y) <$>
@bounded_random.random_r ℕ _ _ g _inst x.to_nat y.to_nat (bool.to_nat_le_to_nat p) }
open_locale fin_fact
/-- generate a random bit vector of length `n` -/
def bitvec.random (n : ℕ) : rand_g g (bitvec n) :=
bitvec.of_fin <$> rand.random (fin $ 2^n)
/-- generate a random bit vector of length `n` -/
def bitvec.random_r {n : ℕ} (x y : bitvec n) (h : x ≤ y) : rand_g g (x .. y) :=
have h' : ∀ (a : fin (2 ^ n)), a ∈ (x.to_fin .. y.to_fin) → bitvec.of_fin a ∈ (x .. y),
begin
simp only [and_imp, set.mem_Icc], intros z h₀ h₁,
replace h₀ := bitvec.of_fin_le_of_fin_of_le h₀,
replace h₁ := bitvec.of_fin_le_of_fin_of_le h₁,
rw bitvec.of_fin_to_fin at h₀ h₁, split; assumption,
end,
subtype.map bitvec.of_fin h' <$> rand.random_r x.to_fin y.to_fin (bitvec.to_fin_le_to_fin_of_le h)
open nat
instance random_bitvec (n : ℕ) : random (bitvec n) :=
{ random := λ _ inst, @bitvec.random _ inst n }
instance bounded_random_bitvec (n : ℕ) : bounded_random (bitvec n) :=
{ random_r := λ _ inst x y p, @bitvec.random_r _ inst _ _ _ p }
|
7eec743ab8f32bbba203e79b1be62197394866ed | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/analysis/normed_space/linear_isometry.lean | 7744ebf115e521c944dc4c54bbb09757aefab835 | [
"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 | 17,962 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Frédéric Dupuis, Heather Macbeth
-/
import analysis.normed_space.basic
/-!
# (Semi-)linear isometries
In this file we define `linear_isometry σ₁₂ E E₂` (notation: `E →ₛₗᵢ[σ₁₂] E₂`) to be a semilinear
isometric embedding of `E` into `E₂` and `linear_isometry_equiv` (notation: `E ≃ₛₗᵢ[σ₁₂] E₂`) to be
a semilinear isometric equivalence between `E` and `E₂`. The notation for the associated purely
linear concepts is `E →ₗᵢ[R] E₂`, `E ≃ₗᵢ[R] E₂`.
We also prove some trivial lemmas and provide convenience constructors.
Since a lot of elementary properties don't require `∥x∥ = 0 → x = 0` we start setting up the
theory for `semi_normed_space` and we specialize to `normed_space` when needed.
-/
open function set
variables {R R₂ R₃ R₄ E E₂ E₃ E₄ F : Type*} [semiring R] [semiring R₂] [semiring R₃] [semiring R₄]
{σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R} {σ₁₃ : R →+* R₃} {σ₃₁ : R₃ →+* R} {σ₁₄ : R →+* R₄}
{σ₄₁ : R₄ →+* R} {σ₂₃ : R₂ →+* R₃} {σ₃₂ : R₃ →+* R₂} {σ₂₄ : R₂ →+* R₄} {σ₄₂ : R₄ →+* R₂}
{σ₃₄ : R₃ →+* R₄} {σ₄₃ : R₄ →+* R₃}
[ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂]
[ring_hom_inv_pair σ₁₃ σ₃₁] [ring_hom_inv_pair σ₃₁ σ₁₃]
[ring_hom_inv_pair σ₂₃ σ₃₂] [ring_hom_inv_pair σ₃₂ σ₂₃]
[ring_hom_inv_pair σ₁₄ σ₄₁] [ring_hom_inv_pair σ₄₁ σ₁₄]
[ring_hom_inv_pair σ₂₄ σ₄₂] [ring_hom_inv_pair σ₄₂ σ₂₄]
[ring_hom_inv_pair σ₃₄ σ₄₃] [ring_hom_inv_pair σ₄₃ σ₃₄]
[ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₁₂ σ₂₄ σ₁₄]
[ring_hom_comp_triple σ₂₃ σ₃₄ σ₂₄] [ring_hom_comp_triple σ₁₃ σ₃₄ σ₁₄]
[ring_hom_comp_triple σ₃₂ σ₂₁ σ₃₁] [ring_hom_comp_triple σ₄₂ σ₂₁ σ₄₁]
[ring_hom_comp_triple σ₄₃ σ₃₂ σ₄₂] [ring_hom_comp_triple σ₄₃ σ₃₁ σ₄₁]
[semi_normed_group E] [semi_normed_group E₂] [semi_normed_group E₃] [semi_normed_group E₄]
[module R E] [module R₂ E₂] [module R₃ E₃] [module R₄ E₄]
[normed_group F] [module R F]
/-- A `σ₁₂`-semilinear isometric embedding of a normed `R`-module into an `R₂`-module. -/
structure linear_isometry (σ₁₂ : R →+* R₂) (E E₂ : Type*) [semi_normed_group E]
[semi_normed_group E₂] [module R E] [module R₂ E₂] extends E →ₛₗ[σ₁₂] E₂ :=
(norm_map' : ∀ x, ∥to_linear_map x∥ = ∥x∥)
notation E ` →ₛₗᵢ[`:25 σ₁₂:25 `] `:0 E₂:0 := linear_isometry σ₁₂ E E₂
notation E ` →ₗᵢ[`:25 R:25 `] `:0 E₂:0 := linear_isometry (ring_hom.id R) E E₂
namespace linear_isometry
/-- We use `f₁` when we need the domain to be a `normed_space`. -/
variables (f : E →ₛₗᵢ[σ₁₂] E₂) (f₁ : F →ₛₗᵢ[σ₁₂] E₂)
instance : has_coe_to_fun (E →ₛₗᵢ[σ₁₂] E₂) := ⟨_, λ f, f.to_fun⟩
@[simp] lemma coe_to_linear_map : ⇑f.to_linear_map = f := rfl
lemma to_linear_map_injective : injective (to_linear_map : (E →ₛₗᵢ[σ₁₂] E₂) → (E →ₛₗ[σ₁₂] E₂))
| ⟨f, _⟩ ⟨g, _⟩ rfl := rfl
lemma coe_fn_injective : injective (λ (f : E →ₛₗᵢ[σ₁₂] E₂) (x : E), f x) :=
linear_map.coe_injective.comp to_linear_map_injective
@[ext] lemma ext {f g : E →ₛₗᵢ[σ₁₂] E₂} (h : ∀ x, f x = g x) : f = g :=
coe_fn_injective $ funext h
@[simp] lemma map_zero : f 0 = 0 := f.to_linear_map.map_zero
@[simp] lemma map_add (x y : E) : f (x + y) = f x + f y := f.to_linear_map.map_add x y
@[simp] lemma map_sub (x y : E) : f (x - y) = f x - f y := f.to_linear_map.map_sub x y
@[simp] lemma map_smulₛₗ (c : R) (x : E) : f (c • x) = σ₁₂ c • f x := f.to_linear_map.map_smulₛₗ c x
@[simp] lemma map_smul [module R E₂] (f : E →ₗᵢ[R] E₂) (c : R) (x : E) : f (c • x) = c • f x :=
f.to_linear_map.map_smul c x
@[simp] lemma norm_map (x : E) : ∥f x∥ = ∥x∥ := f.norm_map' x
@[simp] lemma nnnorm_map (x : E) : nnnorm (f x) = nnnorm x := nnreal.eq $ f.norm_map x
protected lemma isometry : isometry f :=
f.to_linear_map.to_add_monoid_hom.isometry_of_norm f.norm_map
@[simp] lemma dist_map (x y : E) : dist (f x) (f y) = dist x y := f.isometry.dist_eq x y
@[simp] lemma edist_map (x y : E) : edist (f x) (f y) = edist x y := f.isometry.edist_eq x y
protected lemma injective : injective f₁ := f₁.isometry.injective
@[simp] lemma map_eq_iff {x y : F} : f₁ x = f₁ y ↔ x = y := f₁.injective.eq_iff
lemma map_ne {x y : F} (h : x ≠ y) : f₁ x ≠ f₁ y := f₁.injective.ne h
protected lemma lipschitz : lipschitz_with 1 f := f.isometry.lipschitz
protected lemma antilipschitz : antilipschitz_with 1 f := f.isometry.antilipschitz
@[continuity] protected lemma continuous : continuous f := f.isometry.continuous
lemma ediam_image (s : set E) : emetric.diam (f '' s) = emetric.diam s :=
f.isometry.ediam_image s
lemma ediam_range : emetric.diam (range f) = emetric.diam (univ : set E) :=
f.isometry.ediam_range
lemma diam_image (s : set E) : metric.diam (f '' s) = metric.diam s :=
f.isometry.diam_image s
lemma diam_range : metric.diam (range f) = metric.diam (univ : set E) :=
f.isometry.diam_range
/-- Interpret a linear isometry as a continuous linear map. -/
def to_continuous_linear_map : E →SL[σ₁₂] E₂ := ⟨f.to_linear_map, f.continuous⟩
@[simp] lemma coe_to_continuous_linear_map : ⇑f.to_continuous_linear_map = f := rfl
@[simp] lemma comp_continuous_iff {α : Type*} [topological_space α] {g : α → E} :
continuous (f ∘ g) ↔ continuous g :=
f.isometry.comp_continuous_iff
/-- The identity linear isometry. -/
def id : E →ₗᵢ[R] E := ⟨linear_map.id, λ x, rfl⟩
@[simp] lemma coe_id : ⇑(id : E →ₗᵢ[R] E) = _root_.id := rfl
@[simp] lemma id_apply (x : E) : (id : E →ₗᵢ[R] E) x = x := rfl
@[simp] lemma id_to_linear_map : (id.to_linear_map : E →ₗ[R] E) = linear_map.id := rfl
instance : inhabited (E →ₗᵢ[R] E) := ⟨id⟩
/-- Composition of linear isometries. -/
def comp (g : E₂ →ₛₗᵢ[σ₂₃] E₃) (f : E →ₛₗᵢ[σ₁₂] E₂) : E →ₛₗᵢ[σ₁₃] E₃ :=
⟨g.to_linear_map.comp f.to_linear_map, λ x, (g.norm_map _).trans (f.norm_map _)⟩
include σ₁₃
@[simp] lemma coe_comp (g : E₂ →ₛₗᵢ[σ₂₃] E₃) (f : E →ₛₗᵢ[σ₁₂] E₂) :
⇑(g.comp f) = g ∘ f :=
rfl
omit σ₁₃
@[simp] lemma id_comp : (id : E₂ →ₗᵢ[R₂] E₂).comp f = f := ext $ λ x, rfl
@[simp] lemma comp_id : f.comp id = f := ext $ λ x, rfl
include σ₁₃ σ₂₄ σ₁₄
lemma comp_assoc (f : E₃ →ₛₗᵢ[σ₃₄] E₄) (g : E₂ →ₛₗᵢ[σ₂₃] E₃) (h : E →ₛₗᵢ[σ₁₂] E₂) :
(f.comp g).comp h = f.comp (g.comp h) :=
rfl
omit σ₁₃ σ₂₄ σ₁₄
instance : monoid (E →ₗᵢ[R] E) :=
{ one := id,
mul := comp,
mul_assoc := comp_assoc,
one_mul := id_comp,
mul_one := comp_id }
@[simp] lemma coe_one : ⇑(1 : E →ₗᵢ[R] E) = id := rfl
@[simp] lemma coe_mul (f g : E →ₗᵢ[R] E) : ⇑(f * g) = f ∘ g := rfl
end linear_isometry
/-- Construct a `linear_isometry` from a `linear_map` satisfying `isometry`. -/
def linear_map.to_linear_isometry (f : E →ₛₗ[σ₁₂] E₂) (hf : isometry f) : E →ₛₗᵢ[σ₁₂] E₂ :=
{ norm_map' := by { simp_rw [←dist_zero_right, ←f.map_zero], exact λ x, hf.dist_eq x _ },
.. f }
namespace submodule
variables {R' : Type*} [ring R'] [module R' E] (p : submodule R' E)
/-- `submodule.subtype` as a `linear_isometry`. -/
def subtypeₗᵢ : p →ₗᵢ[R'] E := ⟨p.subtype, λ x, rfl⟩
@[simp] lemma coe_subtypeₗᵢ : ⇑p.subtypeₗᵢ = p.subtype := rfl
@[simp] lemma subtypeₗᵢ_to_linear_map : p.subtypeₗᵢ.to_linear_map = p.subtype := rfl
/-- `submodule.subtype` as a `continuous_linear_map`. -/
def subtypeL : p →L[R'] E := p.subtypeₗᵢ.to_continuous_linear_map
@[simp] lemma coe_subtypeL : (p.subtypeL : p →ₗ[R'] E) = p.subtype := rfl
@[simp] lemma coe_subtypeL' : ⇑p.subtypeL = p.subtype := rfl
@[simp] lemma range_subtypeL : p.subtypeL.range = p :=
range_subtype _
@[simp] lemma ker_subtypeL : p.subtypeL.ker = ⊥ :=
ker_subtype _
end submodule
/-- A semilinear isometric equivalence between two normed vector spaces. -/
structure linear_isometry_equiv (σ₁₂ : R →+* R₂) {σ₂₁ : R₂ →+* R} [ring_hom_inv_pair σ₁₂ σ₂₁]
[ring_hom_inv_pair σ₂₁ σ₁₂] (E E₂ : Type*) [semi_normed_group E] [semi_normed_group E₂]
[module R E] [module R₂ E₂] extends E ≃ₛₗ[σ₁₂] E₂ :=
(norm_map' : ∀ x, ∥to_linear_equiv x∥ = ∥x∥)
notation E ` ≃ₛₗᵢ[`:25 σ₁₂:25 `] `:0 E₂:0 := linear_isometry_equiv σ₁₂ E E₂
notation E ` ≃ₗᵢ[`:25 R:25 `] `:0 E₂:0 := linear_isometry_equiv (ring_hom.id R) E E₂
namespace linear_isometry_equiv
variables (e : E ≃ₛₗᵢ[σ₁₂] E₂)
include σ₂₁
instance : has_coe_to_fun (E ≃ₛₗᵢ[σ₁₂] E₂) := ⟨_, λ f, f.to_fun⟩
@[simp] lemma coe_mk (e : E ≃ₛₗ[σ₁₂] E₂) (he : ∀ x, ∥e x∥ = ∥x∥) :
⇑(mk e he) = e :=
rfl
@[simp] lemma coe_to_linear_equiv (e : E ≃ₛₗᵢ[σ₁₂] E₂) : ⇑e.to_linear_equiv = e := rfl
lemma to_linear_equiv_injective : injective (to_linear_equiv : (E ≃ₛₗᵢ[σ₁₂] E₂) → (E ≃ₛₗ[σ₁₂] E₂))
| ⟨e, _⟩ ⟨_, _⟩ rfl := rfl
@[ext] lemma ext {e e' : E ≃ₛₗᵢ[σ₁₂] E₂} (h : ∀ x, e x = e' x) : e = e' :=
to_linear_equiv_injective $ linear_equiv.ext h
/-- Construct a `linear_isometry_equiv` from a `linear_equiv` and two inequalities:
`∀ x, ∥e x∥ ≤ ∥x∥` and `∀ y, ∥e.symm y∥ ≤ ∥y∥`. -/
def of_bounds (e : E ≃ₛₗ[σ₁₂] E₂) (h₁ : ∀ x, ∥e x∥ ≤ ∥x∥) (h₂ : ∀ y, ∥e.symm y∥ ≤ ∥y∥) :
E ≃ₛₗᵢ[σ₁₂] E₂ :=
⟨e, λ x, le_antisymm (h₁ x) $ by simpa only [e.symm_apply_apply] using h₂ (e x)⟩
@[simp] lemma norm_map (x : E) : ∥e x∥ = ∥x∥ := e.norm_map' x
/-- Reinterpret a `linear_isometry_equiv` as a `linear_isometry`. -/
def to_linear_isometry : E →ₛₗᵢ[σ₁₂] E₂ := ⟨e.1, e.2⟩
@[simp] lemma coe_to_linear_isometry : ⇑e.to_linear_isometry = e := rfl
protected lemma isometry : isometry e := e.to_linear_isometry.isometry
/-- Reinterpret a `linear_isometry_equiv` as an `isometric`. -/
def to_isometric : E ≃ᵢ E₂ := ⟨e.to_linear_equiv.to_equiv, e.isometry⟩
@[simp] lemma coe_to_isometric : ⇑e.to_isometric = e := rfl
lemma range_eq_univ (e : E ≃ₛₗᵢ[σ₁₂] E₂) : set.range e = set.univ :=
by { rw ← coe_to_isometric, exact isometric.range_eq_univ _, }
/-- Reinterpret a `linear_isometry_equiv` as an `homeomorph`. -/
def to_homeomorph : E ≃ₜ E₂ := e.to_isometric.to_homeomorph
@[simp] lemma coe_to_homeomorph : ⇑e.to_homeomorph = e := rfl
protected lemma continuous : continuous e := e.isometry.continuous
protected lemma continuous_at {x} : continuous_at e x := e.continuous.continuous_at
protected lemma continuous_on {s} : continuous_on e s := e.continuous.continuous_on
protected lemma continuous_within_at {s x} : continuous_within_at e s x :=
e.continuous.continuous_within_at
/-- Interpret a `linear_isometry_equiv` as a continuous linear equiv. -/
def to_continuous_linear_equiv : E ≃SL[σ₁₂] E₂ :=
{ .. e.to_linear_isometry.to_continuous_linear_map,
.. e.to_homeomorph }
@[simp] lemma coe_to_continuous_linear_equiv : ⇑e.to_continuous_linear_equiv = e := rfl
omit σ₂₁
variables (R E)
/-- Identity map as a `linear_isometry_equiv`. -/
def refl : E ≃ₗᵢ[R] E := ⟨linear_equiv.refl R E, λ x, rfl⟩
variables {R E}
instance : inhabited (E ≃ₗᵢ[R] E) := ⟨refl R E⟩
@[simp] lemma coe_refl : ⇑(refl R E) = id := rfl
/-- The inverse `linear_isometry_equiv`. -/
def symm : E₂ ≃ₛₗᵢ[σ₂₁] E :=
⟨e.to_linear_equiv.symm,
λ x, (e.norm_map _).symm.trans $ congr_arg norm $ e.to_linear_equiv.apply_symm_apply x⟩
@[simp] lemma apply_symm_apply (x : E₂) : e (e.symm x) = x := e.to_linear_equiv.apply_symm_apply x
@[simp] lemma symm_apply_apply (x : E) : e.symm (e x) = x := e.to_linear_equiv.symm_apply_apply x
@[simp] lemma map_eq_zero_iff {x : E} : e x = 0 ↔ x = 0 := e.to_linear_equiv.map_eq_zero_iff
@[simp] lemma symm_symm : e.symm.symm = e := ext $ λ x, rfl
@[simp] lemma to_linear_equiv_symm : e.to_linear_equiv.symm = e.symm.to_linear_equiv := rfl
@[simp] lemma to_isometric_symm : e.to_isometric.symm = e.symm.to_isometric := rfl
@[simp] lemma to_homeomorph_symm : e.to_homeomorph.symm = e.symm.to_homeomorph := rfl
include σ₃₁ σ₃₂
/-- Composition of `linear_isometry_equiv`s as a `linear_isometry_equiv`. -/
def trans (e' : E₂ ≃ₛₗᵢ[σ₂₃] E₃) : E ≃ₛₗᵢ[σ₁₃] E₃ :=
⟨e.to_linear_equiv.trans e'.to_linear_equiv, λ x, (e'.norm_map _).trans (e.norm_map _)⟩
include σ₁₃ σ₂₁
@[simp] lemma coe_trans (e₁ : E ≃ₛₗᵢ[σ₁₂] E₂) (e₂ : E₂ ≃ₛₗᵢ[σ₂₃] E₃) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ :=
rfl
omit σ₁₃ σ₂₁ σ₃₁ σ₃₂
@[simp] lemma trans_refl : e.trans (refl R₂ E₂) = e := ext $ λ x, rfl
@[simp] lemma refl_trans : (refl R E).trans e = e := ext $ λ x, rfl
@[simp] lemma trans_symm : e.trans e.symm = refl R E := ext e.symm_apply_apply
@[simp] lemma symm_trans : e.symm.trans e = refl R₂ E₂ := ext e.apply_symm_apply
include σ₁₃ σ₂₁ σ₃₂ σ₃₁
@[simp] lemma coe_symm_trans (e₁ : E ≃ₛₗᵢ[σ₁₂] E₂) (e₂ : E₂ ≃ₛₗᵢ[σ₂₃] E₃) :
⇑(e₁.trans e₂).symm = e₁.symm ∘ e₂.symm :=
rfl
include σ₁₄ σ₄₁ σ₄₂ σ₄₃ σ₂₄
lemma trans_assoc (eEE₂ : E ≃ₛₗᵢ[σ₁₂] E₂) (eE₂E₃ : E₂ ≃ₛₗᵢ[σ₂₃] E₃) (eE₃E₄ : E₃ ≃ₛₗᵢ[σ₃₄] E₄) :
eEE₂.trans (eE₂E₃.trans eE₃E₄) = (eEE₂.trans eE₂E₃).trans eE₃E₄ :=
rfl
omit σ₂₁ σ₃₁ σ₄₁ σ₃₂ σ₄₂ σ₄₃ σ₁₃ σ₂₄ σ₁₄
instance : group (E ≃ₗᵢ[R] E) :=
{ mul := λ e₁ e₂, e₂.trans e₁,
one := refl _ _,
inv := symm,
one_mul := trans_refl,
mul_one := refl_trans,
mul_assoc := λ _ _ _, trans_assoc _ _ _,
mul_left_inv := trans_symm }
@[simp] lemma coe_one : ⇑(1 : E ≃ₗᵢ[R] E) = id := rfl
@[simp] lemma coe_mul (e e' : E ≃ₗᵢ[R] E) : ⇑(e * e') = e ∘ e' := rfl
@[simp] lemma coe_inv (e : E ≃ₗᵢ[R] E) : ⇑(e⁻¹) = e.symm := rfl
include σ₂₁
/-- Reinterpret a `linear_isometry_equiv` as a `continuous_linear_equiv`. -/
instance : has_coe_t (E ≃ₛₗᵢ[σ₁₂] E₂) (E ≃SL[σ₁₂] E₂) :=
⟨λ e, ⟨e.to_linear_equiv, e.continuous, e.to_isometric.symm.continuous⟩⟩
instance : has_coe_t (E ≃ₛₗᵢ[σ₁₂] E₂) (E →SL[σ₁₂] E₂) := ⟨λ e, ↑(e : E ≃SL[σ₁₂] E₂)⟩
@[simp] lemma coe_coe : ⇑(e : E ≃SL[σ₁₂] E₂) = e := rfl
@[simp] lemma coe_coe' : ((e : E ≃SL[σ₁₂] E₂) : E →SL[σ₁₂] E₂) = e := rfl
@[simp] lemma coe_coe'' : ⇑(e : E →SL[σ₁₂] E₂) = e := rfl
omit σ₂₁
@[simp] lemma map_zero : e 0 = 0 := e.1.map_zero
@[simp] lemma map_add (x y : E) : e (x + y) = e x + e y := e.1.map_add x y
@[simp] lemma map_sub (x y : E) : e (x - y) = e x - e y := e.1.map_sub x y
@[simp] lemma map_smulₛₗ (c : R) (x : E) : e (c • x) = σ₁₂ c • e x := e.1.map_smulₛₗ c x
@[simp] lemma map_smul [module R E₂] {e : E ≃ₗᵢ[R] E₂} (c : R) (x : E) : e (c • x) = c • e x :=
e.1.map_smul c x
@[simp] lemma nnnorm_map (x : E) : nnnorm (e x) = nnnorm x := e.to_linear_isometry.nnnorm_map x
@[simp] lemma dist_map (x y : E) : dist (e x) (e y) = dist x y :=
e.to_linear_isometry.dist_map x y
@[simp] lemma edist_map (x y : E) : edist (e x) (e y) = edist x y :=
e.to_linear_isometry.edist_map x y
protected lemma bijective : bijective e := e.1.bijective
protected lemma injective : injective e := e.1.injective
protected lemma surjective : surjective e := e.1.surjective
@[simp] lemma map_eq_iff {x y : E} : e x = e y ↔ x = y := e.injective.eq_iff
lemma map_ne {x y : E} (h : x ≠ y) : e x ≠ e y := e.injective.ne h
protected lemma lipschitz : lipschitz_with 1 e := e.isometry.lipschitz
protected lemma antilipschitz : antilipschitz_with 1 e := e.isometry.antilipschitz
@[simp] lemma ediam_image (s : set E) : emetric.diam (e '' s) = emetric.diam s :=
e.isometry.ediam_image s
@[simp] lemma diam_image (s : set E) : metric.diam (e '' s) = metric.diam s :=
e.isometry.diam_image s
variables {α : Type*} [topological_space α]
@[simp] lemma comp_continuous_on_iff {f : α → E} {s : set α} :
continuous_on (e ∘ f) s ↔ continuous_on f s :=
e.isometry.comp_continuous_on_iff
@[simp] lemma comp_continuous_iff {f : α → E} :
continuous (e ∘ f) ↔ continuous f :=
e.isometry.comp_continuous_iff
include σ₂₁
/-- Construct a linear isometry equiv from a surjective linear isometry. -/
noncomputable def of_surjective (f : F →ₛₗᵢ[σ₁₂] E₂)
(hfr : function.surjective f) :
F ≃ₛₗᵢ[σ₁₂] E₂ :=
{ norm_map' := f.norm_map,
.. linear_equiv.of_bijective f.to_linear_map f.injective hfr }
omit σ₂₁
variables (R)
/-- The negation operation on a normed space `E`, considered as a linear isometry equivalence. -/
def neg : E ≃ₗᵢ[R] E :=
{ norm_map' := norm_neg,
.. linear_equiv.neg R }
variables {R}
@[simp] lemma coe_neg : (neg R : E → E) = λ x, -x := rfl
@[simp] lemma symm_neg : (neg R : E ≃ₗᵢ[R] E).symm = neg R := rfl
end linear_isometry_equiv
|
f37a37dee328286d1e52a9837b9173848d4b6aa7 | 92b50235facfbc08dfe7f334827d47281471333b | /library/data/equiv.lean | e8b78af8f443b91aaf01d1d77c7699ce7980bab2 | [
"Apache-2.0"
] | permissive | htzh/lean | 24f6ed7510ab637379ec31af406d12584d31792c | d70c79f4e30aafecdfc4a60b5d3512199200ab6e | refs/heads/master | 1,607,677,731,270 | 1,437,089,952,000 | 1,437,089,952,000 | 37,078,816 | 0 | 0 | null | 1,433,780,956,000 | 1,433,780,955,000 | null | UTF-8 | Lean | false | false | 10,678 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
In the standard library we cannot assume the univalence axiom.
We say two types are equivalent if they are isomorphic.
-/
import data.sum data.nat
open function
structure equiv [class] (A B : Type) :=
(to_fun : A → B)
(inv : B → A)
(left_inv : left_inverse inv to_fun)
(right_inv : right_inverse inv to_fun)
namespace equiv
infix `≃`:50 := equiv
namespace ops
attribute equiv.to_fun [coercion]
definition inverse [reducible] {A B : Type} [h : A ≃ B] : B → A :=
λ b, @equiv.inv A B h b
postfix `⁻¹` := inverse
end ops
protected theorem refl [refl] (A : Type) : A ≃ A :=
mk (@id A) (@id A) (λ x, rfl) (λ x, rfl)
protected theorem symm [symm] {A B : Type} : A ≃ B → B ≃ A
| (mk f g h₁ h₂) := mk g f h₂ h₁
protected theorem trans [trans] {A B C : Type} : A ≃ B → B ≃ C → A ≃ C
| (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) :=
mk (f₂ ∘ f₁) (g₁ ∘ g₂)
(show ∀ x, g₁ (g₂ (f₂ (f₁ x))) = x, by intros; rewrite [l₂, l₁])
(show ∀ x, f₂ (f₁ (g₁ (g₂ x))) = x, by intros; rewrite [r₁, r₂])
lemma false_equiv_empty : empty ≃ false :=
mk (λ e, empty.rec _ e) (λ h, false.rec _ h) (λ e, empty.rec _ e) (λ h, false.rec _ h)
lemma arrow_congr {A₁ B₁ A₂ B₂ : Type} : A₁ ≃ A₂ → B₁ ≃ B₂ → (A₁ → B₁) ≃ (A₂ → B₂)
| (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) :=
mk
(λ (h : A₁ → B₁) (a : A₂), f₂ (h (g₁ a)))
(λ (h : A₂ → B₂) (a : A₁), g₂ (h (f₁ a)))
(λ h, funext (λ a, by rewrite [l₁, l₂]))
(λ h, funext (λ a, by rewrite [r₁, r₂]))
section
open unit
lemma arrow_unit_equiv_unit [rewrite] (A : Type) : (A → unit) ≃ unit :=
mk (λ f, star) (λ u, (λ f, star))
(λ f, funext (λ x, by cases (f x); reflexivity))
(λ u, by cases u; reflexivity)
lemma unit_arrow_equiv [rewrite] (A : Type) : (unit → A) ≃ A :=
mk (λ f, f star) (λ a, (λ u, a))
(λ f, funext (λ x, by cases x; reflexivity))
(λ u, rfl)
lemma empty_arrow_equiv_unit [rewrite] (A : Type) : (empty → A) ≃ unit :=
mk (λ f, star) (λ u, λ e, empty.rec _ e)
(λ f, funext (λ x, empty.rec _ x))
(λ u, by cases u; reflexivity)
lemma false_arrow_equiv_unit [rewrite] (A : Type) : (false → A) ≃ unit :=
calc (false → A) ≃ (empty → A) : arrow_congr false_equiv_empty !equiv.refl
... ≃ unit : empty_arrow_equiv_unit
end
lemma prod_congr {A₁ B₁ A₂ B₂ : Type} : A₁ ≃ A₂ → B₁ ≃ B₂ → (A₁ × B₁) ≃ (A₂ × B₂)
| (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) :=
mk
(λ p, match p with (a₁, b₁) := (f₁ a₁, f₂ b₁) end)
(λ p, match p with (a₂, b₂) := (g₁ a₂, g₂ b₂) end)
(λ p, begin cases p, esimp, rewrite [l₁, l₂] end)
(λ p, begin cases p, esimp, rewrite [r₁, r₂] end)
lemma prod_comm [rewrite] (A B : Type) : (A × B) ≃ (B × A) :=
mk (λ p, match p with (a, b) := (b, a) end)
(λ p, match p with (b, a) := (a, b) end)
(λ p, begin cases p, esimp end)
(λ p, begin cases p, esimp end)
lemma prod_assoc [rewrite] (A B C : Type) : ((A × B) × C) ≃ (A × (B × C)) :=
mk (λ t, match t with ((a, b), c) := (a, (b, c)) end)
(λ t, match t with (a, (b, c)) := ((a, b), c) end)
(λ t, begin cases t with ab c, cases ab, esimp end)
(λ t, begin cases t with a bc, cases bc, esimp end)
section
open unit prod.ops
lemma prod_unit_right [rewrite] (A : Type) : (A × unit) ≃ A :=
mk (λ p, p.1)
(λ a, (a, star))
(λ p, begin cases p with a u, cases u, esimp end)
(λ a, rfl)
lemma prod_unit_left [rewrite] (A : Type) : (unit × A) ≃ A :=
calc (unit × A) ≃ (A × unit) : prod_comm
... ≃ A : prod_unit_right
lemma prod_empty_right [rewrite] (A : Type) : (A × empty) ≃ empty :=
mk (λ p, empty.rec _ p.2) (λ e, empty.rec _ e) (λ p, empty.rec _ p.2) (λ e, empty.rec _ e)
lemma prod_empty_left [rewrite] (A : Type) : (empty × A) ≃ empty :=
calc (empty × A) ≃ (A × empty) : prod_comm
... ≃ empty : prod_empty_right
end
section
open sum
lemma sum_congr {A₁ B₁ A₂ B₂ : Type} : A₁ ≃ A₂ → B₁ ≃ B₂ → (A₁ + B₁) ≃ (A₂ + B₂)
| (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) :=
mk
(λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end)
(λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end)
(λ s, begin cases s, {esimp, rewrite l₁}, {esimp, rewrite l₂} end)
(λ s, begin cases s, {esimp, rewrite r₁}, {esimp, rewrite r₂} end)
open bool unit
lemma bool_equiv_unit_sum_unit : bool ≃ (unit + unit) :=
mk (λ b, match b with tt := inl star | ff := inr star end)
(λ s, match s with inl star := tt | inr star := ff end)
(λ b, begin cases b, esimp, esimp end)
(λ s, begin cases s with u u, {cases u, esimp}, {cases u, esimp} end)
lemma sum_comm [rewrite] (A B : Type) : (A + B) ≃ (B + A) :=
mk (λ s, match s with inl a := inr a | inr b := inl b end)
(λ s, match s with inl b := inr b | inr a := inl a end)
(λ s, begin cases s, esimp, esimp end)
(λ s, begin cases s, esimp, esimp end)
lemma sum_assoc [rewrite] (A B C : Type) : ((A + B) + C) ≃ (A + (B + C)) :=
mk (λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end)
(λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end)
(λ s, begin cases s with ab c, cases ab, repeat esimp end)
(λ s, begin cases s with a bc, esimp, cases bc, repeat esimp end)
lemma sum_empty_right [rewrite] (A : Type) : (A + empty) ≃ A :=
mk (λ s, match s with inl a := a | inr e := empty.rec _ e end)
(λ a, inl a)
(λ s, begin cases s with a e, esimp, exact empty.rec _ e end)
(λ a, rfl)
lemma sum_empty_left [rewrite] (A : Type) : (empty + A) ≃ A :=
calc (empty + A) ≃ (A + empty) : sum_comm
... ≃ A : sum_empty_right
end
section
open prod.ops
lemma arrow_prod_equiv_prod_arrow (A B C : Type) : (C → A × B) ≃ ((C → A) × (C → B)) :=
mk (λ f, (λ c, (f c).1, λ c, (f c).2))
(λ p, λ c, (p.1 c, p.2 c))
(λ f, funext (λ c, begin esimp, cases f c, esimp end))
(λ p, begin cases p, esimp end)
lemma arrow_arrow_equiv_prod_arrow (A B C : Type) : (A → B → C) ≃ (A × B → C) :=
mk (λ f, λ p, f p.1 p.2)
(λ f, λ a b, f (a, b))
(λ f, rfl)
(λ f, funext (λ p, begin cases p, esimp end))
open sum
lemma sum_arrow_equiv_prod_arrow (A B C : Type) : ((A + B) → C) ≃ ((A → C) × (B → C)) :=
mk (λ f, (λ a, f (inl a), λ b, f (inr b)))
(λ p, (λ s, match s with inl a := p.1 a | inr b := p.2 b end))
(λ f, funext (λ s, begin cases s, esimp, esimp end))
(λ p, begin cases p, esimp end)
lemma sum_prod_distrib (A B C : Type) : ((A + B) × C) ≃ ((A × C) + (B × C)) :=
mk (λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end)
(λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end)
(λ p, begin cases p with ab c, cases ab, repeat esimp end)
(λ s, begin cases s with ac bc, cases ac, esimp, cases bc, esimp end)
lemma prod_sum_distrib (A B C : Type) : (A × (B + C)) ≃ ((A × B) + (A × C)) :=
calc (A × (B + C)) ≃ ((B + C) × A) : prod_comm
... ≃ ((B × A) + (C × A)) : sum_prod_distrib
... ≃ ((A × B) + (A × C)) : sum_congr !prod_comm !prod_comm
end
section
open sum nat unit prod.ops
lemma nat_equiv_nat_sum_unit : nat ≃ (nat + unit) :=
mk (λ n, match n with 0 := inr star | succ a := inl a end)
(λ s, match s with inl n := succ n | inr star := zero end)
(λ n, begin cases n, repeat esimp end)
(λ s, begin cases s with a u, esimp, {cases u, esimp} end)
lemma nat_sum_unit_equiv_nat [rewrite] : (nat + unit) ≃ nat :=
equiv.symm nat_equiv_nat_sum_unit
lemma nat_prod_nat_equiv_nat [rewrite] : (nat × nat) ≃ nat :=
mk (λ p, mkpair p.1 p.2)
(λ n, unpair n)
(λ p, begin cases p, apply unpair_mkpair end)
(λ n, mkpair_unpair n)
lemma nat_sum_bool_equiv_nat [rewrite] : (nat + bool) ≃ nat :=
calc (nat + bool) ≃ (nat + (unit + unit)) : sum_congr !equiv.refl bool_equiv_unit_sum_unit
... ≃ ((nat + unit) + unit) : sum_assoc
... ≃ (nat + unit) : sum_congr nat_sum_unit_equiv_nat !equiv.refl
... ≃ nat : nat_sum_unit_equiv_nat
open decidable
lemma nat_sum_nat_equiv_nat [rewrite] : (nat + nat) ≃ nat :=
mk (λ s, match s with inl n := 2*n | inr n := 2*n+1 end)
(λ n, if even n then inl (n div 2) else inr ((n - 1) div 2))
(λ s, begin
have two_gt_0 : 2 > 0, from dec_trivial,
cases s,
{esimp, rewrite [if_pos (even_two_mul _), mul_div_cancel_left _ two_gt_0]},
{esimp, rewrite [if_neg (not_even_two_mul_plus_one _), add_sub_cancel, mul_div_cancel_left _ two_gt_0]}
end)
(λ n, by_cases
(λ h : even n, begin rewrite [if_pos h], esimp, rewrite [mul_div_cancel' (dvd_of_even h)] end)
(λ h : ¬ even n,
begin
rewrite [if_neg h], esimp,
cases n,
{exact absurd even_zero h},
{rewrite [-add_one, add_sub_cancel,
mul_div_cancel' (dvd_of_even (even_of_odd_succ (odd_of_not_even h)))]}
end))
end
section
open decidable
definition decidable_eq_of_equiv {A B : Type} [h : decidable_eq A] : A ≃ B → decidable_eq B
| (mk f g l r) :=
take b₁ b₂, match h (g b₁) (g b₂) with
| inl he := inl (assert aux : f (g b₁) = f (g b₂), from congr_arg f he,
begin rewrite *r at aux, exact aux end)
| inr hn := inr (λ b₁eqb₂, by subst b₁eqb₂; exact absurd rfl hn)
end
end
definition inhabited_of_equiv {A B : Type} [h : inhabited A] : A ≃ B → inhabited B
| (mk f g l r) := inhabited.mk (f (inhabited.value h))
section
open subtype
override equiv.ops
definition subtype_equiv_of_subtype {A B : Type} {p : A → Prop} : A ≃ B → {a : A | p a} ≃ {b : B | p (b⁻¹)}
| (mk f g l r) :=
mk (λ s, match s with tag v h := tag (f v) (eq.rec_on (eq.symm (l v)) h) end)
(λ s, match s with tag v h := tag (g v) (eq.rec_on (eq.symm (r v)) h) end)
(λ s, begin cases s, esimp, congruence, rewrite l, reflexivity end)
(λ s, begin cases s, esimp, congruence, rewrite r, reflexivity end)
end
end equiv
|
11b8f63460e3813b60a3e6331a46826b060a25bf | a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7 | /src/linear_algebra/basis.lean | 0714ed441a0deec3a629b9a71bd8d184f18ae806 | [
"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 | 54,664 | 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, Alexander Bentkamp
-/
import linear_algebra.finsupp
import linear_algebra.projection
import order.zorn
import data.fintype.card
/-!
# Linear independence and bases
This file defines linear independence and bases in a module or vector space.
It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light.
## Main definitions
All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or
vector space and `ι : Type*` is an arbitrary indexing type.
* `linear_independent R v` states that the elements of the family `v` are linearly independent.
* `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)`
on the linearly independent vectors `v`, given `hv : linear_independent R v`
(using classical choice). `linear_independent.repr hv` is provided as a linear map.
* `is_basis R v` states that the vector family `v` is a basis, i.e. it is linearly independent and
spans the entire space.
* `is_basis.repr hv x` is the basis version of `linear_independent.repr hv x`. It returns the
linear combination representing `x : M` on a basis `v` of `M` (using classical choice).
The argument `hv` must be a proof that `is_basis R v`. `is_basis.repr hv` is given as a linear
map as well.
* `is_basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the
basis `v : ι → M₁`, given `hv : is_basis R v`.
## Main statements
* `is_basis.ext` states that two linear maps are equal if they coincide on a basis.
* `exists_is_basis` states that every vector space has a basis.
## Implementation notes
We use families instead of sets because it allows us to say that two identical vectors are linearly
dependent. For bases, this is useful as well because we can easily derive ordered bases by using an
ordered index type `ι`.
If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas
`linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two
worlds.
## Tags
linearly dependent, linear dependence, linearly independent, linear independence, basis
-/
noncomputable theory
open function set submodule
open_locale classical big_operators
universe u
variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*}
{M : Type*} {M' : Type*} {V : Type u} {V' : Type*}
section module
variables {v : ι → M}
variables [ring R] [add_comm_group M] [add_comm_group M']
variables [module R M] [module R M']
variables {a b : R} {x y : M}
variables (R) (v)
/-- Linearly independent family of vectors -/
def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥
variables {R} {v}
theorem linear_independent_iff : linear_independent R v ↔
∀l, finsupp.total ι M R v l = 0 → l = 0 :=
by simp [linear_independent, linear_map.ker_eq_bot']
theorem linear_independent_iff' : linear_independent R v ↔
∀ s : finset ι, ∀ g : ι → R, ∑ i in s, g i • v i = 0 → ∀ i ∈ s, g i = 0 :=
linear_independent_iff.trans
⟨λ hf s g hg i his, have h : _ := hf (∑ i in s, finsupp.single i (g i)) $
by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc
g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) :
by rw [finsupp.lapply_apply, finsupp.single_eq_same]
... = ∑ j in s, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j)) :
eq.symm $ finset.sum_eq_single i
(λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji])
(λ hnis, hnis.elim his)
... = (∑ j in s, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm
... = 0 : finsupp.ext_iff.1 h i,
λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $
finsupp.mem_support_iff.2 hni⟩
theorem linear_dependent_iff : ¬ linear_independent R v ↔
∃ s : finset ι, ∃ g : ι → R, s.sum (λ i, g i • v i) = 0 ∧ (∃ i ∈ s, g i ≠ 0) :=
begin
rw linear_independent_iff',
simp only [exists_prop, classical.not_forall],
end
lemma linear_independent_empty_type (h : ¬ nonempty ι) : linear_independent R v :=
begin
rw [linear_independent_iff],
intros,
ext i,
exact false.elim (not_nonempty_iff_imp_false.1 h i)
end
lemma linear_independent.ne_zero
{i : ι} (ne : 0 ≠ (1:R)) (hv : linear_independent R v) : v i ≠ 0 :=
λ h, ne $ eq.symm begin
suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa},
rw linear_independent_iff.1 hv (finsupp.single i 1),
{simp},
{simp [h]}
end
lemma linear_independent.comp
(h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) :=
begin
rw [linear_independent_iff, finsupp.total_comp],
intros l hl,
have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0,
by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp,
ext,
convert h_map_domain a,
simp only [finsupp.map_domain_apply hf],
end
lemma linear_independent_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : linear_independent R v :=
linear_independent_iff.2 (λ l hl, finsupp.eq_zero_of_zero_eq_one zero_eq_one _)
lemma linear_independent.unique (hv : linear_independent R v) {l₁ l₂ : ι →₀ R} :
finsupp.total ι M R v l₁ = finsupp.total ι M R v l₂ → l₁ = l₂ :=
by apply linear_map.ker_eq_bot.1 hv
lemma linear_independent.injective (zero_ne_one : (0 : R) ≠ 1) (hv : linear_independent R v) :
injective v :=
begin
intros i j hij,
let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1,
have h_total : finsupp.total ι M R v l = 0,
{ rw finsupp.total_apply,
rw finsupp.sum_sub_index,
{ simp [finsupp.sum_single_index, hij] },
{ intros, apply sub_smul } },
have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1,
{ rw linear_independent_iff at hv,
simp [eq_add_of_sub_eq' (hv l h_total)] },
show i = j,
{ apply or.elim ((finsupp.single_eq_single_iff _ _ _ _).1 h_single_eq),
simp,
exact λ h, false.elim (zero_ne_one.symm h.1) }
end
lemma linear_independent_span (hs : linear_independent R v) :
@linear_independent ι R (span R (range v))
(λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ :=
begin
rw linear_independent_iff at *,
intros l hl,
apply hs l,
have := congr_arg (submodule.subtype (span R (range v))) hl,
convert this,
rw [finsupp.total_apply, finsupp.total_apply],
unfold finsupp.sum,
rw linear_map.map_sum (submodule.subtype (span R (range v))),
simp
end
section subtype
/-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/
theorem linear_independent_comp_subtype {s : set ι} :
linear_independent R (v ∘ coe : s → M) ↔
∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 :=
begin
rw [linear_independent_iff, finsupp.total_comp],
simp only [linear_map.comp_apply],
split,
{ intros h l hl₁ hl₂,
have h_bij : bij_on coe (coe ⁻¹' ↑l.support : set s) ↑l.support,
{ apply bij_on.mk,
{ apply maps_to_preimage },
{ apply subtype.coe_injective.inj_on },
intros i hi,
rw [image_preimage_eq_inter_range, subtype.range_coe],
exact ⟨hi, (finsupp.mem_supported _ _).1 hl₁ hi⟩ },
show l = 0,
{ apply finsupp.eq_zero_of_comap_domain_eq_zero (coe : s → ι) _ h_bij,
apply h,
convert hl₂,
rw [finsupp.lmap_domain_apply, finsupp.map_domain_comap_domain],
exact subtype.coe_injective,
rw subtype.range_coe,
exact (finsupp.mem_supported _ _).1 hl₁ } },
{ intros h l hl,
have hl' : finsupp.total ι M R v (finsupp.emb_domain ⟨coe, subtype.coe_injective⟩ l) = 0,
{ rw finsupp.emb_domain_eq_map_domain ⟨coe, subtype.coe_injective⟩ l,
apply hl },
apply finsupp.emb_domain_inj.1,
rw [h (finsupp.emb_domain ⟨coe, subtype.coe_injective⟩ l) _ hl',
finsupp.emb_domain_zero],
rw [finsupp.mem_supported, finsupp.support_emb_domain],
intros x hx,
rw [finset.mem_coe, finset.mem_map] at hx,
rcases hx with ⟨i, x', hx'⟩,
rw ←hx',
simp }
end
theorem linear_independent_subtype {s : set M} :
linear_independent R (λ x, x : s → M) ↔
∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 :=
by apply @linear_independent_comp_subtype _ _ _ id
theorem linear_independent_comp_subtype_disjoint {s : set ι} :
linear_independent R (v ∘ coe : s → M) ↔
disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker :=
by rw [linear_independent_comp_subtype, linear_map.disjoint_ker]
theorem linear_independent_subtype_disjoint {s : set M} :
linear_independent R (λ x, x : s → M) ↔
disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker :=
by apply @linear_independent_comp_subtype_disjoint _ _ _ id
theorem linear_independent_iff_total_on {s : set M} :
linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ :=
by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot,
linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype,
map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff]
lemma linear_independent.to_subtype_range
(hv : linear_independent R v) : linear_independent R (λ x, x : range v → M) :=
begin
by_cases zero_eq_one : (0 : R) = 1,
{ apply linear_independent_of_zero_eq_one zero_eq_one },
rw linear_independent_subtype,
intros l hl₁ hl₂,
have h_bij : bij_on v (v ⁻¹' ↑l.support) ↑l.support,
{ apply bij_on.mk,
{ apply maps_to_preimage },
{ apply (linear_independent.injective zero_eq_one hv).inj_on },
intros x hx,
rcases mem_range.1 (((finsupp.mem_supported _ _).1 hl₁ : ↑(l.support) ⊆ range v) hx)
with ⟨i, hi⟩,
rw mem_image,
use i,
rw [mem_preimage, hi],
exact ⟨hx, rfl⟩ },
apply finsupp.eq_zero_of_comap_domain_eq_zero v l,
apply linear_independent_iff.1 hv,
rw [finsupp.total_comap_domain, finset.sum_preimage v l.support h_bij (λ (x : M), l x • x)],
rw [finsupp.total_apply, finsupp.sum] at hl₂,
apply hl₂
end
lemma linear_independent.of_subtype_range (hv : injective v)
(h : linear_independent R (λ x, x : range v → M)) : linear_independent R v :=
begin
rw linear_independent_iff,
intros l hl,
apply finsupp.map_domain_injective hv,
apply linear_independent_subtype.1 h (l.map_domain v),
{ rw finsupp.mem_supported,
intros x hx,
have := finset.mem_coe.2 (finsupp.map_domain_support hx),
rw finset.coe_image at this,
apply set.image_subset_range _ _ this, },
{ rwa [finsupp.total_map_domain _ _ hv, left_id] }
end
lemma linear_independent.restrict_of_comp_subtype {s : set ι}
(hs : linear_independent R (v ∘ coe : s → M)) :
linear_independent R (s.restrict v) :=
begin
have h_restrict : restrict v s = v ∘ coe := rfl,
rw [linear_independent_iff, h_restrict, finsupp.total_comp],
intros l hl,
have h_map_domain_subtype_eq_0 : l.map_domain coe = 0,
{ rw linear_independent_comp_subtype at hs,
apply hs (finsupp.lmap_domain R R coe l) _ hl,
rw finsupp.mem_supported,
simp,
intros x hx,
have := finset.mem_coe.2 (finsupp.map_domain_support (finset.mem_coe.1 hx)),
rw finset.coe_image at this,
exact subtype.coe_image_subset _ _ this },
apply @finsupp.map_domain_injective _ (subtype s) ι,
{ apply subtype.coe_injective },
{ simpa },
end
variables (R M)
lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) :=
by simp [linear_independent_subtype_disjoint]
variables {R M}
lemma linear_independent.mono {t s : set M} (h : t ⊆ s) :
linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) :=
begin
simp only [linear_independent_subtype_disjoint],
exact (disjoint.mono_left (finsupp.supported_mono h))
end
lemma linear_independent.union {s t : set M}
(hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M))
(hst : disjoint (span R s) (span R t)) :
linear_independent R (λ x, x : (s ∪ t) → M) :=
begin
rw [linear_independent_subtype_disjoint, disjoint_def, finsupp.supported_union],
intros l h₁ h₂, rw mem_sup at h₁,
rcases h₁ with ⟨ls, hls, lt, hlt, rfl⟩,
have h_ls_mem_t : finsupp.total M M R id ls ∈ span R t,
{ rw [← image_id t, finsupp.span_eq_map_total],
apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hlt)).1,
rw [← linear_map.map_add, linear_map.mem_ker.1 h₂],
apply zero_mem },
have h_lt_mem_s : finsupp.total M M R id lt ∈ span R s,
{ rw [← image_id s, finsupp.span_eq_map_total],
apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hls)).1,
rw [← linear_map.map_add, add_comm, linear_map.mem_ker.1 h₂],
apply zero_mem },
have h_ls_mem_s : (finsupp.total M M R id) ls ∈ span R s,
{ rw ← image_id s,
apply (finsupp.mem_span_iff_total _).2 ⟨ls, hls, rfl⟩ },
have h_lt_mem_t : (finsupp.total M M R id) lt ∈ span R t,
{ rw ← image_id t,
apply (finsupp.mem_span_iff_total _).2 ⟨lt, hlt, rfl⟩ },
have h_ls_0 : ls = 0 :=
disjoint_def.1 (linear_independent_subtype_disjoint.1 hs) _ hls
(linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id ls) h_ls_mem_s h_ls_mem_t),
have h_lt_0 : lt = 0 :=
disjoint_def.1 (linear_independent_subtype_disjoint.1 ht) _ hlt
(linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id lt) h_lt_mem_s h_lt_mem_t),
show ls + lt = 0,
by simp [h_ls_0, h_lt_0],
end
lemma linear_independent_of_finite (s : set M)
(H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) :
linear_independent R (λ x, x : s → M) :=
linear_independent_subtype.2 $
λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _)
lemma linear_independent_Union_of_directed {η : Type*}
{s : η → set M} (hs : directed (⊆) s)
(h : ∀ i, linear_independent R (λ x, x : s i → M)) :
linear_independent R (λ x, x : (⋃ i, s i) → M) :=
begin
by_cases hη : nonempty η,
{ refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _),
rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩,
rcases hs.finset_le hη fi.to_finset with ⟨i, hi⟩,
exact (h i).mono (subset.trans hI $ bUnion_subset $
λ j hj, hi j (finite.mem_to_finset.2 hj)) },
{ refine (linear_independent_empty _ _).mono _,
rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ }
end
lemma linear_independent_sUnion_of_directed {s : set (set M)}
(hs : directed_on (⊆) s)
(h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) :
linear_independent R (λ x, x : (⋃₀ s) → M) :=
by rw sUnion_eq_Union; exact
linear_independent_Union_of_directed
((directed_on_iff_directed _).1 hs) (by simpa using h)
lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M}
(hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) :
linear_independent R (λ x, x : (⋃a∈s, t a) → M) :=
by rw bUnion_eq_Union; exact
linear_independent_Union_of_directed
((directed_comp _ _ _).2 $ (directed_on_iff_directed _).1 hs)
(by simpa using h)
lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M}
(hl : ∀i, linear_independent R (λ x, x : f i → M))
(hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) :
linear_independent R (λ x, x : (⋃i, f i) → M) :=
begin
rw [Union_eq_Union_finset f],
apply linear_independent_Union_of_directed,
apply directed_of_sup,
exact (assume t₁ t₂ ht, Union_subset_Union $ assume i, Union_subset_Union_const $ assume h, ht h),
assume t, rw [set.Union, ← finset.sup_eq_supr],
refine t.induction_on _ _,
{ rw finset.sup_empty,
apply linear_independent_empty_type (not_nonempty_iff_imp_false.2 _),
exact λ x, set.not_mem_empty x (subtype.mem x) },
{ rintros ⟨i⟩ s his ih,
rw [finset.sup_insert],
refine (hl _).union ih _,
rw [finset.sup_eq_supr],
refine (hd i _ _ his).mono_right _,
{ simp only [(span_Union _).symm],
refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _),
rintros ⟨i⟩, exact ⟨i, le_refl _⟩ },
{ change finite (plift.up ⁻¹' ↑s),
exact s.finite_to_set.preimage (assume i j _ _, plift.up.inj) } }
end
lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*}
{f : Π j : η, ιs j → M}
(hindep : ∀j, linear_independent R (f j))
(hd : ∀i, ∀t:set η, finite t → i ∉ t →
disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) :
linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) :=
begin
by_cases zero_eq_one : (0 : R) = 1,
{ apply linear_independent_of_zero_eq_one zero_eq_one },
apply linear_independent.of_subtype_range,
{ rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy,
by_cases h_cases : x₁ = y₁,
subst h_cases,
{ apply sigma.eq,
rw linear_independent.injective zero_eq_one (hindep _) hxy,
refl },
{ have h0 : f x₁ x₂ = 0,
{ apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁)
(λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)),
rw supr_singleton,
simp only at hxy,
rw hxy,
exact (subset_span (mem_range_self y₂)) },
exact false.elim ((hindep x₁).ne_zero zero_eq_one h0) } },
rw range_sigma_eq_Union_range,
apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd,
end
end subtype
section repr
variables (hv : linear_independent R v)
/-- Canonical isomorphism between linear combinations and the span of linearly independent vectors.
-/
def linear_independent.total_equiv (hv : linear_independent R v) :
(ι →₀ R) ≃ₗ[R] span R (range v) :=
begin
apply linear_equiv.of_bijective
(linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _),
{ rw linear_map.ker_cod_restrict,
apply hv },
{ rw [linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap,
range_subtype, map_top],
rw finsupp.range_total,
apply le_refl (span R (range v)) },
{ intro l,
rw ← finsupp.range_total,
rw linear_map.mem_range,
apply mem_range_self l }
end
/-- Linear combination representing a vector in the span of linearly independent vectors.
Given a family of linearly independent vectors, we can represent any vector in their span as
a linear combination of these vectors. These are provided by this linear map.
It is simply one direction of `linear_independent.total_equiv`. -/
def linear_independent.repr (hv : linear_independent R v) :
span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm
lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x :=
subtype.ext_iff.1 (linear_equiv.apply_symm_apply hv.total_equiv x)
lemma linear_independent.total_comp_repr :
(finsupp.total ι M R v).comp hv.repr = submodule.subtype _ :=
linear_map.ext $ hv.total_repr
lemma linear_independent.repr_ker : hv.repr.ker = ⊥ :=
by rw [linear_independent.repr, linear_equiv.ker]
lemma linear_independent.repr_range : hv.repr.range = ⊤ :=
by rw [linear_independent.repr, linear_equiv.range]
lemma linear_independent.repr_eq
{l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) :
hv.repr x = l :=
begin
have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l)
= finsupp.total ι M R v l := rfl,
have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x,
{ rw eq at this,
exact subtype.ext_iff.2 this },
rw ←linear_equiv.symm_apply_apply hv.total_equiv l,
rw ←this,
refl,
end
lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) :
hv.repr x = finsupp.single i 1 :=
begin
apply hv.repr_eq,
simp [finsupp.total_single, hx]
end
-- TODO: why is this so slow?
lemma linear_independent_iff_not_smul_mem_span :
linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) :=
⟨ λ hv i a ha, begin
rw [finsupp.span_eq_map_total, mem_map] at ha,
rcases ha with ⟨l, hl, e⟩,
rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl,
by_contra hn,
exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _),
end, λ H, linear_independent_iff.2 $ λ l hl, begin
ext i, simp only [finsupp.zero_apply],
by_contra hn,
refine hn (H i _ _),
refine (finsupp.mem_span_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩,
{ rw finsupp.mem_supported',
intros j hj,
have hij : j = i :=
classical.not_not.1
(λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)),
simp [hij] },
{ simp [hl] }
end⟩
end repr
lemma surjective_of_linear_independent_of_span
(hv : linear_independent R v) (f : ι' ↪ ι)
(hss : range v ⊆ span R (range (v ∘ f))) (zero_ne_one : 0 ≠ (1 : R)):
surjective f :=
begin
intros i,
let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.injective).repr,
let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f,
have h_total_l : finsupp.total ι M R v l = v i,
{ dsimp only [l],
rw finsupp.total_map_domain,
rw (hv.comp f f.injective).total_repr,
{ refl },
{ exact f.injective } },
have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1),
by rw [h_total_l, finsupp.total_single, one_smul],
have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq,
dsimp only [l] at l_eq,
rw ←finsupp.emb_domain_eq_map_domain at l_eq,
rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq
with ⟨i', hi'⟩,
use i',
exact hi'.2
end
lemma eq_of_linear_independent_of_span_subtype {s t : set M} (zero_ne_one : (0 : R) ≠ 1)
(hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t :=
begin
let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.coe_injective (subtype.mk.inj hab)⟩,
have h_surj : surjective f,
{ apply surjective_of_linear_independent_of_span hs f _ zero_ne_one,
convert hst; simp [f, comp], },
show s = t,
{ apply subset.antisymm _ h,
intros x hx,
rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩,
convert y.mem,
rw ← subtype.mk.inj hy,
refl }
end
open linear_map
lemma linear_independent.image (hv : linear_independent R v) {f : M →ₗ M'}
(hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) :=
begin
rw [disjoint, ← set.image_univ, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap,
map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj,
unfold linear_independent at hv,
rw hv at hf_inj,
haveI : inhabited M := ⟨0⟩,
rw [linear_independent, finsupp.total_comp],
rw [@finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, ker_comp, eq_bot_iff],
apply hf_inj,
exact λ _, rfl,
end
lemma linear_independent.image_subtype {s : set M} {f : M →ₗ M'}
(hs : linear_independent R (λ x, x : s → M))
(hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') :=
begin
rw [disjoint, ← set.image_id s, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap,
map_le_iff_le_comap, comap_bot] at hf_inj,
haveI : inhabited M := ⟨0⟩,
rw [linear_independent_subtype_disjoint, disjoint, ← finsupp.lmap_domain_supported _ _ f, map_inf_eq_map_inf_comap,
map_le_iff_le_comap, ← ker_comp],
rw [@finsupp.lmap_domain_total _ _ R _ _ _, ker_comp],
{ exact le_trans (le_inf inf_le_left hf_inj)
(le_trans (linear_independent_subtype_disjoint.1 hs) bot_le) },
{ simp }
end
lemma linear_independent.inl_union_inr {s : set M} {t : set M'}
(hs : linear_independent R (λ x, x : s → M))
(ht : linear_independent R (λ x, x : t → M')) :
linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') :=
begin
refine (hs.image_subtype _).union (ht.image_subtype _) _; [simp, simp, skip],
simp only [span_image],
simp [disjoint_iff, prod_inf_prod]
end
lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'}
(hv : linear_independent R v) (hv' : linear_independent R v') :
linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) :=
begin
by_cases zero_eq_one : (0 : R) = 1,
{ apply linear_independent_of_zero_eq_one zero_eq_one },
have inj_v : injective v := (linear_independent.injective zero_eq_one hv),
have inj_v' : injective v' := (linear_independent.injective zero_eq_one hv'),
apply linear_independent.of_subtype_range,
{ apply sum.elim_injective,
{ exact prod.inl_injective.comp inj_v },
{ exact prod.inr_injective.comp inj_v' },
{ intros, simp [hv.ne_zero zero_eq_one] } },
{ rw sum.elim_range,
refine (hv.image _).to_subtype_range.union (hv'.image _).to_subtype_range _;
[simp, simp, skip],
apply disjoint_inl_inr.mono _ _;
simp only [set.range_comp, span_image, linear_map.map_le_range] }
end
/-- Dedekind's linear independence of characters -/
-- See, for example, Keith Conrad's note <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf>
theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [integral_domain L] :
@linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ :=
by letI := classical.dec_eq (G →* L);
letI : mul_action L L := distrib_mul_action.to_mul_action;
-- We prove linear independence by showing that only the trivial linear combination vanishes.
exact linear_independent_iff'.2
-- To do this, we use `finset` induction,
(λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg,
-- Here
-- * `a` is a new character we will insert into the `finset` of characters `s`,
-- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero
-- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero
-- and it remains to prove that `g` vanishes on `insert a s`.
-- We now make the key calculation:
-- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the monoid `G`.
have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G,
-- We prove these expressions are equal by showing
-- the differences of their values on each monoid element `x` is zero
eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x)
(funext $ λ y : G, calc
-- After that, it's just a chase scene.
(∑ i in s, ((g i * i x - g i * a x) • i : G → L)) y
= ∑ i in s, (g i * i x - g i * a x) * i y : pi.finset_sum_apply _ _ _
... = ∑ i in s, (g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl
(λ _ _, sub_mul _ _ _)
... = ∑ i in s, g i * i x * i y - ∑ i in s, g i * a x * i y : finset.sum_sub_distrib
... = (g a * a x * a y + ∑ i in s, g i * i x * i y)
- (g a * a x * a y + ∑ i in s, g i * a x * i y) : by rw add_sub_add_left_eq_sub
... = ∑ i in insert a s, g i * i x * i y - ∑ i in insert a s, g i * a x * i y :
by rw [finset.sum_insert has, finset.sum_insert has]
... = ∑ i in insert a s, g i * i (x * y) - ∑ i in insert a s, a x * (g i * i y) :
congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc]))
(finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm])
... = (∑ i in insert a s, (g i • i : G → L)) (x * y)
- a x * (∑ i in insert a s, (g i • i : G → L)) y :
by rw [pi.finset_sum_apply, pi.finset_sum_apply, finset.mul_sum]; refl
... = 0 - a x * 0 : by rw hg; refl
... = 0 : by rw [mul_zero, sub_zero])
i
his,
-- On the other hand, since `a` is not already in `s`, for any character `i ∈ s`
-- there is some element of the monoid on which it differs from `a`.
have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his,
classical.by_contradiction $ λ h,
have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩,
has $ hia ▸ his,
-- From these two facts we deduce that `g` actually vanishes on `s`,
have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in
have h : g i • i y = g i • a y, from congr_fun (h1 i his) y,
or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy),
-- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish,
-- we deduce that `g a = 0`.
have h4 : g a = 0, from calc
g a = g a * 1 : (mul_one _).symm
... = (g a • a : G → L) 1 : by rw ← a.map_one; refl
... = (∑ i in insert a s, (g i • i : G → L)) 1 : begin
rw finset.sum_eq_single a,
{ intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] },
{ intros haas, exfalso, apply haas, exact finset.mem_insert_self a s }
end
... = 0 : by rw hg; refl,
-- Now we're done; the last two facts together imply that `g` vanishes on every element of `insert a s`.
(finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩)
lemma le_of_span_le_span {s t u: set M} (zero_ne_one : (0 : R) ≠ 1)
(hl : linear_independent R (coe : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u)
(hst : span R s ≤ span R t) : s ⊆ t :=
begin
have := eq_of_linear_independent_of_span_subtype zero_ne_one
(hl.mono (set.union_subset hsu htu))
(set.subset_union_right _ _)
(set.union_subset (set.subset.trans subset_span hst) subset_span),
rw ← this, apply set.subset_union_left
end
lemma span_le_span_iff {s t u: set M} (zero_ne_one : (0 : R) ≠ 1)
(hl : linear_independent R (coe : u → M)) (hsu : s ⊆ u) (htu : t ⊆ u) :
span R s ≤ span R t ↔ s ⊆ t :=
⟨le_of_span_le_span zero_ne_one hl hsu htu, span_mono⟩
variables (R) (v)
/-- A family of vectors is a basis if it is linearly independent and all vectors are in the span. -/
def is_basis := linear_independent R v ∧ span R (range v) = ⊤
variables {R} {v}
section is_basis
variables {s t : set M} (hv : is_basis R v)
lemma is_basis.mem_span (hv : is_basis R v) : ∀ x, x ∈ span R (range v) := eq_top_iff'.1 hv.2
lemma is_basis.comp (hv : is_basis R v) (f : ι' → ι) (hf : bijective f) :
is_basis R (v ∘ f) :=
begin
split,
{ apply hv.1.comp f hf.1 },
{ rw[set.range_comp, range_iff_surjective.2 hf.2, image_univ, hv.2] }
end
lemma is_basis.injective (hv : is_basis R v) (zero_ne_one : (0 : R) ≠ 1) : injective v :=
λ x y h, linear_independent.injective zero_ne_one hv.1 h
lemma is_basis.range (hv : is_basis R v) : is_basis R (λ x, x : range v → M) :=
⟨hv.1.to_subtype_range, by { convert hv.2, ext i, exact ⟨λ ⟨p, hp⟩, hp ▸ p.2, λ hi, ⟨⟨i, hi⟩, rfl⟩⟩ }⟩
/-- Given a basis, any vector can be written as a linear combination of the basis vectors. They are
given by this linear map. This is one direction of `module_equiv_finsupp`. -/
def is_basis.repr : M →ₗ (ι →₀ R) :=
(hv.1.repr).comp (linear_map.id.cod_restrict _ hv.mem_span)
lemma is_basis.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x :=
hv.1.total_repr ⟨x, _⟩
lemma is_basis.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = linear_map.id :=
linear_map.ext hv.total_repr
lemma is_basis.repr_ker : hv.repr.ker = ⊥ :=
linear_map.ker_eq_bot.2 $ left_inverse.injective hv.total_repr
lemma is_basis.repr_range : hv.repr.range = finsupp.supported R R univ :=
by rw [is_basis.repr, linear_map.range, submodule.map_comp,
linear_map.map_cod_restrict, submodule.map_id, comap_top, map_top, hv.1.repr_range,
finsupp.supported_univ]
lemma is_basis.repr_total (x : ι →₀ R) (hx : x ∈ finsupp.supported R R (univ : set ι)) :
hv.repr (finsupp.total ι M R v x) = x :=
begin
rw [← hv.repr_range, linear_map.mem_range] at hx,
cases hx with w hw,
rw [← hw, hv.total_repr],
end
lemma is_basis.repr_eq_single {i} : hv.repr (v i) = finsupp.single i 1 :=
by apply hv.1.repr_eq_single; simp
/-- Construct a linear map given the value at the basis. -/
def is_basis.constr (f : ι → M') : M →ₗ[R] M' :=
(finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f).comp hv.repr
theorem is_basis.constr_apply (f : ι → M') (x : M) :
(hv.constr f : M → M') x = (hv.repr x).sum (λb a, a • f b) :=
by dsimp [is_basis.constr];
rw [finsupp.total_apply, finsupp.sum_map_domain_index]; simp [add_smul]
lemma is_basis.ext {f g : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, f (v i) = g (v i)) : f = g :=
begin
apply linear_map.ext (λ x, linear_eq_on (range v) _ (hv.mem_span x)),
exact (λ y hy, exists.elim (set.mem_range.1 hy) (λ i hi, by rw ←hi; exact h i))
end
@[simp] lemma constr_basis {f : ι → M'} {i : ι} (hv : is_basis R v) :
(hv.constr f : M → M') (v i) = f i :=
by simp [is_basis.constr_apply, hv.repr_eq_single, finsupp.sum_single_index]
lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (hv : is_basis R v)
(h : ∀i, g i = f (v i)) : hv.constr g = f :=
hv.ext $ λ i, (constr_basis hv).trans (h i)
lemma constr_self (f : M →ₗ[R] M') : hv.constr (λ i, f (v i)) = f :=
constr_eq hv $ λ x, rfl
lemma constr_zero (hv : is_basis R v) : hv.constr (λi, (0 : M')) = 0 :=
constr_eq hv $ λ x, rfl
lemma constr_add {g f : ι → M'} (hv : is_basis R v) :
hv.constr (λi, f i + g i) = hv.constr f + hv.constr g :=
constr_eq hv $ λ b, by simp
lemma constr_neg {f : ι → M'} (hv : is_basis R v) : hv.constr (λi, - f i) = - hv.constr f :=
constr_eq hv $ λ b, by simp
lemma constr_sub {g f : ι → M'} (hs : is_basis R v) :
hv.constr (λi, f i - g i) = hs.constr f - hs.constr g :=
by simp [sub_eq_add_neg, constr_add, constr_neg]
-- this only works on functions if `R` is a commutative ring
lemma constr_smul {ι R M} [comm_ring R] [add_comm_group M] [module R M]
{v : ι → R} {f : ι → M} {a : R} (hv : is_basis R v) :
hv.constr (λb, a • f b) = a • hv.constr f :=
constr_eq hv $ by simp [constr_basis hv] {contextual := tt}
lemma constr_range [nonempty ι] (hv : is_basis R v) {f : ι → M'} :
(hv.constr f).range = span R (range f) :=
by rw [is_basis.constr, linear_map.range_comp, linear_map.range_comp, is_basis.repr_range,
finsupp.lmap_domain_supported, ←set.image_univ, ←finsupp.span_eq_map_total, image_id]
/-- Canonical equivalence between a module and the linear combinations of basis vectors. -/
def module_equiv_finsupp (hv : is_basis R v) : M ≃ₗ[R] ι →₀ R :=
(hv.1.total_equiv.trans (linear_equiv.of_top _ hv.2)).symm
@[simp] theorem module_equiv_finsupp_apply_basis (hv : is_basis R v) (i : ι) :
module_equiv_finsupp hv (v i) = finsupp.single i 1 :=
(linear_equiv.symm_apply_eq _).2 $ by simp [linear_independent.total_equiv]
/-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases
`v` and `v'` and a bijection between the indexing sets of the two bases. -/
def equiv_of_is_basis {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v')
(e : ι ≃ ι') : M ≃ₗ[R] M' :=
{ inv_fun := hv'.constr (v ∘ e.symm),
left_inv := have (hv'.constr (v ∘ e.symm)).comp (hv.constr (v' ∘ e)) = linear_map.id,
from hv.ext $ by simp,
λ x, congr_arg (λ h : M →ₗ[R] M, h x) this,
right_inv := have (hv.constr (v' ∘ e)).comp (hv'.constr (v ∘ e.symm)) = linear_map.id,
from hv'.ext $ by simp,
λ y, congr_arg (λ h : M' →ₗ[R] M', h y) this,
..hv.constr (v' ∘ e) }
/-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases
`v` and `v'` and a bijection between the two bases. -/
def equiv_of_is_basis' {v : ι → M} {v' : ι' → M'} (f : M → M') (g : M' → M)
(hv : is_basis R v) (hv' : is_basis R v')
(hf : ∀i, f (v i) ∈ range v') (hg : ∀i, g (v' i) ∈ range v)
(hgf : ∀i, g (f (v i)) = v i) (hfg : ∀i, f (g (v' i)) = v' i) :
M ≃ₗ M' :=
{ inv_fun := hv'.constr (g ∘ v'),
left_inv :=
have (hv'.constr (g ∘ v')).comp (hv.constr (f ∘ v)) = linear_map.id,
from hv.ext $ λ i, exists.elim (hf i)
(λ i' hi', by simp [constr_basis, hi'.symm]; rw [hi', hgf]),
λ x, congr_arg (λ h:M →ₗ[R] M, h x) this,
right_inv :=
have (hv.constr (f ∘ v)).comp (hv'.constr (g ∘ v')) = linear_map.id,
from hv'.ext $ λ i', exists.elim (hg i')
(λ i hi, by simp [constr_basis, hi.symm]; rw [hi, hfg]),
λ y, congr_arg (λ h:M' →ₗ[R] M', h y) this,
..hv.constr (f ∘ v) }
lemma is_basis_inl_union_inr {v : ι → M} {v' : ι' → M'}
(hv : is_basis R v) (hv' : is_basis R v') :
is_basis R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) :=
begin
split,
apply linear_independent_inl_union_inr' hv.1 hv'.1,
rw [sum.elim_range, span_union,
set.range_comp, span_image (inl R M M'), hv.2, map_top,
set.range_comp, span_image (inr R M M'), hv'.2, map_top],
exact linear_map.sup_range_inl_inr
end
end is_basis
lemma is_basis_singleton_one (R : Type*) [unique ι] [ring R] :
is_basis R (λ (_ : ι), (1 : R)) :=
begin
split,
{ refine linear_independent_iff.2 (λ l, _),
rw [finsupp.unique_single l, finsupp.total_single, smul_eq_mul, mul_one],
intro hi,
simp [hi] },
{ refine top_unique (λ _ _, _),
simp [submodule.mem_span_singleton] }
end
protected lemma linear_equiv.is_basis (hs : is_basis R v)
(f : M ≃ₗ[R] M') : is_basis R (f ∘ v) :=
begin
split,
{ apply @linear_independent.image _ _ _ _ _ _ _ _ _ _ hs.1 (f : M →ₗ[R] M'),
simp [linear_equiv.ker f] },
{ rw set.range_comp,
have : span R ((f : M →ₗ[R] M') '' range v) = ⊤,
{ rw [span_image (f : M →ₗ[R] M'), hs.2],
simp },
exact this }
end
lemma is_basis_span (hs : linear_independent R v) :
@is_basis ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self _)⟩) _ _ _ :=
begin
split,
{ apply linear_independent_span hs },
{ rw eq_top_iff',
intro x,
have h₁ : subtype.val '' set.range (λ i, subtype.mk (v i) _) = range v,
by rw ←set.range_comp,
have h₂ : map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _)))
= span R (range v),
by rw [←span_image, submodule.subtype_eq_val, h₁],
have h₃ : (x : M) ∈ map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))),
by rw h₂; apply subtype.mem x,
rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩,
have h_x_eq_y : x = y,
by rw [subtype.ext_iff, ← hy₂]; simp,
rw h_x_eq_y,
exact hy₁ }
end
lemma is_basis_empty (h_empty : ¬ nonempty ι) (h : ∀x:M, x = 0) : is_basis R (λ x : ι, (0 : M)) :=
⟨ linear_independent_empty_type h_empty,
eq_top_iff'.2 $ assume x, (h x).symm ▸ submodule.zero_mem _ ⟩
lemma is_basis_empty_bot (h_empty : ¬ nonempty ι) :
is_basis R (λ _ : ι, (0 : (⊥ : submodule R M))) :=
begin
apply is_basis_empty h_empty,
intro x,
apply subtype.ext_iff_val.2,
exact (submodule.mem_bot R).1 (subtype.mem x),
end
open fintype
variables [fintype ι] (h : is_basis R v)
/-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`.
-/
def equiv_fun_basis : M ≃ₗ[R] (ι → R) :=
linear_equiv.trans (module_equiv_finsupp h)
{ to_fun := finsupp.to_fun,
map_add' := λ x y, by ext; exact finsupp.add_apply,
map_smul' := λ x y, by ext; exact finsupp.smul_apply,
..finsupp.equiv_fun_on_fintype }
/-- A module over a finite ring that admits a finite basis is finite. -/
def module.fintype_of_fintype [fintype R] : fintype M :=
fintype.of_equiv _ (equiv_fun_basis h).to_equiv.symm
theorem module.card_fintype [fintype R] [fintype M] :
card M = (card R) ^ (card ι) :=
calc card M = card (ι → R) : card_congr (equiv_fun_basis h).to_equiv
... = card R ^ card ι : card_fun
/-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps
a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/
@[simp] lemma equiv_fun_basis_symm_apply (x : ι → R) :
(equiv_fun_basis h).symm x = ∑ i, x i • v i :=
begin
change finsupp.sum
((finsupp.equiv_fun_on_fintype.symm : (ι → R) ≃ (ι →₀ R)) x) (λ (i : ι) (a : R), a • v i)
= ∑ i, x i • v i,
dsimp [finsupp.equiv_fun_on_fintype, finsupp.sum],
rw finset.sum_filter,
refine finset.sum_congr rfl (λi hi, _),
by_cases H : x i = 0,
{ simp [H] },
{ simp [H], refl }
end
end module
section vector_space
variables
{v : ι → V}
[field K] [add_comm_group V] [add_comm_group V']
[vector_space K V] [vector_space K V']
{s t : set V} {x y z : V}
include K
open submodule
/- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class
(instead of a data containing type class) -/
section
lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) :=
begin
simp [mem_span_insert],
rintro a z hz rfl h,
refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩,
have a0 : a ≠ 0, {rintro rfl, simp * at *},
simp [a0, smul_add, smul_smul]
end
end
lemma linear_independent_iff_not_mem_span :
linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) :=
begin
apply linear_independent_iff_not_smul_mem_span.trans,
split,
{ intros h i h_in_span,
apply one_ne_zero (h i 1 (by simp [h_in_span])) },
{ intros h i a ha,
by_contradiction ha',
exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) }
end
lemma linear_independent_unique [unique ι] (h : v (default ι) ≠ 0): linear_independent K v :=
begin
rw linear_independent_iff,
intros l hl,
ext i,
rw [unique.eq_default i, finsupp.zero_apply],
by_contra hc,
have := smul_smul (l (default ι))⁻¹ (l (default ι)) (v (default ι)),
rw [finsupp.unique_single l, finsupp.total_single] at hl,
rw [hl, inv_mul_cancel hc, smul_zero, one_smul] at this,
exact h this.symm
end
lemma linear_independent_singleton {x : V} (hx : x ≠ 0) :
linear_independent K (λ x, x : ({x} : set V) → V) :=
begin
apply @linear_independent_unique _ _ _ _ _ _ _ _ _,
apply set.unique_singleton,
apply hx,
end
lemma disjoint_span_singleton {p : submodule K V} {x : V} (x0 : x ≠ 0) :
disjoint p (span K {x}) ↔ x ∉ p :=
⟨λ H xp, x0 (disjoint_def.1 H _ xp (singleton_subset_iff.1 subset_span:_)),
begin
simp [disjoint_def, mem_span_singleton],
rintro xp y yp a rfl,
by_cases a0 : a = 0, {simp [a0]},
exact xp.elim ((smul_mem_iff p a0).1 yp),
end⟩
lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) :
linear_independent K (λ b, b : insert x s → V) :=
begin
rw ← union_singleton,
have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx,
apply hs.union (linear_independent_singleton x0),
rwa [disjoint_span_singleton x0]
end
lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) :
∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) :=
begin
rcases zorn.zorn_subset₀ {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _
⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩,
{ refine ⟨b, bt, sb, λ x xt, _, bi⟩,
by_contra hn,
apply hn,
rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _),
exact subset_span (mem_insert _ _) },
{ refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩,
{ exact sUnion_subset (λ x xc, (hc xc).1) },
{ exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) },
{ exact subset_sUnion_of_mem } }
end
lemma exists_subset_is_basis (hs : linear_independent K (λ x, x : s → V)) :
∃b, s ⊆ b ∧ is_basis K (coe : b → V) :=
let ⟨b, hb₀, hx, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in
⟨ b, hx,
@linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ hb₃,
by simp; exact eq_top_iff.2 hb₂⟩
lemma exists_sum_is_basis (hs : linear_independent K v) :
∃ (ι' : Type u) (v' : ι' → V), is_basis K (sum.elim v v') :=
begin
-- This is a hack: we jump through hoops to reuse `exists_subset_is_basis`.
let s := set.range v,
let e : ι ≃ s := equiv.set.range v (hs.injective zero_ne_one),
have : (λ x, x : s → V) = v ∘ e.symm := by { funext, dsimp, rw [equiv.set.apply_range_symm v], },
have : linear_independent K (λ x, x : s → V),
{ rw this,
exact linear_independent.comp hs _ (e.symm.injective), },
obtain ⟨b, ss, is⟩ := exists_subset_is_basis this,
let e' : ι ⊕ (b \ s : set V) ≃ b :=
calc ι ⊕ (b \ s : set V) ≃ s ⊕ (b \ s : set V) : equiv.sum_congr e (equiv.refl _)
... ≃ b : equiv.set.sum_diff_subset ss,
refine ⟨(b \ s : set V), λ x, x.1, _⟩,
convert is_basis.comp is e' _,
{ funext x,
cases x; simp; refl, },
{ exact e'.bijective, },
end
variables (K V)
lemma exists_is_basis : ∃b : set V, is_basis K (λ i, i : b → V) :=
let ⟨b, _, hb⟩ := exists_subset_is_basis (linear_independent_empty K V : _) in ⟨b, hb⟩
variables {K V}
-- TODO(Mario): rewrite?
lemma exists_of_linear_independent_of_finite_span {t : finset V}
(hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) :
∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card :=
have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) →
∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card :=
assume t, finset.induction_on t
(assume s' hs' _ hss',
have s = ↑s',
from eq_of_linear_independent_of_span_subtype zero_ne_one hs hs' $
by simpa using hss',
⟨s', by simp [this]⟩)
(assume b₁ t hb₁t ih s' hs' hst hss',
have hb₁s : b₁ ∉ s,
from assume h,
have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩,
by rwa [hst] at this,
have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h,
have hst : s ∩ ↑t = ∅,
from eq_empty_of_subset_empty $ subset.trans
(by simp [inter_subset_inter, subset.refl]) (le_of_eq hst),
classical.by_cases
(assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V),
let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in
have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t,
⟨insert b₁ u, by simp [insert_subset_insert hust],
subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩)
(assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V),
let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in
have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h,
have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from
assume b₃ hb₃,
have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V),
by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right],
have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)),
from span_mono this (hss' hb₃),
have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V),
by simpa [insert_eq, -singleton_union, -union_singleton] using hss',
have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)),
from mem_span_insert_exchange (this hb₂s) hb₂t,
by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃,
let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in
⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]),
hsu, by simp [eq, hb₂t', hb₁t, hb₁s']⟩)),
begin
have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t,
{ ext1 x,
by_cases x ∈ s; simp * },
apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s))
(by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])),
intros u h,
exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}),
h.2.1, by simp only [h.2.2, eq]⟩
end
lemma exists_finite_card_le_of_finite_of_linear_independent_of_span
(ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) :
∃h : finite s, h.to_finset.card ≤ ht.to_finset.card :=
have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption,
let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in
have finite s, from u.finite_to_set.subset hsu,
⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩
lemma linear_map.exists_left_inverse_of_injective (f : V →ₗ[K] V')
(hf_inj : f.ker = ⊥) : ∃g:V' →ₗ V, g.comp f = linear_map.id :=
begin
rcases exists_is_basis K V with ⟨B, hB⟩,
have hB₀ : _ := hB.1.to_subtype_range,
have : linear_independent K (λ x, x : f '' B → V'),
{ have h₁ := hB₀.image_subtype
(show disjoint (span K (range (λ i : B, i.val))) (linear_map.ker f), by simp [hf_inj]),
rwa subtype.range_coe at h₁ },
rcases exists_subset_is_basis this with ⟨C, BC, hC⟩,
haveI : inhabited V := ⟨0⟩,
use hC.constr (C.restrict (inv_fun f)),
refine hB.ext (λ b, _),
rw image_subset_iff at BC,
have : f b = (⟨f b, BC b.2⟩ : C) := rfl,
dsimp,
rw [this, constr_basis hC],
exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _
end
lemma submodule.exists_is_compl (p : submodule K V) : ∃ q : submodule K V, is_compl p q :=
let ⟨f, hf⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in
⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩
lemma linear_map.exists_right_inverse_of_surjective (f : V →ₗ[K] V')
(hf_surj : f.range = ⊤) : ∃g:V' →ₗ V, f.comp g = linear_map.id :=
begin
rcases exists_is_basis K V' with ⟨C, hC⟩,
haveI : inhabited V := ⟨0⟩,
use hC.constr (C.restrict (inv_fun f)),
refine hC.ext (λ c, _),
simp [constr_basis hC, right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) c]
end
open submodule linear_map
theorem quotient_prod_linear_equiv (p : submodule K V) :
nonempty ((p.quotient × p) ≃ₗ[K] V) :=
let ⟨q, hq⟩ := p.exists_is_compl in nonempty.intro $
((quotient_equiv_of_is_compl p q hq).prod (linear_equiv.refl _ _)).trans
(prod_equiv_of_is_compl q p hq.symm)
open fintype
variables (K) (V)
theorem vector_space.card_fintype [fintype K] [fintype V] :
∃ n : ℕ, card V = (card K) ^ n :=
exists.elim (exists_is_basis K V) $ λ b hb, ⟨card b, module.card_fintype hb⟩
end vector_space
namespace pi
open set linear_map
section module
variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*}
variables [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)]
lemma linear_independent_std_basis
(v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) :
linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) :=
begin
have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)),
{ intro j,
apply linear_independent.image (hs j),
simp [ker_std_basis] },
apply linear_independent_Union_finite hs',
{ assume j J _ hiJ,
simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union],
have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))
≤ range (std_basis R Ms j),
{ intro j,
rw [span_le, linear_map.range_coe],
apply range_comp_subset_range },
have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))
≤ ⨆ i ∈ {j}, range (std_basis R Ms i),
{ rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)),
apply h₀ },
have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤
⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) :=
supr_le_supr (λ i, supr_le_supr (λ H, h₀ i)),
have h₃ : disjoint (λ (i : η), i ∈ {j}) J,
{ convert set.disjoint_singleton_left.2 hiJ,
rw ←@set_of_mem_eq _ {j},
refl },
exact (disjoint_std_basis_std_basis _ _ _ _ h₃).mono h₁ h₂ }
end
variable [fintype η]
lemma is_basis_std_basis (s : Πj, ιs j → (Ms j)) (hs : ∀j, is_basis R (s j)) :
is_basis R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (s ji.1 ji.2)) :=
begin
split,
{ apply linear_independent_std_basis _ (assume i, (hs i).1) },
have h₁ : Union (λ j, set.range (std_basis R Ms j ∘ s j))
⊆ range (λ (ji : Σ (j : η), ιs j), (std_basis R Ms (ji.fst)) (s (ji.fst) (ji.snd))),
{ apply Union_subset, intro i,
apply range_comp_subset_range (λ x : ιs i, (⟨i, x⟩ : Σ (j : η), ιs j))
(λ (ji : Σ (j : η), ιs j), std_basis R Ms (ji.fst) (s (ji.fst) (ji.snd))) },
have h₂ : ∀ i, span R (range (std_basis R Ms i ∘ s i)) = range (std_basis R Ms i),
{ intro i,
rw [set.range_comp, submodule.span_image, (assume i, (hs i).2), submodule.map_top] },
apply eq_top_mono,
apply span_mono h₁,
rw span_Union,
simp only [h₂],
apply supr_range_std_basis
end
section
variables (R η)
lemma is_basis_fun₀ : is_basis R
(λ (ji : Σ (j : η), unit),
(std_basis R (λ (i : η), R) (ji.fst)) 1) :=
@is_basis_std_basis R η (λi:η, unit) (λi:η, R) _ _ _ _ (λ _ _, (1 : R))
(assume i, @is_basis_singleton_one _ _ _ _)
lemma is_basis_fun : is_basis R (λ i, std_basis R (λi:η, R) i 1) :=
begin
apply (is_basis_fun₀ R η).comp (λ i, ⟨i, punit.star⟩),
apply bijective_iff_has_inverse.2,
use sigma.fst,
suffices : ∀ (a : η) (b : unit), punit.star = b,
{ simpa [function.left_inverse, function.right_inverse] },
exact λ _, punit_eq _
end
end
end module
end pi
|
874c35f45e9b1aa6831cc6afb3ec7f0897668489 | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/run/namespaceIssue.lean | be7d67d78b99692b59c788a1bed69b08eabd67b7 | [
"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 | 86 | lean | new_frontend
def Bla.x := 10
namespace Foo
export Bla(x)
end Foo
open Foo
#check x
|
1b7e181027c063c09094039c0f3719fc3e2cdf07 | 35c41e824c38dc6aa7f0b1467f4d5bc33d61f260 | /xenalib/M1Fstuff.lean | 9d5d2aa87c24eceaeae4bd34f3e2500d263d026c | [] | no_license | kckennylau/xena | 697eb8f55a8f1ce456a241e8b8e4e8a27b91438e | 7dc03dc9588d30d7d36b6904b59ca63a72096229 | refs/heads/master | 1,627,104,810,584 | 1,509,486,416,000 | 1,509,486,416,000 | 107,829,951 | 0 | 0 | null | 1,509,486,381,000 | 1,508,637,567,000 | Lean | UTF-8 | Lean | false | false | 22,591 | lean | import analysis.real init.classical
-- instance coe_rat_real : has_coe rat real := ⟨of_rat⟩
-- example : has_coe int real := by apply_instance
-- instance coe_int_real : has_coe int real := ⟨of_rat ∘ rat.of_int⟩
-- example : has_coe int real := by apply_instance
-- instance coe_nat_real : has_coe nat real := ⟨of_rat ∘ rat.of_int ∘ int.of_nat⟩
-- example : right_cancel_semigroup ℝ := by apply_instance
lemma of_rat_lt_of_rat {q₁ q₂ : ℚ} : of_rat q₁ < of_rat q₂ ↔ q₁ < q₂ :=
begin
simp [lt_iff_le_and_ne, of_rat_le_of_rat]
end
#check @of_rat_inv
run_cmd mk_simp_attr `real_simps
attribute [real_simps] of_rat_zero of_rat_one of_rat_neg of_rat_add of_rat_sub of_rat_mul
attribute [real_simps] of_rat_inv of_rat_le_of_rat of_rat_lt_of_rat
@[real_simps] lemma of_rat_bit0 (a : ℚ) : bit0 (of_rat a) = of_rat (bit0 a) := of_rat_add
@[real_simps] lemma of_rat_bit1 (a : ℚ) : bit1 (of_rat a) = of_rat (bit1 a) :=
by simp [bit1, bit0, of_rat_add,of_rat_one]
@[real_simps] lemma of_rat_div {r₁ r₂ : ℚ} : of_rat r₁ / of_rat r₂ = of_rat (r₁ / r₂) :=
by simp [has_div.div, algebra.div] with real_simps
-- Helpful simp lemmas for reals: thanks to Sebastian Ullrich
run_cmd mk_simp_attr `real_simps2
attribute [real_simps2] rat.cast_zero rat.cast_one rat.cast_neg rat.cast_add rat.cast_sub rat.cast_mul
attribute [real_simps2] rat.cast_le rat.cast_lt rat.cast_bit0 rat.cast_bit1
-- set_option pp.notation false
noncomputable example : discrete_field ℝ := by apply_instance
noncomputable example : division_ring ℝ := by apply_instance
-- set_option pp.all true
/-
@[real_simps2] lemma rat_cast_inv {α : Type} [discrete_field α] [linear_ordered_field α] (r : ℚ) : ((r⁻¹:ℚ):α) = ((r:ℚ):α)⁻¹ :=
begin
cases classical.em (r=0) with Hz Hnz,
rw Hz,
rw [inv_zero,rat.cast_zero],
exact eq.symm (@inv_zero α _inst_1), -- ,inv_zero],
have Hup_nz : ¬ (↑r:α)=0,
intro Hup_z,
rw [←rat.cast_zero] at Hup_z,
-- rw [rat.cast_inj] at Hup_z,
-- rw [mul_eq_mul],
-- simp [Hnz]
admit,
admit
end
#check @rat.cast_inj
#check @inv_zero
#check @rat.cast_zero
#check @eq_inv_iff_mul_eq_one
-/
-- @[real_simps2] lemma rat_cast_div {α : Type} [linear_ordered_field α] (r₁ r₂ : ℚ) : (r₁:α) / (r₂:α) = (((r₁ / r₂):ℚ):α) :=
-- by simp [has_div.div, algebra.div] with real_simps2
-- #check rat_cast_div
-- set_option pp.all true
-- I don't understand this code; however it is the only way that I as
-- a muggle know how to access norm_num. Thanks to Mario Carneiro
namespace tactic
meta def eval_num_tac : tactic unit :=
do t ← target,
(lhs, rhs) ← match_eq t,
(new_lhs, pr1) ← norm_num lhs,
(new_rhs, pr2) ← norm_num rhs,
is_def_eq new_lhs new_rhs,
`[exact eq.trans %%pr1 (eq.symm %%pr2)]
end tactic
example : (((3:real)/4)-12)<6 := by simp with real_simps;exact dec_trivial
example : (6:real) + 9 = 15 := by tactic.eval_num_tac
example : (2:real) * 2 + 3 = 7 := by tactic.eval_num_tac
example : (5:real) ≠ 8 := by simp with real_simps;exact dec_trivial
example : (6:real) < 10 := by simp with real_simps;exact dec_trivial
-- variable α : Type
-- example : set α = (α → Prop) := rfl
/-
#print nonempty
-- set_option pp.all true
noncomputable def floor_with_proof : ℝ → ℤ := λ x,
begin
-- have H2 : 0+x < 1+x, by
-- apply add_lt_add_of_lt_of_le (zero_lt_one) (le_of_eq (rfl)),
-- have H3 : x < x+1, by simp [H2],
let rat_in_interval := {q // x < of_rat q ∧ of_rat q < x + 1},
have H : ∃ (q : ℚ), x < of_rat q ∧ of_rat q < x + 1,
exact @exists_lt_of_rat_of_rat_gt x (x+1) (by simp [zero_lt_one]),
have H2 : ∃ (s : rat_in_interval), true,
simp [H],
have H3 : nonempty rat_in_interval,
apply exists.elim H2,
intro a,
intro Pa,
constructor,
exact a,
have qHq : rat_in_interval := classical.choice (H3),
cases qHq with q Hq,
exact (if (x < rat.floor q) then rat.floor q - 1 else rat.floor q ),
end
-- theorems need classical logic
-- should it be
-- theorem floor_le : ∀ x, floor x ≤ x
-- or
-- theorem floor_ge : ∀ x, x ≥ floor x
-- or any other combination of these ideas?
-- How many? One? Four?
noncomputable theorem floor_le (x : ℝ) : ↑(floor x) ≤ x :=
begin
unfold floor,
simp,
have n : ℤ := floor x,
admit,
end
-- should I prove floor + 1 or 1 + floor?
theorem lt_floor_add_one (x : ℝ) : x < 1 + floor x := sorry
-/
-- set_option pp.notation false
-- set_option pp.all true
-- #check le_of_lt
-- noncomputable example : preorder ℝ := by apply_instance
-- #print sub_lt_iff
-- #check @rat.cast_le
-- #check sub_lt
theorem floor_real_exists : ∀ (x : ℝ), ∃ (n : ℤ), ↑n ≤ x ∧ x < n+1 :=
begin
intro x,
have H : ∃ (q : ℚ), x < ↑q ∧ ↑q < x + 1,
exact @exists_rat_btwn x (x+1) (by simp [zero_lt_one]),
cases H with q Hq,
cases classical.em (x < rat.floor q) with Hb Hs,
exact ⟨rat.floor q - 1,
begin
split,
simp [rat.floor_le q,Hq.right],
suffices H7 : (↑q:real) ≤ x+1,
exact calc (↑(rat.floor q):ℝ) = (↑((rat.floor q):ℚ):ℝ) : by simp
... ≤ (↑q:ℝ) : rat.cast_le.mpr (rat.floor_le q)
... ≤ x+1 : H7,
exact le_of_lt Hq.right,
simp,
rw [←add_assoc],
simp [Hb]
end
⟩,
exact ⟨rat.floor q,
begin
split,
{
have H : (x < ↑(rat.floor q)) ∨ (x ≥ ↑(rat.floor q)),
exact lt_or_ge x ↑(rat.floor q),
cases H with F T,
exact false.elim (Hs F),
exact T
},
{
clear Hs,
have H1 : x < ↑q,
{ exact Hq.left },
clear Hq,
/-
rw [←coe_rat_eq_of_rat] at H1,
suffices H2 : x < ↑(rat.floor q) + ↑(1:ℤ),
simp [H2],
suffices H3 : q < ↑(((rat.floor q):ℤ):ℚ) + ↑(1:ℤ),
exact lt_trans H1 _,-- (by rw [←rat.cast_add]),
-/
-- insanity starts here
suffices H2 : q < ↑((rat.floor q)+(1:ℤ)),
have H3 : ¬ (rat.floor q + 1 ≤ rat.floor q),
intro H4,
suffices H5 : rat.floor q < rat.floor q + 1,
exact (lt_iff_not_ge (rat.floor q) ((rat.floor q)+1)).mp H5 H4,
-- exact (lt_iff_not_ge q (((rat.floor q) + 1):int):rat).mpr,
simp,
tactic.swap,
apply (lt_iff_not_ge q _).mpr,
intro H2,
have H3 : (rat.floor q) + 1 ≤ rat.floor q,
exact rat.le_floor.mpr H2,
have H4: (1:ℤ) > 0,
exact int.one_pos,
suffices H5 : (rat.floor q) + 1 > rat.floor q,
exact (lt_iff_not_ge (rat.floor q) (rat.floor q + 1)).mp H5 H3,
-- rw [add_comm (rat.floor q) (1:ℤ)],
-- exact add_lt_add_left H4 (rat.floor q),add_zero (rat.floor q)],
have H6 :rat.floor q + 0 < rat.floor q + 1,
exact (add_lt_add_left H4 (rat.floor q)),
exact @eq.subst _ (λ y, y < rat.floor q + 1) _ _ (add_zero (rat.floor q)) H6,
clear H3,
suffices H3 : of_rat q < ↑(rat.floor q) + 1,
-- exact lt.trans H1 H3,
exact calc x < ↑q : H1
... = of_rat q : coe_rat_eq_of_rat q
... < ↑(rat.floor q) + 1 : H3,
clear H1,
rw [←coe_rat_eq_of_rat],
have H : (↑(rat.floor q):ℝ) + (1:ℝ) = (((rat.floor q):ℚ):ℝ) + (((1:ℤ):ℚ):ℝ),
simp,
rw [H,←rat.cast_add,rat.cast_lt,←int.cast_add],
exact H2
}
end⟩
end
theorem square_cont_at_zero : ∀ (r:ℝ), r>0 → ∃ (eps:ℝ),(eps>0) ∧ eps^2<r :=
begin
intros r Hrgt0,
cases classical.em (r<1) with Hrl1 Hrnl1,
have H : r^2<r,
unfold pow_nat has_pow_nat.pow_nat monoid.pow,
simp,
exact calc r*r < r*1 : mul_lt_mul_of_pos_left Hrl1 Hrgt0
... = r : mul_one r,
existsi r,
exact ⟨Hrgt0,H⟩,
have Hrge1 : r ≥ 1,
exact le_of_not_lt Hrnl1,
cases le_iff_eq_or_lt.mp Hrge1 with r1 rg1,
existsi ((1/2):ℝ),
split,
suffices H : 0 < ((1/2):ℝ),
exact H,
simp with real_simps,
exact dec_trivial,
-- *TODO* 1/2 > 0 doesn't work!
-- need of_rat_gt, not in realsimps
rw [←r1],
unfold pow_nat has_pow_nat.pow_nat monoid.pow,
simp with real_simps,
exact dec_trivial,
clear Hrnl1 Hrge1,
existsi (1:ℝ),
split,
exact zero_lt_one,
unfold pow_nat has_pow_nat.pow_nat monoid.pow,
simp,
exact rg1
end
theorem exists_square_root (r:ℝ) (rnneg : r ≥ 0) : ∃ (q : ℝ), (q ≥ 0) ∧ q^2=r :=
begin
cases le_iff_eq_or_lt.mp rnneg with r0 rpos,
rw [←r0],
have H : (0:ℝ)≥ 0 ∧ (0:ℝ)^2 = 0,
split,
exact le_of_eq (by simp),
unfold pow_nat has_pow_nat.pow_nat monoid.pow,
simp,
exact ⟨(0:ℝ),H⟩,
clear rnneg,
let s := { x:ℝ | x^2 ≤ r},
have H0 : (0:ℝ) ∈ s,
simp,
unfold pow_nat has_pow_nat.pow_nat monoid.pow,
simp,
exact le_of_lt rpos,
have H1 : max r 1 ∈ upper_bounds s,
cases classical.em (r ≤ 1) with rle1 rgt1,
unfold upper_bounds,
unfold set_of,
intro t,
intro Ht,
suffices H : t ≤ 1,
exact le_trans H (le_max_right r 1),
have H : t^2 ≤ 1,
exact le_trans Ht rle1,
cases classical.em (t≤1) with tle1 tgt1,
exact tle1,
have H2: t > 1,
exact lt_of_not_ge tgt1,
exfalso,
have H3 : t*t>1,
exact calc 1<t : H2
... = t*1 : eq.symm (mul_one t)
... < t*t : mul_lt_mul_of_pos_left H2 (lt_trans zero_lt_one H2),
unfold pow_nat has_pow_nat.pow_nat monoid.pow at H,
simp at H,
exact not_lt_of_ge H H3,
have H : 1<r,
exact lt_of_not_ge rgt1,
unfold upper_bounds,
unfold set_of,
intro t,
intro Ht,
suffices H : t ≤ r,
exact le_trans H (le_max_left r 1),
cases classical.em (t≤r) with Hl Hg,
exact Hl,
have H1 : r<t,
exact lt_of_not_ge Hg,
have H2 : t^2 ≤ r,
exact Ht,
clear H0 Ht s Hg rgt1,
exfalso,
have H3 : 1<t,
exact lt_trans H H1,
have H4 : t^2 < t,
exact lt_of_le_of_lt H2 H1,
have H5 : t < t^2,
exact calc t = 1*t : eq.symm (one_mul t)
... < t*t : mul_lt_mul_of_pos_right H3 (lt_trans zero_lt_one H3)
... = t^2 : by {unfold pow_nat has_pow_nat.pow_nat monoid.pow,simp},
have H6 : t < t,
exact lt_trans H5 H4,
have H7 : ¬ (t=t),
exact ne_of_lt H6,
exact H7 (rfl),
have H : ∃ (x : ℝ), is_lub s x,
exact exists_supremum_real H0 H1,
cases H with q Hq,
existsi q,
unfold is_lub at Hq,
unfold is_least at Hq,
split,
exact Hq.left 0 H0,
have Hqge0 : 0 ≤ q,
exact Hq.left 0 H0,
-- idea is to prove q^2=r by showing not < or >
-- first not <
have H2 : ¬ (q^2<r),
intro Hq2r,
have H2 : q ∈ upper_bounds s,
exact Hq.left,
clear Hq H0 H1,
unfold upper_bounds at H2,
have H3 : ∀ qe, q<qe → ¬(qe^2≤r),
intro qe,
intro qlqe,
intro H4,
have H5 : qe ≤ q,
exact H2 qe H4,
exact not_lt_of_ge H5 qlqe,
have H4 : ∀ eps > 0,(q+eps)^2>r,
intros eps Heps,
exact lt_of_not_ge (H3 (q+eps) ((lt_add_iff_pos_right q).mpr Heps)),
clear H3 H2 s,
cases le_iff_eq_or_lt.mp Hqge0 with Hq0 Hqg0,
cases (square_cont_at_zero r rpos) with eps Heps,
specialize H4 eps,
rw [←Hq0] at H4,
simp at H4,
have H3 : eps^2>r,
exact H4 Heps.left,
exact (lt_iff_not_ge r (eps^2)).mp H3 (le_of_lt Heps.right),
clear Hqge0,
-- want eps such that 2*q*eps+eps^2 <= r-q^2
-- so eps=min((r-q^2)/4q,thing-produced-by-square-cts-function)
have H0 : (0:ℝ)<2,
simp with real_simps,
exact dec_trivial,
have H : 0<(r-q^2),
exact sub_pos_of_lt Hq2r,
have H2 : 0 < (r-q^2)/2,
exact div_pos_of_pos_of_pos H H0,
have H3 : 0 < (r-q^2)/2/(2*q),
exact div_pos_of_pos_of_pos H2 (mul_pos H0 Hqg0),
cases (square_cont_at_zero ((r-q^2)/2) H2) with e0 He0,
let e1 := min ((r-q^2)/2/(2*q)) e0,
have He1 : e1>0,
exact lt_min H3 He0.left,
specialize H4 e1, -- should be a contradiction
have H1 : (q+e1)^2 > r,
exact H4 He1,
have H5 : e1 ≤ ((r-q^2)/2/(2*q)),
exact (min_le_left ((r-q^2)/2/(2*q)) e0),
have H6 : e1*e1<(r - q ^ 2) / 2,
exact calc e1*e1 ≤ e0*e1 : mul_le_mul_of_nonneg_right (min_le_right ((r - q ^ 2) / 2 / (2 * q)) e0) (le_of_lt He1)
... ≤ e0*e0 : mul_le_mul_of_nonneg_left (min_le_right ((r - q ^ 2) / 2 / (2 * q)) e0) (le_of_lt He0.left )
... = e0^2 : by {unfold pow_nat has_pow_nat.pow_nat monoid.pow,simp}
... < (r-q^2)/2 : He0.right,
have Hn1 : (q+e1)^2 < r,
exact calc (q+e1)^2 = (q+e1)*(q+e1) : by {unfold pow_nat has_pow_nat.pow_nat monoid.pow,simp}
... = q*q+2*q*e1+e1*e1 : by rw [mul_add,add_mul,add_mul,mul_comm e1 q,two_mul,add_mul,add_assoc,add_assoc,add_assoc]
... = q^2 + (2*q)*e1 + e1*e1 : by {unfold pow_nat has_pow_nat.pow_nat monoid.pow,simp}
... ≤ q^2 + (2*q)*((r - q ^ 2) / 2 / (2 * q)) + e1*e1 : add_le_add_right (add_le_add_left ((mul_le_mul_left (mul_pos H0 Hqg0)).mpr H5) (q^2)) (e1*e1)
... < q^2 + (2*q)*((r - q ^ 2) / 2 / (2 * q)) + (r-q^2)/2 : add_lt_add_left H6 _
... = r : by rw [mul_comm,div_mul_eq_mul_div,mul_div_assoc,div_self (ne_of_gt (mul_pos H0 Hqg0)),mul_one,add_assoc,div_add_div_same,←two_mul,mul_comm,mul_div_assoc,div_self (ne_of_gt H0),mul_one,add_sub,add_comm,←add_sub,sub_self,add_zero], -- rw [mul_div_cancel'], -- nearly there
exact not_lt_of_ge (le_of_lt H1) Hn1,
-- now not >
have H3 : ¬ (q^2>r),
intro Hq2r,
have H3 : q ∈ lower_bounds (upper_bounds s),
exact Hq.right,
clear Hq H0 H1 H2,
have Hqg0 : 0 < q,
cases le_iff_eq_or_lt.mp Hqge0 with Hq0 H,
tactic.swap,
exact H,
unfold pow_nat has_pow_nat.pow_nat monoid.pow at Hq2r,
rw [←Hq0] at Hq2r,
simp at Hq2r,
exfalso,
exact not_lt_of_ge (le_of_lt rpos) Hq2r,
clear Hqge0,
have H : ∀ (eps:ℝ), (eps > 0 ∧ eps < q) → (q-eps)^2 < r,
unfold lower_bounds at H3,
unfold set_of at H3,
unfold has_mem.mem set.mem has_mem.mem at H3,
intros eps Heps,
have H : ¬ ((q-eps) ∈ (upper_bounds s)),
intro H,
have H2 : q ≤ q-eps,
exact H3 (q-eps) H,
rw [le_sub_iff_add_le] at H2,
have Hf : q<q,
exact calc
q < eps+q : lt_add_of_pos_left q Heps.left
... = q+eps : add_comm eps q
... ≤ q : H2,
have Hf2 : ¬ (q=q),
exact ne_of_lt Hf,
exact Hf2 (by simp),
unfold upper_bounds at H,
unfold has_mem.mem set.mem has_mem.mem set_of at H,
have H2 : ∃ (b:ℝ), ¬ (s b → b ≤ q-eps),
exact classical.not_forall.mp H,
cases H2 with b Hb,
clear H,
cases classical.em (s b) with Hsb Hsnb,
tactic.swap,
have Hnb : s b → b ≤ q - eps,
intro Hsb,
exfalso,
exact Hsnb Hsb,
exfalso,
exact Hb Hnb,
cases classical.em (b ≤ q - eps) with Hlt Hg,
exfalso,
exact Hb (λ _,Hlt),
have Hh : q-eps < b,
exact lt_of_not_ge Hg,
clear Hg Hb,
-- todo: (q-eps)>0, (q-eps)^2<b^2<=r,
have H0 : 0<q-eps,
rw [lt_sub_iff,zero_add],exact Heps.right,
unfold pow_nat has_pow_nat.pow_nat monoid.pow,
exact calc (q-eps)*((q-eps)*1) = (q-eps)*(q-eps) : congr_arg (λ t, (q-eps)*t) (mul_one (q-eps))
... < (q-eps) * b : mul_lt_mul_of_pos_left Hh H0
... < b * b : mul_lt_mul_of_pos_right Hh (lt_trans H0 Hh)
... = b^2 : by { unfold pow_nat has_pow_nat.pow_nat monoid.pow, simp}
... ≤ r : Hsb,
-- We now know (q-eps)^2<r for all eps>0, and q^2>r. Need a contradiction.
-- Idea: (q^2-2*q*eps+eps^2)<r so 2q.eps-eps^2>q^2-r>0,
-- so we need to find eps such that 2q.eps-eps^2<(q^2-r)
-- so set eps=min((q^2-r)/2q,q)
have H0 : (0:ℝ)<2,
simp with real_simps,
exact dec_trivial,
have H1 : 0<(q^2-r),
exact sub_pos_of_lt Hq2r,
have H2 : 0 < (q/2),
exact div_pos_of_pos_of_pos Hqg0 H0,
have J1 : 0 < (q^2-r)/(2*q),
exact div_pos_of_pos_of_pos H1 (mul_pos H0 Hqg0),
let e1 := min ((q^2-r)/(2*q)) (q/2),
have He1 : e1>0,
exact lt_min J1 H2,
specialize H e1, -- should be a contradiction
have J0 : e1<q,
exact calc e1 ≤ (q/2) : min_le_right ((q^2-r)/(2*q)) (q/2)
... = q*(1/2) : by rw [←mul_div_assoc,mul_one]
... < q*1 : mul_lt_mul_of_pos_left (by simp with real_simps;exact dec_trivial) Hqg0
... = q : by rw [mul_one],
have H4 : (q-e1)^2 < r,
exact H ⟨He1,J0⟩,
have H5 : e1 ≤ ((q^2-r)/(2*q)),
exact (min_le_left ((q^2-r)/(2*q)) (q/2)),
have H6 : e1*e1>0,
exact mul_pos He1 He1,
have Hn1 : (q-e1)^2 > r,
exact calc (q-e1)^2 = (q-e1)*(q-e1) : by {unfold pow_nat has_pow_nat.pow_nat monoid.pow,simp}
... = q*q-2*q*e1+e1*e1 : by rw [mul_sub,sub_mul,sub_mul,mul_comm e1 q,two_mul,add_mul];simp
... = q^2 - (2*q)*e1 + e1*e1 : by {unfold pow_nat has_pow_nat.pow_nat monoid.pow,simp}
... > q^2 - (2*q)*e1 : lt_add_of_pos_right (q^2 -(2*q)*e1) H6
... ≥ q^2 - (2*q)*((q ^ 2 - r) / (2 * q)) : sub_le_sub (le_of_eq (eq.refl (q^2))) (mul_le_mul_of_nonneg_left H5 (le_of_lt (mul_pos H0 Hqg0))) -- lt_add_iff_pos_right -- (add_le_add_left ((mul_le_mul_left (mul_pos H0 Hqg0)).mpr H5) (q^2)) (e1*e1)
... = r : by rw [←div_mul_eq_mul_div_comm,div_self (ne_of_gt (mul_pos H0 Hqg0)),one_mul];simp, -- ... = r : by rw [mul_comm,div_mul_eq_mul_div,mul_div_assoc,div_self (ne_of_gt (mul_pos H0 Hqg0)),mul_one,add_assoc,div_add_div_same,←two_mul,mul_comm,mul_div_assoc,div_self (ne_of_gt H0),mul_one,add_sub,add_comm,←add_sub,sub_self,add_zero], -- rw [mul_div_cancel'], -- nearly there
exact not_lt_of_ge (le_of_lt (H ⟨He1,J0⟩)) Hn1,
have H : q^2 ≤ r,
exact le_of_not_lt H3,
cases lt_or_eq_of_le H with Hlt Heq,
exfalso,
exact H2 Hlt,
exact Heq
end
-- set_option pp.notation false
theorem square_is_pow_two {α : Type} [monoid α] {x : α} : x^2 = x*x :=
begin
unfold pow_nat has_pow_nat.pow_nat monoid.pow,
simp
end
theorem square_inj_on_nonneg (x y : ℝ) : (x ≥ 0) → (y ≥ 0) → (x^2 = y^2) → (x=y) :=
begin
assume H_x_ge_zero : x ≥ 0,
assume H_y_ge_zero : y ≥ 0,
assume H_x_pow_two_eq_y_pow_two : x^2 = y^2,
have H : x*x = y*y,
rwa [square_is_pow_two,square_is_pow_two] at H_x_pow_two_eq_y_pow_two,
have H_eq_or_neg : x = y ∨ x = -y,
exact (mul_self_eq_mul_self_iff _ _).mp H,
cases H_eq_or_neg with Heq Hneg,
exact Heq,
have H_x_le_zero : x ≤ 0, exact calc x=-y : Hneg ... ≤ 0 : neg_nonpos.mpr H_y_ge_zero,
have H_x_eq_zero : x = 0, exact eq_iff_le_and_le.2 ⟨H_x_le_zero, H_x_ge_zero⟩,
exact (eq.symm (calc y=-x : eq.symm (neg_eq_iff_neg_eq.1 (eq.symm Hneg))
... = 0 : neg_eq_zero.2 H_x_eq_zero
... = x : eq.symm (H_x_eq_zero))),
end
-- #check exists_square_root
-- exists_square_root : ∀ (r : ℝ), r ≥ 0 → (∃ (q : ℝ), q ≥ 0 ∧ q ^ 2 = r)
theorem exists_unique_square_root : ∀ (r:ℝ), (r ≥ 0) → ∃ (q:ℝ), (q ≥ 0 ∧ q^2 = r ∧ ∀ (s:ℝ), s ≥ 0 ∧ s^2 = r → s=q) :=
begin
intro r,
assume H_r_ge_zero : r ≥ 0,
cases (exists_square_root r H_r_ge_zero) with q H_q_squared_is_r,
suffices H_unique : ∀ (s:ℝ), s ≥ 0 ∧ s ^ 2 = r → s = q,
exact ⟨q,⟨H_q_squared_is_r.left,⟨H_q_squared_is_r.right,H_unique⟩⟩⟩,
intro s,
assume H_s_ge_zero_and_square_is_r,
exact square_inj_on_nonneg s q H_s_ge_zero_and_square_is_r.left H_q_squared_is_r.left (eq.trans H_s_ge_zero_and_square_is_r.right (eq.symm H_q_squared_is_r.right))
end
noncomputable def square_root (x:ℝ) (H_x_nonneg : x ≥ 0) : ℝ := classical.some (exists_square_root x H_x_nonneg)
-- set_option pp.notation false
-- example : (0:ℝ) ≤ 2 := by simp -- rw [←rat.cast_zero,rat.cast_bit0,rat.cast_bit1],
-- #check (square_root 2 _) -- (by {unfold ge;exact dec_trivial}))
/-
meta def sqrt_tac : tactic unit := `[assumption <|> exact dec_trivial]
noncomputable def sqrt (r : ℝ) (h : r ≥ 0 . sqrt_tac) : ℝ :=
classical.some (exists_unique_square_root r h)
-- noncomputable def s2 : ℝ := sqrt 2,
example : (6:real) + 9 = 15 := by simp with real_simps;exact dec_trivial
-- exact dec_trivial
-/
def H_2_ge_0 : (2:ℝ) ≥ 0 := by unfold ge;simp with real_simps;exact dec_trivial
noncomputable def s2 : ℝ := square_root 2 H_2_ge_0
namespace M1F
lemma rat.zero_eq_int_zero (z : int) : ↑ z = (0:rat) → z = 0 :=
begin
simp [rat.mk_eq_zero,nat.one_pos,rat.coe_int_eq_mk]
end
lemma rat.of_int_inj (z₁ z₂ : int) : (z₁ : rat) = (z₂ : rat) → z₁ = z₂ :=
begin
intro H12,
have H2 : ↑(z₁ - z₂) = (0:rat),
exact calc
↑(z₁ - z₂) = (↑z₁ - ↑z₂ : ℚ) : by simp -- (rat.cast_sub z₁ z₂)
... = (↑ z₂ - ↑ z₂:ℚ) : by rw H12
... = (0 : rat) : by simp,
have H3 : z₁ - z₂ = 0,
exact rat.zero_eq_int_zero (z₁ -z₂) H2,
clear H12 H2,
exact sub_eq_zero.mp H3
end
lemma rational_half_not_an_integer : ¬ (∃ y : ℤ, 1/2 = (y:rat)) :=
begin
apply not_exists.2,
rw [one_div_eq_inv],
assume x:ℤ,
intro H,
unfold has_inv.inv at H, -- why does this become such an effort?
unfold division_ring.inv at H,
unfold field.inv at H,
unfold linear_ordered_field.inv at H,
unfold discrete_linear_ordered_field.inv at H,
unfold discrete_field.inv at H,
have H2 : ((2:rat)*rat.inv 2) = (2:rat)*x,
simp [H],
have H21 : (2:rat)≠ 0 := dec_trivial,
have H3 : (2:rat)*rat.inv 2 = (1:rat),
exact rat.mul_inv_cancel 2 H21,
have H4 : (1:rat) = (2:rat)*(x:rat),
exact H3 ▸ H2,
have H5 : ((((2:int)*x):int):rat)=((2:int):rat)*(x:rat),
simp [rat.cast_mul],
have H6 : ↑ ((2:int)*x) = (↑1:rat),
exact eq.trans H5 (eq.symm H4),
clear H H2 H21 H3 H4 H5,
have H7 : 2*x=1,
exact rat.of_int_inj (2*x) 1 H6,
clear H6,
have H8 : (2*x) % 2 = 0,
simp [@int.add_mul_mod_self 0],
have H9 : (1:int) % 2 = 0,
apply @eq.subst ℤ (λ t, t%2 =0) _ _ H7 H8,
have H10 : (1:int) % 2 ≠ 0,
exact dec_trivial,
contradiction,
end
-- set_option pp.all true
lemma real_half_not_an_integer : ¬ (∃ y : ℤ, ((1/2):ℝ) = (y:ℝ)) :=
begin
assume H_real : (∃ y : ℤ, ((1/2):ℝ) = (y:ℝ)),
cases H_real with a Ha,
suffices H2 : ((1:ℤ):ℝ) = ((2:ℤ):ℝ)*((a:ℤ):ℝ),
rw [←int.cast_mul,int.cast_inj] at H2,
have H8 : (2*a) % 2 = 0,
simp [@int.add_mul_mod_self 0],
have H9 : (1:int) % 2 = 0,
apply @eq.subst ℤ (λ t, t%2 =0) _ _ (eq.symm H2) H8,
have H10 : (1:int) % 2 ≠ 0,
exact dec_trivial,
contradiction,
have H20: (2:ℝ) ≠ 0, simp with real_simps,exact dec_trivial,
have H1 : (↑a:ℝ) * 2 = 1,
exact mul_eq_of_eq_div (a:ℝ) 1 H20 (eq.symm Ha),
have H2 : 1 = 2 * (↑a:ℝ),
rw [mul_comm] at H1,
exact eq.symm (H1),
have H3 : (1:ℝ) = ((1:ℤ):ℝ), by simp,
have H4 : (2:ℝ) = ((2:ℤ):ℝ), by simp,
rwa [←H3,←H4],
end
-- #check @of_rat_inj
end M1F
|
355a54902176cdc1d46492af2e645990695605e3 | 2c096fdfecf64e46ea7bc6ce5521f142b5926864 | /src/Lean/Server/References.lean | 020ac7856f180b5c2026bf4863ff623b1d7fd4e7 | [
"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 | 12,313 | lean | /-
Copyright (c) 2021 Joscha Mennicken. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joscha Mennicken
-/
import Lean.Data.Lsp.Internal
import Lean.Server.Utils
/-! # Representing collected and deduplicated definitions and usages -/
namespace Lean.Server
open Lsp Lean.Elab Std
structure Reference where
ident : RefIdent
/-- FVarIds that are logically identical to this reference -/
aliases : Array RefIdent := #[]
range : Lsp.Range
stx : Syntax
ci : ContextInfo
info : Info
isBinder : Bool
deriving Inhabited
structure RefInfo where
definition : Option Reference
usages : Array Reference
namespace RefInfo
def empty : RefInfo := ⟨ none, #[] ⟩
def addRef : RefInfo → Reference → RefInfo
| i@{ definition := none, .. }, ref@{ isBinder := true, .. } =>
{ i with definition := ref }
| i@{ usages, .. }, ref@{ isBinder := false, .. } =>
{ i with usages := usages.push ref }
| i, _ => i
instance : Coe RefInfo Lsp.RefInfo where
coe self :=
{
definition := self.definition.map (·.range)
usages := self.usages.map (·.range)
}
end RefInfo
def ModuleRefs := HashMap RefIdent RefInfo
namespace ModuleRefs
def addRef (self : ModuleRefs) (ref : Reference) : ModuleRefs :=
let refInfo := self.findD ref.ident RefInfo.empty
self.insert ref.ident (refInfo.addRef ref)
instance : Coe ModuleRefs Lsp.ModuleRefs where
coe self := HashMap.ofList <| List.map (fun (k, v) => (k, v)) <| self.toList
end ModuleRefs
end Lean.Server
namespace Lean.Lsp.RefInfo
open Server
def empty : RefInfo := ⟨ none, #[] ⟩
def merge (a : RefInfo) (b : RefInfo) : RefInfo :=
{
definition := b.definition.orElse fun _ => a.definition
usages := a.usages.append b.usages
}
def contains (self : RefInfo) (pos : Lsp.Position) : Bool := Id.run do
if let some range := self.definition then
if contains range pos then
return true
for range in self.usages do
if contains range pos then
return true
false
where
contains (range : Lsp.Range) (pos : Lsp.Position) : Bool :=
range.start <= pos && pos < range.end
end Lean.Lsp.RefInfo
namespace Lean.Lsp.ModuleRefs
open Server
def findAt (self : ModuleRefs) (pos : Lsp.Position) : Array RefIdent := Id.run do
let mut result := #[]
for (ident, info) in self.toList do
if info.contains pos then
result := result.push ident
result
end Lean.Lsp.ModuleRefs
namespace Lean.Server
open IO
open Lsp
open Elab
/-- Content of individual `.ilean` files -/
structure Ilean where
version : Nat := 1
module : Name
references : Lsp.ModuleRefs
deriving FromJson, ToJson
namespace Ilean
def load (path : System.FilePath) : IO Ilean := do
let content ← FS.readFile path
match Json.parse content >>= fromJson? with
| Except.ok ilean => pure ilean
| Except.error msg => throwServerError s!"Failed to load ilean at {path}: {msg}"
end Ilean
/-! # Collecting and deduplicating definitions and usages -/
def identOf : Info → Option (RefIdent × Bool)
| Info.ofTermInfo ti => match ti.expr with
| Expr.const n .. => some (RefIdent.const n, ti.isBinder)
| Expr.fvar id .. => some (RefIdent.fvar id, ti.isBinder)
| _ => none
| Info.ofFieldInfo fi => some (RefIdent.const fi.projName, false)
| Info.ofOptionInfo oi => some (RefIdent.const oi.declName, false)
| _ => none
def findReferences (text : FileMap) (trees : Array InfoTree) : Array Reference := Id.run <| StateT.run' (s := #[]) do
for tree in trees do
tree.visitM' (postNode := fun ci info _ => do
if let some (ident, isBinder) := identOf info then
if let some range := info.range? then
if info.stx.getHeadInfo matches .original .. then -- we are not interested in canonical syntax here
modify (·.push { ident, range := range.toLspRange text, stx := info.stx, ci, info, isBinder }))
get
/--
The `FVarId`s of a function parameter in the function's signature and body
differ. However, they have `TermInfo` nodes with `binder := true` in the exact
same position. Moreover, macros such as do-reassignment `x := e` may create
chains of variable definitions where a helper definition overlaps with a use
of a variable.
This function changes every such group to use a single `FVarId` (the head of the
chain/DAG) and gets rid of duplicate definitions.
-/
partial def combineFvars (trees : Array InfoTree) (refs : Array Reference) : Array Reference := Id.run do
-- Deduplicate definitions based on their exact range
let mut posMap : HashMap Lsp.Range FVarId := HashMap.empty
for ref in refs do
if let { ident := RefIdent.fvar id, range, isBinder := true, .. } := ref then
posMap := posMap.insert range id
let idMap := buildIdMap posMap
let mut refs' := #[]
for ref in refs do
match ref with
| { ident := ident@(RefIdent.fvar id), .. } =>
if idMap.contains id then
refs' := refs'.push { ref with ident := applyIdMap idMap ident, aliases := #[ident] }
else if !idMap.contains id then
refs' := refs'.push ref
| _ =>
refs' := refs'.push ref
refs'
where
findCanonicalBinder (idMap : HashMap FVarId FVarId) (id : FVarId) : FVarId :=
match idMap.find? id with
| some id' => findCanonicalBinder idMap id' -- recursion depth is expected to be very low
| none => id
applyIdMap : HashMap FVarId FVarId → RefIdent → RefIdent
| m, RefIdent.fvar id => RefIdent.fvar <| findCanonicalBinder m id
| _, ident => ident
buildIdMap posMap := Id.run <| StateT.run' (s := HashMap.empty) do
-- map fvar defs to overlapping fvar defs/uses
for ref in refs do
if let { ident := RefIdent.fvar baseId, range, .. } := ref then
if let some id := posMap.find? range then
insertIdMap id baseId
-- apply `FVarAliasInfo`
trees.forM (·.visitM' (postNode := fun _ info _ => do
if let .ofFVarAliasInfo ai := info then
insertIdMap ai.id ai.baseId))
get
-- NOTE: poor man's union-find; see also `findCanonicalBinder`
insertIdMap id baseId := do
let idMap ← get
let id := findCanonicalBinder idMap id
let baseId := findCanonicalBinder idMap baseId
if baseId != id then
modify (·.insert id baseId)
def dedupReferences (refs : Array Reference) (allowSimultaneousBinderUse := false) : Array Reference := Id.run do
let mut refsByIdAndRange : HashMap (RefIdent × Option Bool × Lsp.Range) Reference := HashMap.empty
for ref in refs do
let isBinder := if allowSimultaneousBinderUse then some ref.isBinder else none
let key := (ref.ident, isBinder, ref.range)
refsByIdAndRange := match refsByIdAndRange[key] with
| some ref' => refsByIdAndRange.insert key { ref' with aliases := ref'.aliases ++ ref.aliases }
| none => refsByIdAndRange.insert key ref
let dedupedRefs := refsByIdAndRange.fold (init := #[]) fun refs _ ref => refs.push ref
return dedupedRefs.qsort (·.range < ·.range)
def findModuleRefs (text : FileMap) (trees : Array InfoTree) (localVars : Bool := true)
(allowSimultaneousBinderUse := false) : ModuleRefs := Id.run do
let mut refs :=
dedupReferences (allowSimultaneousBinderUse := allowSimultaneousBinderUse) <|
combineFvars trees <|
findReferences text trees
if !localVars then
refs := refs.filter fun
| { ident := RefIdent.fvar _, .. } => false
| _ => true
refs.foldl (init := HashMap.empty) fun m ref => m.addRef ref
/-! # Collecting and maintaining reference info from different sources -/
structure References where
/-- References loaded from ilean files -/
ileans : HashMap Name (System.FilePath × Lsp.ModuleRefs)
/-- References from workers, overriding the corresponding ilean files -/
workers : HashMap Name (Nat × Lsp.ModuleRefs)
namespace References
def empty : References := { ileans := HashMap.empty, workers := HashMap.empty }
def addIlean (self : References) (path : System.FilePath) (ilean : Ilean) : References :=
{ self with ileans := self.ileans.insert ilean.module (path, ilean.references) }
def removeIlean (self : References) (path : System.FilePath) : References :=
let namesToRemove := self.ileans.toList.filter (fun (_, p, _) => p == path)
|>.map (fun (n, _, _) => n)
namesToRemove.foldl (init := self) fun self name =>
{ self with ileans := self.ileans.erase name }
def updateWorkerRefs (self : References) (name : Name) (version : Nat) (refs : Lsp.ModuleRefs) : References := Id.run do
if let some (currVersion, _) := self.workers.find? name then
if version > currVersion then
return { self with workers := self.workers.insert name (version, refs) }
if version == currVersion then
let current := self.workers.findD name (version, HashMap.empty)
let merged := refs.fold (init := current.snd) fun m ident info =>
m.findD ident Lsp.RefInfo.empty |>.merge info |> m.insert ident
return { self with workers := self.workers.insert name (version, merged) }
return self
def finalizeWorkerRefs (self : References) (name : Name) (version : Nat) (refs : Lsp.ModuleRefs) : References := Id.run do
if let some (currVersion, _) := self.workers.find? name then
if version < currVersion then
return self
return { self with workers := self.workers.insert name (version, refs) }
def removeWorkerRefs (self : References) (name : Name) : References :=
{ self with workers := self.workers.erase name }
def allRefs (self : References) : HashMap Name Lsp.ModuleRefs :=
let ileanRefs := self.ileans.toList.foldl (init := HashMap.empty) fun m (name, _, refs) => m.insert name refs
self.workers.toList.foldl (init := ileanRefs) fun m (name, _, refs) => m.insert name refs
def findAt (self : References) (module : Name) (pos : Lsp.Position) : Array RefIdent := Id.run do
if let some refs := self.allRefs.find? module then
return refs.findAt pos
#[]
def referringTo (self : References) (identModule : Name) (ident : RefIdent) (srcSearchPath : SearchPath)
(includeDefinition : Bool := true) : IO (Array Location) := do
let refsToCheck := match ident with
| RefIdent.const _ => self.allRefs.toList
| RefIdent.fvar _ => match self.allRefs.find? identModule with
| none => []
| some refs => [(identModule, refs)]
let mut result := #[]
for (module, refs) in refsToCheck do
if let some info := refs.find? ident then
if let some path ← srcSearchPath.findModuleWithExt "lean" module then
-- Resolve symlinks (such as `src` in the build dir) so that files are
-- opened in the right folder
let uri := System.Uri.pathToUri <| ← IO.FS.realPath path
if includeDefinition then
if let some range := info.definition then
result := result.push ⟨uri, range⟩
for range in info.usages do
result := result.push ⟨uri, range⟩
return result
def definitionOf? (self : References) (ident : RefIdent) (srcSearchPath : SearchPath)
: IO (Option Location) := do
for (module, refs) in self.allRefs.toList do
if let some info := refs.find? ident then
if let some definition := info.definition then
if let some path ← srcSearchPath.findModuleWithExt "lean" module then
-- Resolve symlinks (such as `src` in the build dir) so that files are
-- opened in the right folder
let uri := System.Uri.pathToUri <| ← IO.FS.realPath path
return some ⟨uri, definition⟩
return none
def definitionsMatching (self : References) (srcSearchPath : SearchPath) (filter : Name → Option α)
(maxAmount? : Option Nat := none) : IO $ Array (α × Location) := do
let mut result := #[]
for (module, refs) in self.allRefs.toList do
if let some path ← srcSearchPath.findModuleWithExt "lean" module then
let uri := System.Uri.pathToUri <| ← IO.FS.realPath path
for (ident, info) in refs.toList do
if let (RefIdent.const name, some definition) := (ident, info.definition) then
if let some a := filter name then
result := result.push (a, ⟨uri, definition⟩)
if let some maxAmount := maxAmount? then
if result.size >= maxAmount then
return result
return result
end References
end Lean.Server
|
05b8e5b87c6f68b650ec24dcf93cc4dc0dfe9b9b | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/algebra/category/Module/basic.lean | 09d3890b4f7e8f1bf28afc934577647b8b7ddbed | [
"Apache-2.0"
] | permissive | vaibhavkarve/mathlib | a574aaf68c0a431a47fa82ce0637f0f769826bfe | 17f8340912468f49bdc30acdb9a9fa02eeb0473a | refs/heads/master | 1,621,263,802,637 | 1,585,399,588,000 | 1,585,399,588,000 | 250,833,447 | 0 | 0 | Apache-2.0 | 1,585,410,341,000 | 1,585,410,341,000 | null | UTF-8 | Lean | false | false | 5,824 | lean | /-
Copyright (c) 2019 Robert A. Spencer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert A. Spencer, Markus Himmel
-/
import algebra.module
import algebra.punit_instances
import algebra.category.Group
import category_theory.concrete_category
import category_theory.limits.shapes.zero
import category_theory.limits.shapes.kernels
import linear_algebra.basic
open category_theory
open category_theory.limits
open category_theory.limits.walking_parallel_pair
universe u
variables (R : Type u) [ring R]
/-- The category of R-modules and their morphisms. -/
structure Module :=
(carrier : Type u)
[is_add_comm_group : add_comm_group carrier]
[is_module : module R carrier]
attribute [instance] Module.is_add_comm_group Module.is_module
namespace Module
-- TODO revisit this after #1438 merges, to check coercions and instances are handled consistently
instance : has_coe_to_sort (Module R) :=
{ S := Type u, coe := Module.carrier }
instance : concrete_category (Module.{u} R) :=
{ to_category :=
{ hom := λ M N, M →ₗ[R] N,
id := λ M, 1,
comp := λ A B C f g, g.comp f },
forget := { obj := λ R, R, map := λ R S f, (f : R → S) },
forget_faithful := { } }
instance has_forget_to_AddCommGroup : has_forget₂ (Module R) AddCommGroup :=
{ forget₂ :=
{ obj := λ M, AddCommGroup.of M,
map := λ M₁ M₂ f, linear_map.to_add_monoid_hom f } }
/-- The object in the category of R-modules associated to an R-module -/
def of (X : Type u) [add_comm_group X] [module R X] : Module R := ⟨R, X⟩
instance : inhabited (Module R) := ⟨of R punit⟩
@[simp]
lemma of_apply (X : Type u) [add_comm_group X] [module R X] : (of R X : Type u) = X := rfl
variables {R}
/-- Forgetting to the underlying type and then building the bundled object returns the original module. -/
@[simps]
def of_self_iso (M : Module R) : Module.of R M ≅ M :=
{ hom := 𝟙 M, inv := 𝟙 M }
instance : subsingleton (of R punit) :=
by { rw of_apply R punit, apply_instance }
instance : has_zero_object.{u} (Module R) :=
{ zero := of R punit,
unique_to := λ X,
{ default := (0 : punit →ₗ[R] X),
uniq := λ _, linear_map.ext $ λ x,
have h : x = 0, from subsingleton.elim _ _,
by simp [h] },
unique_from := λ X,
{ default := (0 : X →ₗ[R] punit),
uniq := λ _, linear_map.ext $ λ x, subsingleton.elim _ _ } }
variables {R} {M N U : Module R}
@[simp] lemma id_apply (m : M) : (𝟙 M : M → M) m = m := rfl
@[simp] lemma coe_comp (f : M ⟶ N) (g : N ⟶ U) :
((f ≫ g) : M → U) = g ∘ f := rfl
instance hom_is_module_hom (f : M ⟶ N) :
is_linear_map R (f : M → N) := linear_map.is_linear _
end Module
variables {R}
variables {X₁ X₂ : Type u}
/-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. -/
@[simps]
def linear_equiv.to_Module_iso
{g₁ : add_comm_group X₁} {g₂ : add_comm_group X₂} {m₁ : module R X₁} {m₂ : module R X₂} (e : X₁ ≃ₗ[R] X₂) :
Module.of R X₁ ≅ Module.of R X₂ :=
{ hom := (e : X₁ →ₗ[R] X₂),
inv := (e.symm : X₂ →ₗ[R] X₁),
hom_inv_id' := begin ext, exact e.left_inv x, end,
inv_hom_id' := begin ext, exact e.right_inv x, end, }
namespace category_theory.iso
/-- Build a `linear_equiv` from an isomorphism in the category `Module R`. -/
@[simps]
def to_linear_equiv {X Y : Module.{u} R} (i : X ≅ Y) : X ≃ₗ[R] Y :=
{ to_fun := i.hom,
inv_fun := i.inv,
left_inv := by tidy,
right_inv := by tidy,
add := by tidy,
smul := by tidy, }.
end category_theory.iso
/-- linear equivalences between `module`s are the same as (isomorphic to) isomorphisms in `Module` -/
@[simps]
def linear_equiv_iso_Group_iso {X Y : Type u} [add_comm_group X] [add_comm_group Y] [module R X] [module R Y] :
(X ≃ₗ[R] Y) ≅ (Module.of R X ≅ Module.of R Y) :=
{ hom := λ e, e.to_Module_iso,
inv := λ i, i.to_linear_equiv, }
namespace Module
section zero_morphisms
instance : has_zero_morphisms.{u} (Module R) :=
{ has_zero := λ M N, ⟨0⟩,
comp_zero' := λ M N f Z, by ext; erw linear_map.zero_apply,
zero_comp' := λ M N Z f, by ext; erw [linear_map.comp_apply, linear_map.zero_apply,
linear_map.zero_apply, linear_map.map_zero] }
end zero_morphisms
section kernel
variables {R} {M N : Module R} (f : M ⟶ N)
/-- The cone on the equalizer diagram of f and 0 induced by the kernel of f -/
def kernel_cone : cone (parallel_pair f 0) :=
{ X := of R f.ker,
π :=
{ app := λ j,
match j with
| zero := f.ker.subtype
| one := 0
end,
naturality' := λ j j' g, by { cases j; cases j'; cases g; tidy } } }
/-- The kernel of a linear map is a kernel in the categorical sense -/
def kernel_is_limit : is_limit (kernel_cone f) :=
{ lift := λ s, linear_map.cod_restrict f.ker (fork.ι s) (λ c, linear_map.mem_ker.2 $
by { erw [←@function.comp_apply _ _ _ f (fork.ι s) c, ←coe_comp, fork.condition,
has_zero_morphisms.comp_zero _ (fork.ι s) N], refl }),
fac' := λ s j, linear_map.ext $ λ x,
begin
rw [coe_comp, function.comp_app, ←linear_map.comp_apply],
cases j,
{ erw @linear_map.subtype_comp_cod_restrict _ _ _ _ _ _ _ _ (fork.ι s) f.ker _, refl },
{ rw [←cone_parallel_pair_right, ←cone_parallel_pair_right], refl }
end,
uniq' := λ s m h, linear_map.ext $ λ x, subtype.ext.2 $
have h₁ : (m ≫ (kernel_cone f).π.app zero).to_fun = (s.π.app zero).to_fun,
by { congr, exact h zero },
by convert @congr_fun _ _ _ _ h₁ x }
end kernel
instance : has_kernels.{u} (Module R) :=
⟨λ _ _ f, ⟨kernel_cone f, kernel_is_limit f⟩⟩
end Module
instance (M : Type u) [add_comm_group M] [module R M] : has_coe (submodule R M) (Module R) :=
⟨ λ N, Module.of R N ⟩
|
3123a55da62192c13188a61def4566456f153541 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/finset/prod.lean | 11fdfe55ee13959f397e6ccf187fcb1361db51c3 | [
"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 | 8,414 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Oliver Nash
-/
import data.finset.card
/-!
# Finsets in product types
This file defines finset constructions on the product type `α × β`. Beware not to confuse with the
`finset.prod` operation which computes the multiplicative product.
## Main declarations
* `finset.product`: Turns `s : finset α`, `t : finset β` into their product in `finset (α × β)`.
* `finset.diag`: For `s : finset α`, `s.diag` is the `finset (α × α)` of pairs `(a, a)` with
`a ∈ s`.
* `finset.off_diag`: For `s : finset α`, `s.off_diag` is the `finset (α × α)` of pairs `(a, b)` with
`a, b ∈ s` and `a ≠ b`.
-/
open multiset
variables {α β γ : Type*}
namespace finset
/-! ### prod -/
section prod
variables {s s' : finset α} {t t' : finset β}
/-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/
protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩
@[simp] lemma product_val : (s.product t).1 = s.1.product t.1 := rfl
@[simp] lemma mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product
@[simp, norm_cast] lemma coe_product (s : finset α) (t : finset β) :
(s.product t : set (α × β)) = (s : set α) ×ˢ (t : set β) :=
set.ext $ λ x, finset.mem_product
lemma subset_product [decidable_eq α] [decidable_eq β] {s : finset (α × β)} :
s ⊆ (s.image prod.fst).product (s.image prod.snd) :=
λ p hp, mem_product.2 ⟨mem_image_of_mem _ hp, mem_image_of_mem _ hp⟩
lemma product_subset_product (hs : s ⊆ s') (ht : t ⊆ t') : s.product t ⊆ s'.product t' :=
λ ⟨x,y⟩ h, mem_product.2 ⟨hs (mem_product.1 h).1, ht (mem_product.1 h).2⟩
lemma product_subset_product_left (hs : s ⊆ s') : s.product t ⊆ s'.product t :=
product_subset_product hs (subset.refl _)
lemma product_subset_product_right (ht : t ⊆ t') : s.product t ⊆ s.product t' :=
product_subset_product (subset.refl _) ht
lemma product_eq_bUnion [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) :
s.product t = s.bUnion (λa, t.image $ λb, (a, b)) :=
ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bUnion, mem_image, exists_prop, prod.mk.inj_iff,
and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left]
lemma product_eq_bUnion_right [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) :
s.product t = t.bUnion (λ b, s.image $ λ a, (a, b)) :=
ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bUnion, mem_image, exists_prop, prod.mk.inj_iff,
and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left]
/-- See also `finset.sup_product_left`. -/
@[simp] lemma product_bUnion [decidable_eq γ] (s : finset α) (t : finset β) (f : α × β → finset γ) :
(s.product t).bUnion f = s.bUnion (λ a, t.bUnion (λ b, f (a, b))) :=
by { classical, simp_rw [product_eq_bUnion, bUnion_bUnion, image_bUnion] }
@[simp] lemma card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t :=
multiset.card_product _ _
lemma filter_product (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] :
(s.product t).filter (λ (x : α × β), p x.1 ∧ q x.2) = (s.filter p).product (t.filter q) :=
by { ext ⟨a, b⟩, simp only [mem_filter, mem_product],
exact and_and_and_comm (a ∈ s) (b ∈ t) (p a) (q b) }
lemma filter_product_card (s : finset α) (t : finset β)
(p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] :
((s.product t).filter (λ (x : α × β), p x.1 ↔ q x.2)).card =
(s.filter p).card * (t.filter q).card + (s.filter (not ∘ p)).card * (t.filter (not ∘ q)).card :=
begin
classical,
rw [← card_product, ← card_product, ← filter_product, ← filter_product, ← card_union_eq],
{ apply congr_arg, ext ⟨a, b⟩, simp only [filter_union_right, mem_filter, mem_product],
split; intros h; use h.1,
simp only [function.comp_app, and_self, h.2, em (q b)],
cases h.2; { try { simp at h_1 }, simp [h_1] } },
{ rw disjoint_iff, change _ ∩ _ = ∅, ext ⟨a, b⟩, rw mem_inter,
simp only [and_imp, mem_filter, not_and, not_not, function.comp_app, iff_false, mem_product,
not_mem_empty], intros, assumption }
end
lemma empty_product (t : finset β) : (∅ : finset α).product t = ∅ := rfl
lemma product_empty (s : finset α) : s.product (∅ : finset β) = ∅ :=
eq_empty_of_forall_not_mem (λ x h, (finset.mem_product.1 h).2)
lemma nonempty.product (hs : s.nonempty) (ht : t.nonempty) : (s.product t).nonempty :=
let ⟨x, hx⟩ := hs, ⟨y, hy⟩ := ht in ⟨(x, y), mem_product.2 ⟨hx, hy⟩⟩
lemma nonempty.fst (h : (s.product t).nonempty) : s.nonempty :=
let ⟨xy, hxy⟩ := h in ⟨xy.1, (mem_product.1 hxy).1⟩
lemma nonempty.snd (h : (s.product t).nonempty) : t.nonempty :=
let ⟨xy, hxy⟩ := h in ⟨xy.2, (mem_product.1 hxy).2⟩
@[simp] lemma nonempty_product : (s.product t).nonempty ↔ s.nonempty ∧ t.nonempty :=
⟨λ h, ⟨h.fst, h.snd⟩, λ h, h.1.product h.2⟩
@[simp] lemma product_eq_empty {s : finset α} {t : finset β} : s.product t = ∅ ↔ s = ∅ ∨ t = ∅ :=
by rw [←not_nonempty_iff_eq_empty, nonempty_product, not_and_distrib, not_nonempty_iff_eq_empty,
not_nonempty_iff_eq_empty]
@[simp] lemma singleton_product {a : α} :
({a} : finset α).product t = t.map ⟨prod.mk a, prod.mk.inj_left _⟩ :=
by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] }
@[simp] lemma product_singleton {b : β} :
s.product {b} = s.map ⟨λ i, (i, b), prod.mk.inj_right _⟩ :=
by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] }
lemma singleton_product_singleton {a : α} {b : β} :
({a} : finset α).product ({b} : finset β) = {(a, b)} :=
by simp only [product_singleton, function.embedding.coe_fn_mk, map_singleton]
@[simp] lemma union_product [decidable_eq α] [decidable_eq β] :
(s ∪ s').product t = s.product t ∪ s'.product t :=
by { ext ⟨x, y⟩, simp only [or_and_distrib_right, mem_union, mem_product] }
@[simp] lemma product_union [decidable_eq α] [decidable_eq β] :
s.product (t ∪ t') = s.product t ∪ s.product t' :=
by { ext ⟨x, y⟩, simp only [and_or_distrib_left, mem_union, mem_product] }
end prod
section diag
variables (s : finset α) [decidable_eq α]
/-- Given a finite set `s`, the diagonal, `s.diag` is the set of pairs of the form `(a, a)` for
`a ∈ s`. -/
def diag := (s.product s).filter (λ (a : α × α), a.fst = a.snd)
/-- Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a ≠ b`
for `a, b ∈ s`. -/
def off_diag := (s.product s).filter (λ (a : α × α), a.fst ≠ a.snd)
@[simp] lemma mem_diag (x : α × α) : x ∈ s.diag ↔ x.1 ∈ s ∧ x.1 = x.2 :=
by { simp only [diag, mem_filter, mem_product], split; intros h;
simp only [h, and_true, eq_self_iff_true, and_self], rw ←h.2, exact h.1 }
@[simp] lemma mem_off_diag (x : α × α) : x ∈ s.off_diag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 :=
by { simp only [off_diag, mem_filter, mem_product], split; intros h;
simp only [h, ne.def, not_false_iff, and_self] }
@[simp] lemma diag_card : (diag s).card = s.card :=
begin
suffices : diag s = s.image (λ a, (a, a)),
{ rw this, apply card_image_of_inj_on, exact λ x1 h1 x2 h2 h3, (prod.mk.inj h3).1 },
ext ⟨a₁, a₂⟩, rw mem_diag, split; intros h; rw finset.mem_image at *,
{ use [a₁, h.1, prod.mk.inj_iff.mpr ⟨rfl, h.2⟩] },
{ rcases h with ⟨a, h1, h2⟩, have h := prod.mk.inj h2, rw [←h.1, ←h.2], use h1 },
end
@[simp] lemma off_diag_card : (off_diag s).card = s.card * s.card - s.card :=
begin
suffices : (diag s).card + (off_diag s).card = s.card * s.card,
{ nth_rewrite 2 ← s.diag_card, simp only [diag_card] at *, rw tsub_eq_of_eq_add_rev, rw this },
rw ← card_product,
apply filter_card_add_filter_neg_card_eq_card,
end
@[simp] lemma diag_empty : (∅ : finset α).diag = ∅ := rfl
@[simp] lemma off_diag_empty : (∅ : finset α).off_diag = ∅ := rfl
@[simp] lemma diag_union_off_diag : s.diag ∪ s.off_diag = s.product s :=
filter_union_filter_neg_eq _ _
@[simp] lemma disjoint_diag_off_diag : disjoint s.diag s.off_diag := disjoint_filter_filter_neg _ _
end diag
end finset
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.