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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
913bac4c597cadea83f2202df17cbdcacdb5b756 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /tests/lean/run/doNotation1.lean | a32deb8392d4b193c2422f1383c883ada3c3fca7 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,495 | lean | open Lean
partial def expandHash : Syntax → StateT Bool MacroM Syntax
| Syntax.node k args =>
if k == `doHash then do set true; `(←MonadState.get)
else do
args ← args.mapM expandHash;
pure $ Syntax.node k args
| stx => pure stx
@[macro Lean.Parser.Term.do] def expandDo : Macro :=
fun stx => do
(stx, expanded) ← expandHash stx false;
if expanded then pure stx
else Macro.throwUnsupported
new_frontend
def f : IO Nat :=
pure 0
def g (x : Nat) : IO Nat :=
pure (x + 1)
def g1 {α : Type} (x : α) : IO (α × α) :=
pure (x, x)
def g2 (p : Nat × Nat) : Nat :=
p.1
set_option trace.Elab.definition true
def h (x : Nat) : StateT Nat IO Nat := do
s ← get;
a ← f; -- liftM inserted here
b ← g1 1; -- liftM inserted here
let x := g2 b;
IO.println b;
pure (s+a)
def myPrint {α} [HasToString α] (a : α) : IO Unit :=
IO.println (">> " ++ toString a)
def h₂ (x : Nat) : StateT Nat IO Nat := do
a ← h 1; -- liftM inserted here
IO.println x;
b ← g1 a; -- liftM inserted here
when (a > 100) $ throw $ IO.userError "Error";
myPrint b.1; -- liftM inserted here
pure (a + 1)
def h₃ (x : Nat) : StateT Nat IO Nat := do
let m1 := do { -- Type inferred from application below
g x; -- liftM inserted here
IO.println 1
};
let m2 (y : Nat) := do { -- Type inferred from application below
h (x+y); -- liftM inserted here
myPrint y -- liftM inserted here
};
a ← h 1; -- liftM inserted here
IO.println x;
b ← g1 a; -- liftM inserted here
when (a > 100) $ throw $ IO.userError "Error";
myPrint b.1; -- liftM inserted here
m1;
m2 a;
pure 1
def tst1 : IO Unit := do
a ← f;
let x := a + 1;
IO.println "hello";
IO.println x
def tst2 : IO Unit := do
let x := ← g $ (←f) + (←f);
IO.println "hello";
IO.println x
def tst3 : IO Unit := do
if (← g 1) > 0 then
IO.println "gt"
else do
x ← f;
y ← g x;
IO.println y
def pred (x : Nat) : IO Bool := do
pure $ (← g x) > 0
def tst4 (x : Nat) : IO Unit := do
if ← pred x then
IO.println "is true"
else do
IO.println "is false"
def pred2 (x : Nat) : IO Bool :=
pure $ x > 0
def tst5 (x : Nat) : IO (Option Nat) :=
if x > 10 then pure x else pure none
def tst6 (x : Nat) : StateT Nat IO (Option Nat) :=
if x > 10 then g x else pure none
syntax:max [doHash] "#" : term
def tst7 : StateT (Nat × Nat) IO Unit := do
if #.1 == 0 then
IO.println "first field is zero"
else
IO.println "first field is not zero"
#check tst7
|
53ef91e7ba2a6c2373cbc8c969633127b9f23324 | 130c49f47783503e462c16b2eff31933442be6ff | /src/Lean/PrettyPrinter/Delaborator/TopDownAnalyze.lean | 1495c5ab198eee5a5b630a829be1b60b5974b1bd | [
"Apache-2.0"
] | permissive | Hazel-Brown/lean4 | 8aa5860e282435ffc30dcdfccd34006c59d1d39c | 79e6732fc6bbf5af831b76f310f9c488d44e7a16 | refs/heads/master | 1,689,218,208,951 | 1,629,736,869,000 | 1,629,736,896,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 26,230 | 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.Meta
import Lean.Util.FindMVar
import Lean.Util.FindLevelMVar
import Lean.Util.CollectLevelParams
import Lean.Util.ReplaceLevel
import Lean.PrettyPrinter.Delaborator.Options
import Lean.PrettyPrinter.Delaborator.SubExpr
import Std.Data.RBMap
/-!
The top-down analyzer is an optional preprocessor to the delaborator that aims
to determine the minimal annotations necessary to ensure that the delaborated
expression can be re-elaborated correctly. Currently, the top-down analyzer
is neither sound nor complete: there may be edge-cases in which the expression
can still not be re-elaborated correctly, and it may also add many annotations
that are not strictly necessary.
-/
namespace Lean
open Lean.Meta
open Std (RBMap)
register_builtin_option pp.analyze : Bool := {
defValue := true
group := "pp.analyze"
descr := "(pretty printer analyzer) determine annotations sufficient to ensure round-tripping"
}
register_builtin_option pp.analyze.checkInstances : Bool := {
-- TODO: It would be great to make this default to `true`, but currently, `MessageData` does not
-- include the `LocalInstances`, so this will be very over-aggressive in inserting instances
-- that would otherwise be easy to synthesize. We may consider threading the instances in the future,
-- or at least tracking a bool for whether the instances have been lost.
defValue := false
group := "pp.analyze"
descr := "(pretty printer analyzer) confirm that instances can be re-synthesized"
}
register_builtin_option pp.analyze.typeAscriptions : Bool := {
defValue := true
group := "pp.analyze"
descr := "(pretty printer analyzer) add type ascriptions when deemed necessary"
}
register_builtin_option pp.analyze.trustSubst : Bool := {
defValue := false
group := "pp.analyze"
descr := "(pretty printer analyzer) always 'pretend' applications that can delab to ▸ are 'regular'"
}
register_builtin_option pp.analyze.trustOfNat : Bool := {
defValue := true
group := "pp.analyze"
descr := "(pretty printer analyzer) always 'pretend' `OfNat.ofNat` applications can elab bottom-up"
}
register_builtin_option pp.analyze.trustOfScientific : Bool := {
defValue := true
group := "pp.analyze"
descr := "(pretty printer analyzer) always 'pretend' `OfScientific.ofScientific` applications can elab bottom-up"
}
register_builtin_option pp.analyze.trustCoe : Bool := {
defValue := false
group := "pp.analyze"
descr := "(pretty printer analyzer) always assume a coercion can be correctly inserted"
}
register_builtin_option pp.analyze.trustId : Bool := {
defValue := true
group := "pp.analyze"
descr := "(pretty printer analyzer) always assume an implicit `fun x => x` can be inferred"
}
register_builtin_option pp.analyze.trustKnownFOType2TypeHOFuns : Bool := {
defValue := true
group := "pp.analyze"
descr := "(pretty printer analyzer) omit higher-order functions whose values seem to be knownType2Type"
}
register_builtin_option pp.analyze.omitMax : Bool := {
defValue := true
group := "pp.analyze"
descr := "(pretty printer analyzer) omit universe `max` annotations (these constraints can actually hurt)"
}
register_builtin_option pp.analyze.knowsType : Bool := {
defValue := true
group := "pp.analyze"
descr := "(pretty printer analyzer) assume the type of the original expression is known"
}
def getPPAnalyze (o : Options) : Bool := o.get pp.analyze.name pp.analyze.defValue
def getPPAnalyzeCheckInstances (o : Options) : Bool := o.get pp.analyze.checkInstances.name pp.analyze.checkInstances.defValue
def getPPAnalyzeTypeAscriptions (o : Options) : Bool := o.get pp.analyze.typeAscriptions.name pp.analyze.typeAscriptions.defValue
def getPPAnalyzeTrustSubst (o : Options) : Bool := o.get pp.analyze.trustSubst.name pp.analyze.trustSubst.defValue
def getPPAnalyzeTrustOfNat (o : Options) : Bool := o.get pp.analyze.trustOfNat.name pp.analyze.trustOfNat.defValue
def getPPAnalyzeTrustOfScientific (o : Options) : Bool := o.get pp.analyze.trustOfScientific.name pp.analyze.trustOfScientific.defValue
def getPPAnalyzeTrustId (o : Options) : Bool := o.get pp.analyze.trustId.name pp.analyze.trustId.defValue
def getPPAnalyzeTrustCoe (o : Options) : Bool := o.get pp.analyze.trustCoe.name pp.analyze.trustCoe.defValue
def getPPAnalyzeTrustKnownFOType2TypeHOFuns (o : Options) : Bool := o.get pp.analyze.trustKnownFOType2TypeHOFuns.name pp.analyze.trustKnownFOType2TypeHOFuns.defValue
def getPPAnalyzeOmitMax (o : Options) : Bool := o.get pp.analyze.omitMax.name pp.analyze.omitMax.defValue
def getPPAnalyzeKnowsType (o : Options) : Bool := o.get pp.analyze.knowsType.name pp.analyze.knowsType.defValue
def getPPAnalysisSkip (o : Options) : Bool := o.get `pp.analysis.skip false
def getPPAnalysisHole (o : Options) : Bool := o.get `pp.analysis.hole false
def getPPAnalysisNamedArg (o : Options) : Bool := o.get `pp.analysis.namedArg false
def getPPAnalysisLetVarType (o : Options) : Bool := o.get `pp.analysis.letVarType false
def getPPAnalysisNeedsType (o : Options) : Bool := o.get `pp.analysis.needsType false
def getPPAnalysisBlockImplicit (o : Options) : Bool := o.get `pp.analysis.blockImplicit false
namespace PrettyPrinter.Delaborator
def returnsPi (motive : Expr) : MetaM Bool := do
lambdaTelescope motive fun xs b => b.isForall
def isNonConstFun (motive : Expr) : MetaM Bool := do
match motive with
| Expr.lam name d b _ => isNonConstFun b
| _ => motive.hasLooseBVars
def isSimpleHOFun (motive : Expr) : MetaM Bool := do
not (← returnsPi motive) && not (← isNonConstFun motive)
def isType2Type (motive : Expr) : MetaM Bool := do
match ← inferType motive with
| Expr.forallE _ (Expr.sort ..) (Expr.sort ..) .. => true
| _ => false
def isFOLike (motive : Expr) : MetaM Bool := do
let f := motive.getAppFn
f.isFVar || f.isConst
def isIdLike (arg : Expr) : Bool := do
-- TODO: allow `id` constant as well?
match arg with
| Expr.lam _ _ (Expr.bvar ..) .. => true
| _ => false
def isCoe (e : Expr) : Bool :=
-- TODO: `coeSort? Builtins doesn't seem to render them anyway
e.isAppOfArity `coe 4
|| (e.isAppOf `coeFun && e.getAppNumArgs >= 4)
|| e.isAppOfArity `coeSort 4
def isStructureInstance (e : Expr) : MetaM Bool := do
match e.isConstructorApp? (← getEnv) with
| some s => isStructure (← getEnv) s.induct
| none => false
namespace TopDownAnalyze
partial def hasMVarAtCurrDepth (e : Expr) : MetaM Bool := do
let mctx ← getMCtx
Option.isSome $ e.findMVar? fun mvarId =>
match mctx.findDecl? mvarId with
| some mdecl => mdecl.depth == mctx.depth
| _ => false
partial def hasLevelMVarAtCurrDepth (e : Expr) : MetaM Bool := do
let mctx ← getMCtx
Option.isSome $ e.findLevelMVar? fun mvarId =>
mctx.findLevelDepth? mvarId == some mctx.depth
private def valUnknown (e : Expr) : MetaM Bool := do
hasMVarAtCurrDepth (← instantiateMVars e)
private def typeUnknown (e : Expr) : MetaM Bool := do
valUnknown (← inferType e)
def isHBinOp (e : Expr) : Bool := do
-- TODO: instead of tracking these explicitly,
-- consider a more general solution that checks for defaultInstances
if e.getAppNumArgs != 6 then return false
let f := e.getAppFn
if !f.isConst then return false
-- Note: we leave out `HPow.hPow because we expect its homogeneous
-- version will change soon
let ops := #[
`HOr.hOr, `HXor.hXor, `HAnd.hAnd,
`HAppend.hAppend, `HOrElse.hOrElse, `HAndThen.hAndThen,
`HAdd.hAdd, `HSub.hSub, `HMul.hMul, `HDiv.hDiv, `HMod.hMod,
`HShiftLeft.hShiftLeft, `HShiftRight]
ops.any fun op => op == f.constName!
def replaceLPsWithVars (e : Expr) : MetaM Expr := do
if !e.hasLevelParam then return e
let lps := collectLevelParams {} e |>.params
let mut replaceMap : Std.HashMap Name Level := {}
for lp in lps do replaceMap := replaceMap.insert lp (← mkFreshLevelMVar)
return e.replaceLevel fun
| Level.param n .. => replaceMap.find! n
| l => if !l.hasParam then some l else none
def isDefEqAssigning (t s : Expr) : MetaM Bool := do
withReader (fun ctx => { ctx with config := { ctx.config with assignSyntheticOpaque := true }}) $
Meta.isDefEq t s
def checkpointDefEq (t s : Expr) : MetaM Bool := do
Meta.checkpointDefEq (mayPostpone := false) do
isDefEqAssigning t s
def isHigherOrder (type : Expr) : MetaM Bool := do
forallTelescopeReducing type fun xs b => xs.size > 0 && b.isSort
def isFunLike (e : Expr) : MetaM Bool := do
forallTelescopeReducing (← inferType e) fun xs b => xs.size > 0
def isSubstLike (e : Expr) : Bool :=
e.isAppOfArity `Eq.ndrec 6 || e.isAppOfArity `Eq.rec 6
def nameNotRoundtrippable (n : Name) : Bool :=
n.hasMacroScopes || isPrivateName n || containsNum n
where
containsNum
| Name.str p .. => containsNum p
| Name.num .. => true
| Name.anonymous => false
def mvarName (mvar : Expr) : MetaM Name := do
(← getMVarDecl mvar.mvarId!).userName
def containsBadMax : Level → Bool
| Level.succ u .. => containsBadMax u
| Level.max u v .. => (u.hasParam && v.hasParam) || containsBadMax u || containsBadMax v
| Level.imax u v .. => containsBadMax u || containsBadMax v
| _ => false
open SubExpr
structure Context where
knowsType : Bool
knowsLevel : Bool -- only constants look at this
inBottomUp : Bool := false
parentIsApp : Bool := false
deriving Inhabited, Repr
structure State where
annotations : RBMap Pos Options compare := {}
postponed : Array (Expr × Expr) := #[] -- not currently used
abbrev AnalyzeM := ReaderT Context (ReaderT SubExpr (StateRefT State MetaM))
def tryUnify (e₁ e₂ : Expr) : AnalyzeM Unit := do
try
let r ← isDefEqAssigning e₁ e₂
if !r then modify fun s => { s with postponed := s.postponed.push (e₁, e₂) }
pure ()
catch ex =>
modify fun s => { s with postponed := s.postponed.push (e₁, e₂) }
partial def inspectOutParams (arg mvar : Expr) : AnalyzeM Unit := do
let argType ← inferType arg -- HAdd α α α
let mvarType ← inferType mvar
let fType ← inferType argType.getAppFn -- Type → Type → outParam Type
let mType ← inferType mvarType.getAppFn
inspectAux fType mType 0 argType.getAppArgs mvarType.getAppArgs
where
inspectAux (fType mType : Expr) (i : Nat) (args mvars : Array Expr) := do
let fType ← whnf fType
let mType ← whnf mType
if not (i < args.size) then return ()
match fType, mType with
| Expr.forallE _ fd fb _, Expr.forallE _ md mb _ => do
-- TODO: do I need to check (← okBottomUp? args[i] mvars[i] fuel).isSafe here?
-- if so, I'll need to take a callback
if isOutParam fd then
tryUnify (args[i]) (mvars[i])
inspectAux (fb.instantiate1 args[i]) (mb.instantiate1 mvars[i]) (i+1) args mvars
| _, _ => return ()
partial def isTrivialBottomUp (e : Expr) : AnalyzeM Bool := do
let opts ← getOptions
return e.isFVar
|| e.isConst || e.isMVar || e.isNatLit || e.isStringLit || e.isSort
|| (getPPAnalyzeTrustOfNat opts && e.isAppOfArity `OfNat.ofNat 3)
|| (getPPAnalyzeTrustOfScientific opts && e.isAppOfArity `OfScientific.ofScientific 5)
partial def canBottomUp (e : Expr) (mvar? : Option Expr := none) (fuel : Nat := 10) : AnalyzeM Bool := do
-- Here we check if `e` can be safely elaborated without its expected type.
-- These are incomplete (and possibly unsound) heuristics.
-- TODO: do I need to snapshot the state before calling this?
match fuel with
| 0 => false
| fuel + 1 =>
if ← isTrivialBottomUp e then return true
let f := e.getAppFn
if !f.isConst && !f.isFVar then return false
let args := e.getAppArgs
let fType ← replaceLPsWithVars (← inferType e.getAppFn)
let ⟨mvars, bInfos, resultType⟩ ← forallMetaBoundedTelescope fType e.getAppArgs.size
for i in [:mvars.size] do
if bInfos[i] == BinderInfo.instImplicit then
inspectOutParams args[i] mvars[i]
else if ← bInfos[i] == BinderInfo.default then
if ← isTrivialBottomUp args[i] then tryUnify args[i] mvars[i]
else if ← typeUnknown mvars[i] <&&> canBottomUp args[i] mvars[i] fuel then tryUnify args[i] mvars[i]
if ← (isHBinOp e <&&> (valUnknown mvars[0] <||> valUnknown mvars[1])) then tryUnify mvars[0] mvars[1]
if mvar?.isSome then tryUnify resultType (← inferType mvar?.get!)
return !(← valUnknown resultType)
def withKnowing (knowsType knowsLevel : Bool) (x : AnalyzeM α) : AnalyzeM α := do
withReader (fun ctx => { ctx with knowsType := knowsType, knowsLevel := knowsLevel }) x
builtin_initialize analyzeFailureId : InternalExceptionId ← registerInternalExceptionId `analyzeFailure
def checkKnowsType : AnalyzeM Unit := do
if not (← read).knowsType then
throw $ Exception.internal analyzeFailureId
def annotateBoolAt (n : Name) (pos : Pos) : AnalyzeM Unit := do
let opts := (← get).annotations.findD pos {} |>.setBool n true
trace[pp.analyze.annotate] "{pos} {n}"
modify fun s => { s with annotations := s.annotations.insert pos opts }
def annotateBool (n : Name) : AnalyzeM Unit := do
annotateBoolAt n (← getPos)
structure App.Context where
f : Expr
fType : Expr
args : Array Expr
mvars : Array Expr
bInfos : Array BinderInfo
forceRegularApp : Bool
structure App.State where
bottomUps : Array Bool
higherOrders : Array Bool
funBinders : Array Bool
provideds : Array Bool
namedArgs : Array Name := #[]
abbrev AnalyzeAppM := ReaderT App.Context (StateT App.State AnalyzeM)
mutual
partial def analyze (parentIsApp : Bool := false) : AnalyzeM Unit := do
checkMaxHeartbeats "Delaborator.topDownAnalyze"
trace[pp.analyze] "{(← read).knowsType}.{(← read).knowsLevel}"
let e ← getExpr
let opts ← getOptions
if ← !e.isAtomic <&&> !(getPPProofs opts) <&&> (try Meta.isProof e catch ex => false) then
if getPPProofsWithType opts then
withType $ withKnowing true true $ analyze
return ()
else
withReader (fun ctx => { ctx with parentIsApp := parentIsApp }) do
match (← getExpr) with
| Expr.app .. => analyzeApp
| Expr.forallE .. => analyzePi
| Expr.lam .. => analyzeLam
| Expr.const .. => analyzeConst
| Expr.sort .. => analyzeSort
| Expr.proj .. => analyzeProj
| Expr.fvar .. => analyzeFVar
| Expr.mdata .. => analyzeMData
| Expr.letE .. => analyzeLet
| Expr.lit .. => pure ()
| Expr.mvar .. => pure ()
| Expr.bvar .. => pure ()
where
analyzeApp := do
let mut willKnowType := (← read).knowsType
if !(← read).knowsType && !(← canBottomUp (← getExpr)) then
annotateBool `pp.analysis.needsType
withType $ withKnowing true false $ analyze
willKnowType := true
else if ← (!(← read).knowsType <||> (← read).inBottomUp) <&&> isStructureInstance (← getExpr) then
withType do
annotateBool `pp.structureInstanceTypes
withKnowing true false $ analyze
willKnowType := true
withKnowing willKnowType true $ analyzeAppStaged (← getExpr).getAppFn (← getExpr).getAppArgs
analyzeAppStaged (f : Expr) (args : Array Expr) : AnalyzeM Unit := do
let fType ← replaceLPsWithVars (← inferType f)
let ⟨mvars, bInfos, resultType⟩ ← forallMetaBoundedTelescope fType args.size
let rest := args.extract mvars.size args.size
let args := args.shrink mvars.size
-- Unify with the expected type
if (← read).knowsType then tryUnify (← inferType (mkAppN f args)) resultType
let forceRegularApp : Bool :=
(getPPAnalyzeTrustSubst (← getOptions) && isSubstLike (← getExpr))
|| (getPPAnalyzeTrustCoe (← getOptions) && isCoe (← getExpr))
analyzeAppStagedCore ⟨f, fType, args, mvars, bInfos, forceRegularApp⟩ |>.run' {
bottomUps := mkArray args.size false,
higherOrders := mkArray args.size false,
provideds := mkArray args.size false,
funBinders := mkArray args.size false
}
if not rest.isEmpty then
-- Note: this shouldn't happen for type-correct terms
if !args.isEmpty then
analyzeAppStaged (mkAppN f args) rest
maybeAddBlockImplicit : AnalyzeM Unit := do
-- See `MonadLift.noConfusion for an example where this is necessary.
if !(← read).parentIsApp then
let type ← inferType (← getExpr)
if type.isForall && type.bindingInfo! == BinderInfo.implicit then
annotateBool `pp.analysis.blockImplicit
analyzeConst : AnalyzeM Unit := do
let Expr.const n ls .. ← getExpr | unreachable!
if !(← read).knowsLevel && !ls.isEmpty then
-- TODO: this is a very crude heuristic, motivated by https://github.com/leanprover/lean4/issues/590
unless getPPAnalyzeOmitMax (← getOptions) && ls.any containsBadMax do
annotateBool `pp.universes
maybeAddBlockImplicit
analyzePi : AnalyzeM Unit := do
withBindingDomain $ withKnowing true false analyze
withBindingBody Name.anonymous analyze
analyzeLam : AnalyzeM Unit := do
if !(← read).knowsType then annotateBool `pp.funBinderTypes
withBindingDomain $ withKnowing true false analyze
withBindingBody Name.anonymous analyze
analyzeLet : AnalyzeM Unit := do
let Expr.letE n t v body .. ← getExpr | unreachable!
if !(← canBottomUp v) then
annotateBool `pp.analysis.letVarType
withLetVarType $ withKnowing true false analyze
withLetValue $ withKnowing true true analyze
else
withReader (fun ctx => { ctx with inBottomUp := true }) do
withLetValue $ withKnowing true true analyze
withLetBody analyze
analyzeSort : AnalyzeM Unit := pure ()
analyzeProj : AnalyzeM Unit := withProj analyze
analyzeFVar : AnalyzeM Unit := maybeAddBlockImplicit
analyzeMData : AnalyzeM Unit := withMDataExpr analyze
partial def analyzeAppStagedCore : AnalyzeAppM Unit := do
collectBottomUps
checkOutParams
collectHigherOrders
hBinOpHeuristic
collectTrivialBottomUps
discard <| processPostponed (mayPostpone := true)
applyFunBinderHeuristic
analyzeFn
for i in [:(← read).args.size] do analyzeArg i
maybeSetExplicit
where
collectBottomUps := do
let ⟨_, _, args, mvars, bInfos, _⟩ ← read
for target in [fun _ => none, fun i => some mvars[i]] do
for i in [:args.size] do
if bInfos[i] == BinderInfo.default then
if ← typeUnknown mvars[i] <&&> canBottomUp args[i] (target i) then
tryUnify args[i] mvars[i]
modify fun s => { s with bottomUps := s.bottomUps.set! i true }
checkOutParams := do
let ⟨_, _, args, mvars, bInfos, _⟩ ← read
for i in [:args.size] do
if bInfos[i] == BinderInfo.instImplicit then inspectOutParams args[i] mvars[i]
collectHigherOrders := do
let ⟨_, _, args, mvars, bInfos, _⟩ ← read
for i in [:args.size] do
if not (bInfos[i] == BinderInfo.implicit || bInfos[i] == BinderInfo.strictImplicit) then continue
if not (← isHigherOrder (← inferType args[i])) then continue
if getPPAnalyzeTrustId (← getOptions) && isIdLike args[i] then continue
if getPPAnalyzeTrustKnownFOType2TypeHOFuns (← getOptions) && not (← valUnknown mvars[i])
&& (← isType2Type (args[i])) && (← isFOLike (args[i])) then continue
tryUnify args[i] mvars[i]
modify fun s => { s with higherOrders := s.higherOrders.set! i true }
hBinOpHeuristic := do
let ⟨_, _, args, mvars, bInfos, _⟩ ← read
if ← (isHBinOp (← getExpr) <&&> (valUnknown mvars[0] <||> valUnknown mvars[1])) then
tryUnify mvars[0] mvars[1]
collectTrivialBottomUps := do
-- motivation: prevent levels from printing in
-- Boo.mk : {α : Type u_1} → {β : Type u_2} → α → β → Boo.{u_1, u_2} α β
let ⟨_, _, args, mvars, bInfos, _⟩ ← read
for i in [:args.size] do
if bInfos[i] == BinderInfo.default then
if ← valUnknown mvars[i] <&&> isTrivialBottomUp args[i] then
tryUnify args[i] mvars[i]
modify fun s => { s with bottomUps := s.bottomUps.set! i true }
applyFunBinderHeuristic := do
let ⟨f, _, args, mvars, bInfos, _⟩ ← read
let rec core (argIdx : Nat) (mvarType : Expr) : AnalyzeAppM Bool := do
match ← getExpr, mvarType with
| Expr.lam _ _ _ .., Expr.forallE n t b .. =>
let mut annotated := false
for i in [:argIdx] do
if ← bInfos[i] == BinderInfo.implicit <&&> valUnknown mvars[i] <&&> withNewMCtxDepth (checkpointDefEq t mvars[i]) then
annotateBool `pp.funBinderTypes
tryUnify args[i] mvars[i]
-- Note: currently we always analyze the lambda binding domains in `analyzeLam`
-- (so we don't need to analyze it again here)
annotated := true
break
let annotatedBody ← withBindingBody Name.anonymous (core argIdx b)
return annotated || annotatedBody
| _, _ => return false
for i in [:args.size] do
if ← bInfos[i] == BinderInfo.default then
let b ← withNaryArg i (core i (← inferType mvars[i]))
if b then modify fun s => { s with funBinders := s.funBinders.set! i true }
analyzeFn := do
-- Now, if this is the first staging, analyze the n-ary function without expected type
let ⟨f, fType, _, _, _, forceRegularApp⟩ ← read
if !f.isApp then withKnowing false (forceRegularApp || !(← hasLevelMVarAtCurrDepth (← instantiateMVars fType))) $ withNaryFn (analyze (parentIsApp := true))
annotateNamedArg (n : Name) : AnalyzeAppM Unit := do
annotateBool `pp.analysis.namedArg
modify fun s => { s with namedArgs := s.namedArgs.push n }
analyzeArg (i : Nat) := do
let ⟨f, _, args, mvars, bInfos, forceRegularApp⟩ ← read
let ⟨bottomUps, higherOrders, funBinders, _, _⟩ ← get
let arg := args[i]
let argType ← inferType arg
let processNaturalImplicit : AnalyzeAppM Unit := do
if (← valUnknown mvars[i] <||> higherOrders[i]) && !forceRegularApp then
annotateNamedArg (← mvarName mvars[i])
modify fun s => { s with provideds := s.provideds.set! i true }
else
annotateBool `pp.analysis.skip
withNaryArg (f.getAppNumArgs + i) do
withTheReader Context (fun ctx => { ctx with inBottomUp := ctx.inBottomUp || bottomUps[i] }) do
match bInfos[i] with
| BinderInfo.default =>
if ← !(← valUnknown mvars[i]) <&&> !(← readThe Context).inBottomUp <&&> !(← isFunLike arg) <&&> !funBinders[i] <&&> checkpointDefEq mvars[i] arg then
annotateBool `pp.analysis.hole
else
modify fun s => { s with provideds := s.provideds.set! i true }
| BinderInfo.implicit => processNaturalImplicit
| BinderInfo.strictImplicit => processNaturalImplicit
| BinderInfo.instImplicit =>
-- Note: apparently checking valUnknown here is not sound, because the elaborator
-- will not happily assign instImplicits that it cannot synthesize
let mut provided := true
if !getPPInstances (← getOptions) then
annotateBool `pp.analysis.skip
provided := false
else if getPPAnalyzeCheckInstances (← getOptions) then
let instResult ← try trySynthInstance argType catch _ => LOption.undef
match instResult with
| LOption.some inst =>
if ← checkpointDefEq inst arg then annotateBool `pp.analysis.skip; provided := false
else annotateNamedArg (← mvarName mvars[i])
| _ => annotateNamedArg (← mvarName mvars[i])
else provided := false
modify fun s => { s with provideds := s.provideds.set! i provided }
| BinderInfo.auxDecl => pure ()
if (← get).provideds[i] then withKnowing (not (← typeUnknown mvars[i])) true analyze
tryUnify mvars[i] args[i]
maybeSetExplicit := do
let ⟨f, _, args, mvars, bInfos, forceRegularApp⟩ ← read
if (← get).namedArgs.any nameNotRoundtrippable then
annotateBool `pp.explicit
for i in [:args.size] do
if !(← get).provideds[i] then
withNaryArg (f.getAppNumArgs + i) do annotateBool `pp.analysis.hole
if bInfos[i] == BinderInfo.instImplicit && getPPInstanceTypes (← getOptions) then
withType (withKnowing true false analyze)
end
end TopDownAnalyze
open TopDownAnalyze SubExpr
def topDownAnalyze (e : Expr) : MetaM OptionsPerPos := do
let s₀ ← get
traceCtx `pp.analyze do
withReader (fun ctx => { ctx with config := Lean.Elab.Term.setElabConfig ctx.config }) do
let ϕ : AnalyzeM OptionsPerPos := do withNewMCtxDepth analyze; (← get).annotations
try
let knowsType := getPPAnalyzeKnowsType (← getOptions)
ϕ { knowsType := knowsType, knowsLevel := knowsType } (mkRoot e) |>.run' {}
catch ex =>
trace[pp.analyze.error] "failed"
pure {}
finally set s₀
builtin_initialize
registerTraceClass `pp.analyze
registerTraceClass `pp.analyze.annotate
registerTraceClass `pp.analyze.tryUnify
registerTraceClass `pp.analyze.error
end Lean.PrettyPrinter.Delaborator
|
ad29defcf07eea771be0576d02261c0021cd3b76 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /archive/imo/imo2005_q3.lean | 28a9ec832e870a2789372f36dfb80f45f3d01fe0 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,478 | lean | /-
Copyright (c) 2021 Manuel Candales. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Manuel Candales
-/
import data.real.basic
/-!
# IMO 2005 Q3
Let `x`, `y` and `z` be positive real numbers such that `xyz ≥ 1`. Prove that:
`(x^5 - x^2)/(x^5 + y^2 + z^2) + (y^5 - y^2)/(y^5 + z^2 + x^2) + (z^5 - z^2)/(z^5 + x^2 + y^2) ≥ 0`
# Solution
The solution by Iurie Boreico from Moldova is presented, which won a special prize during the exam.
The key insight is that `(x^5-x^2)/(x^5+y^2+z^2) ≥ (x^2-y*z)/(x^2+y^2+z^2)`, which is proven by
factoring `(x^5-x^2)/(x^5+y^2+z^2) - (x^5-x^2)/(x^3*(x^2+y^2+z^2))` into a non-negative expression
and then making use of `xyz ≥ 1` to show `(x^5-x^2)/(x^3*(x^2+y^2+z^2)) ≥ (x^2-y*z)/(x^2+y^2+z^2)`.
-/
lemma key_insight (x y z : ℝ) (hx : x > 0) (hy : y > 0) (hz : z > 0) (h : x*y*z ≥ 1) :
(x^5-x^2)/(x^5+y^2+z^2) ≥ (x^2-y*z)/(x^2+y^2+z^2) :=
begin
have h₁ : x^5+y^2+z^2 > 0, linarith [pow_pos hx 5, pow_pos hy 2, pow_pos hz 2],
have h₂ : x^3 > 0, exact pow_pos hx 3,
have h₃ : x^2+y^2+z^2 > 0, linarith [pow_pos hx 2, pow_pos hy 2, pow_pos hz 2],
have h₄ : x^3*(x^2+y^2+z^2) > 0, exact mul_pos h₂ h₃,
have key : (x^5-x^2)/(x^5+y^2+z^2) - (x^5-x^2)/(x^3*(x^2+y^2+z^2))
= ((x^3 - 1)^2*x^2*(y^2 + z^2))/((x^5+y^2+z^2)*(x^3*(x^2+y^2+z^2))),
calc (x^5-x^2)/(x^5+y^2+z^2) - (x^5-x^2)/(x^3*(x^2+y^2+z^2))
= ((x^5-x^2)*(x^3*(x^2+y^2+z^2))-(x^5+y^2+z^2)*(x^5-x^2))/((x^5+y^2+z^2)*(x^3*(x^2+y^2+z^2))):
by exact div_sub_div _ _ (ne_of_gt h₁) (ne_of_gt h₄) -- a/b - c/d = (a*d-b*c)/(b*d)
... = ((x^3 - 1)^2*x^2*(y^2 + z^2))/((x^5+y^2+z^2)*(x^3*(x^2+y^2+z^2))) :
by ring,
have h₅ : ((x^3 - 1)^2*x^2*(y^2 + z^2))/((x^5+y^2+z^2)*(x^3*(x^2+y^2+z^2))) ≥ 0,
{ refine div_nonneg _ _,
refine mul_nonneg (mul_nonneg (pow_two_nonneg _) (pow_two_nonneg _)) _,
exact add_nonneg (pow_two_nonneg _) (pow_two_nonneg _),
exact le_of_lt (mul_pos h₁ h₄) },
calc (x^5-x^2)/(x^5+y^2+z^2)
≥ (x^5-x^2)/(x^3*(x^2+y^2+z^2)) : by linarith [key, h₅]
... ≥ (x^5-x^2*(x*y*z))/(x^3*(x^2+y^2+z^2)) :
by { refine (div_le_div_right h₄).mpr _, simp,
exact (le_mul_iff_one_le_right (pow_pos hx 2)).mpr h }
... = (x^2-y*z)/(x^2+y^2+z^2) :
by { field_simp [ne_of_gt h₂, ne_of_gt h₃], ring },
end
theorem imo2005_q3 (x y z : ℝ) (hx : x > 0) (hy : y > 0) (hz : z > 0) (h : x*y*z ≥ 1) :
(x^5-x^2)/(x^5+y^2+z^2) + (y^5-y^2)/(y^5+z^2+x^2) + (z^5-z^2)/(z^5+x^2+y^2) ≥ 0 :=
begin
calc (x^5-x^2)/(x^5+y^2+z^2) + (y^5-y^2)/(y^5+z^2+x^2) + (z^5-z^2)/(z^5+x^2+y^2)
≥ (x^2-y*z)/(x^2+y^2+z^2) + (y^2-z*x)/(y^2+z^2+x^2) + (z^2-x*y)/(z^2+x^2+y^2) :
by { linarith [key_insight x y z hx hy hz h,
key_insight y z x hy hz hx (by linarith [h]),
key_insight z x y hz hx hy (by linarith [h])] }
... = (x^2 + y^2 + z^2 - y*z - z*x - x*y) / (x^2+y^2+z^2) :
by { have h₁ : y^2+z^2+x^2 = x^2+y^2+z^2, linarith,
have h₂ : z^2+x^2+y^2 = x^2+y^2+z^2, linarith,
rw [h₁, h₂], ring }
... = 1/2*( (x-y)^2 + (y-z)^2 + (z-x)^2 ) / (x^2+y^2+z^2) : by ring
... ≥ 0 :
by { exact div_nonneg
(by linarith [pow_two_nonneg (x-y), pow_two_nonneg (y-z), pow_two_nonneg (z-x)])
(by linarith [pow_two_nonneg x, pow_two_nonneg y, pow_two_nonneg z]) },
end
|
32de8ce3c2b46bcd8a46e5b78a83d73e1934a451 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /11_Tactic-Style_Proofs.org.17.lean | 44af2b755a9c94fea84231106a99790f8a091d27 | [] | 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 | 383 | lean | import standard
import data.nat
open nat
variables x y z : ℕ
example : x = x :=
begin
generalize x, -- goal is x : ℕ ⊢ ∀ (x : ℕ), x = x
intro y, -- goal is x y : ℕ ⊢ y = y
apply rfl
end
example (H : x = y) : y = x :=
begin
generalize H, -- goal is x y : ℕ, H : x = y ⊢ y = x
intro H1, -- goal is x y : ℕ, H H1 : x = y ⊢ y = x
apply (eq.symm H1)
end
|
6626ca0ec521072caf704fed387d0b1062db6467 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/group_theory/group_action/defs.lean | 3911e71d457079a5e480d211d77992df11b1fd3a | [] | 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 | 8,645 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.equiv.basic
import Mathlib.algebra.group.defs
import Mathlib.algebra.group.hom
import Mathlib.logic.embedding
import Mathlib.PostPort
universes u v l u_1 u_2 u_3 w
namespace Mathlib
/-!
# Definitions of group actions
This file defines a hierarchy of group action type-classes:
* `has_scalar α β`
* `mul_action α β`
* `distrib_mul_action α β`
The hierarchy is extended further by `semimodule`, defined elsewhere.
Also provided are type-classes regarding the interaction of different group actions,
* `smul_comm_class M N α`
* `is_scalar_tower M N α`
## Notation
`a • b` is used as notation for `smul a b`.
## Implementation details
This file should avoid depending on other parts of `group_theory`, to avoid import cycles.
More sophisticated lemmas belong in `group_theory.group_action`.
-/
/-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/
class has_scalar (α : Type u) (γ : Type v)
where
smul : α → γ → γ
infixr:73 " • " => Mathlib.has_scalar.smul
/-- Typeclass for multiplicative actions by monoids. This generalizes group actions. -/
class mul_action (α : Type u) (β : Type v) [monoid α]
extends has_scalar α β
where
one_smul : ∀ (b : β), 1 • b = b
mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b
/-- A typeclass mixin saying that two actions on the same space commute. -/
class smul_comm_class (M : Type u_1) (N : Type u_2) (α : Type u_3) [has_scalar M α] [has_scalar N α]
where
smul_comm : ∀ (m : M) (n : N) (a : α), m • n • a = n • m • a
/-- Commutativity of actions is a symmetric relation. This lemma can't be an instance because this
would cause a loop in the instance search graph. -/
theorem smul_comm_class.symm (M : Type u_1) (N : Type u_2) (α : Type u_3) [has_scalar M α] [has_scalar N α] [smul_comm_class M N α] : smul_comm_class N M α :=
smul_comm_class.mk fun (a' : N) (a : M) (b : α) => Eq.symm (smul_comm a a' b)
protected instance smul_comm_class_self (M : Type u_1) (α : Type u_2) [comm_monoid M] [mul_action M α] : smul_comm_class M M α :=
smul_comm_class.mk
fun (a a' : M) (b : α) =>
eq.mpr (id (Eq._oldrec (Eq.refl (a • a' • b = a' • a • b)) (Eq.symm (mul_smul a a' b))))
(eq.mpr (id (Eq._oldrec (Eq.refl ((a * a') • b = a' • a • b)) (mul_comm a a')))
(eq.mpr (id (Eq._oldrec (Eq.refl ((a' * a) • b = a' • a • b)) (mul_smul a' a b))) (Eq.refl (a' • a • b))))
/-- An instance of `is_scalar_tower M N α` states that the multiplicative
action of `M` on `α` is determined by the multiplicative actions of `M` on `N`
and `N` on `α`. -/
class is_scalar_tower (M : Type u_1) (N : Type u_2) (α : Type u_3) [has_scalar M N] [has_scalar N α] [has_scalar M α]
where
smul_assoc : ∀ (x : M) (y : N) (z : α), (x • y) • z = x • y • z
@[simp] theorem smul_assoc {α : Type u} {M : Type u_1} {N : Type u_2} [has_scalar M N] [has_scalar N α] [has_scalar M α] [is_scalar_tower M N α] (x : M) (y : N) (z : α) : (x • y) • z = x • y • z :=
is_scalar_tower.smul_assoc x y z
theorem smul_smul {α : Type u} {β : Type v} [monoid α] [mul_action α β] (a₁ : α) (a₂ : α) (b : β) : a₁ • a₂ • b = (a₁ * a₂) • b :=
Eq.symm (mul_smul a₁ a₂ b)
@[simp] theorem one_smul (α : Type u) {β : Type v} [monoid α] [mul_action α β] (b : β) : 1 • b = b :=
mul_action.one_smul b
/-- Pullback a multiplicative action along an injective map respecting `•`. -/
protected def function.injective.mul_action {α : Type u} {β : Type v} {γ : Type w} [monoid α] [mul_action α β] [has_scalar α γ] (f : γ → β) (hf : function.injective f) (smul : ∀ (c : α) (x : γ), f (c • x) = c • f x) : mul_action α γ :=
mul_action.mk sorry sorry
/-- Pushforward a multiplicative action along a surjective map respecting `•`. -/
protected def function.surjective.mul_action {α : Type u} {β : Type v} {γ : Type w} [monoid α] [mul_action α β] [has_scalar α γ] (f : β → γ) (hf : function.surjective f) (smul : ∀ (c : α) (x : β), f (c • x) = c • f x) : mul_action α γ :=
mul_action.mk sorry sorry
theorem ite_smul {α : Type u} {β : Type v} [monoid α] [mul_action α β] (p : Prop) [Decidable p] (a₁ : α) (a₂ : α) (b : β) : ite p a₁ a₂ • b = ite p (a₁ • b) (a₂ • b) := sorry
theorem smul_ite {α : Type u} {β : Type v} [monoid α] [mul_action α β] (p : Prop) [Decidable p] (a : α) (b₁ : β) (b₂ : β) : a • ite p b₁ b₂ = ite p (a • b₁) (a • b₂) := sorry
namespace mul_action
/-- The regular action of a monoid on itself by left multiplication. -/
def regular (α : Type u) [monoid α] : mul_action α α :=
mk sorry sorry
protected instance is_scalar_tower.left (α : Type u) {β : Type v} [monoid α] [mul_action α β] : is_scalar_tower α α β :=
is_scalar_tower.mk fun (x y : α) (z : β) => mul_smul x y z
/-- Embedding induced by action. -/
def to_fun (α : Type u) (β : Type v) [monoid α] [mul_action α β] : β ↪ α → β :=
function.embedding.mk (fun (y : β) (x : α) => x • y) sorry
@[simp] theorem to_fun_apply {α : Type u} {β : Type v} [monoid α] [mul_action α β] (x : α) (y : β) : coe_fn (to_fun α β) y x = x • y :=
rfl
/-- An action of `α` on `β` and a monoid homomorphism `γ → α` induce an action of `γ` on `β`. -/
def comp_hom {α : Type u} (β : Type v) {γ : Type w} [monoid α] [mul_action α β] [monoid γ] (g : γ →* α) : mul_action γ β :=
mk sorry sorry
end mul_action
@[simp] theorem smul_one_smul {α : Type u} {M : Type u_1} (N : Type u_2) [monoid N] [has_scalar M N] [mul_action N α] [has_scalar M α] [is_scalar_tower M N α] (x : M) (y : α) : (x • 1) • y = x • y :=
eq.mpr (id (Eq._oldrec (Eq.refl ((x • 1) • y = x • y)) (smul_assoc x 1 y)))
(eq.mpr (id (Eq._oldrec (Eq.refl (x • 1 • y = x • y)) (one_smul N y))) (Eq.refl (x • y)))
/-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/
class distrib_mul_action (α : Type u) (β : Type v) [monoid α] [add_monoid β]
extends mul_action α β
where
smul_add : ∀ (r : α) (x y : β), r • (x + y) = r • x + r • y
smul_zero : ∀ (r : α), r • 0 = 0
theorem smul_add {α : Type u} {β : Type v} [monoid α] [add_monoid β] [distrib_mul_action α β] (a : α) (b₁ : β) (b₂ : β) : a • (b₁ + b₂) = a • b₁ + a • b₂ :=
distrib_mul_action.smul_add a b₁ b₂
@[simp] theorem smul_zero {α : Type u} {β : Type v} [monoid α] [add_monoid β] [distrib_mul_action α β] (a : α) : a • 0 = 0 :=
distrib_mul_action.smul_zero a
/-- Pullback a distributive multiplicative action along an injective additive monoid
homomorphism. -/
protected def function.injective.distrib_mul_action {α : Type u} {β : Type v} {γ : Type w} [monoid α] [add_monoid β] [distrib_mul_action α β] [add_monoid γ] [has_scalar α γ] (f : γ →+ β) (hf : function.injective ⇑f) (smul : ∀ (c : α) (x : γ), coe_fn f (c • x) = c • coe_fn f x) : distrib_mul_action α γ :=
distrib_mul_action.mk sorry sorry
/-- Pushforward a distributive multiplicative action along a surjective additive monoid
homomorphism.-/
protected def function.surjective.distrib_mul_action {α : Type u} {β : Type v} {γ : Type w} [monoid α] [add_monoid β] [distrib_mul_action α β] [add_monoid γ] [has_scalar α γ] (f : β →+ γ) (hf : function.surjective ⇑f) (smul : ∀ (c : α) (x : β), coe_fn f (c • x) = c • coe_fn f x) : distrib_mul_action α γ :=
distrib_mul_action.mk sorry sorry
/-- Scalar multiplication by `r` as an `add_monoid_hom`. -/
def const_smul_hom {α : Type u} (β : Type v) [monoid α] [add_monoid β] [distrib_mul_action α β] (r : α) : β →+ β :=
add_monoid_hom.mk (has_scalar.smul r) (smul_zero r) (smul_add r)
@[simp] theorem const_smul_hom_apply {α : Type u} {β : Type v} [monoid α] [add_monoid β] [distrib_mul_action α β] (r : α) (x : β) : coe_fn (const_smul_hom β r) x = r • x :=
rfl
@[simp] theorem smul_neg {α : Type u} {β : Type v} [monoid α] [add_group β] [distrib_mul_action α β] (r : α) (x : β) : r • -x = -(r • x) := sorry
theorem smul_sub {α : Type u} {β : Type v} [monoid α] [add_group β] [distrib_mul_action α β] (r : α) (x : β) (y : β) : r • (x - y) = r • x - r • y := sorry
|
22a2987f1a353e8e0769d25ed539367bba57dff6 | a88f0086fb3e2025ebb21e0ba2f2725774c6979f | /src/data/int/basic.lean | ffc2db6b7a33e25963a865ffe5c0dc75fa34f74c | [
"Apache-2.0"
] | permissive | Kha/stdlib | b5a4456c35def0ca8f1bf2d32dbeebd7639cbc4d | e44b105c72ec77120f43a7a7dd1cd49867a65a41 | refs/heads/master | 1,609,528,111,500 | 1,572,963,395,000 | 1,572,963,395,000 | 98,516,307 | 0 | 1 | null | 1,501,146,352,000 | 1,501,146,352,000 | null | UTF-8 | Lean | false | false | 51,078 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
The integers, with addition, multiplication, and subtraction.
-/
import data.nat.basic data.list.basic algebra.char_zero algebra.order_functions
open nat
namespace int
instance : inhabited ℤ := ⟨int.zero⟩
@[simp] lemma default_eq_zero : default ℤ = 0 := rfl
meta instance : has_to_format ℤ := ⟨λ z, int.rec_on z (λ k, ↑k) (λ k, "-("++↑k++"+1)")⟩
meta instance : has_reflect ℤ := by tactic.mk_has_reflect_instance
attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ
attribute [simp] int.of_nat_eq_coe
@[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl
@[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl
@[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl
@[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl
@[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl
@[simp, elim_cast] theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n
@[simp, elim_cast] theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n
@[simp, elim_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n
@[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n :=
by rw [← int.coe_nat_zero, coe_nat_lt]
@[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 :=
by rw [← int.coe_nat_zero, coe_nat_inj']
@[simp] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 :=
not_congr coe_nat_eq_zero
lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _)
lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n :=
⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h),
λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩
lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n)
@[simp, elim_cast] theorem coe_nat_abs (n : ℕ) : abs (n : ℤ) = n :=
abs_of_nonneg (coe_nat_nonneg n)
/- succ and pred -/
/-- Immediate successor of an integer: `succ n = n + 1` -/
def succ (a : ℤ) := a + 1
/-- Immediate predecessor of an integer: `pred n = n - 1` -/
def pred (a : ℤ) := a - 1
theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl
theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _
theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _
theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _
theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a :=
by rw [neg_succ, succ_pred]
theorem neg_pred (a : ℤ) : -pred a = succ (-a) :=
by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg]
theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a :=
by rw [neg_pred, pred_succ]
theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n
theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n
theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n
theorem lt_succ_self (a : ℤ) : a < succ a :=
lt_add_of_pos_right _ zero_lt_one
theorem pred_self_lt (a : ℤ) : pred a < a :=
sub_lt_self _ zero_lt_one
theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl
theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b :=
@add_le_add_iff_right _ _ a b 1
theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b :=
sub_lt_iff_lt_add.trans lt_add_one_iff
theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b :=
le_sub_iff_add_le
@[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop}
(i : ℤ) (hz : p 0) (hp : ∀i : ℕ, p i → p (i + 1)) (hn : ∀i : ℕ, p (-i) → p (-i - 1)) : p i :=
begin
induction i,
{ induction i,
{ exact hz },
{ exact hp _ i_ih } },
{ have : ∀n:ℕ, p (- n),
{ intro n, induction n,
{ simp [hz] },
{ have := hn _ n_ih, simpa } },
exact this (i + 1) }
end
protected def induction_on' {C : ℤ → Sort*} (z : ℤ) (b : ℤ) :
C b → (∀ k, b ≤ k → C k → C (k + 1)) → (∀ k ≤ b, C k → C (k - 1)) → C z :=
λ H0 Hs Hp,
begin
rw ←sub_add_cancel z b,
induction (z - b),
{ induction a with n ih, { rwa [of_nat_zero, zero_add] },
rw [of_nat_succ, add_assoc, add_comm 1 b, ←add_assoc],
exact Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih },
{ induction a with n ih,
{ rw [neg_succ_of_nat_eq, ←of_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub],
exact Hp _ (le_refl _) H0 },
{ rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, ←neg_succ_of_nat_coe, sub_add_eq_add_sub],
exact Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) (le_refl _))) ih } }
end
/- nat abs -/
attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one
theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b :=
begin
have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b),
{ refine (λ a b : ℕ, sub_nat_nat_elim a b.succ
(λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl);
intros i n e,
{ subst e, rw [add_comm _ i, add_assoc],
exact nat.le_add_right i (b.succ + b).succ },
{ apply succ_le_succ,
rw [← succ_inj e, ← add_assoc, add_comm],
apply nat.le_add_right } },
cases a; cases b with b b; simp [nat_abs, nat.succ_add];
try {refl}; [skip, rw add_comm a b]; apply this
end
theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n :=
by cases n; refl
theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) :=
by cases a; cases b; simp only [(*), int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs]
@[simp] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a :=
by rw [← int.coe_nat_mul, nat_abs_mul_self]
theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 :=
by simp [neg_succ_of_nat_eq]
lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 :=
λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h
@[simp] lemma nat_abs_eq_zero {a : ℤ} : a.nat_abs = 0 ↔ a = 0 :=
⟨int.eq_zero_of_nat_abs_eq_zero, λ h, h.symm ▸ rfl⟩
/- / -/
@[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl
@[simp, move_cast] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl
theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) :
-[1+m] / b = -(m / b + 1) :=
match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end
@[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b)
| (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl
| (m : ℕ) (n+1:ℕ) := rfl
| 0 -[1+ n] := rfl
| (m+1:ℕ) -[1+ n] := (neg_neg _).symm
| -[1+ m] 0 := rfl
| -[1+ m] (n+1:ℕ) := rfl
| -[1+ m] -[1+ n] := rfl
theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) :=
match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ :=
by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl
end
protected theorem div_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b :=
match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _
end
protected theorem div_nonpos {a b : ℤ} (Ha : 0 ≤ a) (Hb : b ≤ 0) : a / b ≤ 0 :=
nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb)
theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 :=
match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _
end
@[simp] protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0
| 0 := rfl
| (n+1:ℕ) := rfl
| -[1+ n] := rfl
@[simp] protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0
| 0 := rfl
| (n+1:ℕ) := rfl
| -[1+ n] := rfl
@[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a
| 0 := rfl
| (n+1:ℕ) := congr_arg of_nat (nat.div_one _)
| -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _)
theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 :=
match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 :=
congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2
end
theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 :=
match b, abs b, abs_eq_nat_abs b, H2 with
| (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2
| -[1+ n], ._, rfl, H2 := neg_inj $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2
end
protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) :
(a + b * c) / c = a / c + b :=
have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from
λ k n a, match a with
| (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos
| -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ =
n - (m / k.succ + 1 : ℕ), begin
cases lt_or_ge m (n*k.succ) with h h,
{ rw [← int.coe_nat_sub h,
← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)],
apply congr_arg of_nat,
rw [mul_comm, nat.mul_sub_div], rwa mul_comm },
{ change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) =
↑n - ((m / nat.succ k : ℕ) + 1),
rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ),
← int.coe_nat_sub h,
← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h),
← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'],
{ apply congr_arg neg_succ_of_nat,
rw [mul_comm, nat.sub_mul_div], rwa mul_comm } }
end
end,
have ∀ {a b c : ℤ}, 0 < c → (a + b * c) / c = a / c + b, from
λ a b c H, match c, eq_succ_of_zero_lt H, b with
| ._, ⟨k, rfl⟩, (n : ℕ) := this
| ._, ⟨k, rfl⟩, -[1+ n] :=
show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from
eq_sub_of_add_eq $ by rw [← this, sub_add_cancel]
end,
match lt_trichotomy c 0 with
| or.inl hlt := neg_inj $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg];
apply this (neg_pos_of_neg hlt)
| or.inr (or.inl heq) := absurd heq H
| or.inr (or.inr hgt) := this hgt
end
protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) :
(a + b * c) / b = a / b + c :=
by rw [mul_comm, int.add_mul_div_right _ _ H]
@[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a :=
by have := int.add_mul_div_right 0 a H;
rwa [zero_add, int.zero_div, zero_add] at this
@[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b :=
by rw [mul_comm, int.mul_div_cancel _ H]
@[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 :=
by have := int.mul_div_cancel 1 H; rwa one_mul at this
/- mod -/
theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl
@[simp] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl
theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) :
-[1+m] % b = b - 1 - m % b :=
by rw [sub_sub, add_comm]; exact
match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end
@[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b
| (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _)
| -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _)
@[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b :=
abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _)
@[simp] theorem zero_mod (b : ℤ) : 0 % b = 0 :=
congr_arg of_nat $ nat.zero_mod _
@[simp] theorem mod_zero : ∀ (a : ℤ), a % 0 = a
| (m : ℕ) := congr_arg of_nat $ nat.mod_zero _
| -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _
@[simp] theorem mod_one : ∀ (a : ℤ), a % 1 = 0
| (m : ℕ) := congr_arg of_nat $ nat.mod_one _
| -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl
theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a :=
match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 :=
congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2)
end
theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → 0 ≤ a % b
| (m : ℕ) n H := coe_zero_le _
| -[1+ m] n H :=
sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H)
theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : 0 < b) : a % b < b :=
match a, b, eq_succ_of_zero_lt H with
| (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _))
| -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _)
end
theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b :=
by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos_of_ne_zero H)
theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] :=
begin
rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)],
apply eq_neg_of_eq_neg,
rw [neg_sub, sub_sub_self, add_right_comm],
exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm
end
theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a
| (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _)
| (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _)
| 0 -[1+ n] := rfl
| (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _,
by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _)
| -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl
| -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ
| -[1+ m] -[1+ n] := mod_add_div_aux m n.succ
theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) :=
eq_sub_of_add_eq (mod_add_div _ _)
@[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c :=
if cz : c = 0 then by rw [cz, mul_zero, add_zero] else
by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz,
mul_add, mul_comm, add_sub_add_right_eq_sub]
@[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b :=
by rw [mul_comm, add_mul_mod_self]
@[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b :=
by have := add_mul_mod_self_left a b 1; rwa mul_one at this
@[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a :=
by rw [add_comm, add_mod_self]
@[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n :=
by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm;
rwa [add_right_comm, mod_add_div] at this
@[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k :=
by rw [add_comm, mod_add_mod, add_comm]
theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) :
(m + i) % n = (k + i) % n :=
by rw [← mod_add_mod, ← mod_add_mod k, H]
theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) :
(i + m) % n = (i + k) % n :=
by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm]
theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔
m % n = k % n :=
⟨λ H, by have := add_mod_eq_add_mod_right (-i) H;
rwa [add_neg_cancel_right, add_neg_cancel_right] at this,
add_mod_eq_add_mod_right _⟩
theorem mod_add_cancel_left {m n k i : ℤ} :
(i + m) % n = (i + k) % n ↔ m % n = k % n :=
by rw [add_comm, add_comm i, mod_add_cancel_right]
theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔
m % n = k % n :=
mod_add_cancel_right _
theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 :=
(mod_sub_cancel_right k).symm.trans $ by simp
@[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 :=
by rw [← zero_add (a * b), add_mul_mod_self, zero_mod]
@[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 :=
by rw [mul_comm, mul_mod_left]
@[simp] theorem mod_self {a : ℤ} : a % a = 0 :=
by have := mul_mod_left 1 a; rwa one_mul at this
@[simp] theorem mod_mod (a b : ℤ) : a % b % b = a % b :=
by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]}
@[simp] theorem mod_mod_of_dvd (n : int) {m k : int} (h : m ∣ k) : n % k % m = n % m :=
begin
conv { to_rhs, rw ←mod_add_div n k },
rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left]
end
/- properties of / and % -/
@[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c :=
suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from
match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with
| ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _
| ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ :=
by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg];
apply congr_arg has_neg.neg; apply this
end,
λ m k b, match b, k with
| (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos)
| -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero]
| -[1+ n], k+1 := congr_arg neg_succ_of_nat $
show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin
apply nat.div_eq_of_lt_le,
{ refine le_trans _ (nat.le_add_right _ _),
rw [← nat.mul_div_mul _ _ m.succ_pos],
apply nat.div_mul_le_self },
{ change m.succ * n.succ ≤ _,
rw [mul_left_comm],
apply nat.mul_le_mul_left,
apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1,
apply nat.lt_succ_self }
end
end
@[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : 0 < b) :
a * b / (c * b) = a / c :=
by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H]
@[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b % (a * c) = a * (b % c) :=
by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc]
theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : 0 < b) : a < (a / b + 1) * b :=
by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt;
rw [← mod_def]; apply mod_lt_of_pos _ H
theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a :=
suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from
λ a b, match b, eq_coe_or_neg b with
| ._, ⟨n, or.inl rfl⟩ := this _ _
| ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this
end,
λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact
coe_nat_le_coe_nat_of_le (match a, n with
| (m : ℕ), n := nat.div_le_self _ _
| -[1+ m], 0 := nat.zero_le _
| -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _)
end)
theorem div_le_self {a : ℤ} (b : ℤ) (Ha : 0 ≤ a) : a / b ≤ a :=
by have := le_trans (le_abs_self _) (abs_div_le_abs a b);
rwa [abs_of_nonneg Ha] at this
theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a :=
by have := mod_add_div a b; rwa [H, zero_add] at this
theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a :=
by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H]
lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 :=
have h : n % 2 < 2 := abs_of_nonneg (show 0 ≤ (2 : ℤ), from dec_trivial) ▸ int.mod_lt _ dec_trivial,
have h₁ : 0 ≤ n % 2 := int.mod_nonneg _ dec_trivial,
match (n % 2), h, h₁ with
| (0 : ℕ) := λ _ _, or.inl rfl
| (1 : ℕ) := λ _ _, or.inr rfl
| (k + 2 : ℕ) := λ h _, absurd h dec_trivial
| -[1+ a] := λ _ h₁, absurd h₁ dec_trivial
end
/- dvd -/
@[elim_cast] theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n :=
⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim
(λm0, by simp [m0] at ae; simp [ae, m0])
(λm0l, by {
cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a
(by simp [ae.symm]) (by simpa using m0l)) with k e,
subst a, exact ⟨k, int.coe_nat_inj ae⟩ }),
λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩
theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs :=
by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd]
theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n :=
by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd]
theorem dvd_antisymm {a b : ℤ} (H1 : 0 ≤ a) (H2 : 0 ≤ b) : a ∣ b → b ∣ a → a = b :=
begin
rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs],
rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'],
apply nat.dvd_antisymm
end
theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b :=
⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩
theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0
| a ._ ⟨c, rfl⟩ := mul_mod_right _ _
theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 :=
⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩
theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b :=
(nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e])
theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b :=
(nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e])
instance decidable_dvd : @decidable_rel ℤ (∣) :=
assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm
protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a :=
div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H)
protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b :=
by rw [mul_comm, int.div_mul_cancel H]
protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c)
| ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else
by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz]
theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a
| a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else
by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az];
apply dvd_mul_right
protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) :
a = b * c :=
by rw [← H2, int.mul_div_cancel' H1]
protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) :
a / b = c :=
by rw [H2, int.mul_div_cancel_left _ H1]
protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) :
a / b = c ↔ a = b * c :=
⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩
protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) :
a / b = c ↔ a = c * b :=
by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H'
protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) :
a = c * b :=
by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2]
protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) :
a / b = c :=
int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2])
theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b)
| ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else
by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz]
lemma add_div_of_dvd {a b c : ℤ} :
c ∣ a → c ∣ b → (a + b) / c = a / c + b / c :=
begin
intros h1 h2,
by_cases h3 : c = 0,
{ rw [h3, zero_dvd_iff] at *,
rw [h1, h2, h3], refl },
{ apply eq_of_mul_eq_mul_right h3,
rw add_mul, repeat {rw [int.div_mul_cancel]};
try {apply dvd_add}; assumption }
end
theorem div_sign : ∀ a b, a / sign b = a * sign b
| a (n+1:ℕ) := by unfold sign; simp
| a 0 := by simp [sign]
| a -[1+ n] := by simp [sign]
@[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b
| a 0 := by simp
| 0 b := by simp
| (m+1:ℕ) (n+1:ℕ) := rfl
| (m+1:ℕ) -[1+ n] := rfl
| -[1+ m] (n+1:ℕ) := rfl
| -[1+ m] -[1+ n] := rfl
protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) :=
if az : a = 0 then by simp [az] else
(int.div_eq_of_eq_mul_left (mt eq_zero_of_abs_eq_zero az)
(sign_mul_abs _).symm).symm
theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i
| (n+1:ℕ) := mul_one _
| 0 := mul_zero _
| -[1+ n] := mul_neg_one _
theorem le_of_dvd {a b : ℤ} (bpos : 0 < b) (H : a ∣ b) : a ≤ b :=
match a, b, eq_succ_of_zero_lt bpos, H with
| (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $
nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H
| -[1+ m], ._, ⟨n, rfl⟩, _ :=
le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _)
end
theorem eq_one_of_dvd_one {a : ℤ} (H : 0 ≤ a) (H' : a ∣ 1) : a = 1 :=
match a, eq_coe_of_zero_le H, H' with
| ._, ⟨n, rfl⟩, H' := congr_arg coe $
nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H'
end
theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : 0 ≤ a) (H' : a * b = 1) : a = 1 :=
eq_one_of_dvd_one H ⟨b, H'.symm⟩
theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : 0 ≤ b) (H' : a * b = 1) : b = 1 :=
eq_one_of_mul_eq_one_right H (by rw [mul_comm, H'])
lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z
| (int.of_nat _) haz := int.coe_nat_dvd.2 haz
| -[1+k] haz :=
begin
change ↑a ∣ -(k+1 : ℤ),
apply dvd_neg_of_dvd,
apply int.coe_nat_dvd.2,
exact haz
end
lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs
| (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz)
| -[1+k] haz :=
have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz,
int.coe_nat_dvd.1 haz'
lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) :
↑(p ^ m) ∣ k :=
begin
induction k,
{ apply int.coe_nat_dvd.2,
apply pow_dvd_of_le_of_pow_dvd hmn,
apply int.coe_nat_dvd.1 hdiv },
{ change -[1+k] with -(↑(k+1) : ℤ),
apply dvd_neg_of_dvd,
apply int.coe_nat_dvd.2,
apply pow_dvd_of_le_of_pow_dvd hmn,
apply int.coe_nat_dvd.1,
apply dvd_of_dvd_neg,
exact hdiv }
end
lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m :=
by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk
/- / and ordering -/
protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a :=
le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H
protected theorem div_le_of_le_mul {a b c : ℤ} (H : 0 < c) (H' : a ≤ b * c) : a / c ≤ b :=
le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H
protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : 0 < c) (H3 : a < b / c) : a * c < b :=
lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3)
protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : 0 < c) (H2 : a ≤ b / c) : a * c ≤ b :=
le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1))
protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : 0 < c) (H2 : a * c ≤ b) : a ≤ b / c :=
le_of_lt_add_one $ lt_of_mul_lt_mul_right
(lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1)
protected theorem le_div_iff_mul_le {a b c : ℤ} (H : 0 < c) : a ≤ b / c ↔ a * c ≤ b :=
⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩
protected theorem div_le_div {a b c : ℤ} (H : 0 < c) (H' : a ≤ b) : a / c ≤ b / c :=
int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H')
protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : 0 < c) (H' : a < b * c) : a / c < b :=
lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H')
protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : 0 < c) (H2 : a / c < b) : a < b * c :=
lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2)
protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : 0 < c) : a / c < b ↔ a < b * c :=
⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩
protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ a) (H3 : a / b ≤ c) :
a ≤ c * b :=
by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1
protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ c) (H3 : a * b < c) :
a < c / b :=
lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3)
protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : 0 < c) (H' : c ∣ b) :
a < b / c ↔ a * c < b :=
⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩
theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : 0 < a) (H2 : 0 ≤ b) (H3 : b ∣ a) : 0 < a / b :=
int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul)
theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H1 : b ∣ a) (H2 : d ∣ c) (H3 : b ≠ 0)
(H4 : d ≠ 0) (H5 : a * d = b * c) :
a / b = c / d :=
int.div_eq_of_eq_mul_right H3 $
by rw [← int.mul_div_assoc _ H2]; exact
(int.div_eq_of_eq_mul_left H4 H5.symm).symm
theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0) (hbc : b ∣ c)
(h : b * a = c * d) : a = c / b * d :=
begin
cases hbc with k hk,
subst hk,
rw int.mul_div_cancel_left, rw mul_assoc at h,
apply _root_.eq_of_mul_eq_mul_left _ h,
repeat {assumption}
end
theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ}
(h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] :=
begin
change sub_nat_nat _ _ = _,
have h' : n.succ - m = (n - m).succ,
apply succ_sub,
apply le_of_lt_succ h,
simp [*, sub_nat_nat]
end
theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ}
(h : n.succ ≤ m) : of_nat m + -[1+n] = of_nat (m - n.succ) :=
begin
change sub_nat_nat _ _ = _,
have h' : n.succ - m = 0,
apply sub_eq_zero_of_le h,
simp [*, sub_nat_nat]
end
@[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl
/- to_nat -/
theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0
| (n : ℕ) := (max_eq_left (coe_zero_le n)).symm
| -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm
@[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a :=
by rw [to_nat_eq_max, max_eq_left h]
@[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl
theorem le_to_nat (a : ℤ) : a ≤ to_nat a :=
by rw [to_nat_eq_max]; apply le_max_left
@[simp] theorem to_nat_le {a : ℤ} {n : ℕ} : to_nat a ≤ n ↔ a ≤ n :=
by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff];
exact and_iff_left (coe_zero_le _)
@[simp] theorem lt_to_nat {n : ℕ} {a : ℤ} : n < to_nat a ↔ (n : ℤ) < a :=
le_iff_le_iff_lt_iff_lt.1 to_nat_le
theorem to_nat_le_to_nat {a b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b :=
by rw to_nat_le; exact le_trans h (le_to_nat b)
theorem to_nat_lt_to_nat {a b : ℤ} (hb : 0 < b) : to_nat a < to_nat b ↔ a < b :=
⟨λ h, begin cases a, exact lt_to_nat.1 h, exact lt_trans (neg_succ_of_nat_lt_zero a) hb, end,
λ h, begin rw lt_to_nat, cases a, exact h, exact hb end⟩
theorem lt_of_to_nat_lt {a b : ℤ} (h : to_nat a < to_nat b) : a < b :=
(to_nat_lt_to_nat $ lt_to_nat.1 $ lt_of_le_of_lt (nat.zero_le _) h).1 h
def to_nat' : ℤ → option ℕ
| (n : ℕ) := some n
| -[1+ n] := none
theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n
| (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm
| -[1+ m] n := by split; intro h; cases h
/- units -/
@[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 :=
units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹,
by rw [← nat_abs_mul, units.mul_inv]; refl,
by rw [← nat_abs_mul, units.inv_mul]; refl⟩
theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 :=
by simpa [units.ext_iff, units_nat_abs] using nat_abs_eq u
lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u :=
(units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl)
/- bitwise ops -/
@[simp] lemma bodd_zero : bodd 0 = ff := rfl
@[simp] lemma bodd_one : bodd 1 = tt := rfl
@[simp] lemma bodd_two : bodd 2 = ff := rfl
@[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd :=
by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros;
simp [bodd, -of_nat_eq_coe]
@[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd :=
by cases n; simp; refl
@[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n :=
by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe]
@[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) :=
by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, bodd, -of_nat_eq_coe]
@[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n :=
by cases m with m m; cases n with n n; unfold has_mul.mul; simp [int.mul, bodd, -of_nat_eq_coe]
theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n
| (n : ℕ) :=
by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ),
by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2
| -[1+ n] := begin
refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2),
dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul],
{ change -[1+ 2 * nat.div2 n] = _, rw zero_add },
{ rw [zero_add, add_comm], refl }
end
theorem div2_val : ∀ n, div2 n = n / 2
| (n : ℕ) := congr_arg of_nat n.div2_val
| -[1+ n] := congr_arg neg_succ_of_nat n.div2_val
lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm
lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _)
lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 :=
by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val }
lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n :=
(bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _
def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n :=
by rw [← bit_decomp n]; apply h
@[simp] lemma bit_zero : bit ff 0 = 0 := rfl
@[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bodd_bit (b n) : bodd (bit b n) = b :=
by rw bit_val; simp; cases b; cases bodd n; refl
@[simp] lemma div2_bit (b n) : div2 (bit b n) = n :=
begin
rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add],
cases b, all_goals {exact dec_trivial}
end
@[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b
| (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero];
clear test_bit_zero; cases b; refl
@[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m
| (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ]
private meta def bitwise_tac : tactic unit := `[
funext m,
funext n,
cases m with m m; cases n with n n; try {refl},
all_goals {
apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat,
try {dsimp [nat.land, nat.ldiff, nat.lor]},
try {rw [
show nat.bitwise (λ a b, a && bnot b) n m =
nat.bitwise (λ a b, b && bnot a) m n, from
congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]},
apply congr_arg (λ f, nat.bitwise f m n),
funext a,
funext b,
cases a; cases b; refl
},
all_goals {unfold nat.land nat.ldiff nat.lor}
]
theorem bitwise_or : bitwise bor = lor := by bitwise_tac
theorem bitwise_and : bitwise band = land := by bitwise_tac
theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac
theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac
@[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) :
bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) :=
begin
cases m with m m; cases n with n n;
repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ };
unfold bitwise nat_bitwise bnot;
[ induction h : f ff ff,
induction h : f ff tt,
induction h : f tt ff,
induction h : f tt tt ],
all_goals {
unfold cond, rw nat.bitwise_bit,
repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } },
all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl }
end
@[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) :=
by rw [← bitwise_or, bitwise_bit]
@[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) :=
by rw [← bitwise_and, bitwise_bit]
@[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) :=
by rw [← bitwise_diff, bitwise_bit]
@[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) :=
by rw [← bitwise_xor, bitwise_bit]
@[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n)
| (n : ℕ) := by simp [lnot]
| -[1+ n] := by simp [lnot]
@[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) :
test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) :=
begin
induction k with k IH generalizing m n;
apply bit_cases_on m; intros a m';
apply bit_cases_on n; intros b n';
rw bitwise_bit,
{ simp [test_bit_zero] },
{ simp [test_bit_succ, IH] }
end
@[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k :=
by rw [← bitwise_or, test_bit_bitwise]
@[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k :=
by rw [← bitwise_and, test_bit_bitwise]
@[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) :=
by rw [← bitwise_diff, test_bit_bitwise]
@[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) :=
by rw [← bitwise_xor, test_bit_bitwise]
@[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k)
| (n : ℕ) k := by simp [lnot, test_bit]
| -[1+ n] k := by simp [lnot, test_bit]
lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k
| (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _)
| -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _)
| (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ
(λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k)
(λ i n, congr_arg coe $
by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right)
(λ i n, congr_arg coe $
by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl)
| -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ
(λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k])
(λ i n, congr_arg neg_succ_of_nat $
by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right)
(λ i n, congr_arg neg_succ_of_nat $
by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl)
lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k :=
shiftl_add _ _ _
@[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl
@[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg]
@[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl
@[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl
@[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl
@[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl
lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k
| (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat,
← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add]
| -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ,
← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add]
lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n)
| (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _)
| -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _)
lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n)
| (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _)
| -[1+ m] n := begin
rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl,
exact coe_nat_lt_coe_nat_of_lt (nat.pos_pow_of_pos _ dec_trivial)
end
lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) :=
congr_arg coe (nat.one_shiftl _)
@[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0
| (n : ℕ) := congr_arg coe (nat.zero_shiftl _)
| -[1+ n] := congr_arg coe (nat.zero_shiftr _)
@[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _
/- Least upper bound property for integers -/
theorem exists_least_of_bdd {P : ℤ → Prop} [HP : decidable_pred P]
(Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z)
(Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) :=
let ⟨b, Hb⟩ := Hbdd in
have EX : ∃ n : ℕ, P (b + n), from
let ⟨elt, Helt⟩ := Hinh in
match elt, le.dest (Hb _ Helt), Helt with
| ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩
end,
⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h,
match z, le.dest (Hb _ h), h with
| ._, ⟨n, rfl⟩, h := add_le_add_left
(int.coe_nat_le.2 $ nat.find_min' _ h) _
end⟩
theorem exists_greatest_of_bdd {P : ℤ → Prop} [HP : decidable_pred P]
(Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b)
(Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) :=
have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from
let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩,
have Hinh' : ∃ z : ℤ, P (-z), from
let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩,
let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in
⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩
/- cast (injection into groups with one) -/
@[simp] theorem nat_cast_eq_coe_nat : ∀ n,
@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n =
@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n
| 0 := rfl
| (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n)
section cast
variables {α : Type*}
section
variables [has_neg α] [has_zero α] [has_one α] [has_add α]
/-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/
protected def cast : ℤ → α
| (n : ℕ) := n
| -[1+ n] := -(n+1)
@[priority 10] instance cast_coe : has_coe ℤ α := ⟨int.cast⟩
@[simp, squash_cast] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl
@[simp] theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl
@[simp, squash_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl
@[simp] theorem cast_coe_nat' (n : ℕ) :
(@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n : α) = n :=
by simp
@[simp, move_cast] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl
end
@[simp, squash_cast] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one
@[simp, move_cast] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n :=
begin
unfold sub_nat_nat, cases e : n - m,
{ simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] },
{ rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e,
nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] },
end
@[simp, move_cast] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n
| 0 := neg_zero.symm
| (n+1) := rfl
@[simp, move_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n
| (m : ℕ) (n : ℕ) := nat.cast_add _ _
| (m : ℕ) -[1+ n] := cast_sub_nat_nat _ _
| -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $
show (n:α) = -(m+1) + n + (m+1),
by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm,
nat.cast_add, cast_succ, neg_add_cancel_left]
| -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1),
by rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add];
apply congr_arg (λ x:ℕ, -(x:α)); simp
@[simp, move_cast] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n
| (n : ℕ) := cast_neg_of_nat _
| -[1+ n] := (neg_neg _).symm
@[move_cast] theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n :=
by simp
@[simp] theorem cast_eq_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) = 0 ↔ n = 0 :=
⟨λ h, begin cases n,
{ exact congr_arg coe (nat.cast_eq_zero.1 h) },
{ rw [cast_neg_succ_of_nat, neg_eq_zero, ← cast_succ, nat.cast_eq_zero] at h,
contradiction }
end, λ h, by rw [h, cast_zero]⟩
@[simp, elim_cast] theorem cast_inj [add_group α] [has_one α] [char_zero α] {m n : ℤ} : (m : α) = n ↔ m = n :=
by rw [← sub_eq_zero, ← cast_sub, cast_eq_zero, sub_eq_zero]
theorem cast_injective [add_group α] [has_one α] [char_zero α] : function.injective (coe : ℤ → α)
| m n := cast_inj.1
@[simp] theorem cast_ne_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) ≠ 0 ↔ n ≠ 0 :=
not_congr cast_eq_zero
@[simp, move_cast] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n
| (m : ℕ) (n : ℕ) := nat.cast_mul _ _
| (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $
show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1),
by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg]
| -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $
show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n,
by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul]
| -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1),
by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg]
instance cast.is_ring_hom [ring α] :
is_ring_hom (int.cast : ℤ → α) :=
⟨cast_one, cast_mul, cast_add⟩
instance coe.is_ring_hom [ring α] : is_ring_hom (coe : ℤ → α) := cast.is_ring_hom
theorem mul_cast_comm [ring α] (a : α) (n : ℤ) : a * n = n * a :=
by cases n; simp [nat.mul_cast_comm, left_distrib, right_distrib, *]
@[simp, squash_cast, move_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n := by {unfold bit0, simp}
@[simp, squash_cast, move_cast] theorem coe_nat_bit1 (n : ℕ) : (↑(bit1 n) : ℤ) = bit1 ↑n := by {unfold bit1, unfold bit0, simp}
@[simp, squash_cast, move_cast] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _
@[simp, squash_cast, move_cast] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n :=
by rw [bit1, cast_add, cast_one, cast_bit0]; refl
lemma cast_two [ring α] : ((2 : ℤ) : α) = 2 := by simp
theorem cast_nonneg [linear_ordered_ring α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n
| (n : ℕ) := by simp
| -[1+ n] := by simpa [not_le_of_gt (neg_succ_lt_zero n)] using
show -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one
@[simp, elim_cast] theorem cast_le [linear_ordered_ring α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n :=
by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg]
@[simp, elim_cast] theorem cast_lt [linear_ordered_ring α] {m n : ℤ} : (m : α) < n ↔ m < n :=
by simpa [-cast_le] using not_congr (@cast_le α _ n m)
@[simp] theorem cast_nonpos [linear_ordered_ring α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 :=
by rw [← cast_zero, cast_le]
@[simp] theorem cast_pos [linear_ordered_ring α] {n : ℤ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_lt_zero [linear_ordered_ring α] {n : ℤ} : (n : α) < 0 ↔ n < 0 :=
by rw [← cast_zero, cast_lt]
theorem eq_cast [add_group α] [has_one α] (f : ℤ → α)
(H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (n : ℤ) : f n = n :=
begin
have H : ∀ (n : ℕ), f n = n :=
nat.eq_cast' (λ n, f n) H1 (λ x y, Hadd x y),
cases n, {apply H},
apply eq_neg_of_add_eq_zero,
rw [← nat.cast_zero, ← H 0, int.coe_nat_zero,
← show -[1+ n] + (↑n + 1) = 0, from neg_add_self (↑n+1),
Hadd, show f (n+1) = n+1, from H (n+1)]
end
lemma eq_cast' [ring α] (f : ℤ → α) [is_ring_hom f] : f = int.cast :=
funext $ int.eq_cast f (is_ring_hom.map_one f) (λ _ _, is_ring_hom.map_add f)
@[simp, squash_cast] theorem cast_id (n : ℤ) : ↑n = n :=
(eq_cast id rfl (λ _ _, rfl) n).symm
@[simp, move_cast] theorem cast_min [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b :=
by by_cases a ≤ b; simp [h, min]
@[simp, move_cast] theorem cast_max [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b :=
by by_cases a ≤ b; simp [h, max]
@[simp, move_cast] theorem cast_abs [decidable_linear_ordered_comm_ring α] {q : ℤ} : ((abs q : ℤ) : α) = abs q :=
by simp [abs]
end cast
section decidable
def range (m n : ℤ) : list ℤ :=
(list.range (to_nat (n-m))).map $ λ r, m+r
theorem mem_range_iff {m n r : ℤ} : r ∈ range m n ↔ m ≤ r ∧ r < n :=
⟨λ H, let ⟨s, h1, h2⟩ := list.mem_map.1 H in h2 ▸
⟨le_add_of_nonneg_right trivial,
add_lt_of_lt_sub_left $ match n-m, h1 with
| (k:ℕ), h1 := by rwa [list.mem_range, to_nat_coe_nat, ← coe_nat_lt] at h1
end⟩,
λ ⟨h1, h2⟩, list.mem_map.2 ⟨to_nat (r-m),
list.mem_range.2 $ by rw [← coe_nat_lt, to_nat_of_nonneg (sub_nonneg_of_le h1),
to_nat_of_nonneg (sub_nonneg_of_le (le_of_lt (lt_of_le_of_lt h1 h2)))];
exact sub_lt_sub_right h2 _,
show m + _ = _, by rw [to_nat_of_nonneg (sub_nonneg_of_le h1), add_sub_cancel'_right]⟩⟩
instance decidable_le_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r < n → P r) :=
decidable_of_iff (∀ r ∈ range m n, P r) $ by simp only [mem_range_iff, and_imp]
instance decidable_le_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r ≤ n → P r) :=
decidable_of_iff (∀ r ∈ range m (n+1), P r) $ by simp only [mem_range_iff, and_imp, lt_add_one_iff]
instance decidable_lt_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r < n → P r) :=
int.decidable_le_lt P _ _
instance decidable_lt_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r ≤ n → P r) :=
int.decidable_le_le P _ _
end decidable
end int
|
9c58560a617fd1b088072fa96341728293e1c1da | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/matrix/bilinear_form.lean | ea6878ba4f3d3f6ee5e489eff60deea10362822b | [
"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 | 22,779 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen, Kexing Ying
-/
import linear_algebra.matrix.basis
import linear_algebra.matrix.nondegenerate
import linear_algebra.matrix.nonsingular_inverse
import linear_algebra.matrix.to_linear_equiv
import linear_algebra.bilinear_form
import linear_algebra.matrix.sesquilinear_form
/-!
# Bilinear form
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the conversion between bilinear forms and matrices.
## Main definitions
* `matrix.to_bilin` given a basis define a bilinear form
* `matrix.to_bilin'` define the bilinear form on `n → R`
* `bilin_form.to_matrix`: calculate the matrix coefficients of a bilinear form
* `bilin_form.to_matrix'`: calculate the matrix coefficients of a bilinear form on `n → R`
## Notations
In this file we use the following type variables:
- `M`, `M'`, ... are modules over the semiring `R`,
- `M₁`, `M₁'`, ... are modules over the ring `R₁`,
- `M₂`, `M₂'`, ... are modules over the commutative semiring `R₂`,
- `M₃`, `M₃'`, ... are modules over the commutative ring `R₃`,
- `V`, ... is a vector space over the field `K`.
## Tags
bilinear_form, matrix, basis
-/
variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M]
variables {R₁ : Type*} {M₁ : Type*} [ring R₁] [add_comm_group M₁] [module R₁ M₁]
variables {R₂ : Type*} {M₂ : Type*} [comm_semiring R₂] [add_comm_monoid M₂] [module R₂ M₂]
variables {R₃ : Type*} {M₃ : Type*} [comm_ring R₃] [add_comm_group M₃] [module R₃ M₃]
variables {V : Type*} {K : Type*} [field K] [add_comm_group V] [module K V]
variables {B : bilin_form R M} {B₁ : bilin_form R₁ M₁} {B₂ : bilin_form R₂ M₂}
section matrix
variables {n o : Type*}
open_locale big_operators
open bilin_form finset linear_map matrix
open_locale matrix
/-- The map from `matrix n n R` to bilinear forms on `n → R`.
This is an auxiliary definition for the equivalence `matrix.to_bilin_form'`. -/
def matrix.to_bilin'_aux [fintype n] (M : matrix n n R₂) : bilin_form R₂ (n → R₂) :=
{ bilin := λ v w, ∑ i j, v i * M i j * w j,
bilin_add_left := λ x y z, by simp only [pi.add_apply, add_mul, sum_add_distrib],
bilin_smul_left := λ a x y, by simp only [pi.smul_apply, smul_eq_mul, mul_assoc, mul_sum],
bilin_add_right := λ x y z, by simp only [pi.add_apply, mul_add, sum_add_distrib],
bilin_smul_right := λ a x y,
by simp only [pi.smul_apply, smul_eq_mul, mul_assoc, mul_left_comm, mul_sum] }
lemma matrix.to_bilin'_aux_std_basis [fintype n] [decidable_eq n] (M : matrix n n R₂)
(i j : n) : M.to_bilin'_aux (std_basis R₂ (λ _, R₂) i 1) (std_basis R₂ (λ _, R₂) j 1) = M i j :=
begin
rw [matrix.to_bilin'_aux, coe_fn_mk, sum_eq_single i, sum_eq_single j],
{ simp only [std_basis_same, std_basis_same, one_mul, mul_one] },
{ rintros j' - hj',
apply mul_eq_zero_of_right,
exact std_basis_ne R₂ (λ _, R₂) _ _ hj' 1 },
{ intros,
have := finset.mem_univ j,
contradiction },
{ rintros i' - hi',
refine finset.sum_eq_zero (λ j _, _),
apply mul_eq_zero_of_left,
apply mul_eq_zero_of_left,
exact std_basis_ne R₂ (λ _, R₂) _ _ hi' 1 },
{ intros,
have := finset.mem_univ i,
contradiction }
end
/-- The linear map from bilinear forms to `matrix n n R` given an `n`-indexed basis.
This is an auxiliary definition for the equivalence `matrix.to_bilin_form'`. -/
def bilin_form.to_matrix_aux (b : n → M₂) : bilin_form R₂ M₂ →ₗ[R₂] matrix n n R₂ :=
{ to_fun := λ B, of $ λ i j, B (b i) (b j),
map_add' := λ f g, rfl,
map_smul' := λ f g, rfl }
@[simp] lemma bilin_form.to_matrix_aux_apply (B : bilin_form R₂ M₂) (b : n → M₂) (i j : n) :
bilin_form.to_matrix_aux b B i j = B (b i) (b j) := rfl
variables [fintype n] [fintype o]
lemma to_bilin'_aux_to_matrix_aux [decidable_eq n] (B₂ : bilin_form R₂ (n → R₂)) :
matrix.to_bilin'_aux (bilin_form.to_matrix_aux (λ j, std_basis R₂ (λ _, R₂) j 1) B₂) = B₂ :=
begin
refine ext_basis (pi.basis_fun R₂ n) (λ i j, _),
rw [pi.basis_fun_apply, pi.basis_fun_apply, matrix.to_bilin'_aux_std_basis,
bilin_form.to_matrix_aux_apply]
end
section to_matrix'
/-! ### `to_matrix'` section
This section deals with the conversion between matrices and bilinear forms on `n → R₂`.
-/
variables [decidable_eq n] [decidable_eq o]
/-- The linear equivalence between bilinear forms on `n → R` and `n × n` matrices -/
def bilin_form.to_matrix' : bilin_form R₂ (n → R₂) ≃ₗ[R₂] matrix n n R₂ :=
{ inv_fun := matrix.to_bilin'_aux,
left_inv := by convert to_bilin'_aux_to_matrix_aux,
right_inv := λ M,
by { ext i j, simp only [to_fun_eq_coe, bilin_form.to_matrix_aux_apply,
matrix.to_bilin'_aux_std_basis] },
..bilin_form.to_matrix_aux (λ j, std_basis R₂ (λ _, R₂) j 1) }
@[simp] lemma bilin_form.to_matrix_aux_std_basis (B : bilin_form R₂ (n → R₂)) :
bilin_form.to_matrix_aux (λ j, std_basis R₂ (λ _, R₂) j 1) B =
bilin_form.to_matrix' B :=
rfl
/-- The linear equivalence between `n × n` matrices and bilinear forms on `n → R` -/
def matrix.to_bilin' : matrix n n R₂ ≃ₗ[R₂] bilin_form R₂ (n → R₂) :=
bilin_form.to_matrix'.symm
@[simp] lemma matrix.to_bilin'_aux_eq (M : matrix n n R₂) :
matrix.to_bilin'_aux M = matrix.to_bilin' M :=
rfl
lemma matrix.to_bilin'_apply (M : matrix n n R₂) (x y : n → R₂) :
matrix.to_bilin' M x y = ∑ i j, x i * M i j * y j := rfl
lemma matrix.to_bilin'_apply' (M : matrix n n R₂) (v w : n → R₂) :
matrix.to_bilin' M v w = matrix.dot_product v (M.mul_vec w) :=
begin
simp_rw [matrix.to_bilin'_apply, matrix.dot_product,
matrix.mul_vec, matrix.dot_product],
refine finset.sum_congr rfl (λ _ _, _),
rw finset.mul_sum,
refine finset.sum_congr rfl (λ _ _, _),
rw ← mul_assoc,
end
@[simp] lemma matrix.to_bilin'_std_basis (M : matrix n n R₂) (i j : n) :
matrix.to_bilin' M (std_basis R₂ (λ _, R₂) i 1) (std_basis R₂ (λ _, R₂) j 1) =
M i j :=
matrix.to_bilin'_aux_std_basis M i j
@[simp] lemma bilin_form.to_matrix'_symm :
(bilin_form.to_matrix'.symm : matrix n n R₂ ≃ₗ[R₂] _) = matrix.to_bilin' :=
rfl
@[simp] lemma matrix.to_bilin'_symm :
(matrix.to_bilin'.symm : _ ≃ₗ[R₂] matrix n n R₂) = bilin_form.to_matrix' :=
bilin_form.to_matrix'.symm_symm
@[simp] lemma matrix.to_bilin'_to_matrix' (B : bilin_form R₂ (n → R₂)) :
matrix.to_bilin' (bilin_form.to_matrix' B) = B :=
matrix.to_bilin'.apply_symm_apply B
@[simp] lemma bilin_form.to_matrix'_to_bilin' (M : matrix n n R₂) :
bilin_form.to_matrix' (matrix.to_bilin' M) = M :=
bilin_form.to_matrix'.apply_symm_apply M
@[simp] lemma bilin_form.to_matrix'_apply (B : bilin_form R₂ (n → R₂)) (i j : n) :
bilin_form.to_matrix' B i j =
B (std_basis R₂ (λ _, R₂) i 1) (std_basis R₂ (λ _, R₂) j 1) :=
rfl
@[simp] lemma bilin_form.to_matrix'_comp (B : bilin_form R₂ (n → R₂))
(l r : (o → R₂) →ₗ[R₂] (n → R₂)) :
(B.comp l r).to_matrix' = l.to_matrix'ᵀ ⬝ B.to_matrix' ⬝ r.to_matrix' :=
begin
ext i j,
simp only [bilin_form.to_matrix'_apply, bilin_form.comp_apply, transpose_apply, matrix.mul_apply,
linear_map.to_matrix', linear_equiv.coe_mk, sum_mul],
rw sum_comm,
conv_lhs { rw ← bilin_form.sum_repr_mul_repr_mul (pi.basis_fun R₂ n) (l _) (r _) },
rw finsupp.sum_fintype,
{ apply sum_congr rfl,
rintros i' -,
rw finsupp.sum_fintype,
{ apply sum_congr rfl,
rintros j' -,
simp only [smul_eq_mul, pi.basis_fun_repr, mul_assoc, mul_comm, mul_left_comm,
pi.basis_fun_apply, of_apply] },
{ intros, simp only [zero_smul, smul_zero] } },
{ intros, simp only [zero_smul, finsupp.sum_zero] }
end
lemma bilin_form.to_matrix'_comp_left (B : bilin_form R₂ (n → R₂))
(f : (n → R₂) →ₗ[R₂] (n → R₂)) : (B.comp_left f).to_matrix' = f.to_matrix'ᵀ ⬝ B.to_matrix' :=
by simp only [bilin_form.comp_left, bilin_form.to_matrix'_comp, to_matrix'_id, matrix.mul_one]
lemma bilin_form.to_matrix'_comp_right (B : bilin_form R₂ (n → R₂))
(f : (n → R₂) →ₗ[R₂] (n → R₂)) : (B.comp_right f).to_matrix' = B.to_matrix' ⬝ f.to_matrix' :=
by simp only [bilin_form.comp_right, bilin_form.to_matrix'_comp, to_matrix'_id,
transpose_one, matrix.one_mul]
lemma bilin_form.mul_to_matrix'_mul (B : bilin_form R₂ (n → R₂))
(M : matrix o n R₂) (N : matrix n o R₂) :
M ⬝ B.to_matrix' ⬝ N = (B.comp Mᵀ.to_lin' N.to_lin').to_matrix' :=
by simp only [B.to_matrix'_comp, transpose_transpose, to_matrix'_to_lin']
lemma bilin_form.mul_to_matrix' (B : bilin_form R₂ (n → R₂)) (M : matrix n n R₂) :
M ⬝ B.to_matrix' = (B.comp_left Mᵀ.to_lin').to_matrix' :=
by simp only [B.to_matrix'_comp_left, transpose_transpose, to_matrix'_to_lin']
lemma bilin_form.to_matrix'_mul (B : bilin_form R₂ (n → R₂)) (M : matrix n n R₂) :
B.to_matrix' ⬝ M = (B.comp_right M.to_lin').to_matrix' :=
by simp only [B.to_matrix'_comp_right, to_matrix'_to_lin']
lemma matrix.to_bilin'_comp (M : matrix n n R₂) (P Q : matrix n o R₂) :
M.to_bilin'.comp P.to_lin' Q.to_lin' = (Pᵀ ⬝ M ⬝ Q).to_bilin' :=
bilin_form.to_matrix'.injective
(by simp only [bilin_form.to_matrix'_comp, bilin_form.to_matrix'_to_bilin', to_matrix'_to_lin'])
end to_matrix'
section to_matrix
/-! ### `to_matrix` section
This section deals with the conversion between matrices and bilinear forms on
a module with a fixed basis.
-/
variables [decidable_eq n] (b : basis n R₂ M₂)
/-- `bilin_form.to_matrix b` is the equivalence between `R`-bilinear forms on `M` and
`n`-by-`n` matrices with entries in `R`, if `b` is an `R`-basis for `M`. -/
noncomputable def bilin_form.to_matrix : bilin_form R₂ M₂ ≃ₗ[R₂] matrix n n R₂ :=
(bilin_form.congr b.equiv_fun).trans bilin_form.to_matrix'
/-- `bilin_form.to_matrix b` is the equivalence between `R`-bilinear forms on `M` and
`n`-by-`n` matrices with entries in `R`, if `b` is an `R`-basis for `M`. -/
noncomputable def matrix.to_bilin : matrix n n R₂ ≃ₗ[R₂] bilin_form R₂ M₂ :=
(bilin_form.to_matrix b).symm
@[simp] lemma bilin_form.to_matrix_apply (B : bilin_form R₂ M₂) (i j : n) :
bilin_form.to_matrix b B i j = B (b i) (b j) :=
by rw [bilin_form.to_matrix, linear_equiv.trans_apply, bilin_form.to_matrix'_apply, congr_apply,
b.equiv_fun_symm_std_basis, b.equiv_fun_symm_std_basis]
@[simp] lemma matrix.to_bilin_apply (M : matrix n n R₂) (x y : M₂) :
matrix.to_bilin b M x y = ∑ i j, b.repr x i * M i j * b.repr y j :=
begin
rw [matrix.to_bilin, bilin_form.to_matrix, linear_equiv.symm_trans_apply, ← matrix.to_bilin'],
simp only [congr_symm, congr_apply, linear_equiv.symm_symm, matrix.to_bilin'_apply,
basis.equiv_fun_apply]
end
-- Not a `simp` lemma since `bilin_form.to_matrix` needs an extra argument
lemma bilinear_form.to_matrix_aux_eq (B : bilin_form R₂ M₂) :
bilin_form.to_matrix_aux b B = bilin_form.to_matrix b B :=
ext (λ i j, by rw [bilin_form.to_matrix_apply, bilin_form.to_matrix_aux_apply])
@[simp] lemma bilin_form.to_matrix_symm :
(bilin_form.to_matrix b).symm = matrix.to_bilin b :=
rfl
@[simp] lemma matrix.to_bilin_symm :
(matrix.to_bilin b).symm = bilin_form.to_matrix b :=
(bilin_form.to_matrix b).symm_symm
lemma matrix.to_bilin_basis_fun :
matrix.to_bilin (pi.basis_fun R₂ n) = matrix.to_bilin' :=
by { ext M, simp only [matrix.to_bilin_apply, matrix.to_bilin'_apply, pi.basis_fun_repr] }
lemma bilin_form.to_matrix_basis_fun :
bilin_form.to_matrix (pi.basis_fun R₂ n) = bilin_form.to_matrix' :=
by { ext B, rw [bilin_form.to_matrix_apply, bilin_form.to_matrix'_apply,
pi.basis_fun_apply, pi.basis_fun_apply] }
@[simp] lemma matrix.to_bilin_to_matrix (B : bilin_form R₂ M₂) :
matrix.to_bilin b (bilin_form.to_matrix b B) = B :=
(matrix.to_bilin b).apply_symm_apply B
@[simp] lemma bilin_form.to_matrix_to_bilin (M : matrix n n R₂) :
bilin_form.to_matrix b (matrix.to_bilin b M) = M :=
(bilin_form.to_matrix b).apply_symm_apply M
variables {M₂' : Type*} [add_comm_monoid M₂'] [module R₂ M₂']
variables (c : basis o R₂ M₂')
variables [decidable_eq o]
-- Cannot be a `simp` lemma because `b` must be inferred.
lemma bilin_form.to_matrix_comp
(B : bilin_form R₂ M₂) (l r : M₂' →ₗ[R₂] M₂) :
bilin_form.to_matrix c (B.comp l r) =
(to_matrix c b l)ᵀ ⬝ bilin_form.to_matrix b B ⬝ to_matrix c b r :=
begin
ext i j,
simp only [bilin_form.to_matrix_apply, bilin_form.comp_apply, transpose_apply, matrix.mul_apply,
linear_map.to_matrix', linear_equiv.coe_mk, sum_mul],
rw sum_comm,
conv_lhs { rw ← bilin_form.sum_repr_mul_repr_mul b },
rw finsupp.sum_fintype,
{ apply sum_congr rfl,
rintros i' -,
rw finsupp.sum_fintype,
{ apply sum_congr rfl,
rintros j' -,
simp only [smul_eq_mul, linear_map.to_matrix_apply,
basis.equiv_fun_apply, mul_assoc, mul_comm, mul_left_comm] },
{ intros, simp only [zero_smul, smul_zero] } },
{ intros, simp only [zero_smul, finsupp.sum_zero] }
end
lemma bilin_form.to_matrix_comp_left (B : bilin_form R₂ M₂) (f : M₂ →ₗ[R₂] M₂) :
bilin_form.to_matrix b (B.comp_left f) = (to_matrix b b f)ᵀ ⬝ bilin_form.to_matrix b B :=
by simp only [comp_left, bilin_form.to_matrix_comp b b, to_matrix_id, matrix.mul_one]
lemma bilin_form.to_matrix_comp_right (B : bilin_form R₂ M₂) (f : M₂ →ₗ[R₂] M₂) :
bilin_form.to_matrix b (B.comp_right f) = bilin_form.to_matrix b B ⬝ (to_matrix b b f) :=
by simp only [bilin_form.comp_right, bilin_form.to_matrix_comp b b, to_matrix_id,
transpose_one, matrix.one_mul]
@[simp]
lemma bilin_form.to_matrix_mul_basis_to_matrix (c : basis o R₂ M₂) (B : bilin_form R₂ M₂) :
(b.to_matrix c)ᵀ ⬝ bilin_form.to_matrix b B ⬝ b.to_matrix c = bilin_form.to_matrix c B :=
by rw [← linear_map.to_matrix_id_eq_basis_to_matrix, ← bilin_form.to_matrix_comp,
bilin_form.comp_id_id]
lemma bilin_form.mul_to_matrix_mul (B : bilin_form R₂ M₂)
(M : matrix o n R₂) (N : matrix n o R₂) :
M ⬝ bilin_form.to_matrix b B ⬝ N =
bilin_form.to_matrix c (B.comp (to_lin c b Mᵀ) (to_lin c b N)) :=
by simp only [B.to_matrix_comp b c, to_matrix_to_lin, transpose_transpose]
lemma bilin_form.mul_to_matrix (B : bilin_form R₂ M₂) (M : matrix n n R₂) :
M ⬝ bilin_form.to_matrix b B =
bilin_form.to_matrix b (B.comp_left (to_lin b b Mᵀ)) :=
by rw [B.to_matrix_comp_left b, to_matrix_to_lin, transpose_transpose]
lemma bilin_form.to_matrix_mul (B : bilin_form R₂ M₂) (M : matrix n n R₂) :
bilin_form.to_matrix b B ⬝ M =
bilin_form.to_matrix b (B.comp_right (to_lin b b M)) :=
by rw [B.to_matrix_comp_right b, to_matrix_to_lin]
lemma matrix.to_bilin_comp (M : matrix n n R₂) (P Q : matrix n o R₂) :
(matrix.to_bilin b M).comp (to_lin c b P) (to_lin c b Q) = matrix.to_bilin c (Pᵀ ⬝ M ⬝ Q) :=
(bilin_form.to_matrix c).injective
(by simp only [bilin_form.to_matrix_comp b c, bilin_form.to_matrix_to_bilin, to_matrix_to_lin])
end to_matrix
end matrix
section matrix_adjoints
open_locale matrix
variables {n : Type*} [fintype n]
variables (b : basis n R₃ M₃)
variables (J J₃ A A' : matrix n n R₃)
@[simp] lemma is_adjoint_pair_to_bilin' [decidable_eq n] :
bilin_form.is_adjoint_pair (matrix.to_bilin' J) (matrix.to_bilin' J₃)
(matrix.to_lin' A) (matrix.to_lin' A') ↔
matrix.is_adjoint_pair J J₃ A A' :=
begin
rw bilin_form.is_adjoint_pair_iff_comp_left_eq_comp_right,
have h : ∀ (B B' : bilin_form R₃ (n → R₃)), B = B' ↔
(bilin_form.to_matrix' B) = (bilin_form.to_matrix' B'),
{ intros B B',
split; intros h,
{ rw h },
{ exact bilin_form.to_matrix'.injective h } },
rw [h, bilin_form.to_matrix'_comp_left, bilin_form.to_matrix'_comp_right,
linear_map.to_matrix'_to_lin', linear_map.to_matrix'_to_lin',
bilin_form.to_matrix'_to_bilin', bilin_form.to_matrix'_to_bilin'],
refl,
end
@[simp] lemma is_adjoint_pair_to_bilin [decidable_eq n] :
bilin_form.is_adjoint_pair (matrix.to_bilin b J) (matrix.to_bilin b J₃)
(matrix.to_lin b b A) (matrix.to_lin b b A') ↔
matrix.is_adjoint_pair J J₃ A A' :=
begin
rw bilin_form.is_adjoint_pair_iff_comp_left_eq_comp_right,
have h : ∀ (B B' : bilin_form R₃ M₃), B = B' ↔
(bilin_form.to_matrix b B) = (bilin_form.to_matrix b B'),
{ intros B B',
split; intros h,
{ rw h },
{ exact (bilin_form.to_matrix b).injective h } },
rw [h, bilin_form.to_matrix_comp_left, bilin_form.to_matrix_comp_right,
linear_map.to_matrix_to_lin, linear_map.to_matrix_to_lin,
bilin_form.to_matrix_to_bilin, bilin_form.to_matrix_to_bilin],
refl,
end
lemma matrix.is_adjoint_pair_equiv' [decidable_eq n] (P : matrix n n R₃) (h : is_unit P) :
(Pᵀ ⬝ J ⬝ P).is_adjoint_pair (Pᵀ ⬝ J ⬝ P) A A' ↔
J.is_adjoint_pair J (P ⬝ A ⬝ P⁻¹) (P ⬝ A' ⬝ P⁻¹) :=
have h' : is_unit P.det := P.is_unit_iff_is_unit_det.mp h,
begin
let u := P.nonsing_inv_unit h',
let v := Pᵀ.nonsing_inv_unit (P.is_unit_det_transpose h'),
let x := Aᵀ * Pᵀ * J,
let y := J * P * A',
suffices : x * ↑u = ↑v * y ↔ ↑v⁻¹ * x = y * ↑u⁻¹,
{ dunfold matrix.is_adjoint_pair,
repeat { rw matrix.transpose_mul, },
simp only [←matrix.mul_eq_mul, ←mul_assoc, P.transpose_nonsing_inv],
conv_lhs { to_rhs, rw [mul_assoc, mul_assoc], congr, skip, rw ←mul_assoc, },
conv_rhs { rw [mul_assoc, mul_assoc], conv { to_lhs, congr, skip, rw ←mul_assoc }, },
exact this, },
rw units.eq_mul_inv_iff_mul_eq, conv_rhs { rw mul_assoc, }, rw v.inv_mul_eq_iff_eq_mul,
end
variables [decidable_eq n]
/-- The submodule of pair-self-adjoint matrices with respect to bilinear forms corresponding to
given matrices `J`, `J₂`. -/
def pair_self_adjoint_matrices_submodule' : submodule R₃ (matrix n n R₃) :=
(bilin_form.is_pair_self_adjoint_submodule (matrix.to_bilin' J) (matrix.to_bilin' J₃)).map
((linear_map.to_matrix' : ((n → R₃) →ₗ[R₃] (n → R₃)) ≃ₗ[R₃] matrix n n R₃) :
((n → R₃) →ₗ[R₃] (n → R₃)) →ₗ[R₃] matrix n n R₃)
lemma mem_pair_self_adjoint_matrices_submodule' :
A ∈ (pair_self_adjoint_matrices_submodule J J₃) ↔ matrix.is_adjoint_pair J J₃ A A :=
by simp only [mem_pair_self_adjoint_matrices_submodule]
/-- The submodule of self-adjoint matrices with respect to the bilinear form corresponding to
the matrix `J`. -/
def self_adjoint_matrices_submodule' : submodule R₃ (matrix n n R₃) :=
pair_self_adjoint_matrices_submodule J J
lemma mem_self_adjoint_matrices_submodule' :
A ∈ self_adjoint_matrices_submodule J ↔ J.is_self_adjoint A :=
by simp only [mem_self_adjoint_matrices_submodule]
/-- The submodule of skew-adjoint matrices with respect to the bilinear form corresponding to
the matrix `J`. -/
def skew_adjoint_matrices_submodule' : submodule R₃ (matrix n n R₃) :=
pair_self_adjoint_matrices_submodule (-J) J
lemma mem_skew_adjoint_matrices_submodule' :
A ∈ skew_adjoint_matrices_submodule J ↔ J.is_skew_adjoint A :=
by simp only [mem_skew_adjoint_matrices_submodule]
end matrix_adjoints
namespace bilin_form
section det
open matrix
variables {A : Type*} [comm_ring A] [is_domain A] [module A M₃] (B₃ : bilin_form A M₃)
variables {ι : Type*} [decidable_eq ι] [fintype ι]
lemma _root_.matrix.nondegenerate_to_bilin'_iff_nondegenerate_to_bilin {M : matrix ι ι R₂}
(b : basis ι R₂ M₂) : M.to_bilin'.nondegenerate ↔ (matrix.to_bilin b M).nondegenerate :=
(nondegenerate_congr_iff b.equiv_fun.symm).symm
-- Lemmas transferring nondegeneracy between a matrix and its associated bilinear form
theorem _root_.matrix.nondegenerate.to_bilin' {M : matrix ι ι R₃} (h : M.nondegenerate) :
M.to_bilin'.nondegenerate :=
λ x hx, h.eq_zero_of_ortho $ λ y, by simpa only [to_bilin'_apply'] using hx y
@[simp] lemma _root_.matrix.nondegenerate_to_bilin'_iff {M : matrix ι ι R₃} :
M.to_bilin'.nondegenerate ↔ M.nondegenerate :=
⟨λ h v hv, h v $ λ w, (M.to_bilin'_apply' _ _).trans $ hv w, matrix.nondegenerate.to_bilin'⟩
theorem _root_.matrix.nondegenerate.to_bilin {M : matrix ι ι R₃} (h : M.nondegenerate)
(b : basis ι R₃ M₃) : (to_bilin b M).nondegenerate :=
(matrix.nondegenerate_to_bilin'_iff_nondegenerate_to_bilin b).mp h.to_bilin'
@[simp] lemma _root_.matrix.nondegenerate_to_bilin_iff {M : matrix ι ι R₃} (b : basis ι R₃ M₃) :
(to_bilin b M).nondegenerate ↔ M.nondegenerate :=
by rw [←matrix.nondegenerate_to_bilin'_iff_nondegenerate_to_bilin,
matrix.nondegenerate_to_bilin'_iff]
-- Lemmas transferring nondegeneracy between a bilinear form and its associated matrix
@[simp] theorem nondegenerate_to_matrix'_iff {B : bilin_form R₃ (ι → R₃)} :
B.to_matrix'.nondegenerate ↔ B.nondegenerate :=
matrix.nondegenerate_to_bilin'_iff.symm.trans $ (matrix.to_bilin'_to_matrix' B).symm ▸ iff.rfl
theorem nondegenerate.to_matrix' {B : bilin_form R₃ (ι → R₃)} (h : B.nondegenerate) :
B.to_matrix'.nondegenerate :=
nondegenerate_to_matrix'_iff.mpr h
@[simp] theorem nondegenerate_to_matrix_iff {B : bilin_form R₃ M₃} (b : basis ι R₃ M₃) :
(to_matrix b B).nondegenerate ↔ B.nondegenerate :=
(matrix.nondegenerate_to_bilin_iff b).symm.trans $ (matrix.to_bilin_to_matrix b B).symm ▸ iff.rfl
theorem nondegenerate.to_matrix {B : bilin_form R₃ M₃} (h : B.nondegenerate)
(b : basis ι R₃ M₃) : (to_matrix b B).nondegenerate :=
(nondegenerate_to_matrix_iff b).mpr h
-- Some shorthands for combining the above with `matrix.nondegenerate_of_det_ne_zero`
lemma nondegenerate_to_bilin'_iff_det_ne_zero {M : matrix ι ι A} :
M.to_bilin'.nondegenerate ↔ M.det ≠ 0 :=
by rw [matrix.nondegenerate_to_bilin'_iff, matrix.nondegenerate_iff_det_ne_zero]
theorem nondegenerate_to_bilin'_of_det_ne_zero' (M : matrix ι ι A) (h : M.det ≠ 0) :
M.to_bilin'.nondegenerate :=
nondegenerate_to_bilin'_iff_det_ne_zero.mpr h
lemma nondegenerate_iff_det_ne_zero {B : bilin_form A M₃}
(b : basis ι A M₃) : B.nondegenerate ↔ (to_matrix b B).det ≠ 0 :=
by rw [←matrix.nondegenerate_iff_det_ne_zero, nondegenerate_to_matrix_iff]
theorem nondegenerate_of_det_ne_zero (b : basis ι A M₃) (h : (to_matrix b B₃).det ≠ 0) :
B₃.nondegenerate :=
(nondegenerate_iff_det_ne_zero b).mpr h
end det
end bilin_form
|
9a514bb8b87e82bb38411a04631e2643b77c3ada | b7f22e51856f4989b970961f794f1c435f9b8f78 | /hott/types/pi.hlean | 9095e1d6cd95b0581059b0a541c692c3ae70832c | [
"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 | 14,316 | hlean | /-
Copyright (c) 2014-15 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Partially ported from Coq HoTT
Theorems about pi-types (dependent function spaces)
-/
import types.sigma arity cubical.square
open eq equiv is_equiv funext sigma unit bool is_trunc prod function sigma.ops
namespace pi
variables {A A' : Type} {B : A → Type} {B' : A' → Type} {C : Πa, B a → Type}
{D : Πa b, C a b → Type}
{a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {f g : Πa, B a}
/- Paths -/
/-
Paths [p : f ≈ g] in a function type [Πx:X, P x] are equivalent to functions taking values
in path types, [H : Πx:X, f x ≈ g x], or concisely, [H : f ~ g].
This equivalence, however, is just the combination of [apd10] and function extensionality
[funext], and as such, [eq_of_homotopy]
Now we show how these things compute.
-/
definition apd10_eq_of_homotopy (h : f ~ g) : apd10 (eq_of_homotopy h) ~ h :=
apd10 (right_inv apd10 h)
definition eq_of_homotopy_eta (p : f = g) : eq_of_homotopy (apd10 p) = p :=
left_inv apd10 p
definition eq_of_homotopy_idp (f : Πa, B a) : eq_of_homotopy (λx : A, refl (f x)) = refl f :=
!eq_of_homotopy_eta
/- homotopy.symm is an equivalence -/
definition is_equiv_homotopy_symm : is_equiv (homotopy.symm : f ~ g → g ~ f) :=
begin
fapply adjointify homotopy.symm homotopy.symm,
{ intro p, apply eq_of_homotopy, intro a,
unfold homotopy.symm, apply inv_inv },
{ intro p, apply eq_of_homotopy, intro a,
unfold homotopy.symm, apply inv_inv }
end
/-
The identification of the path space of a dependent function space,
up to equivalence, is of course just funext.
-/
definition eq_equiv_homotopy (f g : Πx, B x) : (f = g) ≃ (f ~ g) :=
equiv.mk apd10 _
definition pi_eq_equiv (f g : Πx, B x) : (f = g) ≃ (f ~ g) := !eq_equiv_homotopy
definition is_equiv_eq_of_homotopy (f g : Πx, B x)
: is_equiv (eq_of_homotopy : f ~ g → f = g) :=
_
definition homotopy_equiv_eq (f g : Πx, B x) : (f ~ g) ≃ (f = g) :=
equiv.mk eq_of_homotopy _
/- Transport -/
definition pi_transport (p : a = a') (f : Π(b : B a), C a b)
: (transport (λa, Π(b : B a), C a b) p f) ~ (λb, !tr_inv_tr ▸ (p ▸D (f (p⁻¹ ▸ b)))) :=
by induction p; reflexivity
/- A special case of [transport_pi] where the type [B] does not depend on [A],
and so it is just a fixed type [B]. -/
definition pi_transport_constant {C : A → A' → Type} (p : a = a') (f : Π(b : A'), C a b) (b : A')
: (transport _ p f) b = p ▸ (f b) :=
by induction p; reflexivity
/- Pathovers -/
definition pi_pathover {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'}
(r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[apd011 C p q] g b') : f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
apply eq_of_pathover_idp, apply r
end
definition pi_pathover_left {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'}
(r : Π(b : B a), f b =[apd011 C p !pathover_tr] g (p ▸ b)) : f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
apply eq_of_pathover_idp, apply r
end
definition pi_pathover_right {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'}
(r : Π(b' : B a'), f (p⁻¹ ▸ b') =[apd011 C p !tr_pathover] g b') : f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
apply eq_of_pathover_idp, apply r
end
definition pi_pathover_constant {C : A → A' → Type} {f : Π(b : A'), C a b}
{g : Π(b : A'), C a' b} {p : a = a'}
(r : Π(b : A'), f b =[p] g b) : f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
exact eq_of_pathover_idp (r b),
end
-- a version where C is uncurried, but where the conclusion of r is still a proper pathover
-- instead of a heterogenous equality
definition pi_pathover' {C : (Σa, B a) → Type} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩}
{p : a = a'} (r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[dpair_eq_dpair p q] g b')
: f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
apply (@eq_of_pathover_idp _ C), exact (r b b (pathover.idpatho b)),
end
definition pi_pathover_left' {C : (Σa, B a) → Type} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩}
{p : a = a'} (r : Π(b : B a), f b =[dpair_eq_dpair p !pathover_tr] g (p ▸ b))
: f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
apply eq_of_pathover_idp, esimp at r, exact !pathover_ap (r b)
end
definition pi_pathover_right' {C : (Σa, B a) → Type} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩}
{p : a = a'} (r : Π(b' : B a'), f (p⁻¹ ▸ b') =[dpair_eq_dpair p !tr_pathover] g b')
: f =[p] g :=
begin
cases p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
apply eq_of_pathover_idp, esimp at r, exact !pathover_ap (r b)
end
/- Maps on paths -/
/- The action of maps given by lambda. -/
definition ap_lambdaD {C : A' → Type} (p : a = a') (f : Πa b, C b) :
ap (λa b, f a b) p = eq_of_homotopy (λb, ap (λa, f a b) p) :=
begin
apply (eq.rec_on p),
apply inverse,
apply eq_of_homotopy_idp
end
/- Dependent paths -/
/- with more implicit arguments the conclusion of the following theorem is
(Π(b : B a), transportD B C p b (f b) = g (transport B p b)) ≃
(transport (λa, Π(b : B a), C a b) p f = g) -/
definition heq_piD (p : a = a') (f : Π(b : B a), C a b)
(g : Π(b' : B a'), C a' b') : (Π(b : B a), p ▸D (f b) = g (p ▸ b)) ≃ (p ▸ f = g) :=
eq.rec_on p (λg, !homotopy_equiv_eq) g
definition heq_pi {C : A → Type} (p : a = a') (f : Π(b : B a), C a)
(g : Π(b' : B a'), C a') : (Π(b : B a), p ▸ (f b) = g (p ▸ b)) ≃ (p ▸ f = g) :=
eq.rec_on p (λg, !homotopy_equiv_eq) g
section
open sigma sigma.ops
/- more implicit arguments:
(Π(b : B a), transport C (sigma_eq p idp) (f b) = g (p ▸ b)) ≃
(Π(b : B a), transportD B (λ(a : A) (b : B a), C ⟨a, b⟩) p b (f b) = g (transport B p b)) -/
definition heq_pi_sigma {C : (Σa, B a) → Type} (p : a = a')
(f : Π(b : B a), C ⟨a, b⟩) (g : Π(b' : B a'), C ⟨a', b'⟩) :
(Π(b : B a), (sigma_eq p !pathover_tr) ▸ (f b) = g (p ▸ b)) ≃
(Π(b : B a), p ▸D (f b) = g (p ▸ b)) :=
eq.rec_on p (λg, !equiv.rfl) g
end
/- Functorial action -/
variables (f0 : A' → A) (f1 : Π(a':A'), B (f0 a') → B' a')
/- The functoriality of [forall] is slightly subtle: it is contravariant in the domain type and covariant in the codomain, but the codomain is dependent on the domain. -/
definition pi_functor [unfold_full] : (Π(a:A), B a) → (Π(a':A'), B' a') :=
λg a', f1 a' (g (f0 a'))
definition pi_functor_left [unfold_full] (B : A → Type) : (Π(a:A), B a) → (Π(a':A'), B (f0 a')) :=
pi_functor f0 (λa, id)
definition pi_functor_right [unfold_full] {B' : A → Type} (f1 : Π(a:A), B a → B' a)
: (Π(a:A), B a) → (Π(a:A), B' a) :=
pi_functor id f1
definition ap_pi_functor {g g' : Π(a:A), B a} (h : g ~ g')
: ap (pi_functor f0 f1) (eq_of_homotopy h)
= eq_of_homotopy (λa':A', (ap (f1 a') (h (f0 a')))) :=
begin
apply (is_equiv_rect (@apd10 A B g g')), intro p, clear h,
cases p,
apply concat,
exact (ap (ap (pi_functor f0 f1)) (eq_of_homotopy_idp g)),
apply symm, apply eq_of_homotopy_idp
end
/- Equivalences -/
definition is_equiv_pi_functor [instance] [constructor] [H0 : is_equiv f0]
[H1 : Πa', is_equiv (f1 a')] : is_equiv (pi_functor f0 f1) :=
begin
apply (adjointify (pi_functor f0 f1) (pi_functor f0⁻¹
(λ(a : A) (b' : B' (f0⁻¹ a)), transport B (right_inv f0 a) ((f1 (f0⁻¹ a))⁻¹ b')))),
begin
intro h, apply eq_of_homotopy, intro a', esimp,
rewrite [adj f0 a',-tr_compose,fn_tr_eq_tr_fn _ f1,right_inv (f1 _)],
apply apdt
end,
begin
intro h, apply eq_of_homotopy, intro a, esimp,
rewrite [left_inv (f1 _)],
apply apdt
end
end
definition pi_equiv_pi_of_is_equiv [constructor] [H : is_equiv f0]
[H1 : Πa', is_equiv (f1 a')] : (Πa, B a) ≃ (Πa', B' a') :=
equiv.mk (pi_functor f0 f1) _
definition pi_equiv_pi [constructor] (f0 : A' ≃ A) (f1 : Πa', (B (to_fun f0 a') ≃ B' a'))
: (Πa, B a) ≃ (Πa', B' a') :=
pi_equiv_pi_of_is_equiv (to_fun f0) (λa', to_fun (f1 a'))
definition pi_equiv_pi_right [constructor] {P Q : A → Type} (g : Πa, P a ≃ Q a)
: (Πa, P a) ≃ (Πa, Q a) :=
pi_equiv_pi equiv.rfl g
/- Equivalence if one of the types is contractible -/
definition pi_equiv_of_is_contr_left [constructor] (B : A → Type) [H : is_contr A]
: (Πa, B a) ≃ B (center A) :=
begin
fapply equiv.MK,
{ intro f, exact f (center A)},
{ intro b a, exact center_eq a ▸ b},
{ intro b, rewrite [prop_eq_of_is_contr (center_eq (center A)) idp]},
{ intro f, apply eq_of_homotopy, intro a, induction (center_eq a),
rewrite [prop_eq_of_is_contr (center_eq (center A)) idp]}
end
definition pi_equiv_of_is_contr_right [constructor] [H : Πa, is_contr (B a)]
: (Πa, B a) ≃ unit :=
begin
fapply equiv.MK,
{ intro f, exact star},
{ intro u a, exact !center},
{ intro u, induction u, reflexivity},
{ intro f, apply eq_of_homotopy, intro a, apply is_prop.elim}
end
/- Interaction with other type constructors -/
-- most of these are in the file of the other type constructor
definition pi_empty_left [constructor] (B : empty → Type) : (Πx, B x) ≃ unit :=
begin
fapply equiv.MK,
{ intro f, exact star},
{ intro x y, contradiction},
{ intro x, induction x, reflexivity},
{ intro f, apply eq_of_homotopy, intro y, contradiction},
end
definition pi_unit_left [constructor] (B : unit → Type) : (Πx, B x) ≃ B star :=
!pi_equiv_of_is_contr_left
definition pi_bool_left [constructor] (B : bool → Type) : (Πx, B x) ≃ B ff × B tt :=
begin
fapply equiv.MK,
{ intro f, exact (f ff, f tt)},
{ intro x b, induction x, induction b: assumption},
{ intro x, induction x, reflexivity},
{ intro f, apply eq_of_homotopy, intro b, induction b: reflexivity},
end
/- Truncatedness: any dependent product of n-types is an n-type -/
theorem is_trunc_pi (B : A → Type) (n : trunc_index)
[H : ∀a, is_trunc n (B a)] : is_trunc n (Πa, B a) :=
begin
revert B H,
eapply (trunc_index.rec_on n),
{intro B H,
fapply is_contr.mk,
intro a, apply center,
intro f, apply eq_of_homotopy,
intro x, apply (center_eq (f x))},
{intro n IH B H,
fapply is_trunc_succ_intro, intro f g,
fapply is_trunc_equiv_closed,
apply equiv.symm, apply eq_equiv_homotopy,
apply IH,
intro a,
show is_trunc n (f a = g a), from
is_trunc_eq n (f a) (g a)}
end
local attribute is_trunc_pi [instance]
theorem is_trunc_pi_eq [instance] [priority 500] (n : trunc_index) (f g : Πa, B a)
[H : ∀a, is_trunc n (f a = g a)] : is_trunc n (f = g) :=
begin
apply is_trunc_equiv_closed_rev,
apply eq_equiv_homotopy
end
theorem is_trunc_not [instance] (n : trunc_index) (A : Type) : is_trunc (n.+1) ¬A :=
by unfold not;exact _
theorem is_prop_pi_eq [instance] [priority 490] (a : A) : is_prop (Π(a' : A), a = a') :=
is_prop_of_imp_is_contr
( assume (f : Πa', a = a'),
have is_contr A, from is_contr.mk a f,
by exact _) /- force type clas resolution -/
theorem is_prop_neg (A : Type) : is_prop (¬A) := _
local attribute ne [reducible]
theorem is_prop_ne [instance] {A : Type} (a b : A) : is_prop (a ≠ b) := _
/- Symmetry of Π -/
definition is_equiv_flip [instance] {P : A → A' → Type}
: is_equiv (@function.flip A A' P) :=
begin
fapply is_equiv.mk,
exact (@function.flip _ _ (function.flip P)),
repeat (intro f; apply idp)
end
definition pi_comm_equiv {P : A → A' → Type} : (Πa b, P a b) ≃ (Πb a, P a b) :=
equiv.mk (@function.flip _ _ P) _
/- Dependent functions are equivalent to nondependent functions into the total space together
with a homotopy -/
definition pi_equiv_arrow_sigma_right [constructor] {A : Type} {B : A → Type} (f : Πa, B a) :
Σ(f : A → Σa, B a), pr1 ∘ f ~ id :=
⟨λa, ⟨a, f a⟩, λa, idp⟩
definition pi_equiv_arrow_sigma_left.{u v} [unfold 3] {A : Type.{u}} {B : A → Type.{v}}
(v : Σ(f : A → Σa, B a), pr1 ∘ f ~ id) (a : A) : B a :=
transport B (v.2 a) (v.1 a).2
open funext
definition pi_equiv_arrow_sigma [constructor] {A : Type} (B : A → Type) :
(Πa, B a) ≃ Σ(f : A → Σa, B a), pr1 ∘ f ~ id :=
begin
fapply equiv.MK,
{ exact pi_equiv_arrow_sigma_right},
{ exact pi_equiv_arrow_sigma_left},
{ intro v, induction v with f p, fapply sigma_eq: esimp,
{ apply eq_of_homotopy, intro a, fapply sigma_eq: esimp,
{ exact (p a)⁻¹},
{ apply inverseo, apply pathover_tr}},
{ apply pi_pathover_constant, intro a, apply eq_pathover_constant_right,
refine ap_compose (λf, f a) _ _ ⬝ph _,
refine ap02 _ !compose_eq_of_homotopy ⬝ph _,
refine !ap_eq_apd10 ⬝ph _,
refine apd10 (right_inv apd10 _) a ⬝ph _,
esimp, refine !sigma_eq_pr1 ⬝ph _, apply square_of_eq, exact !con.left_inv⁻¹}},
{ intro a, reflexivity}
end
end pi
attribute pi.is_trunc_pi [instance] [priority 1520]
namespace pi
/- pointed pi types -/
open pointed
definition pointed_pi [instance] [constructor] {A : Type} (P : A → Type) [H : Πx, pointed (P x)]
: pointed (Πx, P x) :=
pointed.mk (λx, pt)
definition ppi [constructor] {A : Type} (P : A → Type*) : Type* :=
pointed.mk' (Πa, P a)
notation `Π*` binders `, ` r:(scoped P, ppi P) := r
definition ptpi [constructor] {n : ℕ₋₂} {A : Type} (P : A → n-Type*) : n-Type* :=
ptrunctype.mk' n (Πa, P a)
end pi
|
db06f3c154d2d46795bc9e407337385a940b59c0 | fffbc47930dc6615e66ece42324ce57a21d5b64b | /src/topology/algebra/monoid.lean | 8f8bae5503c33f832479f76c303dd12ce5e42e56 | [
"Apache-2.0"
] | permissive | skbaek/mathlib | 3caae8ae413c66862293a95fd2fbada3647b1228 | f25340175631cdc85ad768a262433f968d0d6450 | refs/heads/master | 1,588,130,123,636 | 1,558,287,609,000 | 1,558,287,609,000 | 160,935,713 | 0 | 0 | Apache-2.0 | 1,544,271,146,000 | 1,544,271,146,000 | null | UTF-8 | Lean | false | false | 5,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, Mario Carneiro
Theory of topological monoids.
TODO: generalize `topological_monoid` and `topological_add_monoid` to semigroups, or add a type class
`topological_operator α (*)`.
-/
import topology.constructions
import algebra.pi_instances
open classical set lattice filter topological_space
local attribute [instance] classical.prop_decidable
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
section topological_monoid
/-- A topological monoid is a monoid in which the multiplication is continuous as a function
`α × α → α`. -/
class topological_monoid (α : Type u) [topological_space α] [monoid α] : Prop :=
(continuous_mul : continuous (λp:α×α, p.1 * p.2))
/-- A topological (additive) monoid is a monoid in which the addition is
continuous as a function `α × α → α`. -/
class topological_add_monoid (α : Type u) [topological_space α] [add_monoid α] : Prop :=
(continuous_add : continuous (λp:α×α, p.1 + p.2))
attribute [to_additive topological_add_monoid] topological_monoid
attribute [to_additive topological_add_monoid.mk] topological_monoid.mk
attribute [to_additive topological_add_monoid.continuous_add] topological_monoid.continuous_mul
section
variables [topological_space α] [monoid α] [topological_monoid α]
@[to_additive continuous_add']
lemma continuous_mul' : continuous (λp:α×α, p.1 * p.2) :=
topological_monoid.continuous_mul α
@[to_additive continuous_add]
lemma continuous_mul [topological_space β] {f : β → α} {g : β → α}
(hf : continuous f) (hg : continuous g) :
continuous (λx, f x * g x) :=
continuous_mul'.comp (hf.prod_mk hg)
-- @[to_additive continuous_smul]
lemma continuous_pow : ∀ n : ℕ, continuous (λ a : α, a ^ n)
| 0 := by simpa using continuous_const
| (k+1) := show continuous (λ (a : α), a * a ^ k), from continuous_mul continuous_id (continuous_pow _)
@[to_additive tendsto_add']
lemma tendsto_mul' {a b : α} : tendsto (λp:α×α, p.fst * p.snd) (nhds (a, b)) (nhds (a * b)) :=
continuous_iff_continuous_at.mp (topological_monoid.continuous_mul α) (a, b)
@[to_additive tendsto_add]
lemma tendsto_mul {f : β → α} {g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) :
tendsto (λx, f x * g x) x (nhds (a * b)) :=
tendsto.comp (by rw [←nhds_prod_eq]; exact tendsto_mul') (hf.prod_mk hg)
@[to_additive tendsto_list_sum]
lemma tendsto_list_prod {f : γ → β → α} {x : filter β} {a : γ → α} :
∀l:list γ, (∀c∈l, tendsto (f c) x (nhds (a c))) →
tendsto (λb, (l.map (λc, f c b)).prod) x (nhds ((l.map a).prod))
| [] _ := by simp [tendsto_const_nhds]
| (f :: l) h :=
begin
simp,
exact tendsto_mul
(h f (list.mem_cons_self _ _))
(tendsto_list_prod l (assume c hc, h c (list.mem_cons_of_mem _ hc)))
end
@[to_additive continuous_list_sum]
lemma continuous_list_prod [topological_space β] {f : γ → β → α} (l : list γ)
(h : ∀c∈l, continuous (f c)) :
continuous (λa, (l.map (λc, f c a)).prod) :=
continuous_iff_continuous_at.2 $ assume x, tendsto_list_prod l $ assume c hc,
continuous_iff_continuous_at.1 (h c hc) x
@[to_additive prod.topological_add_monoid]
instance [topological_space β] [monoid β] [topological_monoid β] : topological_monoid (α × β) :=
⟨continuous.prod_mk
(continuous_mul (continuous_fst.comp continuous_fst) (continuous_fst.comp continuous_snd))
(continuous_mul (continuous_snd.comp continuous_fst) (continuous_snd.comp continuous_snd)) ⟩
attribute [instance] prod.topological_add_monoid
end
section
variables [topological_space α] [comm_monoid α] [topological_monoid α]
@[to_additive tendsto_multiset_sum]
lemma tendsto_multiset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : multiset γ) :
(∀c∈s, tendsto (f c) x (nhds (a c))) →
tendsto (λb, (s.map (λc, f c b)).prod) x (nhds ((s.map a).prod)) :=
by { rcases s with ⟨l⟩, simp, exact tendsto_list_prod l }
@[to_additive tendsto_finset_sum]
lemma tendsto_finset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : finset γ) :
(∀c∈s, tendsto (f c) x (nhds (a c))) → tendsto (λb, s.prod (λc, f c b)) x (nhds (s.prod a)) :=
tendsto_multiset_prod _
@[to_additive continuous_multiset_sum]
lemma continuous_multiset_prod [topological_space β] {f : γ → β → α} (s : multiset γ) :
(∀c∈s, continuous (f c)) → continuous (λa, (s.map (λc, f c a)).prod) :=
by { rcases s with ⟨l⟩, simp, exact continuous_list_prod l }
@[to_additive continuous_finset_sum]
lemma continuous_finset_prod [topological_space β] {f : γ → β → α} (s : finset γ) :
(∀c∈s, continuous (f c)) → continuous (λa, s.prod (λc, f c a)) :=
continuous_multiset_prod _
@[to_additive is_add_submonoid.mem_nhds_zero]
lemma is_submonoid.mem_nhds_one (β : set α) [is_submonoid β] (oβ : is_open β) :
β ∈ nhds (1 : α) :=
mem_nhds_sets_iff.2 ⟨β, (by refl), oβ, is_submonoid.one_mem _⟩
end
end topological_monoid
|
d9968ba540dbdad7f7579a8df312053fea42845c | 4727251e0cd73359b15b664c3170e5d754078599 | /src/linear_algebra/direct_sum/tensor_product.lean | 384cd8fc38511b3884c6071c3621b9b4c7258d8d | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 2,183 | 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
-/
import linear_algebra.tensor_product
import algebra.direct_sum.module
/-!
# Tensor products of direct sums
This file shows that taking `tensor_product`s commutes with taking `direct_sum`s in both arguments.
-/
section ring
namespace tensor_product
open_locale tensor_product
open_locale direct_sum
open linear_map
local attribute [ext] tensor_product.ext
variables (R : Type*) [comm_ring R]
variables (ι₁ : Type*) (ι₂ : Type*)
variables [decidable_eq ι₁] [decidable_eq ι₂]
variables (M₁ : ι₁ → Type*) (M₂ : ι₂ → Type*)
variables [Π i₁, add_comm_group (M₁ i₁)] [Π i₂, add_comm_group (M₂ i₂)]
variables [Π i₁, module R (M₁ i₁)] [Π i₂, module R (M₂ i₂)]
/-- The linear equivalence `(⨁ i₁, M₁ i₁) ⊗ (⨁ i₂, M₂ i₂) ≃ (⨁ i₁, ⨁ i₂, M₁ i₁ ⊗ M₂ i₂)`, i.e.
"tensor product distributes over direct sum". -/
def direct_sum :
(⨁ i₁, M₁ i₁) ⊗[R] (⨁ i₂, M₂ i₂) ≃ₗ[R] (⨁ (i : ι₁ × ι₂), M₁ i.1 ⊗[R] M₂ i.2) :=
begin
refine linear_equiv.of_linear
(lift $ direct_sum.to_module R _ _ $ λ i₁, flip $ direct_sum.to_module R _ _ $ λ i₂,
flip $ curry $ direct_sum.lof R (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) (i₁, i₂))
(direct_sum.to_module R _ _ $ λ i, map (direct_sum.lof R _ _ _) (direct_sum.lof R _ _ _))
_ _; [ext ⟨i₁, i₂⟩ x₁ x₂ : 4, ext i₁ i₂ x₁ x₂ : 5],
repeat { rw compr₂_apply <|> rw comp_apply <|> rw id_apply <|> rw mk_apply <|>
rw direct_sum.to_module_lof <|> rw map_tmul <|> rw lift.tmul <|> rw flip_apply <|>
rw curry_apply },
end
@[simp] theorem direct_sum_lof_tmul_lof (i₁ : ι₁) (m₁ : M₁ i₁) (i₂ : ι₂) (m₂ : M₂ i₂) :
direct_sum R ι₁ ι₂ M₁ M₂ (direct_sum.lof R ι₁ M₁ i₁ m₁ ⊗ₜ direct_sum.lof R ι₂ M₂ i₂ m₂) =
direct_sum.lof R (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) (i₁, i₂) (m₁ ⊗ₜ m₂) :=
by simp [direct_sum]
end tensor_product
end ring
|
6b21c43deaa044adffd884d8f7b2a889ddc1e2e4 | 92b50235facfbc08dfe7f334827d47281471333b | /hott/arity.hlean | f4be844c9bbb123803661cd0fd6ab042810cda37 | [
"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,918 | hlean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Theorems about functions with multiple arguments
-/
variables {A U V W X Y Z : Type} {B : A → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type}
{E : Πa b c, D a b c → Type} {F : Πa b c d, E a b c d → Type}
{G : Πa b c d e, F a b c d e → Type} {H : Πa b c d e f, G a b c d e f → Type}
variables {a a' : A} {u u' : U} {v v' : V} {w w' : W} {x x' x'' : X} {y y' : Y} {z z' : Z}
{b : B a} {b' : B a'}
{c : C a b} {c' : C a' b'}
{d : D a b c} {d' : D a' b' c'}
{e : E a b c d} {e' : E a' b' c' d'}
{ff : F a b c d e} {f' : F a' b' c' d' e'}
{g : G a b c d e ff} {g' : G a' b' c' d' e' f'}
{h : H a b c d e ff g} {h' : H a' b' c' d' e' f' g'}
namespace eq
/-
Naming convention:
The theorem which states how to construct an path between two function applications is
api₀i₁...iₙ.
Here i₀, ... iₙ are digits, n is the arity of the function(s),
and iⱼ specifies the dimension of the path between the jᵗʰ argument
(i₀ specifies the dimension of the path between the functions).
A value iⱼ ≡ 0 means that the jᵗʰ arguments are definitionally equal
The functions are non-dependent, except when the theorem name contains trailing zeroes
(where the function is dependent only in the arguments where it doesn't result in any
transports in the theorem statement).
For the fully-dependent versions (except that the conclusion doesn't contain a transport)
we write
apdi₀i₁...iₙ.
For versions where only some arguments depend on some other arguments,
or for versions with transport in the conclusion (like apd), we don't have a
consistent naming scheme (yet).
We don't prove each theorem systematically, but prove only the ones which we actually need.
-/
definition homotopy2 [reducible] (f g : Πa b, C a b) : Type :=
Πa b, f a b = g a b
definition homotopy3 [reducible] (f g : Πa b c, D a b c) : Type :=
Πa b c, f a b c = g a b c
definition homotopy4 [reducible] (f g : Πa b c d, E a b c d) : Type :=
Πa b c d, f a b c d = g a b c d
notation f `~2`:50 g := homotopy2 f g
notation f `~3`:50 g := homotopy3 f g
definition ap011 (f : U → V → W) (Hu : u = u') (Hv : v = v') : f u v = f u' v' :=
by cases Hu; congruence; repeat assumption
definition ap0111 (f : U → V → W → X) (Hu : u = u') (Hv : v = v') (Hw : w = w')
: f u v w = f u' v' w' :=
by cases Hu; congruence; repeat assumption
definition ap01111 (f : U → V → W → X → Y) (Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x')
: f u v w x = f u' v' w' x' :=
by cases Hu; congruence; repeat assumption
definition ap011111 (f : U → V → W → X → Y → Z)
(Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') (Hy : y = y')
: f u v w x y = f u' v' w' x' y' :=
by cases Hu; congruence; repeat assumption
definition ap0111111 (f : U → V → W → X → Y → Z → A)
(Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') (Hy : y = y') (Hz : z = z')
: f u v w x y z = f u' v' w' x' y' z' :=
by cases Hu; congruence; repeat assumption
definition ap010 (f : X → Πa, B a) (Hx : x = x') : f x ~ f x' :=
by intros; cases Hx; reflexivity
definition ap0100 (f : X → Πa b, C a b) (Hx : x = x') : f x ~2 f x' :=
by intros; cases Hx; reflexivity
definition ap01000 (f : X → Πa b c, D a b c) (Hx : x = x') : f x ~3 f x' :=
by intros; cases Hx; reflexivity
definition apd011 (f : Πa, B a → Z) (Ha : a = a') (Hb : transport B Ha b = b')
: f a b = f a' b' :=
by cases Ha; cases Hb; reflexivity
definition apd0111 (f : Πa b, C a b → Z) (Ha : a = a') (Hb : transport B Ha b = b')
(Hc : cast (apd011 C Ha Hb) c = c')
: f a b c = f a' b' c' :=
by cases Ha; cases Hb; cases Hc; reflexivity
definition apd01111 (f : Πa b c, D a b c → Z) (Ha : a = a') (Hb : transport B Ha b = b')
(Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d')
: f a b c d = f a' b' c' d' :=
by cases Ha; cases Hb; cases Hc; cases Hd; reflexivity
definition apd011111 (f : Πa b c d, E a b c d → Z) (Ha : a = a') (Hb : transport B Ha b = b')
(Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d')
(He : cast (apd01111 E Ha Hb Hc Hd) e = e')
: f a b c d e = f a' b' c' d' e' :=
by cases Ha; cases Hb; cases Hc; cases Hd; cases He; reflexivity
definition apd0111111 (f : Πa b c d e, F a b c d e → Z) (Ha : a = a') (Hb : transport B Ha b = b')
(Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d')
(He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f')
: f a b c d e ff = f a' b' c' d' e' f' :=
begin cases Ha, cases Hb, cases Hc, cases Hd, cases He, cases Hf, reflexivity end
-- definition apd0111111 (f : Πa b c d e ff, G a b c d e ff → Z) (Ha : a = a') (Hb : transport B Ha b = b')
-- (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d')
-- (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f')
-- (Hg : cast (apd0111111 G Ha Hb Hc Hd He Hf) g = g')
-- : f a b c d e ff g = f a' b' c' d' e' f' g' :=
-- by cases Ha; cases Hb; cases Hc; cases Hd; cases He; cases Hf; cases Hg; reflexivity
-- definition apd01111111 (f : Πa b c d e ff g, G a b c d e ff g → Z) (Ha : a = a') (Hb : transport B Ha b = b')
-- (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d')
-- (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f')
-- (Hg : cast (apd0111111 G Ha Hb Hc Hd He Hf) g = g') (Hh : cast (apd01111111 H Ha Hb Hc Hd He Hf Hg) h = h')
-- : f a b c d e ff g h = f a' b' c' d' e' f' g' h' :=
-- by cases Ha; cases Hb; cases Hc; cases Hd; cases He; cases Hf; cases Hg; cases Hh; reflexivity
definition apd100 [unfold 6] {f g : Πa b, C a b} (p : f = g) : f ~2 g :=
λa b, apd10 (apd10 p a) b
definition apd1000 [unfold 7] {f g : Πa b c, D a b c} (p : f = g) : f ~3 g :=
λa b c, apd100 (apd10 p a) b c
/- some properties of these variants of ap -/
-- we only prove what we currently need
definition ap010_con (f : X → Πa, B a) (p : x = x') (q : x' = x'') :
ap010 f (p ⬝ q) a = ap010 f p a ⬝ ap010 f q a :=
eq.rec_on q (eq.rec_on p idp)
definition ap010_ap (f : X → Πa, B a) (g : Y → X) (p : y = y') :
ap010 f (ap g p) a = ap010 (λy, f (g y)) p a :=
eq.rec_on p idp
/- the following theorems are function extentionality for functions with multiple arguments -/
definition eq_of_homotopy2 {f g : Πa b, C a b} (H : f ~2 g) : f = g :=
eq_of_homotopy (λa, eq_of_homotopy (H a))
definition eq_of_homotopy3 {f g : Πa b c, D a b c} (H : f ~3 g) : f = g :=
eq_of_homotopy (λa, eq_of_homotopy2 (H a))
definition eq_of_homotopy2_id (f : Πa b, C a b)
: eq_of_homotopy2 (λa b, idpath (f a b)) = idpath f :=
begin
transitivity eq_of_homotopy (λ a, idpath (f a)),
{apply (ap eq_of_homotopy), apply eq_of_homotopy, intros, apply eq_of_homotopy_idp},
apply eq_of_homotopy_idp
end
definition eq_of_homotopy3_id (f : Πa b c, D a b c)
: eq_of_homotopy3 (λa b c, idpath (f a b c)) = idpath f :=
begin
transitivity _,
{apply (ap eq_of_homotopy), apply eq_of_homotopy, intros, apply eq_of_homotopy2_id},
apply eq_of_homotopy_idp
end
definition eq_of_homotopy2_inv {f g : Πa b, C a b} (H : f ~2 g)
: eq_of_homotopy2 (λa b, (H a b)⁻¹) = (eq_of_homotopy2 H)⁻¹ :=
ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy_inv)) ⬝ !eq_of_homotopy_inv
definition eq_of_homotopy3_inv {f g : Πa b c, D a b c} (H : f ~3 g)
: eq_of_homotopy3 (λa b c, (H a b c)⁻¹) = (eq_of_homotopy3 H)⁻¹ :=
ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy2_inv)) ⬝ !eq_of_homotopy_inv
definition eq_of_homotopy2_con {f g h : Πa b, C a b} (H1 : f ~2 g) (H2 : g ~2 h)
: eq_of_homotopy2 (λa b, H1 a b ⬝ H2 a b) = eq_of_homotopy2 H1 ⬝ eq_of_homotopy2 H2 :=
ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy_con)) ⬝ !eq_of_homotopy_con
definition eq_of_homotopy3_con {f g h : Πa b c, D a b c} (H1 : f ~3 g) (H2 : g ~3 h)
: eq_of_homotopy3 (λa b c, H1 a b c ⬝ H2 a b c) = eq_of_homotopy3 H1 ⬝ eq_of_homotopy3 H2 :=
ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy2_con)) ⬝ !eq_of_homotopy_con
end eq
open eq is_equiv
namespace funext
definition is_equiv_apd100 [instance] (f g : Πa b, C a b) : is_equiv (@apd100 A B C f g) :=
adjointify _
eq_of_homotopy2
begin
intro H, esimp [apd100, eq_of_homotopy2, function.compose],
apply eq_of_homotopy, intro a,
apply concat, apply (ap (λx, apd10 (x a))), apply (right_inv apd10),
apply (right_inv apd10)
end
begin
intro p, cases p, apply eq_of_homotopy2_id
end
definition is_equiv_apd1000 [instance] (f g : Πa b c, D a b c)
: is_equiv (@apd1000 A B C D f g) :=
adjointify _
eq_of_homotopy3
begin
intro H, esimp,
apply eq_of_homotopy, intro a,
transitivity apd100 (eq_of_homotopy2 (H a)),
{apply ap (λx, apd100 (x a)),
apply right_inv apd10},
apply right_inv apd100
end
begin
intro p, cases p, apply eq_of_homotopy3_id
end
end funext
namespace eq
open funext
local attribute funext.is_equiv_apd100 [instance]
protected definition homotopy2.rec_on {f g : Πa b, C a b} {P : (f ~2 g) → Type}
(p : f ~2 g) (H : Π(q : f = g), P (apd100 q)) : P p :=
right_inv apd100 p ▸ H (eq_of_homotopy2 p)
protected definition homotopy3.rec_on {f g : Πa b c, D a b c} {P : (f ~3 g) → Type}
(p : f ~3 g) (H : Π(q : f = g), P (apd1000 q)) : P p :=
right_inv apd1000 p ▸ H (eq_of_homotopy3 p)
definition apd10_ap (f : X → Πa, B a) (p : x = x')
: apd10 (ap f p) = ap010 f p :=
eq.rec_on p idp
definition eq_of_homotopy_ap010 (f : X → Πa, B a) (p : x = x')
: eq_of_homotopy (ap010 f p) = ap f p :=
inv_eq_of_eq !apd10_ap⁻¹
definition ap_eq_ap_of_homotopy {f : X → Πa, B a} {p q : x = x'} (H : ap010 f p ~ ap010 f q)
: ap f p = ap f q :=
calc
ap f p = eq_of_homotopy (ap010 f p) : eq_of_homotopy_ap010
... = eq_of_homotopy (ap010 f q) : eq_of_homotopy H
... = ap f q : eq_of_homotopy_ap010
end eq
|
8c9e71cc76220fee3fc65665faa61a3334c3f3c4 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/algebraic_geometry/presheafed_space/has_colimits.lean | 6bc6c28c403272a603048f2de543ee541e218de8 | [
"Apache-2.0"
] | permissive | mcncm/mathlib | 8d25099344d9d2bee62822cb9ed43aa3e09fa05e | fde3d78cadeec5ef827b16ae55664ef115e66f57 | refs/heads/master | 1,672,743,316,277 | 1,602,618,514,000 | 1,602,618,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,841 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebraic_geometry.presheafed_space
import topology.category.Top.limits
import topology.sheaves.limits
import category_theory.limits.concrete_category
/-!
# `PresheafedSpace C` has colimits.
If `C` has limits, then the category `PresheafedSpace C` has colimits,
and the forgetful functor to `Top` preserves these colimits.
When restricted to a diagram where the underlying continuous maps are open embeddings,
this says that we can glue presheaved spaces.
Given a diagram `F : J ⥤ PresheafedSpace C`,
we first build the colimit of the underlying topological spaces,
as `colimit (F ⋙ PresheafedSpace.forget C)`. Call that colimit space `X`.
Our strategy is to push each of the presheaves `F.obj j`
forward along the continuous map `colimit.ι (F ⋙ PresheafedSpace.forget C) j` to `X`.
Since pushforward is functorial, we obtain a diagram `J ⥤ (presheaf C X)ᵒᵖ`
of presheaves on a single space `X`.
(Note that the arrows now point the other direction,
because this is the way `PresheafedSpace C` is set up.)
The limit of this diagram then constitutes the colimit presheaf.
-/
noncomputable theory
universes v u
open category_theory
open Top
open Top.presheaf
open topological_space
open opposite
open category_theory.category
open category_theory.limits
open category_theory.functor
variables {J : Type v} [small_category J]
variables {C : Type u} [category.{v} C]
namespace algebraic_geometry
namespace PresheafedSpace
@[simp]
lemma map_id_c_app (F : J ⥤ PresheafedSpace C) (j) (U) :
(F.map (𝟙 j)).c.app (op U) =
(pushforward.id (F.obj j).presheaf).inv.app (op U) ≫
(pushforward_eq (by { simp, refl }) (F.obj j).presheaf).hom.app (op U) :=
begin
cases U,
dsimp,
simp [PresheafedSpace.congr_app (F.map_id j)],
refl,
end
@[simp]
lemma map_comp_c_app (F : J ⥤ PresheafedSpace C) {j₁ j₂ j₃} (f : j₁ ⟶ j₂) (g : j₂ ⟶ j₃) (U) :
(F.map (f ≫ g)).c.app (op U) =
(F.map g).c.app (op U) ≫
(pushforward_map (F.map g).base (F.map f).c).app (op U) ≫
(pushforward.comp (F.obj j₁).presheaf (F.map f).base (F.map g).base).inv.app (op U) ≫
(pushforward_eq (by { rw F.map_comp, refl }) _).hom.app _ :=
begin
cases U,
dsimp,
simp only [PresheafedSpace.congr_app (F.map_comp f g)],
dsimp, simp,
end
/--
Given a diagram of presheafed spaces,
we can push all the presheaves forward to the colimit `X` of the underlying topological spaces,
obtaining a diagram in `(presheaf C X)ᵒᵖ`.
-/
@[simps]
def pushforward_diagram_to_colimit (F : J ⥤ PresheafedSpace C) :
J ⥤ (presheaf C (colimit (F ⋙ PresheafedSpace.forget C)))ᵒᵖ :=
{ obj := λ j, op ((colimit.ι (F ⋙ PresheafedSpace.forget C) j) _* (F.obj j).presheaf),
map := λ j j' f,
(pushforward_map (colimit.ι (F ⋙ PresheafedSpace.forget C) j') (F.map f).c ≫
(pushforward.comp (F.obj j).presheaf ((F ⋙ PresheafedSpace.forget C).map f)
(colimit.ι (F ⋙ PresheafedSpace.forget C) j')).inv ≫
(pushforward_eq (colimit.w (F ⋙ PresheafedSpace.forget C) f) (F.obj j).presheaf).hom).op,
map_id' := λ j,
begin
apply (op_equiv _ _).injective,
ext U,
op_induction U,
cases U,
dsimp, simp, dsimp, simp,
end,
map_comp' := λ j₁ j₂ j₃ f g,
begin
apply (op_equiv _ _).injective,
ext U,
dsimp,
simp only [map_comp_c_app, id.def, eq_to_hom_op, pushforward_map_app, eq_to_hom_map, assoc,
id_comp, pushforward.comp_inv_app, pushforward_eq_hom_app],
dsimp,
simp only [eq_to_hom_trans, id_comp],
congr' 1,
-- The key fact is `(F.map f).c.congr`,
-- which allows us in rewrite in the argument of `(F.map f).c.app`.
rw (F.map f).c.congr,
-- Now we pick up the pieces. First, we say what we want to replace that open set by:
swap 3,
refine op ((opens.map (colimit.ι (F ⋙ PresheafedSpace.forget C) j₂)).obj (unop U)),
-- Now we show the open sets are equal.
swap 2,
{ apply unop_injective,
rw ←opens.map_comp_obj,
congr,
exact colimit.w (F ⋙ PresheafedSpace.forget C) g, },
-- Finally, the original goal is now easy:
swap 2,
{ simp, refl, },
end, }
variables [has_limits C]
/--
Auxilliary definition for `PresheafedSpace.has_colimits`.
-/
@[simps]
def colimit (F : J ⥤ PresheafedSpace C) : PresheafedSpace C :=
{ carrier := colimit (F ⋙ PresheafedSpace.forget C),
presheaf := limit (pushforward_diagram_to_colimit F).left_op, }
/--
Auxilliary definition for `PresheafedSpace.has_colimits`.
-/
@[simps]
def colimit_cocone (F : J ⥤ PresheafedSpace C) : cocone F :=
{ X := colimit F,
ι :=
{ app := λ j,
{ base := colimit.ι (F ⋙ PresheafedSpace.forget C) j,
c := limit.π _ (op j), },
naturality' := λ j j' f,
begin
fapply PresheafedSpace.ext,
{ ext x,
exact colimit.w_apply (F ⋙ PresheafedSpace.forget C) f x, },
{ ext U,
op_induction U,
cases U,
dsimp,
simp only [PresheafedSpace.id_c_app, eq_to_hom_op, eq_to_hom_map, assoc,
pushforward.comp_inv_app],
rw ← congr_arg nat_trans.app (limit.w (pushforward_diagram_to_colimit F).left_op f.op),
dsimp,
simp only [eq_to_hom_op, eq_to_hom_map, assoc, id_comp, pushforward.comp_inv_app],
congr,
dsimp,
simp only [id_comp],
rw ←is_iso.inv_comp_eq,
simp, refl, }
end, }, }
namespace colimit_cocone_is_colimit
/--
Auxilliary definition for `PresheafedSpace.colimit_cocone_is_colimit`.
-/
def desc_c_app (F : J ⥤ PresheafedSpace C) (s : cocone F) (U : (opens ↥(s.X.carrier))ᵒᵖ) :
s.X.presheaf.obj U ⟶
(colimit.desc (F ⋙ PresheafedSpace.forget C)
((PresheafedSpace.forget C).map_cocone s) _*
limit (pushforward_diagram_to_colimit F).left_op).obj
U :=
begin
refine
limit.lift _ { X := s.X.presheaf.obj U, π := { app := λ j, _, naturality' := λ j j' f, _, }} ≫
(limit_obj_iso_limit_comp_evaluation _ _).inv,
-- We still need to construct the `app` and `naturality'` fields omitted above.
{ refine (s.ι.app (unop j)).c.app U ≫ (F.obj (unop j)).presheaf.map (eq_to_hom _),
dsimp,
rw ←opens.map_comp_obj,
simp, },
{ rw (PresheafedSpace.congr_app (s.w f.unop).symm U),
dsimp,
have w := functor.congr_obj (congr_arg opens.map
(colimit.ι_desc ((PresheafedSpace.forget C).map_cocone s) (unop j))) (unop U),
simp only [opens.map_comp_obj_unop] at w,
replace w := congr_arg op w,
have w' := nat_trans.congr (F.map f.unop).c w,
rw w',
dsimp, simp, dsimp, simp, refl, },
end
lemma desc_c_naturality (F : J ⥤ PresheafedSpace C) (s : cocone F)
{U V : (opens ↥(s.X.carrier))ᵒᵖ} (i : U ⟶ V) :
s.X.presheaf.map i ≫ desc_c_app F s V =
desc_c_app F s U ≫
(colimit.desc (F ⋙ forget C) ((forget C).map_cocone s) _* (colimit_cocone F).X.presheaf).map i :=
begin
dsimp [desc_c_app],
ext,
simp only [limit.lift_π, nat_trans.naturality, limit.lift_π_assoc, eq_to_hom_map, assoc,
pushforward_obj_map, nat_trans.naturality_assoc, op_map,
limit_obj_iso_limit_comp_evaluation_inv_π_app_assoc,
limit_obj_iso_limit_comp_evaluation_inv_π_app],
dsimp,
have w := functor.congr_hom (congr_arg opens.map
(colimit.ι_desc ((PresheafedSpace.forget C).map_cocone s) (unop j))) (i.unop),
simp only [opens.map_comp_map] at w,
replace w := congr_arg has_hom.hom.op w,
rw w,
dsimp, simp,
end
end colimit_cocone_is_colimit
open colimit_cocone_is_colimit
/--
Auxilliary definition for `PresheafedSpace.has_colimits`.
-/
def colimit_cocone_is_colimit (F : J ⥤ PresheafedSpace C) : is_colimit (colimit_cocone F) :=
{ desc := λ s,
{ base := colimit.desc (F ⋙ PresheafedSpace.forget C) ((PresheafedSpace.forget C).map_cocone s),
c :=
{ app := λ U, desc_c_app F s U,
naturality' := λ U V i, desc_c_naturality F s i }, },
uniq' := λ s m w,
begin
-- We need to use the identity on the continuous maps twice, so we prepare that first:
have t : m.base = colimit.desc (F ⋙ PresheafedSpace.forget C) ((PresheafedSpace.forget C).map_cocone s),
{ ext,
dsimp,
simp only [colimit.ι_desc_apply, map_cocone_ι],
rw ← w j,
simp, },
fapply PresheafedSpace.ext, -- could `ext` please not reorder goals?
{ exact t, },
{ ext U j, dsimp [desc_c_app],
simp only [limit.lift_π, eq_to_hom_op, eq_to_hom_map, assoc,
limit_obj_iso_limit_comp_evaluation_inv_π_app],
rw PresheafedSpace.congr_app (w (unop j)).symm U,
dsimp,
have w := congr_arg op (functor.congr_obj (congr_arg opens.map t) (unop U)),
rw nat_trans.congr (limit.π (pushforward_diagram_to_colimit F).left_op j) w,
simp, dsimp, simp, }
end, }
/--
When `C` has limits, the category of presheaved spaces with values in `C` itself has colimits.
-/
instance : has_colimits (PresheafedSpace C) :=
{ has_colimits_of_shape := λ J 𝒥, by exactI
{ has_colimit := λ F, has_colimit.mk
{ cocone := colimit_cocone F,
is_colimit := colimit_cocone_is_colimit F } } }
/--
The underlying topological space of a colimit of presheaved spaces is
the colimit of the underlying topological spaces.
-/
instance forget_preserves_colimits : preserves_colimits (PresheafedSpace.forget C) :=
{ preserves_colimits_of_shape := λ J 𝒥, by exactI
{ preserves_colimit := λ F, preserves_colimit_of_preserves_colimit_cocone
(colimit_cocone_is_colimit F)
begin
apply is_colimit.of_iso_colimit (colimit.is_colimit _),
fapply cocones.ext,
{ refl, },
{ intro j, dsimp, simp, }
end } }
end PresheafedSpace
end algebraic_geometry
|
258ba75502a85e750b449a8e9263f8f056c87435 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /02_Dependent_Type_Theory.org.25.lean | a1c653cea04a7d1b91f3b4694d91abeedb5125a4 | [] | 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 | 247 | lean | /- page 23 -/
import standard
section useful
variables (A B C : Type)
variables (g : B → C) (f : A → B) (h : A → A)
variable x : A
definition compose := g (f x)
definition do_twice := h (h x)
definition do_thrice := h (h (h x))
end useful
|
0409378ba7b5777a311ff0e4693a4827a486e345 | fe84e287c662151bb313504482b218a503b972f3 | /src/exercises/loh/binomial_solution.lean | 8035eb44761999645ce6ff03d119a76a1d758bbb | [] | no_license | NeilStrickland/lean_lib | 91e163f514b829c42fe75636407138b5c75cba83 | 6a9563de93748ace509d9db4302db6cd77d8f92c | refs/heads/master | 1,653,408,198,261 | 1,652,996,419,000 | 1,652,996,419,000 | 181,006,067 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 525 | lean | import tactic
lemma binomial_solution (x : ℤ) : x ^ 2 - 2 * x + 1 = 0 ↔ x = 1 :=
begin
split; intro h,
{ have : (x - 1) ^ 2 = x ^ 2 - 2 * x + 1 := by {
rw[pow_two, pow_two, two_mul, mul_sub, mul_one, sub_mul, one_mul],
rw[← sub_add, sub_add_eq_sub_sub]
},
rw[← this] at h,
exact sub_eq_zero.mp (pow_eq_zero h)
},
{ rw[h], refl }
end
lemma binomial_solution' (x : ℤ) : x ^ 2 - 2 * x + 1 = 0 ↔ x = 1 :=
by { split; intro h, nlinarith, simp[h], refl }
#print binomial_solution
|
f3ae2897665d2ef7a2afbd8fe278efe44c1ec5a2 | e9dbaaae490bc072444e3021634bf73664003760 | /src/Background/Array.lean | 93899468a5cb05d04ac51900684053a1294735fc | [
"Apache-2.0"
] | permissive | liaofei1128/geometry | 566d8bfe095ce0c0113d36df90635306c60e975b | 3dd128e4eec8008764bb94e18b932f9ffd66e6b3 | refs/heads/master | 1,678,996,510,399 | 1,581,454,543,000 | 1,583,337,839,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 162 | lean | import Geo.Background.List
namespace Array
universe u
variable {α : Type u}
def allP (xs : Array α) (p : α → Prop) : Prop :=
xs.toList.allP p
end Array
|
f2ed583a4df1e14603ccc4eb1b56bd7d34e55617 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/rewrite_search/types_auto.lean | ca717d7fd18453162788c563efb7bc9c6fd1ff3f | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,620 | lean | /-
Copyright (c) 2020 Kevin Lacker, Keeley Hoek, Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Lacker, Keeley Hoek, Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.nth_rewrite.default
import Mathlib.PostPort
universes l
namespace Mathlib
/-!
# Types used in rewrite search.
-/
namespace tactic.rewrite_search
/--
`side` represents the side of an equation, either the left or the right.
-/
inductive side where
| L : side
| R : side
/-- Convert a side to a human-readable string. -/
/-- Convert a side to the string "lhs" or "rhs", for use in tactic name generation. -/
def side.to_xhs : side → string := sorry
/--
A `how` contains information needed by the explainer to generate code for a rewrite.
`rule_index` denotes which rule in the static list of rules is used.
`location` describes which match of that rule was used, to work with `nth_rewrite`.
`addr` is a list of "left" and "right" describing which subexpression is rewritten.
-/
/-- Convert a `how` to a human-readable string. -/
/-- `rewrite` represents a single step of rewriting, that proves `exp` using `proof`. -/
/--
`proof_unit` represents a sequence of steps that can be applied to one side of the
equation to prove a particular expression.
-/
/--
Configuration options for a rewrite search.
`max_iterations` controls how many vertices are expanded in the graph search.
`explain` generates Lean code to replace the call to `rewrite_search`.
`explain_using_conv` changes the nature of the explanation.
-/
end Mathlib |
9e9046984270c868c64d7afc081d7324fcae2f98 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebraic_geometry/gluing.lean | 18c770363b79aa6d549cda08e446b59401cbf93f | [
"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 | 17,355 | 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 algebraic_geometry.presheafed_space.gluing
/-!
# Gluing Schemes
Given a family of gluing data of schemes, we may glue them together.
## Main definitions
* `algebraic_geometry.Scheme.glue_data`: A structure containing the family of gluing data.
* `algebraic_geometry.Scheme.glue_data.glued`: The glued scheme.
This is defined as the multicoequalizer of `∐ V i j ⇉ ∐ U i`, so that the general colimit API
can be used.
* `algebraic_geometry.Scheme.glue_data.ι`: The immersion `ι i : U i ⟶ glued` for each `i : J`.
* `algebraic_geometry.Scheme.glue_data.iso_carrier`: The isomorphism between the underlying space
of the glued scheme and the gluing of the underlying topological spaces.
* `algebraic_geometry.Scheme.open_cover.glue_data`: The glue data associated with an open cover.
* `algebraic_geometry.Scheme.open_cover.from_glue_data`: The canonical morphism
`𝒰.glue_data.glued ⟶ X`. This has an `is_iso` instance.
* `algebraic_geometry.Scheme.open_cover.glue_morphisms`: We may glue a family of compatible
morphisms defined on an open cover of a scheme.
## Main results
* `algebraic_geometry.Scheme.glue_data.ι_is_open_immersion`: The map `ι i : U i ⟶ glued`
is an open immersion for each `i : J`.
* `algebraic_geometry.Scheme.glue_data.ι_jointly_surjective` : The underlying maps of
`ι i : U i ⟶ glued` are jointly surjective.
* `algebraic_geometry.Scheme.glue_data.V_pullback_cone_is_limit` : `V i j` is the pullback
(intersection) of `U i` and `U j` over the glued space.
* `algebraic_geometry.Scheme.glue_data.ι_eq_iff_rel` : `ι i x = ι j y` if and only if they coincide
when restricted to `V i i`.
* `algebraic_geometry.Scheme.glue_data.is_open_iff` : An subset of the glued scheme is open iff
all its preimages in `U i` are open.
## Implementation details
All the hard work is done in `algebraic_geometry/presheafed_space/gluing.lean` where we glue
presheafed spaces, sheafed spaces, and locally ringed spaces.
-/
noncomputable theory
universe u
open topological_space category_theory opposite
open category_theory.limits algebraic_geometry.PresheafedSpace
open category_theory.glue_data
namespace algebraic_geometry
namespace Scheme
/--
A family of gluing data consists of
1. An index type `J`
2. An scheme `U i` for each `i : J`.
3. An scheme `V i j` for each `i j : J`.
(Note that this is `J × J → Scheme` rather than `J → J → Scheme` to connect to the
limits library easier.)
4. An open immersion `f i j : V i j ⟶ U i` for each `i j : ι`.
5. A transition map `t i j : V i j ⟶ V j i` for each `i j : ι`.
such that
6. `f i i` is an isomorphism.
7. `t i i` is the identity.
8. `V i j ×[U i] V i k ⟶ V i j ⟶ V j i` factors through `V j k ×[U j] V j i ⟶ V j i` via some
`t' : V i j ×[U i] V i k ⟶ V j k ×[U j] V j i`.
9. `t' i j k ≫ t' j k i ≫ t' k i j = 𝟙 _`.
We can then glue the schemes `U i` together by identifying `V i j` with `V j i`, such
that the `U i`'s are open subschemes of the glued space.
-/
@[nolint has_nonempty_instance]
structure glue_data extends category_theory.glue_data Scheme :=
(f_open : ∀ i j, is_open_immersion (f i j))
attribute [instance] glue_data.f_open
namespace glue_data
variables (D : glue_data)
include D
local notation `𝖣` := D.to_glue_data
/-- The glue data of locally ringed spaces spaces associated to a family of glue data of schemes. -/
abbreviation to_LocallyRingedSpace_glue_data : LocallyRingedSpace.glue_data :=
{ f_open := D.f_open,
to_glue_data := 𝖣 .map_glue_data forget_to_LocallyRingedSpace }
/-- (Implementation). The glued scheme of a glue data.
This should not be used outside this file. Use `Scheme.glue_data.glued` instead. -/
def glued_Scheme : Scheme :=
begin
apply LocallyRingedSpace.is_open_immersion.Scheme
D.to_LocallyRingedSpace_glue_data.to_glue_data.glued,
intro x,
obtain ⟨i, y, rfl⟩ := D.to_LocallyRingedSpace_glue_data.ι_jointly_surjective x,
refine ⟨_, _ ≫ D.to_LocallyRingedSpace_glue_data.to_glue_data.ι i, _⟩,
swap, exact (D.U i).affine_cover.map y,
split,
{ dsimp [-set.mem_range],
rw [coe_comp, set.range_comp],
refine set.mem_image_of_mem _ _,
exact (D.U i).affine_cover.covers y },
{ apply_instance },
end
instance : creates_colimit 𝖣 .diagram.multispan forget_to_LocallyRingedSpace :=
creates_colimit_of_fully_faithful_of_iso D.glued_Scheme
(has_colimit.iso_of_nat_iso (𝖣 .diagram_iso forget_to_LocallyRingedSpace).symm)
instance : preserves_colimit 𝖣 .diagram.multispan forget_to_Top :=
begin
delta forget_to_Top LocallyRingedSpace.forget_to_Top,
apply_instance,
end
instance : has_multicoequalizer 𝖣 .diagram :=
has_colimit_of_created _ forget_to_LocallyRingedSpace
/-- The glued scheme of a glued space. -/
abbreviation glued : Scheme := 𝖣 .glued
/-- The immersion from `D.U i` into the glued space. -/
abbreviation ι (i : D.J) : D.U i ⟶ D.glued := 𝖣 .ι i
/-- The gluing as sheafed spaces is isomorphic to the gluing as presheafed spaces. -/
abbreviation iso_LocallyRingedSpace :
D.glued.to_LocallyRingedSpace ≅ D.to_LocallyRingedSpace_glue_data.to_glue_data.glued :=
𝖣 .glued_iso forget_to_LocallyRingedSpace
lemma ι_iso_LocallyRingedSpace_inv (i : D.J) :
D.to_LocallyRingedSpace_glue_data.to_glue_data.ι i ≫ D.iso_LocallyRingedSpace.inv = 𝖣 .ι i :=
𝖣 .ι_glued_iso_inv forget_to_LocallyRingedSpace i
instance ι_is_open_immersion (i : D.J) :
is_open_immersion (𝖣 .ι i) :=
by { rw ← D.ι_iso_LocallyRingedSpace_inv, apply_instance }
lemma ι_jointly_surjective (x : 𝖣 .glued.carrier) :
∃ (i : D.J) (y : (D.U i).carrier), (D.ι i).1.base y = x :=
𝖣 .ι_jointly_surjective (forget_to_Top ⋙ forget Top) x
@[simp, reassoc]
lemma glue_condition (i j : D.J) :
D.t i j ≫ D.f j i ≫ D.ι j = D.f i j ≫ D.ι i :=
𝖣 .glue_condition i j
/-- The pullback cone spanned by `V i j ⟶ U i` and `V i j ⟶ U j`.
This is a pullback diagram (`V_pullback_cone_is_limit`). -/
def V_pullback_cone (i j : D.J) : pullback_cone (D.ι i) (D.ι j) :=
pullback_cone.mk (D.f i j) (D.t i j ≫ D.f j i) (by simp)
/-- The following diagram is a pullback, i.e. `Vᵢⱼ` is the intersection of `Uᵢ` and `Uⱼ` in `X`.
Vᵢⱼ ⟶ Uᵢ
| |
↓ ↓
Uⱼ ⟶ X
-/
def V_pullback_cone_is_limit (i j : D.J) :
is_limit (D.V_pullback_cone i j) :=
𝖣 .V_pullback_cone_is_limit_of_map forget_to_LocallyRingedSpace i j
(D.to_LocallyRingedSpace_glue_data.V_pullback_cone_is_limit _ _)
/-- The underlying topological space of the glued scheme is isomorphic to the gluing of the
underlying spacess -/
def iso_carrier :
D.glued.carrier ≅ D.to_LocallyRingedSpace_glue_data.to_SheafedSpace_glue_data
.to_PresheafedSpace_glue_data.to_Top_glue_data.to_glue_data.glued :=
begin
refine (PresheafedSpace.forget _).map_iso _ ≪≫
glue_data.glued_iso _ (PresheafedSpace.forget _),
refine SheafedSpace.forget_to_PresheafedSpace.map_iso _ ≪≫
SheafedSpace.glue_data.iso_PresheafedSpace _,
refine LocallyRingedSpace.forget_to_SheafedSpace.map_iso _ ≪≫
LocallyRingedSpace.glue_data.iso_SheafedSpace _,
exact Scheme.glue_data.iso_LocallyRingedSpace _
end
@[simp]
lemma ι_iso_carrier_inv (i : D.J) :
D.to_LocallyRingedSpace_glue_data.to_SheafedSpace_glue_data
.to_PresheafedSpace_glue_data.to_Top_glue_data.to_glue_data.ι i ≫ D.iso_carrier.inv =
(D.ι i).1.base :=
begin
delta iso_carrier,
simp only [functor.map_iso_inv, iso.trans_inv, iso.trans_assoc,
glue_data.ι_glued_iso_inv_assoc, functor.map_iso_trans, category.assoc],
iterate 3 { erw ← comp_base },
simp_rw ← category.assoc,
rw D.to_LocallyRingedSpace_glue_data.to_SheafedSpace_glue_data.ι_iso_PresheafedSpace_inv i,
erw D.to_LocallyRingedSpace_glue_data.ι_iso_SheafedSpace_inv i,
change (_ ≫ D.iso_LocallyRingedSpace.inv).1.base = _,
rw D.ι_iso_LocallyRingedSpace_inv i
end
/-- An equivalence relation on `Σ i, D.U i` that holds iff `𝖣 .ι i x = 𝖣 .ι j y`.
See `Scheme.gluing_data.ι_eq_iff`. -/
def rel (a b : Σ i, ((D.U i).carrier : Type*)) : Prop :=
a = b ∨ ∃ (x : (D.V (a.1, b.1)).carrier),
(D.f _ _).1.base x = a.2 ∧ (D.t _ _ ≫ D.f _ _).1.base x = b.2
lemma ι_eq_iff (i j : D.J) (x : (D.U i).carrier) (y : (D.U j).carrier) :
(𝖣 .ι i).1.base x = (𝖣 .ι j).1.base y ↔ D.rel ⟨i, x⟩ ⟨j, y⟩ :=
begin
refine iff.trans _ (D.to_LocallyRingedSpace_glue_data.to_SheafedSpace_glue_data
.to_PresheafedSpace_glue_data.to_Top_glue_data.ι_eq_iff_rel i j x y),
rw ← ((Top.mono_iff_injective D.iso_carrier.inv).mp infer_instance).eq_iff,
simp_rw [← comp_apply, D.ι_iso_carrier_inv]
end
lemma is_open_iff (U : set D.glued.carrier) : is_open U ↔ ∀ i, is_open ((D.ι i).1.base ⁻¹' U) :=
begin
rw ← (Top.homeo_of_iso D.iso_carrier.symm).is_open_preimage,
rw Top.glue_data.is_open_iff,
apply forall_congr,
intro i,
erw [← set.preimage_comp, ← coe_comp, ι_iso_carrier_inv]
end
/-- The open cover of the glued space given by the glue data. -/
def open_cover (D : Scheme.glue_data) : open_cover D.glued :=
{ J := D.J,
obj := D.U,
map := D.ι,
f := λ x, (D.ι_jointly_surjective x).some,
covers := λ x, ⟨_, (D.ι_jointly_surjective x).some_spec.some_spec⟩ }
end glue_data
namespace open_cover
variables {X : Scheme.{u}} (𝒰 : open_cover.{u} X)
/-- (Implementation) the transition maps in the glue data associated with an open cover. -/
def glued_cover_t' (x y z : 𝒰.J) :
pullback (pullback.fst : pullback (𝒰.map x) (𝒰.map y) ⟶ _)
(pullback.fst : pullback (𝒰.map x) (𝒰.map z) ⟶ _) ⟶
pullback (pullback.fst : pullback (𝒰.map y) (𝒰.map z) ⟶ _)
(pullback.fst : pullback (𝒰.map y) (𝒰.map x) ⟶ _) :=
begin
refine (pullback_right_pullback_fst_iso _ _ _).hom ≫ _,
refine _ ≫ (pullback_symmetry _ _).hom,
refine _ ≫ (pullback_right_pullback_fst_iso _ _ _).inv,
refine pullback.map _ _ _ _ (pullback_symmetry _ _).hom (𝟙 _) (𝟙 _) _ _,
{ simp [pullback.condition] },
{ simp }
end
@[simp, reassoc]
lemma glued_cover_t'_fst_fst (x y z : 𝒰.J) :
𝒰.glued_cover_t' x y z ≫ pullback.fst ≫ pullback.fst = pullback.fst ≫ pullback.snd :=
by { delta glued_cover_t', simp }
@[simp, reassoc]
lemma glued_cover_t'_fst_snd (x y z : 𝒰.J) :
glued_cover_t' 𝒰 x y z ≫ pullback.fst ≫ pullback.snd = pullback.snd ≫ pullback.snd :=
by { delta glued_cover_t', simp }
@[simp, reassoc]
lemma glued_cover_t'_snd_fst (x y z : 𝒰.J) :
glued_cover_t' 𝒰 x y z ≫ pullback.snd ≫ pullback.fst = pullback.fst ≫ pullback.snd :=
by { delta glued_cover_t', simp }
@[simp, reassoc]
lemma glued_cover_t'_snd_snd (x y z : 𝒰.J) :
glued_cover_t' 𝒰 x y z ≫ pullback.snd ≫ pullback.snd = pullback.fst ≫ pullback.fst :=
by { delta glued_cover_t', simp }
lemma glued_cover_cocycle_fst (x y z : 𝒰.J) :
glued_cover_t' 𝒰 x y z ≫ glued_cover_t' 𝒰 y z x ≫ glued_cover_t' 𝒰 z x y ≫ pullback.fst =
pullback.fst :=
by apply pullback.hom_ext; simp
lemma glued_cover_cocycle_snd (x y z : 𝒰.J) :
glued_cover_t' 𝒰 x y z ≫ glued_cover_t' 𝒰 y z x ≫ glued_cover_t' 𝒰 z x y ≫ pullback.snd =
pullback.snd :=
by apply pullback.hom_ext; simp [pullback.condition]
lemma glued_cover_cocycle (x y z : 𝒰.J) :
glued_cover_t' 𝒰 x y z ≫ glued_cover_t' 𝒰 y z x ≫ glued_cover_t' 𝒰 z x y = 𝟙 _ :=
begin
apply pullback.hom_ext; simp_rw [category.id_comp, category.assoc],
apply glued_cover_cocycle_fst,
apply glued_cover_cocycle_snd,
end
/-- The glue data associated with an open cover.
The canonical isomorphism `𝒰.glued_cover.glued ⟶ X` is provided by `𝒰.from_glued`. -/
@[simps]
def glued_cover : Scheme.glue_data.{u} :=
{ J := 𝒰.J,
U := 𝒰.obj,
V := λ ⟨x, y⟩, pullback (𝒰.map x) (𝒰.map y),
f := λ x y, pullback.fst,
f_id := λ x, infer_instance,
t := λ x y, (pullback_symmetry _ _).hom,
t_id := λ x, by simpa,
t' := λ x y z, glued_cover_t' 𝒰 x y z,
t_fac := λ x y z, by apply pullback.hom_ext; simp,
-- The `cocycle` field could have been `by tidy` but lean timeouts.
cocycle := λ x y z, glued_cover_cocycle 𝒰 x y z,
f_open := λ x, infer_instance }
/-- The canonical morphism from the gluing of an open cover of `X` into `X`.
This is an isomorphism, as witnessed by an `is_iso` instance. -/
def from_glued : 𝒰.glued_cover.glued ⟶ X :=
begin
fapply multicoequalizer.desc,
exact λ x, (𝒰.map x),
rintro ⟨x, y⟩,
change pullback.fst ≫ _ = ((pullback_symmetry _ _).hom ≫ pullback.fst) ≫ _,
simpa using pullback.condition
end
@[simp, reassoc]
lemma ι_from_glued (x : 𝒰.J) :
𝒰.glued_cover.ι x ≫ 𝒰.from_glued = 𝒰.map x :=
multicoequalizer.π_desc _ _ _ _ _
lemma from_glued_injective : function.injective 𝒰.from_glued.1.base :=
begin
intros x y h,
obtain ⟨i, x, rfl⟩ := 𝒰.glued_cover.ι_jointly_surjective x,
obtain ⟨j, y, rfl⟩ := 𝒰.glued_cover.ι_jointly_surjective y,
simp_rw [← comp_apply, ← SheafedSpace.comp_base, ← LocallyRingedSpace.comp_val] at h,
erw [ι_from_glued, ι_from_glued] at h,
let e := (Top.pullback_cone_is_limit _ _).cone_point_unique_up_to_iso
(is_limit_of_has_pullback_of_preserves_limit Scheme.forget_to_Top
(𝒰.map i) (𝒰.map j)),
rw 𝒰.glued_cover.ι_eq_iff,
right,
use e.hom ⟨⟨x, y⟩, h⟩,
simp_rw ← comp_apply,
split,
{ erw is_limit.cone_point_unique_up_to_iso_hom_comp _ _ walking_cospan.left, refl },
{ erw [pullback_symmetry_hom_comp_fst,
is_limit.cone_point_unique_up_to_iso_hom_comp _ _ walking_cospan.right], refl }
end
instance from_glued_stalk_iso (x : 𝒰.glued_cover.glued.carrier) :
is_iso (PresheafedSpace.stalk_map 𝒰.from_glued.val x) :=
begin
obtain ⟨i, x, rfl⟩ := 𝒰.glued_cover.ι_jointly_surjective x,
have := PresheafedSpace.stalk_map.congr_hom _ _
(congr_arg LocallyRingedSpace.hom.val $ 𝒰.ι_from_glued i) x,
erw PresheafedSpace.stalk_map.comp at this,
rw ← is_iso.eq_comp_inv at this,
rw this,
apply_instance,
end
lemma from_glued_open_map : is_open_map 𝒰.from_glued.1.base :=
begin
intros U hU,
rw is_open_iff_forall_mem_open,
intros x hx,
rw 𝒰.glued_cover.is_open_iff at hU,
use 𝒰.from_glued.val.base '' U ∩ set.range (𝒰.map (𝒰.f x)).1.base,
use set.inter_subset_left _ _,
split,
{ rw ← set.image_preimage_eq_inter_range,
apply (show is_open_immersion (𝒰.map (𝒰.f x)), by apply_instance).base_open.is_open_map,
convert hU (𝒰.f x) using 1,
rw ← ι_from_glued, erw coe_comp, rw set.preimage_comp,
congr' 1,
refine set.preimage_image_eq _ 𝒰.from_glued_injective },
{ exact ⟨hx, 𝒰.covers x⟩ }
end
lemma from_glued_open_embedding : open_embedding 𝒰.from_glued.1.base :=
open_embedding_of_continuous_injective_open (by continuity) 𝒰.from_glued_injective
𝒰.from_glued_open_map
instance : epi 𝒰.from_glued.val.base :=
begin
rw Top.epi_iff_surjective,
intro x,
obtain ⟨y, h⟩ := 𝒰.covers x,
use (𝒰.glued_cover.ι (𝒰.f x)).1.base y,
rw ← comp_apply,
rw ← 𝒰.ι_from_glued (𝒰.f x) at h,
exact h
end
instance from_glued_open_immersion : is_open_immersion 𝒰.from_glued :=
SheafedSpace.is_open_immersion.of_stalk_iso _ 𝒰.from_glued_open_embedding
instance : is_iso 𝒰.from_glued :=
begin
apply is_iso_of_reflects_iso _ (Scheme.forget_to_LocallyRingedSpace ⋙
LocallyRingedSpace.forget_to_SheafedSpace ⋙ SheafedSpace.forget_to_PresheafedSpace),
change @is_iso (PresheafedSpace _) _ _ _ 𝒰.from_glued.val,
apply PresheafedSpace.is_open_immersion.to_iso,
end
/-- Given an open cover of `X`, and a morphism `𝒰.obj x ⟶ Y` for each open subscheme in the cover,
such that these morphisms are compatible in the intersection (pullback), we may glue the morphisms
together into a morphism `X ⟶ Y`.
Note:
If `X` is exactly (defeq to) the gluing of `U i`, then using `multicoequalizer.desc` suffices.
-/
def glue_morphisms {Y : Scheme} (f : ∀ x, 𝒰.obj x ⟶ Y)
(hf : ∀ x y, (pullback.fst : pullback (𝒰.map x) (𝒰.map y) ⟶ _) ≫ f x = pullback.snd ≫ f y) :
X ⟶ Y :=
begin
refine inv 𝒰.from_glued ≫ _,
fapply multicoequalizer.desc,
exact f,
rintro ⟨i, j⟩,
change pullback.fst ≫ f i = (_ ≫ _) ≫ f j,
erw pullback_symmetry_hom_comp_fst,
exact hf i j
end
@[simp, reassoc]
lemma ι_glue_morphisms {Y : Scheme} (f : ∀ x, 𝒰.obj x ⟶ Y)
(hf : ∀ x y, (pullback.fst : pullback (𝒰.map x) (𝒰.map y) ⟶ _) ≫ f x = pullback.snd ≫ f y)
(x : 𝒰.J) : (𝒰.map x) ≫ 𝒰.glue_morphisms f hf = f x :=
begin
rw [← ι_from_glued, category.assoc],
erw [is_iso.hom_inv_id_assoc, multicoequalizer.π_desc],
end
lemma hom_ext {Y : Scheme} (f₁ f₂ : X ⟶ Y) (h : ∀ x, 𝒰.map x ≫ f₁ = 𝒰.map x ≫ f₂) : f₁ = f₂ :=
begin
rw ← cancel_epi 𝒰.from_glued,
apply multicoequalizer.hom_ext,
intro x,
erw multicoequalizer.π_desc_assoc,
erw multicoequalizer.π_desc_assoc,
exact h x,
end
end open_cover
end Scheme
end algebraic_geometry
|
5efb3ebbbb62dec4e82d79c9aded5c193a2d2d25 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/data/set/card.lean | 05f3dcbbe656bb5ad86e0357a14f21d68c5021ec | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 5,879 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
Cardinality of finite sets.
-/
import .finite data.finset.card
open nat classical
namespace set
variable {A : Type}
noncomputable definition card (s : set A) := finset.card (set.to_finset s)
theorem card_to_set (s : finset A) : card (finset.to_set s) = finset.card s :=
by rewrite [↑card, to_finset_to_set]
theorem card_of_not_finite {s : set A} (nfins : ¬ finite s) : card s = 0 :=
by rewrite [↑card, to_finset_of_not_finite nfins]
theorem card_empty : card (∅ : set A) = 0 :=
by rewrite [-finset.to_set_empty, card_to_set]
theorem card_insert_of_mem {a : A} {s : set A} (H : a ∈ s) : card (insert a s) = card s :=
if fins : finite s then
(by rewrite [↑card, to_finset_insert, -mem_to_finset_eq at H, finset.card_insert_of_mem H])
else
(have ¬ finite (insert a s), from suppose _, absurd (!finite_of_finite_insert this) fins,
by rewrite [card_of_not_finite fins, card_of_not_finite this])
theorem card_insert_of_not_mem {a : A} {s : set A} [finite s] (H : a ∉ s) :
card (insert a s) = card s + 1 :=
by rewrite [↑card, to_finset_insert, -mem_to_finset_eq at H, finset.card_insert_of_not_mem H]
theorem card_insert_le (a : A) (s : set A) [finite s] :
card (insert a s) ≤ card s + 1 :=
if H : a ∈ s then by rewrite [card_insert_of_mem H]; apply le_succ
else by rewrite [card_insert_of_not_mem H]
theorem card_singleton (a : A) : card '{a} = 1 :=
by rewrite [card_insert_of_not_mem !not_mem_empty, card_empty]
/- Note: the induction tactic does not work well with the set induction principle with the
extra predicate "finite". -/
theorem eq_empty_of_card_eq_zero {s : set A} [finite s] : card s = 0 → s = ∅ :=
induction_on_finite s
(by intro H; exact rfl)
(begin
intro a s' fins' anins IH H,
rewrite (card_insert_of_not_mem anins) at H,
apply nat.no_confusion H
end)
theorem card_upto (n : ℕ) : card {i | i < n} = n :=
by rewrite [↑card, to_finset_upto, finset.card_upto]
theorem card_add_card (s₁ s₂ : set A) [finite s₁] [finite s₂] :
card s₁ + card s₂ = card (s₁ ∪ s₂) + card (s₁ ∩ s₂) :=
begin
rewrite [-to_set_to_finset s₁, -to_set_to_finset s₂],
rewrite [-finset.to_set_union, -finset.to_set_inter, *card_to_set],
apply finset.card_add_card
end
theorem card_union (s₁ s₂ : set A) [finite s₁] [finite s₂] :
card (s₁ ∪ s₂) = card s₁ + card s₂ - card (s₁ ∩ s₂) :=
calc
card (s₁ ∪ s₂) = card (s₁ ∪ s₂) + card (s₁ ∩ s₂) - card (s₁ ∩ s₂) : nat.add_sub_cancel
... = card s₁ + card s₂ - card (s₁ ∩ s₂) : card_add_card s₁ s₂
theorem card_union_of_disjoint {s₁ s₂ : set A} [finite s₁] [finite s₂] (H : s₁ ∩ s₂ = ∅) :
card (s₁ ∪ s₂) = card s₁ + card s₂ :=
by rewrite [card_union, H, card_empty]
theorem card_eq_card_add_card_diff {s₁ s₂ : set A} [finite s₁] [finite s₂] (H : s₁ ⊆ s₂) :
card s₂ = card s₁ + card (s₂ \ s₁) :=
have H1 : s₁ ∩ (s₂ \ s₁) = ∅,
from eq_empty_of_forall_not_mem (take x, assume H, (and.right (and.right H)) (and.left H)),
have s₂ = s₁ ∪ (s₂ \ s₁), from eq.symm (union_diff_cancel H),
calc
card s₂ = card (s₁ ∪ (s₂ \ s₁)) : {this}
... = card s₁ + card (s₂ \ s₁) : card_union_of_disjoint H1
theorem card_le_card_of_subset {s₁ s₂ : set A} [finite s₁] [finite s₂] (H : s₁ ⊆ s₂) :
card s₁ ≤ card s₂ :=
calc
card s₂ = card s₁ + card (s₂ \ s₁) : card_eq_card_add_card_diff H
... ≥ card s₁ : le_add_right
variable {B : Type}
theorem card_image_eq_of_inj_on {f : A → B} {s : set A} [finite s] (injfs : inj_on f s) :
card (image f s) = card s :=
begin
rewrite [↑card, to_finset_image];
apply finset.card_image_eq_of_inj_on,
rewrite to_set_to_finset,
apply injfs
end
theorem card_le_of_inj_on (a : set A) (b : set B) [finite b]
(Pex : ∃ f : A → B, inj_on f a ∧ (image f a ⊆ b)) :
card a ≤ card b :=
by_cases
(assume fina : finite a,
obtain f H, from Pex,
finset.card_le_of_inj_on (to_finset a) (to_finset b)
(exists.intro f
begin
rewrite [finset.subset_eq_to_set_subset, finset.to_set_image, *to_set_to_finset],
exact H
end))
(assume nfina : ¬ finite a,
by rewrite [card_of_not_finite nfina]; exact !zero_le)
theorem card_image_le (f : A → B) (s : set A) [finite s] : card (image f s) ≤ card s :=
by rewrite [↑card, to_finset_image]; apply finset.card_image_le
theorem inj_on_of_card_image_eq {f : A → B} {s : set A} [finite s]
(H : card (image f s) = card s) : inj_on f s :=
begin
rewrite -to_set_to_finset,
apply finset.inj_on_of_card_image_eq,
rewrite [-to_finset_to_set (finset.image _ _), finset.to_set_image, to_set_to_finset],
exact H
end
theorem card_pos_of_mem {a : A} {s : set A} [finite s] (H : a ∈ s) : card s > 0 :=
have (#finset a ∈ to_finset s), by rewrite [finset.mem_eq_mem_to_set, to_set_to_finset]; apply H,
finset.card_pos_of_mem this
theorem eq_of_card_eq_of_subset {s₁ s₂ : set A} [finite s₁] [finite s₂]
(Hcard : card s₁ = card s₂) (Hsub : s₁ ⊆ s₂) :
s₁ = s₂ :=
begin
rewrite [-to_set_to_finset s₁, -to_set_to_finset s₂, -finset.eq_eq_to_set_eq],
apply finset.eq_of_card_eq_of_subset Hcard,
rewrite [to_finset_subset_to_finset_eq],
exact Hsub
end
theorem exists_two_of_card_gt_one {s : set A} (H : 1 < card s) : ∃ a b, a ∈ s ∧ b ∈ s ∧ a ≠ b :=
have fins : finite s, from
by_contradiction
(assume nfins, by rewrite [card_of_not_finite nfins at H]; apply !not_succ_le_zero H),
by rewrite [-to_set_to_finset s]; apply finset.exists_two_of_card_gt_one H
end set
|
66168c175c640a1f866a2ca735b9298012033b54 | 4e3bf8e2b29061457a887ac8889e88fa5aa0e34c | /lean/love11_logical_foundations_of_mathematics_exercise_sheet.lean | 80665ac63ae3e2180b81a0fd3979c7ab3807cd70 | [] | no_license | mukeshtiwari/logical_verification_2019 | 9f964c067a71f65eb8884743273fbeef99e6503d | 16f62717f55ed5b7b87e03ae0134791a9bef9b9a | refs/heads/master | 1,619,158,844,208 | 1,585,139,500,000 | 1,585,139,500,000 | 249,906,380 | 0 | 0 | null | 1,585,118,728,000 | 1,585,118,727,000 | null | UTF-8 | Lean | false | false | 4,182 | lean | /- LoVe Exercise 11: Logical Foundations of Mathematics -/
import .love11_logical_foundations_of_mathematics_demo
namespace LoVe
universe variable u
set_option pp.beta true
/- Question 1: Subtypes -/
namespace my_vector
/- Recall the definition of vectors from the lecture: -/
#check vector
/- The following function adds two lists of integers elementwise. If one
function is longer than the other, the tail of the longer function is
truncated. -/
def list_add : list ℤ → list ℤ → list ℤ
| [] [] := []
| (x :: xs) (y :: ys) := (x + y) :: list_add xs ys
| [] (y :: ys) := []
| (x :: xs) [] := []
/- 1.1. Show that if the lists have the same length, the resulting list also has
that length. -/
lemma length_list_add :
∀(xs : list ℤ) (ys : list ℤ) (h : list.length xs = list.length ys),
list.length (list_add xs ys) = list.length xs
| [] [] :=
sorry
| (x :: xs) (y :: ys) :=
sorry
| [] (y :: ys) :=
sorry
| (x :: xs) [] :=
sorry
/- 1.2. Define componentwise addition on vectors using `list_add` and
`length_list_add`. -/
def add {n : ℕ} : vector ℤ n → vector ℤ n → vector ℤ n :=
sorry
/- 1.3. Show that `list_add` and `add` are commutative. -/
lemma list_add_comm :
∀(xs : list ℤ) (ys : list ℤ), list_add xs ys = list_add ys xs
sorry
lemma add_comm {n : ℕ} (x y : vector ℤ n) :
add x y = add y x :=
sorry
end my_vector
/- Question 2: Integers as Quotients -/
/- Recall the construction of integers from the lecture: -/
#check myℤ.rel
#check rel_iff
#check myℤ
/- 2.1. Define negation using `quotient.lift`. -/
def neg : myℤ → myℤ :=
sorry
/- 2.2. Prove the following lemmas. -/
lemma neg_mk (p n : ℕ) :
neg ⟦(p, n)⟧ = ⟦(n, p)⟧ :=
sorry
lemma myℤ.neg_neg (a : myℤ) :
neg (neg a) = a :=
sorry
/- Question 3: Nonempty Types -/
/- In the lecture, we saw the inductive predicate `nonempty` that states that a
type has at least one element: -/
#print nonempty
/- 3.1. The purpose of this exercise is to think about what would happen if all
types had at least one element. To investigate this, we introduce this fact as
an axiom as follows. Introducing axioms should be generally avoided or done
with great care, since they can easily lead to contradictions, as we will
see. -/
axiom sort_nonempty (α : Sort u) :
nonempty α
/- This axiom gives us a fact `sort_nonempty` without having to prove it. It
resembles a lemma proved by sorry, just without the warning. -/
#check sort_nonempty
/- Prove that this axiom leads to a contradiction, i.e., lets us derive
`false`. -/
lemma proof_of_false : false :=
sorry
/- 3.2 (**optional**). Prove that even the following weaker axiom leads to a
contradiction. Of course, you may not use the axiom or the lemma from 3.1.
Hint: Subtypes can help. -/
axiom all_nonempty_Type (α : Type u) : nonempty α
lemma proof_of_false₂ : false :=
sorry
/- Question 4 (**optional**): Hilbert Choice -/
/- The following command enables noncomputable decidability on every `Prop`. The
`priority 0` attribute ensures this is used only when necessary; otherwise, it
would make some computable definitions noncomputable for Lean. -/
local attribute [instance, priority 0] classical.prop_decidable
/- 4.1 (**optional**). Prove the following lemma. -/
lemma exists_minimal_arg.aux (f : ℕ → ℕ) :
∀x n, f n = x → ∃n, ∀i, f n ≤ f i
| x n eq :=
begin
-- this works thanks to `classical.prop_decidable`
by_cases (∃n', f n' < x),
repeat { sorry }
end
/- Now this interesting lemma falls off: -/
lemma exists_minimal_arg (f : ℕ → ℕ) :
∃n : ℕ, ∀i : ℕ, f n ≤ f i :=
exists_minimal_arg.aux f _ 0 rfl
/- 4.2 (**optional**). Use what you learned in the lecture notes to define the
following function, which returns the (or an) index of the minimal element in
`f`'s image. -/
noncomputable def minimal_arg (f : ℕ → ℕ) : ℕ :=
sorry
/- 4.3 (**optional**). Prove the following characteristic lemma about your
definition. -/
lemma minimal_arg_spec (f : ℕ → ℕ) :
∀i : ℕ, f (minimal_arg f) ≤ f i :=
sorry
end LoVe
|
a997060d5d8149eb14e17f45c206e501f27d1d0a | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /library/data/nat/order.lean | 839e0844d57d1979ad2ee7c36572d8bec6bfa394 | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,616 | lean | --- Copyright (c) 2014 Floris van Doorn. All rights reserved.
--- Released under Apache 2.0 license as described in the file LICENSE.
--- Author: Floris van Doorn, Leonardo de Moura
-- data.nat.order
-- ==============
--
-- The ordering on the natural numbers
import .basic
open eq.ops
namespace nat
-- Less than or equal
-- ------------------
theorem le.succ_right {n m : ℕ} (h : n ≤ m) : n ≤ succ m :=
le.rec_on h
(le.of_lt (lt.base n))
(λ b (h : n < b), le.of_lt (lt.step h))
theorem le.add_right (n k : ℕ) : n ≤ n + k :=
induction_on k
(calc n ≤ n : le.refl n
... = n + zero : add.zero_right)
(λ k (ih : n ≤ n + k), calc
n ≤ succ (n + k) : le.succ_right ih
... = n + succ k : add.succ_right)
theorem le_intro {n m k : ℕ} (h : n + k = m) : n ≤ m :=
h ▸ le.add_right n k
theorem le_elim {n m : ℕ} (h : n ≤ m) : ∃k, n + k = m :=
le.rec_on h
(exists_intro 0 rfl)
(λ m (h : n < m), lt.rec_on h
(exists_intro 1 rfl)
(λ b hlt (ih : ∃ (k : ℕ), n + k = b),
obtain (k : ℕ) (h : n + k = b), from ih,
exists_intro (succ k) (calc
n + succ k = succ (n + k) : add.succ_right
... = succ b : h)))
-- ### partial order (totality is part of less than)
theorem le_refl (n : ℕ) : n ≤ n :=
le.refl n
theorem zero_le (n : ℕ) : 0 ≤ n :=
le_intro !add.zero_left
theorem le_zero {n : ℕ} (H : n ≤ 0) : n = 0 :=
obtain (k : ℕ) (Hk : n + k = 0), from le_elim H,
add.eq_zero_left Hk
theorem not_succ_zero_le (n : ℕ) : ¬ succ n ≤ 0 :=
not_intro
(assume H : succ n ≤ 0,
have H2 : succ n = 0, from le_zero H,
absurd H2 !succ_ne_zero)
theorem le_trans {n m k : ℕ} (H1 : n ≤ m) (H2 : m ≤ k) : n ≤ k :=
le.trans H1 H2
theorem le_antisym {n m : ℕ} (H1 : n ≤ m) (H2 : m ≤ n) : n = m :=
obtain (k : ℕ) (Hk : n + k = m), from (le_elim H1),
obtain (l : ℕ) (Hl : m + l = n), from (le_elim H2),
have L1 : k + l = 0, from
add.cancel_left
(calc
n + (k + l) = n + k + l : !add.assoc⁻¹
... = m + l : {Hk}
... = n : Hl
... = n + 0 : !add.zero_right⁻¹),
have L2 : k = 0, from add.eq_zero_left L1,
calc
n = n + 0 : !add.zero_right⁻¹
... = n + k : {L2⁻¹}
... = m : Hk
-- ### interaction with addition
theorem le_add_right (n m : ℕ) : n ≤ n + m :=
le_intro rfl
theorem le_add_left (n m : ℕ): n ≤ m + n :=
le_intro !add.comm
theorem add_le_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k + n ≤ k + m :=
obtain (l : ℕ) (Hl : n + l = m), from (le_elim H),
le_intro
(calc
k + n + l = k + (n + l) : !add.assoc
... = k + m : {Hl})
theorem add_le_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n + k ≤ m + k :=
!add.comm ▸ !add.comm ▸ add_le_left H k
theorem add_le {n m k l : ℕ} (H1 : n ≤ k) (H2 : m ≤ l) : n + m ≤ k + l :=
le_trans (add_le_right H1 m) (add_le_left H2 k)
theorem add_le_cancel_left {n m k : ℕ} (H : k + n ≤ k + m) : n ≤ m :=
obtain (l : ℕ) (Hl : k + n + l = k + m), from (le_elim H),
le_intro (add.cancel_left
(calc
k + (n + l) = k + n + l : !add.assoc⁻¹
... = k + m : Hl))
theorem add_le_cancel_right {n m k : ℕ} (H : n + k ≤ m + k) : n ≤ m :=
add_le_cancel_left (!add.comm ▸ !add.comm ▸ H)
theorem add_le_inv {n m k l : ℕ} (H1 : n + m ≤ k + l) (H2 : k ≤ n) : m ≤ l :=
obtain (a : ℕ) (Ha : k + a = n), from le_elim H2,
have H3 : k + (a + m) ≤ k + l, from !add.assoc ▸ Ha⁻¹ ▸ H1,
have H4 : a + m ≤ l, from add_le_cancel_left H3,
show m ≤ l, from le_trans !le_add_left H4
-- add_rewrite le_add_right le_add_left
-- ### interaction with successor and predecessor
theorem succ_le {n m : ℕ} (H : n ≤ m) : succ n ≤ succ m :=
!add.one ▸ !add.one ▸ add_le_right H 1
theorem succ_le_cancel {n m : ℕ} (H : succ n ≤ succ m) : n ≤ m :=
add_le_cancel_right (!add.one⁻¹ ▸ !add.one⁻¹ ▸ H)
theorem self_le_succ (n : ℕ) : n ≤ succ n :=
le_intro !add.one
theorem le_imp_le_succ {n m : ℕ} (H : n ≤ m) : n ≤ succ m :=
le_trans H !self_le_succ
theorem le_imp_succ_le_or_eq {n m : ℕ} (H : n ≤ m) : succ n ≤ m ∨ n = m :=
obtain (k : ℕ) (Hk : n + k = m), from (le_elim H),
discriminate
(assume H3 : k = 0,
have Heq : n = m,
from calc
n = n + 0 : !add.zero_right⁻¹
... = n + k : {H3⁻¹}
... = m : Hk,
or.inr Heq)
(take l : nat,
assume H3 : k = succ l,
have Hlt : succ n ≤ m, from
(le_intro
(calc
succ n + l = n + succ l : !add.move_succ
... = n + k : {H3⁻¹}
... = m : Hk)),
or.inl Hlt)
theorem le_ne_imp_succ_le {n m : ℕ} (H1 : n ≤ m) (H2 : n ≠ m) : succ n ≤ m :=
or.resolve_left (le_imp_succ_le_or_eq H1) H2
theorem le_succ_imp_le_or_eq {n m : ℕ} (H : n ≤ succ m) : n ≤ m ∨ n = succ m :=
or.imp_or_left (le_imp_succ_le_or_eq H)
(take H2 : succ n ≤ succ m, show n ≤ m, from succ_le_cancel H2)
theorem succ_le_imp_le_and_ne {n m : ℕ} (H : succ n ≤ m) : n ≤ m ∧ n ≠ m :=
obtain (k : ℕ) (H2 : succ n + k = m), from (le_elim H),
and.intro
(have H3 : n + succ k = m,
from calc
n + succ k = succ n + k : !add.move_succ⁻¹
... = m : H2,
show n ≤ m, from le_intro H3)
(assume H3 : n = m,
have H4 : succ n ≤ n, from H3⁻¹ ▸ H,
have H5 : succ n = n, from le_antisym H4 !self_le_succ,
show false, from absurd H5 succ.ne_self)
theorem le_pred_self (n : ℕ) : pred n ≤ n :=
case n
(pred.zero⁻¹ ▸ !le_refl)
(take k : ℕ, !pred.succ⁻¹ ▸ !self_le_succ)
theorem pred_le {n m : ℕ} (H : n ≤ m) : pred n ≤ pred m :=
discriminate
(take Hn : n = 0,
have H2 : pred n = 0,
from calc
pred n = pred 0 : {Hn}
... = 0 : pred.zero,
H2⁻¹ ▸ !zero_le)
(take k : ℕ,
assume Hn : n = succ k,
obtain (l : ℕ) (Hl : n + l = m), from le_elim H,
have H2 : pred n + l = pred m,
from calc
pred n + l = pred (succ k) + l : {Hn}
... = k + l : {!pred.succ}
... = pred (succ (k + l)) : !pred.succ⁻¹
... = pred (succ k + l) : {!add.succ_left⁻¹}
... = pred (n + l) : {Hn⁻¹}
... = pred m : {Hl},
le_intro H2)
theorem pred_le_imp_le_or_eq {n m : ℕ} (H : pred n ≤ m) : n ≤ m ∨ n = succ m :=
discriminate
(take Hn : n = 0,
or.inl (Hn⁻¹ ▸ !zero_le))
(take k : ℕ,
assume Hn : n = succ k,
have H2 : pred n = k,
from calc
pred n = pred (succ k) : {Hn}
... = k : !pred.succ,
have H3 : k ≤ m, from H2 ▸ H,
have H4 : succ k ≤ m ∨ k = m, from le_imp_succ_le_or_eq H3,
show n ≤ m ∨ n = succ m, from
or.imp_or H4
(take H5 : succ k ≤ m, show n ≤ m, from Hn⁻¹ ▸ H5)
(take H5 : k = m, show n = succ m, from H5 ▸ Hn))
-- ### interaction with multiplication
theorem mul_le_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k * n ≤ k * m :=
obtain (l : ℕ) (Hl : n + l = m), from (le_elim H),
have H2 : k * n + k * l = k * m, from
calc
k * n + k * l = k * (n + l) : mul.distr_left
... = k * m : {Hl},
le_intro H2
theorem mul_le_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n * k ≤ m * k :=
!mul.comm ▸ !mul.comm ▸ (mul_le_left H k)
theorem mul_le {n m k l : ℕ} (H1 : n ≤ k) (H2 : m ≤ l) : n * m ≤ k * l :=
le_trans (mul_le_right H1 m) (mul_le_left H2 k)
-- Less than, Greater than, Greater than or equal
-- ----------------------------------------------
theorem lt_intro {n m k : ℕ} (H : succ n + k = m) : n < m :=
le_succ_imp_lt (le_intro H)
theorem lt_elim {n m : ℕ} (H : n < m) : ∃ k, succ n + k = m :=
le_elim (lt_imp_le_succ H)
theorem lt_add_succ (n m : ℕ) : n < n + succ m :=
lt_intro !add.move_succ
-- ### basic facts
theorem lt_imp_ne {n m : ℕ} (H : n < m) : n ≠ m :=
λ heq : n = m, absurd H (heq ▸ !lt.irrefl)
theorem lt_irrefl (n : ℕ) : ¬ n < n :=
not_intro (assume H : n < n, absurd rfl (lt_imp_ne H))
theorem lt_def (n m : ℕ) : n < m ↔ succ n ≤ m :=
iff.intro
(λ h, lt_imp_le_succ h)
(λ h, le_succ_imp_lt h)
theorem succ_pos (n : ℕ) : 0 < succ n :=
!zero_lt_succ
theorem lt_imp_eq_succ {n m : ℕ} (H : n < m) : exists k, m = succ k :=
discriminate
(take (Hm : m = 0), absurd (Hm ▸ H) !not_lt_zero)
(take (l : ℕ) (Hm : m = succ l), exists_intro l Hm)
-- ### interaction with le
theorem self_lt_succ (n : ℕ) : n < succ n :=
lt.base n
theorem lt_imp_le {n m : ℕ} (H : n < m) : n ≤ m :=
le.of_lt H
theorem le_imp_lt_or_eq {n m : ℕ} (H : n ≤ m) : n < m ∨ n = m :=
or.swap (le_def_right H)
theorem le_ne_imp_lt {n m : ℕ} (H1 : n ≤ m) (H2 : n ≠ m) : n < m :=
or.resolve_left (le_imp_lt_or_eq H1) H2
theorem lt_succ_imp_le {n m : ℕ} (H : n < succ m) : n ≤ m :=
succ_le_cancel (lt_imp_le_succ H)
theorem le_imp_not_gt {n m : ℕ} (H : n ≤ m) : ¬ n > m :=
le.rec_on H
!lt.irrefl
(λ m (h : n < m), lt.asymm h)
theorem lt_imp_not_ge {n m : ℕ} (H : n < m) : ¬ n ≥ m :=
not_intro (assume H2 : m ≤ n, absurd (lt_le.trans H H2) !lt_irrefl)
theorem lt_antisym {n m : ℕ} (H : n < m) : ¬ m < n :=
lt.asymm H
-- le_imp_not_gt (lt_imp_le H)
-- ### interaction with addition
theorem add_lt_left {n m : ℕ} (H : n < m) (k : ℕ) : k + n < k + m :=
le_succ_imp_lt (!add.succ_right ▸ add_le_left (lt_imp_le_succ H) k)
theorem add_lt_right {n m : ℕ} (H : n < m) (k : ℕ) : n + k < m + k :=
!add.comm ▸ !add.comm ▸ add_lt_left H k
theorem add_le_lt {n m k l : ℕ} (H1 : n ≤ k) (H2 : m < l) : n + m < k + l :=
le_lt.trans (add_le_right H1 m) (add_lt_left H2 k)
theorem add_lt_le {n m k l : ℕ} (H1 : n < k) (H2 : m ≤ l) : n + m < k + l :=
lt_le.trans (add_lt_right H1 m) (add_le_left H2 k)
theorem add_lt {n m k l : ℕ} (H1 : n < k) (H2 : m < l) : n + m < k + l :=
add_lt_le H1 (lt_imp_le H2)
theorem add_lt_cancel_left {n m k : ℕ} (H : k + n < k + m) : n < m :=
le_succ_imp_lt (add_le_cancel_left (!add.succ_right⁻¹ ▸ (lt_imp_le_succ H)))
theorem add_lt_cancel_right {n m k : ℕ} (H : n + k < m + k) : n < m :=
add_lt_cancel_left (!add.comm ▸ !add.comm ▸ H)
-- ### interaction with successor (see also the interaction with le)
theorem succ_lt {n m : ℕ} (H : n < m) : succ n < succ m :=
!add.one ▸ !add.one ▸ add_lt_right H 1
theorem succ_lt_cancel {n m : ℕ} (H : succ n < succ m) : n < m :=
add_lt_cancel_right (!add.one⁻¹ ▸ !add.one⁻¹ ▸ H)
theorem lt_imp_lt_succ {n m : ℕ} (H : n < m) : n < succ m :=
lt.step H
-- ### totality of lt and le
theorem le_or_gt {n m : ℕ} : n ≤ m ∨ n > m :=
or.rec_on (lt.trichotomy n m)
(λ h : n < m, or.inl (le.of_lt h))
(λ h : n = m ∨ m < n, or.rec_on h
(λ h : n = m, eq.rec_on h (or.inl !le.refl))
(λ h : m < n, or.inr h))
theorem trichotomy_alt (n m : ℕ) : (n < m ∨ n = m) ∨ n > m :=
or.rec_on (lt.trichotomy n m)
(λ h, or.inl (or.inl h))
(λ h, or.rec_on h
(λ h, or.inl (or.inr h))
(λ h, or.inr h))
theorem trichotomy (n m : ℕ) : n < m ∨ n = m ∨ n > m :=
lt.trichotomy n m
theorem le_total (n m : ℕ) : n ≤ m ∨ m ≤ n :=
or.imp_or_right le_or_gt (assume H : m < n, lt_imp_le H)
theorem not_lt_imp_ge {n m : ℕ} (H : ¬ n < m) : n ≥ m :=
or.resolve_left le_or_gt H
theorem not_le_imp_gt {n m : ℕ} (H : ¬ n ≤ m) : n > m :=
or.resolve_right le_or_gt H
-- ### misc
protected theorem strong_induction_on {P : nat → Prop} (n : ℕ) (H : ∀n, (∀m, m < n → P m) → P n) : P n :=
have H1 : ∀ {n m : nat}, m < n → P m, from
take n,
induction_on n
(show ∀m, m < 0 → P m, from take m H, absurd H !not_lt_zero)
(take n',
assume IH : ∀ {m : nat}, m < n' → P m,
have H2: P n', from H n' @IH,
show ∀m, m < succ n' → P m, from
take m,
assume H3 : m < succ n',
or.elim (le_imp_lt_or_eq (lt_succ_imp_le H3))
(assume H4: m < n', IH H4)
(assume H4: m = n', H4⁻¹ ▸ H2)),
H1 !self_lt_succ
protected theorem case_strong_induction_on {P : nat → Prop} (a : nat) (H0 : P 0)
(Hind : ∀(n : nat), (∀m, m ≤ n → P m) → P (succ n)) : P a :=
strong_induction_on a (
take n,
show (∀m, m < n → P m) → P n, from
case n
(assume H : (∀m, m < 0 → P m), show P 0, from H0)
(take n,
assume H : (∀m, m < succ n → P m),
show P (succ n), from
Hind n (take m, assume H1 : m ≤ n, H _ (le_imp_lt_succ H1))))
-- Positivity
-- ---------
--
-- Writing "t > 0" is the preferred way to assert that a natural number is positive.
-- ### basic
theorem case_zero_pos {P : ℕ → Prop} (y : ℕ) (H0 : P 0) (H1 : ∀ {y : nat}, y > 0 → P y) : P y :=
case y H0 (take y, H1 !succ_pos)
theorem zero_or_pos {n : ℕ} : n = 0 ∨ n > 0 :=
or.imp_or_left
(or.swap (le_imp_lt_or_eq !zero_le))
(take H : 0 = n, H⁻¹)
theorem succ_imp_pos {n m : ℕ} (H : n = succ m) : n > 0 :=
H⁻¹ ▸ !succ_pos
theorem ne_zero_imp_pos {n : ℕ} (H : n ≠ 0) : n > 0 :=
or.elim zero_or_pos (take H2 : n = 0, absurd H2 H) (take H2 : n > 0, H2)
theorem pos_imp_ne_zero {n : ℕ} (H : n > 0) : n ≠ 0 :=
ne.symm (lt_imp_ne H)
theorem pos_imp_eq_succ {n : ℕ} (H : n > 0) : exists l, n = succ l :=
lt_imp_eq_succ H
theorem add_pos_right {n k : ℕ} (H : k > 0) : n + k > n :=
!add.zero_right ▸ add_lt_left H n
theorem add_pos_left {n : ℕ} {k : ℕ} (H : k > 0) : k + n > n :=
!add.comm ▸ add_pos_right H
-- ### multiplication
theorem mul_pos {n m : ℕ} (Hn : n > 0) (Hm : m > 0) : n * m > 0 :=
obtain (k : ℕ) (Hk : n = succ k), from pos_imp_eq_succ Hn,
obtain (l : ℕ) (Hl : m = succ l), from pos_imp_eq_succ Hm,
succ_imp_pos (calc
n * m = succ k * m : {Hk}
... = succ k * succ l : {Hl}
... = succ k * l + succ k : !mul.succ_right
... = succ (succ k * l + k) : !add.succ_right)
theorem mul_pos_imp_pos_left {n m : ℕ} (H : n * m > 0) : n > 0 :=
discriminate
(assume H2 : n = 0,
have H3 : n * m = 0,
from calc
n * m = 0 * m : {H2}
... = 0 : !mul.zero_left,
have H4 : 0 > 0, from H3 ▸ H,
absurd H4 !lt_irrefl)
(take l : nat,
assume Hl : n = succ l,
Hl⁻¹ ▸ !succ_pos)
theorem mul_pos_imp_pos_right {m n : ℕ} (H : n * m > 0) : m > 0 :=
mul_pos_imp_pos_left (!mul.comm ▸ H)
-- ### interaction of mul with le and lt
theorem mul_lt_left {n m k : ℕ} (Hk : k > 0) (H : n < m) : k * n < k * m :=
have H2 : k * n < k * n + k, from add_pos_right Hk,
have H3 : k * n + k ≤ k * m, from !mul.succ_right ▸ mul_le_left (lt_imp_le_succ H) k,
lt_le.trans H2 H3
theorem mul_lt_right {n m k : ℕ} (Hk : k > 0) (H : n < m) : n * k < m * k :=
!mul.comm ▸ !mul.comm ▸ mul_lt_left Hk H
theorem mul_le_lt {n m k l : ℕ} (Hk : k > 0) (H1 : n ≤ k) (H2 : m < l) : n * m < k * l :=
le_lt.trans (mul_le_right H1 m) (mul_lt_left Hk H2)
theorem mul_lt_le {n m k l : ℕ} (Hl : l > 0) (H1 : n < k) (H2 : m ≤ l) : n * m < k * l :=
le_lt.trans (mul_le_left H2 n) (mul_lt_right Hl H1)
theorem mul_lt {n m k l : ℕ} (H1 : n < k) (H2 : m < l) : n * m < k * l :=
have H3 : n * m ≤ k * m, from mul_le_right (lt_imp_le H1) m,
have H4 : k * m < k * l, from mul_lt_left (le_lt.trans !zero_le H1) H2,
le_lt.trans H3 H4
theorem mul_lt_cancel_left {n m k : ℕ} (H : k * n < k * m) : n < m :=
or.elim le_or_gt
(assume H2 : m ≤ n,
have H3 : k * m ≤ k * n, from mul_le_left H2 k,
absurd H3 (lt_imp_not_ge H))
(assume H2 : n < m, H2)
theorem mul_lt_cancel_right {n m k : ℕ} (H : n * k < m * k) : n < m :=
mul_lt_cancel_left (!mul.comm ▸ !mul.comm ▸ H)
theorem mul_le_cancel_left {n m k : ℕ} (Hk : k > 0) (H : k * n ≤ k * m) : n ≤ m :=
have H2 : k * n < k * m + k, from le_lt.trans H (add_pos_right Hk),
have H3 : k * n < k * succ m, from !mul.succ_right⁻¹ ▸ H2,
have H4 : n < succ m, from mul_lt_cancel_left H3,
show n ≤ m, from lt_succ_imp_le H4
theorem mul_le_cancel_right {n k m : ℕ} (Hm : m > 0) (H : n * m ≤ k * m) : n ≤ k :=
mul_le_cancel_left Hm (!mul.comm ▸ !mul.comm ▸ H)
theorem mul_cancel_left {m k n : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k :=
have H2 : n * m ≤ n * k, from H ▸ !le_refl,
have H3 : n * k ≤ n * m, from H ▸ !le_refl,
have H4 : m ≤ k, from mul_le_cancel_left Hn H2,
have H5 : k ≤ m, from mul_le_cancel_left Hn H3,
le_antisym H4 H5
theorem mul_cancel_left_or {n m k : ℕ} (H : n * m = n * k) : n = 0 ∨ m = k :=
or.imp_or_right zero_or_pos
(assume Hn : n > 0, mul_cancel_left Hn H)
theorem mul_cancel_right {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k :=
mul_cancel_left Hm (!mul.comm ▸ !mul.comm ▸ H)
theorem mul_cancel_right_or {n m k : ℕ} (H : n * m = k * m) : m = 0 ∨ n = k :=
mul_cancel_left_or (!mul.comm ▸ !mul.comm ▸ H)
theorem mul_eq_one_left {n m : ℕ} (H : n * m = 1) : n = 1 :=
have H2 : n * m > 0, from H⁻¹ ▸ !succ_pos,
have H3 : n > 0, from mul_pos_imp_pos_left H2,
have H4 : m > 0, from mul_pos_imp_pos_right H2,
or.elim le_or_gt
(assume H5 : n ≤ 1,
show n = 1, from le_antisym H5 (lt_imp_le_succ H3))
(assume H5 : n > 1,
have H6 : n * m ≥ 2 * 1, from mul_le (lt_imp_le_succ H5) (lt_imp_le_succ H4),
have H7 : 1 ≥ 2, from !mul.one_right ▸ H ▸ H6,
absurd !self_lt_succ (le_imp_not_gt H7))
theorem mul_eq_one_right {n m : ℕ} (H : n * m = 1) : m = 1 :=
mul_eq_one_left (!mul.comm ▸ H)
end nat
|
59328a80d441333dcc205a14928d3b6d68e595b6 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Lean/Elab/PreDefinition/WF/Rel.lean | d998d6b3980b560cbc766ba9dca7f4258b84fade | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 7,710 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Tactic.Apply
import Lean.Meta.Tactic.Rename
import Lean.Meta.Tactic.Intro
import Lean.Elab.SyntheticMVars
import Lean.Elab.PreDefinition.Basic
import Lean.Elab.PreDefinition.WF.TerminationHint
namespace Lean.Elab.WF
open Meta
open Term
private def getRefFromElems (elems : Array TerminationByElement) : Syntax := Id.run do
for elem in elems do
if !elem.implicit then
return elem.ref
return elems[0]!.ref
private partial def unpackMutual (preDefs : Array PreDefinition) (mvarId : MVarId) (fvarId : FVarId) : TermElabM (Array (FVarId × MVarId)) := do
let rec go (i : Nat) (mvarId : MVarId) (fvarId : FVarId) (result : Array (FVarId × MVarId)) : TermElabM (Array (FVarId × MVarId)) := do
if i < preDefs.size - 1 then
let #[s₁, s₂] ← mvarId.cases fvarId | unreachable!
go (i + 1) s₂.mvarId s₂.fields[0]!.fvarId! (result.push (s₁.fields[0]!.fvarId!, s₁.mvarId))
else
return result.push (fvarId, mvarId)
go 0 mvarId fvarId #[]
private partial def unpackUnary (preDef : PreDefinition) (prefixSize : Nat) (mvarId : MVarId) (fvarId : FVarId) (element : TerminationByElement) : TermElabM MVarId := do
let varNames ← lambdaTelescope preDef.value fun xs _ => do
let mut varNames ← xs.mapM fun x => x.fvarId!.getUserName
if element.vars.size > varNames.size then
throwErrorAt element.vars[varNames.size]! "too many variable names"
for i in [:element.vars.size] do
let varStx := element.vars[i]!
if varStx.isIdent then
varNames := varNames.set! (varNames.size - element.vars.size + i) varStx.getId
return varNames
let mut mvarId := mvarId
for localDecl in (← Term.getMVarDecl mvarId).lctx, varName in varNames[:prefixSize] do
unless localDecl.userName == varName do
mvarId ← mvarId.rename localDecl.fvarId varName
let numPackedArgs := varNames.size - prefixSize
let rec go (i : Nat) (mvarId : MVarId) (fvarId : FVarId) : TermElabM MVarId := do
trace[Elab.definition.wf] "i: {i}, varNames: {varNames}, goal: {mvarId}"
if i < numPackedArgs - 1 then
let #[s] ← mvarId.cases fvarId #[{ varNames := [varNames[prefixSize + i]!] }] | unreachable!
go (i+1) s.mvarId s.fields[1]!.fvarId!
else
mvarId.rename fvarId varNames.back
go 0 mvarId fvarId
def getNumCandidateArgs (fixedPrefixSize : Nat) (preDefs : Array PreDefinition) : MetaM (Array Nat) := do
preDefs.mapM fun preDef =>
lambdaTelescope preDef.value fun xs _ =>
return xs.size - fixedPrefixSize
/--
Given a predefinition with value `fun (x_₁ ... xₙ) (y_₁ : α₁)... (yₘ : αₘ) => ...`,
where `n = fixedPrefixSize`, return an array `A` s.t. `i ∈ A` iff `sizeOf yᵢ` reduces to a literal.
This is the case for types such as `Prop`, `Type u`, etc.
This arguments should not be considered when guessing a well-founded relation.
See `generateCombinations?`
-/
def getForbiddenByTrivialSizeOf (fixedPrefixSize : Nat) (preDef : PreDefinition) : MetaM (Array Nat) :=
lambdaTelescope preDef.value fun xs _ => do
let mut result := #[]
for x in xs[fixedPrefixSize:], i in [:xs.size] do
try
let sizeOf ← whnfD (← mkAppM ``sizeOf #[x])
if sizeOf.isLit then
result := result.push i
catch _ =>
result := result.push i
return result
def generateCombinations? (forbiddenArgs : Array (Array Nat)) (numArgs : Array Nat) (threshold : Nat := 32) : Option (Array (Array Nat)) :=
go 0 #[] |>.run #[] |>.2
where
isForbidden (fidx : Nat) (argIdx : Nat) : Bool :=
if h : fidx < forbiddenArgs.size then
forbiddenArgs.get ⟨fidx, h⟩ |>.contains argIdx
else
false
go (fidx : Nat) : OptionT (ReaderT (Array Nat) (StateM (Array (Array Nat)))) Unit := do
if h : fidx < numArgs.size then
let n := numArgs.get ⟨fidx, h⟩
for argIdx in [:n] do
unless isForbidden fidx argIdx do
withReader (·.push argIdx) (go (fidx + 1))
else
modify (·.push (← read))
if (← get).size > threshold then
failure
termination_by _ fidx => numArgs.size - fidx
def elabWFRel (preDefs : Array PreDefinition) (unaryPreDefName : Name) (fixedPrefixSize : Nat) (argType : Expr) (wf? : Option TerminationWF) (k : Expr → TermElabM α) : TermElabM α := do
let α := argType
let u ← getLevel α
let expectedType := mkApp (mkConst ``WellFoundedRelation [u]) α
trace[Elab.definition.wf] "elabWFRel start: {(← mkFreshTypeMVar).mvarId!}"
match wf? with
| some (TerminationWF.core wfStx) => withDeclName unaryPreDefName do
let wfRel ← instantiateMVars (← withSynthesize <| elabTermEnsuringType wfStx expectedType)
let pendingMVarIds ← getMVars wfRel
discard <| logUnassignedUsingErrorInfos pendingMVarIds
k wfRel
| some (TerminationWF.ext elements) => go expectedType elements
| none => guess expectedType
where
go (expectedType : Expr) (elements : Array TerminationByElement) : TermElabM α :=
withDeclName unaryPreDefName <| withRef (getRefFromElems elements) do
let mainMVarId := (← mkFreshExprSyntheticOpaqueMVar expectedType).mvarId!
let [fMVarId, wfRelMVarId, _] ← mainMVarId.apply (← mkConstWithFreshMVarLevels ``invImage) | throwError "failed to apply 'invImage'"
let (d, fMVarId) ← fMVarId.intro1
let subgoals ← unpackMutual preDefs fMVarId d
for (d, mvarId) in subgoals, element in elements, preDef in preDefs do
let mvarId ← unpackUnary preDef fixedPrefixSize mvarId d element
mvarId.withContext do
let value ← Term.withSynthesize <| elabTermEnsuringType element.body (← mvarId.getType)
mvarId.assign value
let wfRelVal ← synthInstance (← inferType (mkMVar wfRelMVarId))
wfRelMVarId.assign wfRelVal
k (← instantiateMVars (mkMVar mainMVarId))
generateElements (numArgs : Array Nat) (argCombination : Array Nat) : TermElabM (Array TerminationByElement) := do
let mut result := #[]
let var ← `(x)
let hole ← `(_)
for preDef in preDefs, numArg in numArgs, argIdx in argCombination, i in [:preDefs.size] do
let mut vars := #[var]
for _ in [:numArg - argIdx - 1] do
vars := vars.push hole
-- TODO: improve this.
-- The following trick allows a function `f` in a mutual block to invoke `g` appearing before it with the input argument.
-- We should compute the "right" order (if there is one) in the future.
let body ← if preDefs.size > 1 then `((sizeOf x, $(quote i))) else `(sizeOf x)
result := result.push {
ref := preDef.ref
declName := preDef.declName
vars := vars
body := body
implicit := false
}
return result
guess (expectedType : Expr) : TermElabM α := do
-- TODO: add support for lex
let numArgs ← getNumCandidateArgs fixedPrefixSize preDefs
-- TODO: include in `forbiddenArgs` arguments that are fixed but are not in the fixed prefix
let forbiddenArgs ← preDefs.mapM fun preDef => getForbiddenByTrivialSizeOf fixedPrefixSize preDef
-- TODO: add option to control the maximum number of cases to try
if let some combs := generateCombinations? forbiddenArgs numArgs then
for comb in combs do
let elements ← generateElements numArgs comb
if let some r ← observing? (go expectedType elements) then
return r
throwError "failed to prove termination, use `termination_by` to specify a well-founded relation"
end Lean.Elab.WF
|
00be56fc2249061bab190328d06796b06b2ff2d0 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/topology/algebra/order/compact.lean | 16b76cbd0680a93c7d3728f07039a1ea6f503c50 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 17,905 | lean | /-
Copyright (c) 2021 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Yury Kudryashov
-/
import topology.algebra.order.intermediate_value
/-!
# Compactness of a closed interval
In this file we prove that a closed interval in a conditionally complete linear ordered type with
order topology (or a product of such types) is compact.
We prove the extreme value theorem (`is_compact.exists_forall_le`, `is_compact.exists_forall_ge`):
a continuous function on a compact set takes its minimum and maximum values. We provide many
variations of this theorem.
We also prove that the image of a closed interval under a continuous map is a closed interval, see
`continuous_on.image_Icc`.
## Tags
compact, extreme value theorem
-/
open filter order_dual topological_space function set
open_locale filter topological_space
/-!
### Compactness of a closed interval
In this section we define a typeclass `compact_Icc_space α` saying that all closed intervals in `α`
are compact. Then we provide an instance for a `conditionally_complete_linear_order` and prove that
the product (both `α × β` and an indexed product) of spaces with this property inherits the
property.
We also prove some simple lemmas about spaces with this property.
-/
/-- This typeclass says that all closed intervals in `α` are compact. This is true for all
conditionally complete linear orders with order topology and products (finite or infinite)
of such spaces. -/
class compact_Icc_space (α : Type*) [topological_space α] [preorder α] : Prop :=
(is_compact_Icc : ∀ {a b : α}, is_compact (Icc a b))
export compact_Icc_space (is_compact_Icc)
/-- A closed interval in a conditionally complete linear order is compact. -/
@[priority 100]
instance conditionally_complete_linear_order.to_compact_Icc_space
(α : Type*) [conditionally_complete_linear_order α] [topological_space α] [order_topology α] :
compact_Icc_space α :=
begin
refine ⟨λ a b, _⟩,
cases le_or_lt a b with hab hab, swap, { simp [hab] },
refine is_compact_iff_ultrafilter_le_nhds.2 (λ f hf, _),
contrapose! hf,
rw [le_principal_iff],
have hpt : ∀ x ∈ Icc a b, {x} ∉ f,
from λ x hx hxf, hf x hx ((le_pure_iff.2 hxf).trans (pure_le_nhds x)),
set s := {x ∈ Icc a b | Icc a x ∉ f},
have hsb : b ∈ upper_bounds s, from λ x hx, hx.1.2,
have sbd : bdd_above s, from ⟨b, hsb⟩,
have ha : a ∈ s, by simp [hpt, hab],
rcases hab.eq_or_lt with rfl|hlt, { exact ha.2 },
set c := Sup s,
have hsc : is_lub s c, from is_lub_cSup ⟨a, ha⟩ sbd,
have hc : c ∈ Icc a b, from ⟨hsc.1 ha, hsc.2 hsb⟩,
specialize hf c hc,
have hcs : c ∈ s,
{ cases hc.1.eq_or_lt with heq hlt, { rwa ← heq },
refine ⟨hc, λ hcf, hf (λ U hU, _)⟩,
rcases (mem_nhds_within_Iic_iff_exists_Ioc_subset' hlt).1 (mem_nhds_within_of_mem_nhds hU)
with ⟨x, hxc, hxU⟩,
rcases ((hsc.frequently_mem ⟨a, ha⟩).and_eventually
(Ioc_mem_nhds_within_Iic ⟨hxc, le_rfl⟩)).exists
with ⟨y, ⟨hyab, hyf⟩, hy⟩,
refine mem_of_superset(f.diff_mem_iff.2 ⟨hcf, hyf⟩) (subset.trans _ hxU),
rw diff_subset_iff,
exact subset.trans Icc_subset_Icc_union_Ioc
(union_subset_union subset.rfl $ Ioc_subset_Ioc_left hy.1.le) },
cases hc.2.eq_or_lt with heq hlt, { rw ← heq, exact hcs.2 },
contrapose! hf,
intros U hU,
rcases (mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset hlt).1 (mem_nhds_within_of_mem_nhds hU)
with ⟨y, hxy, hyU⟩,
refine mem_of_superset _ hyU, clear_dependent U,
have hy : y ∈ Icc a b, from ⟨hc.1.trans hxy.1.le, hxy.2⟩,
by_cases hay : Icc a y ∈ f,
{ refine mem_of_superset (f.diff_mem_iff.2 ⟨f.diff_mem_iff.2 ⟨hay, hcs.2⟩, hpt y hy⟩) _,
rw [diff_subset_iff, union_comm, Ico_union_right hxy.1.le, diff_subset_iff],
exact Icc_subset_Icc_union_Icc },
{ exact ((hsc.1 ⟨hy, hay⟩).not_lt hxy.1).elim },
end
instance {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] [Π i, topological_space (α i)]
[Π i, compact_Icc_space (α i)] : compact_Icc_space (Π i, α i) :=
⟨λ a b, pi_univ_Icc a b ▸ is_compact_univ_pi $ λ i, is_compact_Icc⟩
instance pi.compact_Icc_space' {α β : Type*} [preorder β] [topological_space β]
[compact_Icc_space β] : compact_Icc_space (α → β) :=
pi.compact_Icc_space
instance {α β : Type*} [preorder α] [topological_space α] [compact_Icc_space α]
[preorder β] [topological_space β] [compact_Icc_space β] :
compact_Icc_space (α × β) :=
⟨λ a b, (Icc_prod_eq a b).symm ▸ is_compact_Icc.prod is_compact_Icc⟩
/-- An unordered closed interval is compact. -/
lemma is_compact_interval {α : Type*} [linear_order α] [topological_space α] [compact_Icc_space α]
{a b : α} : is_compact (interval a b) :=
is_compact_Icc
/-- A complete linear order is a compact space.
We do not register an instance for a `[compact_Icc_space α]` because this would only add instances
for products (indexed or not) of complete linear orders, and we have instances with higher priority
that cover these cases. -/
@[priority 100] -- See note [lower instance priority]
instance compact_space_of_complete_linear_order {α : Type*} [complete_linear_order α]
[topological_space α] [order_topology α] :
compact_space α :=
⟨by simp only [← Icc_bot_top, is_compact_Icc]⟩
section
variables {α : Type*} [preorder α] [topological_space α] [compact_Icc_space α]
instance compact_space_Icc (a b : α) : compact_space (Icc a b) :=
is_compact_iff_compact_space.mp is_compact_Icc
end
/-!
### Min and max elements of a compact set
-/
variables {α β γ : Type*} [conditionally_complete_linear_order α] [topological_space α]
[order_topology α] [topological_space β] [topological_space γ]
lemma is_compact.Inf_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
Inf s ∈ s :=
hs.is_closed.cInf_mem ne_s hs.bdd_below
lemma is_compact.Sup_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : Sup s ∈ s :=
@is_compact.Inf_mem αᵒᵈ _ _ _ _ hs ne_s
lemma is_compact.is_glb_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_glb s (Inf s) :=
is_glb_cInf ne_s hs.bdd_below
lemma is_compact.is_lub_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_lub s (Sup s) :=
@is_compact.is_glb_Inf αᵒᵈ _ _ _ _ hs ne_s
lemma is_compact.is_least_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_least s (Inf s) :=
⟨hs.Inf_mem ne_s, (hs.is_glb_Inf ne_s).1⟩
lemma is_compact.is_greatest_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_greatest s (Sup s) :=
@is_compact.is_least_Inf αᵒᵈ _ _ _ _ hs ne_s
lemma is_compact.exists_is_least {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x, is_least s x :=
⟨_, hs.is_least_Inf ne_s⟩
lemma is_compact.exists_is_greatest {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x, is_greatest s x :=
⟨_, hs.is_greatest_Sup ne_s⟩
lemma is_compact.exists_is_glb {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x ∈ s, is_glb s x :=
⟨_, hs.Inf_mem ne_s, hs.is_glb_Inf ne_s⟩
lemma is_compact.exists_is_lub {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x ∈ s, is_lub s x :=
⟨_, hs.Sup_mem ne_s, hs.is_lub_Sup ne_s⟩
lemma is_compact.exists_Inf_image_eq_and_le {s : set β} (hs : is_compact s) (ne_s : s.nonempty)
{f : β → α} (hf : continuous_on f s) :
∃ x ∈ s, Inf (f '' s) = f x ∧ ∀ y ∈ s, f x ≤ f y :=
let ⟨x, hxs, hx⟩ := (hs.image_of_continuous_on hf).Inf_mem (ne_s.image f)
in ⟨x, hxs, hx.symm, λ y hy,
hx.trans_le $ cInf_le (hs.image_of_continuous_on hf).bdd_below $ mem_image_of_mem f hy⟩
lemma is_compact.exists_Sup_image_eq_and_ge {s : set β} (hs : is_compact s) (ne_s : s.nonempty)
{f : β → α} (hf : continuous_on f s) :
∃ x ∈ s, Sup (f '' s) = f x ∧ ∀ y ∈ s, f y ≤ f x :=
@is_compact.exists_Inf_image_eq_and_le αᵒᵈ _ _ _ _ _ _ hs ne_s _ hf
lemma is_compact.exists_Inf_image_eq {s : set β} (hs : is_compact s) (ne_s : s.nonempty)
{f : β → α} (hf : continuous_on f s) :
∃ x ∈ s, Inf (f '' s) = f x :=
let ⟨x, hxs, hx, _⟩ := hs.exists_Inf_image_eq_and_le ne_s hf in ⟨x, hxs, hx⟩
lemma is_compact.exists_Sup_image_eq :
∀ {s : set β}, is_compact s → s.nonempty → ∀ {f : β → α}, continuous_on f s →
∃ x ∈ s, Sup (f '' s) = f x :=
@is_compact.exists_Inf_image_eq αᵒᵈ _ _ _ _ _
lemma eq_Icc_of_connected_compact {s : set α} (h₁ : is_connected s) (h₂ : is_compact s) :
s = Icc (Inf s) (Sup s) :=
eq_Icc_cInf_cSup_of_connected_bdd_closed h₁ h₂.bdd_below h₂.bdd_above h₂.is_closed
/-!
### Extreme value theorem
-/
/-- The **extreme value theorem**: a continuous function realizes its minimum on a compact set. -/
lemma is_compact.exists_forall_le {s : set β} (hs : is_compact s) (ne_s : s.nonempty)
{f : β → α} (hf : continuous_on f s) :
∃x∈s, ∀y∈s, f x ≤ f y :=
begin
rcases (hs.image_of_continuous_on hf).exists_is_least (ne_s.image f)
with ⟨_, ⟨x, hxs, rfl⟩, hx⟩,
exact ⟨x, hxs, ball_image_iff.1 hx⟩
end
/-- The **extreme value theorem**: a continuous function realizes its maximum on a compact set. -/
lemma is_compact.exists_forall_ge :
∀ {s : set β}, is_compact s → s.nonempty → ∀ {f : β → α}, continuous_on f s →
∃x∈s, ∀y∈s, f y ≤ f x :=
@is_compact.exists_forall_le αᵒᵈ _ _ _ _ _
/-- The **extreme value theorem**: if a function `f` is continuous on a closed set `s` and it is
larger than a value in its image away from compact sets, then it has a minimum on this set. -/
lemma continuous_on.exists_forall_le' {s : set β} {f : β → α} (hf : continuous_on f s)
(hsc : is_closed s) {x₀ : β} (h₀ : x₀ ∈ s) (hc : ∀ᶠ x in cocompact β ⊓ 𝓟 s, f x₀ ≤ f x) :
∃ x ∈ s, ∀ y ∈ s, f x ≤ f y :=
begin
rcases (has_basis_cocompact.inf_principal _).eventually_iff.1 hc with ⟨K, hK, hKf⟩,
have hsub : insert x₀ (K ∩ s) ⊆ s, from insert_subset.2 ⟨h₀, inter_subset_right _ _⟩,
obtain ⟨x, hx, hxf⟩ : ∃ x ∈ insert x₀ (K ∩ s), ∀ y ∈ insert x₀ (K ∩ s), f x ≤ f y :=
((hK.inter_right hsc).insert x₀).exists_forall_le (insert_nonempty _ _) (hf.mono hsub),
refine ⟨x, hsub hx, λ y hy, _⟩,
by_cases hyK : y ∈ K,
exacts [hxf _ (or.inr ⟨hyK, hy⟩), (hxf _ (or.inl rfl)).trans (hKf ⟨hyK, hy⟩)]
end
/-- The **extreme value theorem**: if a function `f` is continuous on a closed set `s` and it is
smaller than a value in its image away from compact sets, then it has a maximum on this set. -/
lemma continuous_on.exists_forall_ge' {s : set β} {f : β → α} (hf : continuous_on f s)
(hsc : is_closed s) {x₀ : β} (h₀ : x₀ ∈ s) (hc : ∀ᶠ x in cocompact β ⊓ 𝓟 s, f x ≤ f x₀) :
∃ x ∈ s, ∀ y ∈ s, f y ≤ f x :=
@continuous_on.exists_forall_le' αᵒᵈ _ _ _ _ _ _ _ hf hsc _ h₀ hc
/-- The **extreme value theorem**: if a continuous function `f` is larger than a value in its range
away from compact sets, then it has a global minimum. -/
lemma _root_.continuous.exists_forall_le' {f : β → α} (hf : continuous f) (x₀ : β)
(h : ∀ᶠ x in cocompact β, f x₀ ≤ f x) : ∃ (x : β), ∀ (y : β), f x ≤ f y :=
let ⟨x, _, hx⟩ := hf.continuous_on.exists_forall_le' is_closed_univ (mem_univ x₀)
(by rwa [principal_univ, inf_top_eq])
in ⟨x, λ y, hx y (mem_univ y)⟩
/-- The **extreme value theorem**: if a continuous function `f` is smaller than a value in its range
away from compact sets, then it has a global maximum. -/
lemma _root_.continuous.exists_forall_ge' {f : β → α} (hf : continuous f) (x₀ : β)
(h : ∀ᶠ x in cocompact β, f x ≤ f x₀) : ∃ (x : β), ∀ (y : β), f y ≤ f x :=
@continuous.exists_forall_le' αᵒᵈ _ _ _ _ _ _ hf x₀ h
/-- The **extreme value theorem**: if a continuous function `f` tends to infinity away from compact
sets, then it has a global minimum. -/
lemma _root_.continuous.exists_forall_le [nonempty β] {f : β → α}
(hf : continuous f) (hlim : tendsto f (cocompact β) at_top) :
∃ x, ∀ y, f x ≤ f y :=
by { inhabit β, exact hf.exists_forall_le' default (hlim.eventually $ eventually_ge_at_top _) }
/-- The **extreme value theorem**: if a continuous function `f` tends to negative infinity away from
compact sets, then it has a global maximum. -/
lemma continuous.exists_forall_ge [nonempty β] {f : β → α}
(hf : continuous f) (hlim : tendsto f (cocompact β) at_bot) :
∃ x, ∀ y, f y ≤ f x :=
@continuous.exists_forall_le αᵒᵈ _ _ _ _ _ _ _ hf hlim
lemma is_compact.Sup_lt_iff_of_continuous {f : β → α}
{K : set β} (hK : is_compact K) (h0K : K.nonempty) (hf : continuous_on f K) (y : α) :
Sup (f '' K) < y ↔ ∀ x ∈ K, f x < y :=
begin
refine ⟨λ h x hx, (le_cSup (hK.bdd_above_image hf) $ mem_image_of_mem f hx).trans_lt h, λ h, _⟩,
obtain ⟨x, hx, h2x⟩ := hK.exists_forall_ge h0K hf,
refine (cSup_le (h0K.image f) _).trans_lt (h x hx),
rintro _ ⟨x', hx', rfl⟩, exact h2x x' hx'
end
lemma is_compact.lt_Inf_iff_of_continuous {α β : Type*}
[conditionally_complete_linear_order α] [topological_space α]
[order_topology α] [topological_space β] {f : β → α}
{K : set β} (hK : is_compact K) (h0K : K.nonempty) (hf : continuous_on f K) (y : α) :
y < Inf (f '' K) ↔ ∀ x ∈ K, y < f x :=
@is_compact.Sup_lt_iff_of_continuous αᵒᵈ β _ _ _ _ _ _ hK h0K hf y
/-- A continuous function with compact support has a global minimum. -/
@[to_additive]
lemma _root_.continuous.exists_forall_le_of_has_compact_mul_support [nonempty β] [has_one α]
{f : β → α} (hf : continuous f) (h : has_compact_mul_support f) :
∃ (x : β), ∀ (y : β), f x ≤ f y :=
begin
obtain ⟨_, ⟨x, rfl⟩, hx⟩ := (h.is_compact_range hf).exists_is_least (range_nonempty _),
rw [mem_lower_bounds, forall_range_iff] at hx,
exact ⟨x, hx⟩,
end
/-- A continuous function with compact support has a global maximum. -/
@[to_additive]
lemma continuous.exists_forall_ge_of_has_compact_mul_support [nonempty β] [has_one α]
{f : β → α} (hf : continuous f) (h : has_compact_mul_support f) :
∃ (x : β), ∀ (y : β), f y ≤ f x :=
@continuous.exists_forall_le_of_has_compact_mul_support αᵒᵈ _ _ _ _ _ _ _ _ hf h
lemma is_compact.continuous_Sup {f : γ → β → α}
{K : set β} (hK : is_compact K) (hf : continuous ↿f) :
continuous (λ x, Sup (f x '' K)) :=
begin
rcases eq_empty_or_nonempty K with rfl|h0K,
{ simp_rw [image_empty], exact continuous_const },
rw [continuous_iff_continuous_at],
intro x,
obtain ⟨y, hyK, h2y, hy⟩ :=
hK.exists_Sup_image_eq_and_ge h0K
(show continuous (λ y, f x y), from hf.comp $ continuous.prod.mk x).continuous_on,
rw [continuous_at, h2y, tendsto_order],
have := tendsto_order.mp ((show continuous (λ x, f x y), from
hf.comp $ continuous_id.prod_mk continuous_const).tendsto x),
refine ⟨λ z hz, _, λ z hz, _⟩,
{ refine (this.1 z hz).mono (λ x' hx', hx'.trans_le $ le_cSup _ $ mem_image_of_mem (f x') hyK),
exact hK.bdd_above_image (hf.comp $ continuous.prod.mk x').continuous_on },
{ have h : ({x} : set γ) ×ˢ K ⊆ ↿f ⁻¹' (Iio z),
{ rintro ⟨x', y'⟩ ⟨hx', hy'⟩, cases hx', exact (hy y' hy').trans_lt hz },
obtain ⟨u, v, hu, hv, hxu, hKv, huv⟩ :=
generalized_tube_lemma is_compact_singleton hK (is_open_Iio.preimage hf) h,
refine eventually_of_mem (hu.mem_nhds (singleton_subset_iff.mp hxu)) (λ x' hx', _),
rw [hK.Sup_lt_iff_of_continuous h0K
(show continuous (f x'), from (hf.comp $ continuous.prod.mk x')).continuous_on],
exact λ y' hy', huv (mk_mem_prod hx' (hKv hy')) }
end
lemma is_compact.continuous_Inf {f : γ → β → α}
{K : set β} (hK : is_compact K) (hf : continuous ↿f) :
continuous (λ x, Inf (f x '' K)) :=
@is_compact.continuous_Sup αᵒᵈ β γ _ _ _ _ _ _ _ hK hf
namespace continuous_on
/-!
### Image of a closed interval
-/
variables [densely_ordered α] [conditionally_complete_linear_order β] [order_topology β]
{f : α → β} {a b c : α}
open_locale interval
lemma image_Icc (hab : a ≤ b) (h : continuous_on f $ Icc a b) :
f '' Icc a b = Icc (Inf $ f '' Icc a b) (Sup $ f '' Icc a b) :=
eq_Icc_of_connected_compact ⟨(nonempty_Icc.2 hab).image f, is_preconnected_Icc.image f h⟩
(is_compact_Icc.image_of_continuous_on h)
lemma image_interval_eq_Icc (h : continuous_on f $ [a, b]) :
f '' [a, b] = Icc (Inf (f '' [a, b])) (Sup (f '' [a, b])) :=
begin
cases le_total a b with h2 h2,
{ simp_rw [interval_of_le h2] at h ⊢, exact h.image_Icc h2 },
{ simp_rw [interval_of_ge h2] at h ⊢, exact h.image_Icc h2 },
end
lemma image_interval (h : continuous_on f $ [a, b]) :
f '' [a, b] = [Inf (f '' [a, b]), Sup (f '' [a, b])] :=
begin
refine h.image_interval_eq_Icc.trans (interval_of_le _).symm,
refine cInf_le_cSup _ _ (nonempty_interval.image _); rw h.image_interval_eq_Icc,
exacts [bdd_below_Icc, bdd_above_Icc]
end
lemma Inf_image_Icc_le (h : continuous_on f $ Icc a b) (hc : c ∈ Icc a b) :
Inf (f '' (Icc a b)) ≤ f c :=
begin
rw h.image_Icc (nonempty_Icc.mp (set.nonempty_of_mem hc)),
exact cInf_le bdd_below_Icc (mem_Icc.mpr ⟨cInf_le (is_compact_Icc.bdd_below_image h) ⟨c, hc, rfl⟩,
le_cSup (is_compact_Icc.bdd_above_image h) ⟨c, hc, rfl⟩⟩),
end
lemma le_Sup_image_Icc (h : continuous_on f $ Icc a b) (hc : c ∈ Icc a b) :
f c ≤ Sup (f '' (Icc a b)) :=
begin
rw h.image_Icc (nonempty_Icc.mp (set.nonempty_of_mem hc)),
exact le_cSup bdd_above_Icc (mem_Icc.mpr ⟨cInf_le (is_compact_Icc.bdd_below_image h) ⟨c, hc, rfl⟩,
le_cSup (is_compact_Icc.bdd_above_image h) ⟨c, hc, rfl⟩⟩),
end
end continuous_on
|
4a9dc62712624523dce2dbcf3cb6673e8284c1dc | 947b78d97130d56365ae2ec264df196ce769371a | /src/Init/Control/Except.lean | 7b40b0e9161b15a7b7921317fa556d10931635ff | [
"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 | 9,490 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jared Roesch, Sebastian Ullrich
The Except monad transformer.
-/
prelude
import Init.Data.ToString
import Init.Control.Alternative
import Init.Control.MonadControl
import Init.Control.Id
import Init.Control.MonadFunctor
import Init.Control.MonadRun
universes u v w u'
inductive Except (ε : Type u) (α : Type v)
| error : ε → Except
| ok : α → Except
attribute [unbox] Except
instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) :=
⟨Except.error (arbitrary ε)⟩
section
variables {ε : Type u} {α : Type v}
protected def Except.toString [HasToString ε] [HasToString α] : Except ε α → String
| Except.error e => "(error " ++ toString e ++ ")"
| Except.ok a => "(ok " ++ toString a ++ ")"
protected def Except.repr [HasRepr ε] [HasRepr α] : Except ε α → String
| Except.error e => "(error " ++ repr e ++ ")"
| Except.ok a => "(ok " ++ repr a ++ ")"
instance [HasToString ε] [HasToString α] : HasToString (Except ε α) :=
⟨Except.toString⟩
instance [HasRepr ε] [HasRepr α] : HasRepr (Except ε α) :=
⟨Except.repr⟩
end
namespace Except
variables {ε : Type u}
@[inline] protected def return {α : Type v} (a : α) : Except ε α :=
Except.ok a
@[inline] protected def map {α β : Type v} (f : α → β) : Except ε α → Except ε β
| Except.error err => Except.error err
| Except.ok v => Except.ok $ f v
@[inline] protected def mapError {ε' : Type u} {α : Type v} (f : ε → ε') : Except ε α → Except ε' α
| Except.error err => Except.error $ f err
| Except.ok v => Except.ok v
@[inline] protected def bind {α β : Type v} (ma : Except ε α) (f : α → Except ε β) : Except ε β :=
match ma with
| (Except.error err) => Except.error err
| (Except.ok v) => f v
@[inline] protected def toBool {α : Type v} : Except ε α → Bool
| Except.ok _ => true
| Except.error _ => false
@[inline] protected def toOption {α : Type v} : Except ε α → Option α
| Except.ok a => some a
| Except.error _ => none
@[inline] protected def catch {α : Type u} (ma : Except ε α) (handle : ε → Except ε α) : Except ε α :=
match ma with
| Except.ok a => Except.ok a
| Except.error e => handle e
instance : Monad (Except ε) :=
{ pure := @Except.return _, bind := @Except.bind _, map := @Except.map _ }
end Except
def ExceptT (ε : Type u) (m : Type u → Type v) (α : Type u) : Type v :=
m (Except ε α)
@[inline] def ExceptT.mk {ε : Type u} {m : Type u → Type v} {α : Type u} (x : m (Except ε α)) : ExceptT ε m α :=
x
@[inline] def ExceptT.run {ε : Type u} {m : Type u → Type v} {α : Type u} (x : ExceptT ε m α) : m (Except ε α) :=
x
namespace ExceptT
variables {ε : Type u} {m : Type u → Type v} [Monad m]
@[inline] protected def pure {α : Type u} (a : α) : ExceptT ε m α :=
ExceptT.mk $ pure (Except.ok a)
@[inline] protected def bindCont {α β : Type u} (f : α → ExceptT ε m β) : Except ε α → m (Except ε β)
| Except.ok a => f a
| Except.error e => pure (Except.error e)
@[inline] protected def bind {α β : Type u} (ma : ExceptT ε m α) (f : α → ExceptT ε m β) : ExceptT ε m β :=
ExceptT.mk $ ma >>= ExceptT.bindCont f
@[inline] protected def map {α β : Type u} (f : α → β) (x : ExceptT ε m α) : ExceptT ε m β :=
ExceptT.mk $ x >>= fun a => match a with
| (Except.ok a) => pure $ Except.ok (f a)
| (Except.error e) => pure $ Except.error e
@[inline] protected def lift {α : Type u} (t : m α) : ExceptT ε m α :=
ExceptT.mk $ Except.ok <$> t
instance exceptTOfExcept : MonadLift (Except ε) (ExceptT ε m) :=
⟨fun α e => ExceptT.mk $ pure e⟩
instance : MonadLift m (ExceptT ε m) :=
⟨@ExceptT.lift _ _ _⟩
@[inline] protected def catch {α : Type u} (ma : ExceptT ε m α) (handle : ε → ExceptT ε m α) : ExceptT ε m α :=
ExceptT.mk $ ma >>= fun res => match res with
| Except.ok a => pure (Except.ok a)
| Except.error e => (handle e)
instance (m') [Monad m'] : MonadFunctor m m' (ExceptT ε m) (ExceptT ε m') :=
⟨fun _ f x => f x⟩
instance : Monad (ExceptT ε m) :=
{ pure := @ExceptT.pure _ _ _, bind := @ExceptT.bind _ _ _, map := @ExceptT.map _ _ _ }
@[inline] protected def adapt {ε' α : Type u} (f : ε → ε') : ExceptT ε m α → ExceptT ε' m α :=
fun x => ExceptT.mk $ Except.mapError f <$> x
end ExceptT
/-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/
class MonadExceptOf (ε : Type u) (m : Type v → Type w) :=
(throw {α : Type v} : ε → m α)
(catch {α : Type v} : m α → (ε → m α) → m α)
abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α :=
MonadExceptOf.throw e
abbrev catchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α :=
MonadExceptOf.catch x handle
instance ExceptT.monadExceptParent (m : Type u → Type v) (ε₁ : Type u) (ε₂ : Type u) [Monad m] [MonadExceptOf ε₁ m] : MonadExceptOf ε₁ (ExceptT ε₂ m) :=
{ throw := fun α e => ExceptT.mk $ throwThe ε₁ e,
catch := fun α x handle => ExceptT.mk $ catchThe ε₁ x handle }
instance ExceptT.monadExceptSelf (m : Type u → Type v) (ε : Type u) [Monad m] : MonadExceptOf ε (ExceptT ε m) :=
{ throw := fun α e => ExceptT.mk $ pure (Except.error e),
catch := @ExceptT.catch ε _ _ }
instance (ε) : MonadExceptOf ε (Except ε) :=
{ throw := fun α => Except.error,
catch := @Except.catch _ }
/-- Similar to `MonadExceptOf`, but `ε` is an outParam for convenience -/
class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) :=
(throw {α : Type v} : ε → m α)
(catch {α : Type v} : m α → (ε → m α) → m α)
export MonadExcept (throw catch)
instance MonadExceptOf.isMonadExcept (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m :=
{ throw := fun _ e => throwThe ε e,
catch := fun _ x handle => catchThe ε x handle }
namespace MonadExcept
variables {ε : Type u} {m : Type v → Type w}
@[inline] protected def orelse [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) : m α :=
catch t₁ $ fun _ => t₂
instance [MonadExcept ε m] {α : Type v} : HasOrelse (m α) :=
⟨MonadExcept.orelse⟩
/-- Alternative orelse operator that allows to select which exception should be used.
The default is to use the first exception since the standard `orelse` uses the second. -/
@[inline] def orelse' [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) (useFirstEx := true) : m α :=
catch t₁ $ fun e₁ => catch t₂ $ fun e₂ => throw (if useFirstEx then e₁ else e₂)
end MonadExcept
/-- Adapt a Monad stack, changing its top-most error Type.
Note: This class can be seen as a simplification of the more "principled" definition
```
class MonadExceptFunctor (ε ε' : outParam (Type u)) (n n' : Type u → Type u) :=
(map {α : Type u} : (∀ {m : Type u → Type u} [Monad m], ExceptT ε m α → ExceptT ε' m α) → n α → n' α)
`` -/
class MonadExceptAdapter (ε ε' : outParam (Type u)) (m m' : Type u → Type v) :=
(adaptExcept {α : Type u} : (ε → ε') → m α → m' α)
export MonadExceptAdapter (adaptExcept)
section
variables {ε ε' : Type u} {m m' : Type u → Type v}
instance monadExceptAdapterTrans {n n' : Type u → Type v} [MonadExceptAdapter ε ε' m m'] [MonadFunctor m m' n n'] : MonadExceptAdapter ε ε' n n' :=
⟨fun α f => monadMap (fun α => (adaptExcept f : m α → m' α))⟩
instance [Monad m] : MonadExceptAdapter ε ε' (ExceptT ε m) (ExceptT ε' m) :=
⟨fun α => ExceptT.adapt⟩
end
instance (ε m out) [MonadRun out m] : MonadRun (fun α => out (Except ε α)) (ExceptT ε m) :=
⟨fun α => run⟩
@[inline] def observing {ε α : Type u} {m : Type u → Type v} [Monad m] [MonadExcept ε m] (x : m α) : m (Except ε α) :=
catch (do a ← x; pure (Except.ok a)) (fun ex => pure (Except.error ex))
instance ExceptT.monadControl (ε : Type u) (m : Type u → Type v) [Monad m] : MonadControl m (ExceptT ε m) := {
stM := fun α => Except ε α,
liftWith := fun α f => liftM $ f fun β x => x.run,
restoreM := fun α x => x,
}
class MonadFinally (m : Type u → Type v) :=
(finally' {α β} : m α → (Option α → m β) → m (α × β))
export MonadFinally (finally')
/-- Execute `x` and then execute `finalizer` even if `x` threw an exception -/
@[inline] abbrev finally {m : Type u → Type v} {α β : Type u} [MonadFinally m] [Functor m] (x : m α) (finalizer : m β) : m α := do
Prod.fst <$> finally' x (fun _ => finalizer)
instance Id.finally : MonadFinally Id :=
{ finally' := fun α β x h =>
let a := x;
let b := h (some x);
pure (a, b) }
instance ExceptT.finally {m : Type u → Type v} {ε : Type u} [MonadFinally m] [Monad m] : MonadFinally (ExceptT ε m) :=
{ finally' := fun α β x h => ExceptT.mk do
r ← finally' x (fun e? => match e? with
| some (Except.ok a) => h (some a)
| _ => h none);
match r with
| (Except.ok a, Except.ok b) => pure (Except.ok (a, b))
| (_, Except.error e) => pure (Except.error e) -- second error has precedence
| (Except.error e, _) => pure (Except.error e) }
|
86635dd0b816eede34605617836432e748502aa3 | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /library/algebra/complete_lattice.lean | d7e24a56f1d2d321331dcaa10ee911c94a45569b | [
"Apache-2.0"
] | permissive | davidmueller13/lean | 65a3ed141b4088cd0a268e4de80eb6778b21a0e9 | c626e2e3c6f3771e07c32e82ee5b9e030de5b050 | refs/heads/master | 1,611,278,313,401 | 1,444,021,177,000 | 1,444,021,177,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,967 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
Complete lattices
TODO: define dual complete lattice and simplify proof of dual theorems.
-/
import algebra.lattice data.set.basic
open set
namespace algebra
variable {A : Type}
structure complete_lattice [class] (A : Type) extends lattice A :=
(Inf : set A → A)
(Sup : set A → A)
(Inf_le : ∀ {a : A} {s : set A}, a ∈ s → le (Inf s) a)
(le_Inf : ∀ {b : A} {s : set A}, (∀ (a : A), a ∈ s → le b a) → le b (Inf s))
(le_Sup : ∀ {a : A} {s : set A}, a ∈ s → le a (Sup s))
(Sup_le : ∀ {b : A} {s : set A} (h : ∀ (a : A), a ∈ s → le a b), le (Sup s) b)
-- Minimal complete_lattice definition based just on Inf.
-- We latet show that complete_lattice_Inf is a complete_lattice
structure complete_lattice_Inf [class] (A : Type) extends weak_order A :=
(Inf : set A → A)
(Inf_le : ∀ {a : A} {s : set A}, a ∈ s → le (Inf s) a)
(le_Inf : ∀ {b : A} {s : set A}, (∀ (a : A), a ∈ s → le b a) → le b (Inf s))
-- Minimal complete_lattice definition based just on Sup.
-- We later show that complete_lattice_Sup is a complete_lattice
structure complete_lattice_Sup [class] (A : Type) extends weak_order A :=
(Sup : set A → A)
(le_Sup : ∀ {a : A} {s : set A}, a ∈ s → le a (Sup s))
(Sup_le : ∀ {b : A} {s : set A} (h : ∀ (a : A), a ∈ s → le a b), le (Sup s) b)
namespace complete_lattice_Inf
variable [C : complete_lattice_Inf A]
include C
definition Sup (s : set A) : A :=
Inf {b | ∀ a, a ∈ s → a ≤ b}
local prefix `⨅`:70 := Inf
local prefix `⨆`:65 := Sup
lemma le_Sup {a : A} {s : set A} : a ∈ s → a ≤ ⨆ s :=
suppose a ∈ s, le_Inf
(show ∀ (b : A), (∀ (a : A), a ∈ s → a ≤ b) → a ≤ b, from
take b, assume h, h a `a ∈ s`)
lemma Sup_le {b : A} {s : set A} (h : ∀ (a : A), a ∈ s → a ≤ b) : ⨆ s ≤ b :=
Inf_le h
definition inf (a b : A) := ⨅ '{a, b}
definition sup (a b : A) := ⨆ '{a, b}
local infix `⊓` := inf
local infix `⊔` := sup
lemma inf_le_left (a b : A) : a ⊓ b ≤ a :=
Inf_le !mem_insert
lemma inf_le_right (a b : A) : a ⊓ b ≤ b :=
Inf_le (!mem_insert_of_mem !mem_insert)
lemma le_inf {a b c : A} : c ≤ a → c ≤ b → c ≤ a ⊓ b :=
assume h₁ h₂,
le_Inf (take x, suppose x ∈ '{a, b},
or.elim (eq_or_mem_of_mem_insert this)
(suppose x = a, by subst x; assumption)
(suppose x ∈ '{b},
assert x = b, from !eq_of_mem_singleton this,
by subst x; assumption))
lemma le_sup_left (a b : A) : a ≤ a ⊔ b :=
le_Sup !mem_insert
lemma le_sup_right (a b : A) : b ≤ a ⊔ b :=
le_Sup (!mem_insert_of_mem !mem_insert)
lemma sup_le {a b c : A} : a ≤ c → b ≤ c → a ⊔ b ≤ c :=
assume h₁ h₂,
Sup_le (take x, suppose x ∈ '{a, b},
or.elim (eq_or_mem_of_mem_insert this)
(suppose x = a, by subst x; assumption)
(suppose x ∈ '{b},
assert x = b, from !eq_of_mem_singleton this,
by subst x; assumption))
end complete_lattice_Inf
-- Every complete_lattice_Inf is a complete_lattice_Sup
definition complete_lattice_Inf_to_complete_lattice_Sup [instance] [C : complete_lattice_Inf A] : complete_lattice_Sup A :=
⦃ complete_lattice_Sup, C ⦄
-- Every complete_lattice_Inf is a complete_lattice
definition complete_lattice_Inf_to_complete_lattice [instance] [C : complete_lattice_Inf A] : complete_lattice A :=
⦃ complete_lattice, C ⦄
namespace complete_lattice_Sup
variable [C : complete_lattice_Sup A]
include C
definition Inf (s : set A) : A :=
Sup {b | ∀ a, a ∈ s → b ≤ a}
lemma Inf_le {a : A} {s : set A} : a ∈ s → Inf s ≤ a :=
suppose a ∈ s, Sup_le
(show ∀ (b : A), (∀ (a : A), a ∈ s → b ≤ a) → b ≤ a, from
take b, assume h, h a `a ∈ s`)
lemma le_Inf {b : A} {s : set A} (h : ∀ (a : A), a ∈ s → b ≤ a) : b ≤ Inf s :=
le_Sup h
end complete_lattice_Sup
-- Every complete_lattice_Sup is a complete_lattice_Inf
definition complete_lattice_Sup_to_complete_lattice_Inf [instance] [C : complete_lattice_Sup A] : complete_lattice_Inf A :=
⦃ complete_lattice_Inf, C ⦄
-- Every complete_lattice_Sup is a complete_lattice
definition complete_lattice_Sup_to_complete_lattice [instance] [C : complete_lattice_Sup A] : complete_lattice A :=
_
namespace complete_lattice
variable [C : complete_lattice A]
include C
prefix `⨅`:70 := Inf
prefix `⨆`:65 := Sup
infix ` ⊓ ` := inf
infix ` ⊔ ` := sup
variable {f : A → A}
premise (mono : ∀ x y : A, x ≤ y → f x ≤ f y)
theorem knaster_tarski : ∃ a, f a = a ∧ ∀ b, f b = b → a ≤ b :=
let a := ⨅ {u | f u ≤ u} in
have h₁ : f a = a, from
have ge : f a ≤ a, from
have ∀ b, b ∈ {u | f u ≤ u} → f a ≤ b, from
take b, suppose f b ≤ b,
have a ≤ b, from Inf_le this,
have f a ≤ f b, from !mono this,
le.trans `f a ≤ f b` `f b ≤ b`,
le_Inf this,
have le : a ≤ f a, from
have f (f a) ≤ f a, from !mono ge,
have f a ∈ {u | f u ≤ u}, from this,
Inf_le this,
le.antisymm ge le,
have h₂ : ∀ b, f b = b → a ≤ b, from
take b,
suppose f b = b,
have b ∈ {u | f u ≤ u}, from
show f b ≤ b, by rewrite this; apply le.refl,
Inf_le this,
exists.intro a (and.intro h₁ h₂)
theorem knaster_tarski_dual : ∃ a, f a = a ∧ ∀ b, f b = b → b ≤ a :=
let a := ⨆ {u | u ≤ f u} in
have h₁ : f a = a, from
have le : a ≤ f a, from
have ∀ b, b ∈ {u | u ≤ f u} → b ≤ f a, from
take b, suppose b ≤ f b,
have b ≤ a, from le_Sup this,
have f b ≤ f a, from !mono this,
le.trans `b ≤ f b` `f b ≤ f a`,
Sup_le this,
have ge : f a ≤ a, from
have f a ≤ f (f a), from !mono le,
have f a ∈ {u | u ≤ f u}, from this,
le_Sup this,
le.antisymm ge le,
have h₂ : ∀ b, f b = b → b ≤ a, from
take b,
suppose f b = b,
have b ≤ f b, by rewrite this; apply le.refl,
le_Sup this,
exists.intro a (and.intro h₁ h₂)
definition bot : A := ⨅ univ
definition top : A := ⨆ univ
notation `⊥` := bot
notation `⊤` := top
lemma bot_le (a : A) : ⊥ ≤ a :=
Inf_le !mem_univ
lemma eq_bot {a : A} : (∀ b, a ≤ b) → a = ⊥ :=
assume h,
have a ≤ ⊥, from le_Inf (take b bin, h b),
le.antisymm this !bot_le
lemma le_top (a : A) : a ≤ ⊤ :=
le_Sup !mem_univ
lemma eq_top {a : A} : (∀ b, b ≤ a) → a = ⊤ :=
assume h,
have ⊤ ≤ a, from Sup_le (take b bin, h b),
le.antisymm !le_top this
lemma Inf_singleton {a : A} : ⨅'{a} = a :=
have ⨅'{a} ≤ a, from
Inf_le !mem_insert,
have a ≤ ⨅'{a}, from
le_Inf (take b, suppose b ∈ '{a}, assert b = a, from eq_of_mem_singleton this, by rewrite this; apply le.refl),
le.antisymm `⨅'{a} ≤ a` `a ≤ ⨅'{a}`
lemma Sup_singleton {a : A} : ⨆'{a} = a :=
have ⨆'{a} ≤ a, from
Sup_le (take b, suppose b ∈ '{a}, assert b = a, from eq_of_mem_singleton this, by rewrite this; apply le.refl),
have a ≤ ⨆'{a}, from
le_Sup !mem_insert,
le.antisymm `⨆'{a} ≤ a` `a ≤ ⨆'{a}`
lemma Inf_antimono {s₁ s₂ : set A} : s₁ ⊆ s₂ → ⨅ s₂ ≤ ⨅ s₁ :=
suppose s₁ ⊆ s₂, le_Inf (take a : A, suppose a ∈ s₁, Inf_le (mem_of_subset_of_mem `s₁ ⊆ s₂` `a ∈ s₁`))
lemma Sup_mono {s₁ s₂ : set A} : s₁ ⊆ s₂ → ⨆ s₁ ≤ ⨆ s₂ :=
suppose s₁ ⊆ s₂, Sup_le (take a : A, suppose a ∈ s₁, le_Sup (mem_of_subset_of_mem `s₁ ⊆ s₂` `a ∈ s₁`))
lemma Inf_union (s₁ s₂ : set A) : ⨅ (s₁ ∪ s₂) = (⨅s₁) ⊓ (⨅s₂) :=
have le₁ : ⨅ (s₁ ∪ s₂) ≤ (⨅s₁) ⊓ (⨅s₂), from
!le_inf
(le_Inf (take a : A, suppose a ∈ s₁, Inf_le (mem_unionl `a ∈ s₁`)))
(le_Inf (take a : A, suppose a ∈ s₂, Inf_le (mem_unionr `a ∈ s₂`))),
have le₂ : (⨅s₁) ⊓ (⨅s₂) ≤ ⨅ (s₁ ∪ s₂), from
le_Inf (take a : A, suppose a ∈ s₁ ∪ s₂,
or.elim this
(suppose a ∈ s₁,
have (⨅s₁) ⊓ (⨅s₂) ≤ ⨅s₁, from !inf_le_left,
have ⨅s₁ ≤ a, from Inf_le `a ∈ s₁`,
le.trans `(⨅s₁) ⊓ (⨅s₂) ≤ ⨅s₁` `⨅s₁ ≤ a`)
(suppose a ∈ s₂,
have (⨅s₁) ⊓ (⨅s₂) ≤ ⨅s₂, from !inf_le_right,
have ⨅s₂ ≤ a, from Inf_le `a ∈ s₂`,
le.trans `(⨅s₁) ⊓ (⨅s₂) ≤ ⨅s₂` `⨅s₂ ≤ a`)),
le.antisymm le₁ le₂
lemma Sup_union (s₁ s₂ : set A) : ⨆ (s₁ ∪ s₂) = (⨆s₁) ⊔ (⨆s₂) :=
have le₁ : ⨆ (s₁ ∪ s₂) ≤ (⨆s₁) ⊔ (⨆s₂), from
Sup_le (take a : A, suppose a ∈ s₁ ∪ s₂,
or.elim this
(suppose a ∈ s₁,
have a ≤ ⨆s₁, from le_Sup `a ∈ s₁`,
have ⨆s₁ ≤ (⨆s₁) ⊔ (⨆s₂), from !le_sup_left,
le.trans `a ≤ ⨆s₁` `⨆s₁ ≤ (⨆s₁) ⊔ (⨆s₂)`)
(suppose a ∈ s₂,
have a ≤ ⨆s₂, from le_Sup `a ∈ s₂`,
have ⨆s₂ ≤ (⨆s₁) ⊔ (⨆s₂), from !le_sup_right,
le.trans `a ≤ ⨆s₂` `⨆s₂ ≤ (⨆s₁) ⊔ (⨆s₂)`)),
have le₂ : (⨆s₁) ⊔ (⨆s₂) ≤ ⨆ (s₁ ∪ s₂), from
!sup_le
(Sup_le (take a : A, suppose a ∈ s₁, le_Sup (mem_unionl `a ∈ s₁`)))
(Sup_le (take a : A, suppose a ∈ s₂, le_Sup (mem_unionr `a ∈ s₂`))),
le.antisymm le₁ le₂
lemma Inf_empty_eq_Sup_univ : ⨅ (∅ : set A) = ⨆ univ :=
have le₁ : ⨅ ∅ ≤ ⨆ univ, from
le_Sup !mem_univ,
have le₂ : ⨆ univ ≤ ⨅ ∅, from
le_Inf (take a, suppose a ∈ ∅, absurd this !not_mem_empty),
le.antisymm le₁ le₂
lemma Sup_empty_eq_Inf_univ : ⨆ (∅ : set A) = ⨅ univ :=
have le₁ : ⨆ (∅ : set A) ≤ ⨅ univ, from
Sup_le (take a, suppose a ∈ ∅, absurd this !not_mem_empty),
have le₂ : ⨅ univ ≤ ⨆ (∅ : set A), from
Inf_le !mem_univ,
le.antisymm le₁ le₂
end complete_lattice
end algebra
|
e6b1c88ce0a9a0553b620060e3127fcf71db0380 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/measure_theory/function/convergence_in_measure.lean | a641cdf84b018d24cdd66084edb460359e21c5bf | [
"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 | 16,852 | lean | /-
Copyright (c) 2022 Rémy Degenne, Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne, Kexing Ying
-/
import measure_theory.function.egorov
/-!
# Convergence in measure
We define convergence in measure which is one of the many notions of convergence in probability.
A sequence of functions `f` is said to converge in measure to some function `g`
if for all `ε > 0`, the measure of the set `{x | ε ≤ dist (f i x) (g x)}` tends to 0 as `i`
converges along some given filter `l`.
Convergence in measure is most notably used in the formulation of the weak law of large numbers
and is also useful in theorems such as the Vitali convergence theorem. This file provides some
basic lemmas for working with convergence in measure and establishes some relations between
convergence in measure and other notions of convergence.
## Main definitions
* `measure_theory.tendsto_in_measure (μ : measure α) (f : ι → α → E) (g : α → E)`: `f` converges
in `μ`-measure to `g`.
## Main results
* `measure_theory.tendsto_in_measure_of_tendsto_ae`: convergence almost everywhere in a finite
measure space implies convergence in measure.
* `measure_theory.tendsto_in_measure.exists_seq_tendsto_ae`: if `f` is a sequence of functions
which converges in measure to `g`, then `f` has a subsequence which convergence almost
everywhere to `g`.
* `measure_theory.tendsto_in_measure_of_tendsto_snorm`: convergence in Lp implies convergence
in measure.
-/
open topological_space filter
open_locale nnreal ennreal measure_theory topological_space
namespace measure_theory
variables {α ι E : Type*} {m : measurable_space α} {μ : measure α}
/-- A sequence of functions `f` is said to converge in measure to some function `g` if for all
`ε > 0`, the measure of the set `{x | ε ≤ dist (f i x) (g x)}` tends to 0 as `i` converges along
some given filter `l`. -/
def tendsto_in_measure [has_dist E] {m : measurable_space α}
(μ : measure α) (f : ι → α → E) (l : filter ι) (g : α → E) : Prop :=
∀ ε (hε : 0 < ε), tendsto (λ i, μ {x | ε ≤ dist (f i x) (g x)}) l (𝓝 0)
lemma tendsto_in_measure_iff_norm [semi_normed_group E] {l : filter ι}
{f : ι → α → E} {g : α → E} :
tendsto_in_measure μ f l g
↔ ∀ ε (hε : 0 < ε), tendsto (λ i, μ {x | ε ≤ ∥f i x - g x∥}) l (𝓝 0) :=
by simp_rw [tendsto_in_measure, dist_eq_norm]
namespace tendsto_in_measure
variables [has_dist E] {l : filter ι} {f f' : ι → α → E} {g g' : α → E}
protected lemma congr' (h_left : ∀ᶠ i in l, f i =ᵐ[μ] f' i) (h_right : g =ᵐ[μ] g')
(h_tendsto : tendsto_in_measure μ f l g) :
tendsto_in_measure μ f' l g' :=
begin
intros ε hε,
suffices : (λ i, μ {x | ε ≤ dist (f' i x) (g' x)})
=ᶠ[l] (λ i, μ {x | ε ≤ dist (f i x) (g x)}),
{ rw tendsto_congr' this,
exact h_tendsto ε hε, },
filter_upwards [h_left] with i h_ae_eq,
refine measure_congr _,
filter_upwards [h_ae_eq, h_right] with x hxf hxg,
rw eq_iff_iff,
change ε ≤ dist (f' i x) (g' x) ↔ ε ≤ dist (f i x) (g x),
rw [hxg, hxf],
end
protected lemma congr (h_left : ∀ i, f i =ᵐ[μ] f' i) (h_right : g =ᵐ[μ] g')
(h_tendsto : tendsto_in_measure μ f l g) :
tendsto_in_measure μ f' l g' :=
tendsto_in_measure.congr' (eventually_of_forall h_left) h_right h_tendsto
lemma congr_left (h : ∀ i, f i =ᵐ[μ] f' i) (h_tendsto : tendsto_in_measure μ f l g) :
tendsto_in_measure μ f' l g :=
h_tendsto.congr h (eventually_eq.rfl)
lemma congr_right (h : g =ᵐ[μ] g') (h_tendsto : tendsto_in_measure μ f l g) :
tendsto_in_measure μ f l g' :=
h_tendsto.congr (λ i, eventually_eq.rfl) h
end tendsto_in_measure
section exists_seq_tendsto_ae
variables [metric_space E]
variables {f : ℕ → α → E} {g : α → E}
/-- Auxiliary lemma for `tendsto_in_measure_of_tendsto_ae`. -/
lemma tendsto_in_measure_of_tendsto_ae_of_strongly_measurable [is_finite_measure μ]
(hf : ∀ n, strongly_measurable (f n)) (hg : strongly_measurable g)
(hfg : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x))) :
tendsto_in_measure μ f at_top g :=
begin
refine λ ε hε, ennreal.tendsto_at_top_zero.mpr (λ δ hδ, _),
by_cases hδi : δ = ∞,
{ simp only [hδi, implies_true_iff, le_top, exists_const], },
lift δ to ℝ≥0 using hδi,
rw [gt_iff_lt, ennreal.coe_pos, ← nnreal.coe_pos] at hδ,
obtain ⟨t, htm, ht, hunif⟩ := tendsto_uniformly_on_of_ae_tendsto' hf hg hfg hδ,
rw ennreal.of_real_coe_nnreal at ht,
rw metric.tendsto_uniformly_on_iff at hunif,
obtain ⟨N, hN⟩ := eventually_at_top.1 (hunif ε hε),
refine ⟨N, λ n hn, _⟩,
suffices : {x : α | ε ≤ dist (f n x) (g x)} ⊆ t, from (measure_mono this).trans ht,
rw ← set.compl_subset_compl,
intros x hx,
rw [set.mem_compl_eq, set.nmem_set_of_eq, dist_comm, not_le],
exact hN n hn x hx,
end
/-- Convergence a.e. implies convergence in measure in a finite measure space. -/
lemma tendsto_in_measure_of_tendsto_ae [is_finite_measure μ]
(hf : ∀ n, ae_strongly_measurable (f n) μ)
(hfg : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x))) :
tendsto_in_measure μ f at_top g :=
begin
have hg : ae_strongly_measurable g μ, from ae_strongly_measurable_of_tendsto_ae _ hf hfg,
refine tendsto_in_measure.congr (λ i, (hf i).ae_eq_mk.symm) hg.ae_eq_mk.symm _,
refine tendsto_in_measure_of_tendsto_ae_of_strongly_measurable
(λ i, (hf i).strongly_measurable_mk) hg.strongly_measurable_mk _,
have hf_eq_ae : ∀ᵐ x ∂μ, ∀ n, (hf n).mk (f n) x = f n x,
from ae_all_iff.mpr (λ n, (hf n).ae_eq_mk.symm),
filter_upwards [hf_eq_ae, hg.ae_eq_mk, hfg] with x hxf hxg hxfg,
rw [← hxg, funext (λ n, hxf n)],
exact hxfg,
end
namespace exists_seq_tendsto_ae
lemma exists_nat_measure_lt_two_inv (hfg : tendsto_in_measure μ f at_top g) (n : ℕ) :
∃ N, ∀ m ≥ N, μ {x | 2⁻¹ ^ n ≤ dist (f m x) (g x)} ≤ 2⁻¹ ^ n :=
begin
specialize hfg (2⁻¹ ^ n) (by simp only [zero_lt_bit0, pow_pos, zero_lt_one, inv_pos]),
rw ennreal.tendsto_at_top_zero at hfg,
exact hfg (2⁻¹ ^ n) (pos_iff_ne_zero.mpr (λ h_zero, by simpa using pow_eq_zero h_zero))
end
/-- Given a sequence of functions `f` which converges in measure to `g`,
`seq_tendsto_ae_seq_aux` is a sequence such that
`∀ m ≥ seq_tendsto_ae_seq_aux n, μ {x | 2⁻¹ ^ n ≤ dist (f m x) (g x)} ≤ 2⁻¹ ^ n`. -/
noncomputable
def seq_tendsto_ae_seq_aux (hfg : tendsto_in_measure μ f at_top g) (n : ℕ) :=
classical.some (exists_nat_measure_lt_two_inv hfg n)
/-- Transformation of `seq_tendsto_ae_seq_aux` to makes sure it is strictly monotone. -/
noncomputable
def seq_tendsto_ae_seq (hfg : tendsto_in_measure μ f at_top g) : ℕ → ℕ
| 0 := seq_tendsto_ae_seq_aux hfg 0
| (n + 1) := max (seq_tendsto_ae_seq_aux hfg (n + 1))
(seq_tendsto_ae_seq n + 1)
lemma seq_tendsto_ae_seq_succ (hfg : tendsto_in_measure μ f at_top g) {n : ℕ} :
seq_tendsto_ae_seq hfg (n + 1) =
max (seq_tendsto_ae_seq_aux hfg (n + 1)) (seq_tendsto_ae_seq hfg n + 1) :=
by rw seq_tendsto_ae_seq
lemma seq_tendsto_ae_seq_spec (hfg : tendsto_in_measure μ f at_top g)
(n k : ℕ) (hn : seq_tendsto_ae_seq hfg n ≤ k) :
μ {x | 2⁻¹ ^ n ≤ dist (f k x) (g x)} ≤ 2⁻¹ ^ n :=
begin
cases n,
{ exact classical.some_spec (exists_nat_measure_lt_two_inv hfg 0) k hn },
{ exact classical.some_spec (exists_nat_measure_lt_two_inv hfg _) _
(le_trans (le_max_left _ _) hn) }
end
lemma seq_tendsto_ae_seq_strict_mono (hfg : tendsto_in_measure μ f at_top g) :
strict_mono (seq_tendsto_ae_seq hfg) :=
begin
refine strict_mono_nat_of_lt_succ (λ n, _),
rw seq_tendsto_ae_seq_succ,
exact lt_of_lt_of_le (lt_add_one $ seq_tendsto_ae_seq hfg n) (le_max_right _ _),
end
end exists_seq_tendsto_ae
/-- If `f` is a sequence of functions which converges in measure to `g`, then there exists a
subsequence of `f` which converges a.e. to `g`. -/
lemma tendsto_in_measure.exists_seq_tendsto_ae
(hfg : tendsto_in_measure μ f at_top g) :
∃ ns : ℕ → ℕ, strict_mono ns ∧ ∀ᵐ x ∂μ, tendsto (λ i, f (ns i) x) at_top (𝓝 (g x)) :=
begin
/- Since `f` tends to `g` in measure, it has a subsequence `k ↦ f (ns k)` such that
`μ {|f (ns k) - g| ≥ 2⁻ᵏ} ≤ 2⁻ᵏ` for all `k`. Defining
`s := ⋂ k, ⋃ i ≥ k, {|f (ns k) - g| ≥ 2⁻ᵏ}`, we see that `μ s = 0` by the
first Borel-Cantelli lemma.
On the other hand, as `s` is precisely the set for which `f (ns k)`
doesn't converge to `g`, `f (ns k)` converges almost everywhere to `g` as required. -/
have h_lt_ε_real : ∀ (ε : ℝ) (hε : 0 < ε), ∃ k : ℕ, 2 * 2⁻¹ ^ k < ε,
{ intros ε hε,
obtain ⟨k, h_k⟩ : ∃ (k : ℕ), 2⁻¹ ^ k < ε := exists_pow_lt_of_lt_one hε (by norm_num),
refine ⟨k + 1, (le_of_eq _).trans_lt h_k⟩,
rw pow_add, ring },
set ns := exists_seq_tendsto_ae.seq_tendsto_ae_seq hfg,
use ns,
let S := λ k, {x | 2⁻¹ ^ k ≤ dist (f (ns k) x) (g x)},
have hμS_le : ∀ k, μ (S k) ≤ 2⁻¹ ^ k :=
λ k, exists_seq_tendsto_ae.seq_tendsto_ae_seq_spec hfg k (ns k) (le_rfl),
set s := filter.at_top.limsup S with hs,
have hμs : μ s = 0,
{ refine measure_limsup_eq_zero (ne_of_lt $ lt_of_le_of_lt (ennreal.tsum_le_tsum hμS_le) _),
simp only [ennreal.tsum_geometric, ennreal.one_sub_inv_two, inv_inv],
dec_trivial },
have h_tendsto : ∀ x ∈ sᶜ, tendsto (λ i, f (ns i) x) at_top (𝓝 (g x)),
{ refine λ x hx, metric.tendsto_at_top.mpr (λ ε hε, _),
rw [hs, limsup_eq_infi_supr_of_nat] at hx,
simp only [set.supr_eq_Union, set.infi_eq_Inter, set.compl_Inter, set.compl_Union,
set.mem_Union, set.mem_Inter, set.mem_compl_eq, set.mem_set_of_eq, not_le] at hx,
obtain ⟨N, hNx⟩ := hx,
obtain ⟨k, hk_lt_ε⟩ := h_lt_ε_real ε hε,
refine ⟨max N (k - 1), λ n hn_ge, lt_of_le_of_lt _ hk_lt_ε⟩,
specialize hNx n ((le_max_left _ _).trans hn_ge),
have h_inv_n_le_k : (2 : ℝ)⁻¹ ^ n ≤ 2 * 2⁻¹ ^ k,
{ rw [mul_comm, ← inv_mul_le_iff' (@two_pos ℝ _ _)],
conv_lhs { congr, rw ← pow_one (2 : ℝ)⁻¹ },
rw [← pow_add, add_comm],
exact pow_le_pow_of_le_one ((one_div (2 : ℝ)) ▸ one_half_pos.le) (inv_le_one one_le_two)
((le_tsub_add.trans (add_le_add_right (le_max_right _ _) 1)).trans
(add_le_add_right hn_ge 1)) },
exact le_trans hNx.le h_inv_n_le_k },
rw ae_iff,
refine ⟨exists_seq_tendsto_ae.seq_tendsto_ae_seq_strict_mono hfg, measure_mono_null (λ x, _) hμs⟩,
rw [set.mem_set_of_eq, ← @not_not (x ∈ s), not_imp_not],
exact h_tendsto x,
end
lemma tendsto_in_measure.exists_seq_tendsto_in_measure_at_top
{u : filter ι} [ne_bot u] [is_countably_generated u] {f : ι → α → E} {g : α → E}
(hfg : tendsto_in_measure μ f u g) :
∃ ns : ℕ → ι, tendsto_in_measure μ (λ n, f (ns n)) at_top g :=
begin
obtain ⟨ns, h_tendsto_ns⟩ : ∃ (ns : ℕ → ι), tendsto ns at_top u := exists_seq_tendsto u,
exact ⟨ns, λ ε hε, (hfg ε hε).comp h_tendsto_ns⟩,
end
lemma tendsto_in_measure.exists_seq_tendsto_ae'
{u : filter ι} [ne_bot u] [is_countably_generated u] {f : ι → α → E} {g : α → E}
(hfg : tendsto_in_measure μ f u g) :
∃ ns : ℕ → ι, ∀ᵐ x ∂μ, tendsto (λ i, f (ns i) x) at_top (𝓝 (g x)) :=
begin
obtain ⟨ms, hms⟩ := hfg.exists_seq_tendsto_in_measure_at_top,
obtain ⟨ns, -, hns⟩ := hms.exists_seq_tendsto_ae,
exact ⟨ms ∘ ns, hns⟩,
end
end exists_seq_tendsto_ae
section ae_measurable_of
variables [measurable_space E] [normed_group E] [borel_space E]
lemma tendsto_in_measure.ae_measurable
{u : filter ι} [ne_bot u] [is_countably_generated u]
{f : ι → α → E} {g : α → E} (hf : ∀ n, ae_measurable (f n) μ)
(h_tendsto : tendsto_in_measure μ f u g) :
ae_measurable g μ :=
begin
obtain ⟨ns, hns⟩ := h_tendsto.exists_seq_tendsto_ae',
exact ae_measurable_of_tendsto_metric_ae at_top (λ n, hf (ns n)) hns,
end
end ae_measurable_of
section tendsto_in_measure_of
variables [normed_group E] {p : ℝ≥0∞}
variables {f : ι → α → E} {g : α → E}
/-- This lemma is superceded by `measure_theory.tendsto_in_measure_of_tendsto_snorm` where we
allow `p = ∞` and only require `ae_strongly_measurable`. -/
lemma tendsto_in_measure_of_tendsto_snorm_of_strongly_measurable
(hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞)
(hf : ∀ n, strongly_measurable (f n)) (hg : strongly_measurable g) {l : filter ι}
(hfg : tendsto (λ n, snorm (f n - g) p μ) l (𝓝 0)) :
tendsto_in_measure μ f l g :=
begin
intros ε hε,
replace hfg := ennreal.tendsto.const_mul (tendsto.ennrpow_const p.to_real hfg)
(or.inr $ @ennreal.of_real_ne_top (1 / ε ^ (p.to_real))),
simp only [mul_zero, ennreal.zero_rpow_of_pos (ennreal.to_real_pos hp_ne_zero hp_ne_top)] at hfg,
rw ennreal.tendsto_nhds_zero at hfg ⊢,
intros δ hδ,
refine (hfg δ hδ).mono (λ n hn, _),
refine le_trans _ hn,
rw [ennreal.of_real_div_of_pos (real.rpow_pos_of_pos hε _), ennreal.of_real_one, mul_comm,
mul_one_div, ennreal.le_div_iff_mul_le _ (or.inl (ennreal.of_real_ne_top)), mul_comm],
{ convert mul_meas_ge_le_pow_snorm' μ hp_ne_zero hp_ne_top ((hf n).sub hg).ae_strongly_measurable
(ennreal.of_real ε),
{ exact (ennreal.of_real_rpow_of_pos hε).symm },
{ ext x,
rw [dist_eq_norm, ← ennreal.of_real_le_of_real_iff (norm_nonneg _),
of_real_norm_eq_coe_nnnorm],
exact iff.rfl } },
{ rw [ne, ennreal.of_real_eq_zero, not_le],
exact or.inl (real.rpow_pos_of_pos hε _) },
end
/-- This lemma is superceded by `measure_theory.tendsto_in_measure_of_tendsto_snorm` where we
allow `p = ∞`. -/
lemma tendsto_in_measure_of_tendsto_snorm_of_ne_top
(hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞)
(hf : ∀ n, ae_strongly_measurable (f n) μ) (hg : ae_strongly_measurable g μ) {l : filter ι}
(hfg : tendsto (λ n, snorm (f n - g) p μ) l (𝓝 0)) :
tendsto_in_measure μ f l g :=
begin
refine tendsto_in_measure.congr (λ i, (hf i).ae_eq_mk.symm) hg.ae_eq_mk.symm _,
refine tendsto_in_measure_of_tendsto_snorm_of_strongly_measurable hp_ne_zero hp_ne_top
(λ i, (hf i).strongly_measurable_mk) hg.strongly_measurable_mk _,
have : (λ n, snorm ((hf n).mk (f n) - hg.mk g) p μ) = (λ n, snorm (f n - g) p μ),
{ ext1 n, refine snorm_congr_ae (eventually_eq.sub (hf n).ae_eq_mk.symm hg.ae_eq_mk.symm), },
rw this,
exact hfg,
end
/-- See also `measure_theory.tendsto_in_measure_of_tendsto_snorm` which work for general
Lp-convergence for all `p ≠ 0`. -/
lemma tendsto_in_measure_of_tendsto_snorm_top {E} [normed_group E] {f : ι → α → E} {g : α → E}
{l : filter ι} (hfg : tendsto (λ n, snorm (f n - g) ∞ μ) l (𝓝 0)) :
tendsto_in_measure μ f l g :=
begin
intros δ hδ,
simp only [snorm_exponent_top, snorm_ess_sup] at hfg,
rw ennreal.tendsto_nhds_zero at hfg ⊢,
intros ε hε,
specialize hfg ((ennreal.of_real δ) / 2) (ennreal.div_pos_iff.2
⟨(ennreal.of_real_pos.2 hδ).ne.symm, ennreal.two_ne_top⟩),
refine hfg.mono (λ n hn, _),
simp only [true_and, gt_iff_lt, ge_iff_le, zero_tsub, zero_le, zero_add, set.mem_Icc,
pi.sub_apply] at *,
have : ess_sup (λ (x : α), (∥f n x - g x∥₊ : ℝ≥0∞)) μ < ennreal.of_real δ :=
lt_of_le_of_lt hn (ennreal.half_lt_self (ennreal.of_real_pos.2 hδ).ne.symm
ennreal.of_real_lt_top.ne),
refine ((le_of_eq _).trans (ae_lt_of_ess_sup_lt this).le).trans hε.le,
congr' with x,
simp only [ennreal.of_real_le_iff_le_to_real ennreal.coe_lt_top.ne, ennreal.coe_to_real,
not_lt, coe_nnnorm, set.mem_set_of_eq, set.mem_compl_eq],
rw ← dist_eq_norm (f n x) (g x),
refl
end
/-- Convergence in Lp implies convergence in measure. -/
lemma tendsto_in_measure_of_tendsto_snorm {l : filter ι}
(hp_ne_zero : p ≠ 0) (hf : ∀ n, ae_strongly_measurable (f n) μ) (hg : ae_strongly_measurable g μ)
(hfg : tendsto (λ n, snorm (f n - g) p μ) l (𝓝 0)) :
tendsto_in_measure μ f l g :=
begin
by_cases hp_ne_top : p = ∞,
{ subst hp_ne_top,
exact tendsto_in_measure_of_tendsto_snorm_top hfg },
{ exact tendsto_in_measure_of_tendsto_snorm_of_ne_top hp_ne_zero hp_ne_top hf hg hfg }
end
/-- Convergence in Lp implies convergence in measure. -/
lemma tendsto_in_measure_of_tendsto_Lp [hp : fact (1 ≤ p)]
{f : ι → Lp E p μ} {g : Lp E p μ} {l : filter ι} (hfg : tendsto f l (𝓝 g)) :
tendsto_in_measure μ (λ n, f n) l g :=
tendsto_in_measure_of_tendsto_snorm (ennreal.zero_lt_one.trans_le hp.elim).ne.symm
(λ n, Lp.ae_strongly_measurable _) (Lp.ae_strongly_measurable _)
((Lp.tendsto_Lp_iff_tendsto_ℒp' _ _).mp hfg)
end tendsto_in_measure_of
end measure_theory
|
7008d22b12284c8aeebd252de46f23bdd199dac8 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/group_theory/submonoid/membership.lean | b6e020331a6430a0a24caadcbda04d0430fd73e2 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,745 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard,
Amelia Livingston, Yury Kudryashov
-/
import group_theory.submonoid.operations
import algebra.big_operators.basic
import algebra.free_monoid
import algebra.pointwise
/-!
# Submonoids: membership criteria
In this file we prove various facts about membership in a submonoid:
* `list_prod_mem`, `multiset_prod_mem`, `prod_mem`: if each element of a collection belongs
to a multiplicative submonoid, then so does their product;
* `list_sum_mem`, `multiset_sum_mem`, `sum_mem`: if each element of a collection belongs
to an additive submonoid, then so does their sum;
* `pow_mem`, `nsmul_mem`: if `x ∈ S` where `S` is a multiplicative (resp., additive) submonoid and
`n` is a natural number, then `x^n` (resp., `n • x`) belongs to `S`;
* `mem_supr_of_directed`, `coe_supr_of_directed`, `mem_Sup_of_directed_on`,
`coe_Sup_of_directed_on`: the supremum of a directed collection of submonoid is their union.
* `sup_eq_range`, `mem_sup`: supremum of two submonoids `S`, `T` of a commutative monoid is the set
of products;
* `closure_singleton_eq`, `mem_closure_singleton`: the multiplicative (resp., additive) closure
of `{x}` consists of powers (resp., natural multiples) of `x`.
## Tags
submonoid, submonoids
-/
open_locale big_operators
variables {M : Type*}
variables {A : Type*}
namespace submonoid
section assoc
variables [monoid M] (S : submonoid M)
@[simp, norm_cast] theorem coe_pow (x : S) (n : ℕ) : ↑(x ^ n) = (x ^ n : M) :=
S.subtype.map_pow x n
@[simp, norm_cast] theorem coe_list_prod (l : list S) : (l.prod : M) = (l.map coe).prod :=
S.subtype.map_list_prod l
@[simp, norm_cast] theorem coe_multiset_prod {M} [comm_monoid M] (S : submonoid M)
(m : multiset S) : (m.prod : M) = (m.map coe).prod :=
S.subtype.map_multiset_prod m
@[simp, norm_cast] theorem coe_finset_prod {ι M} [comm_monoid M] (S : submonoid M)
(f : ι → S) (s : finset ι) :
↑(∏ i in s, f i) = (∏ i in s, f i : M) :=
S.subtype.map_prod f s
/-- Product of a list of elements in a submonoid is in the submonoid. -/
@[to_additive "Sum of a list of elements in an `add_submonoid` is in the `add_submonoid`."]
lemma list_prod_mem : ∀ {l : list M}, (∀x ∈ l, x ∈ S) → l.prod ∈ S
| [] h := S.one_mem
| (a::l) h :=
suffices a * l.prod ∈ S, by rwa [list.prod_cons],
have a ∈ S ∧ (∀ x ∈ l, x ∈ S), from list.forall_mem_cons.1 h,
S.mul_mem this.1 (list_prod_mem this.2)
/-- Product of a multiset of elements in a submonoid of a `comm_monoid` is in the submonoid. -/
@[to_additive "Sum of a multiset of elements in an `add_submonoid` of an `add_comm_monoid` is
in the `add_submonoid`."]
lemma multiset_prod_mem {M} [comm_monoid M] (S : submonoid M) (m : multiset M) :
(∀a ∈ m, a ∈ S) → m.prod ∈ S :=
begin
refine quotient.induction_on m (assume l hl, _),
rw [multiset.quot_mk_to_coe, multiset.coe_prod],
exact S.list_prod_mem hl
end
/-- Product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is in the
submonoid. -/
@[to_additive "Sum of elements in an `add_submonoid` of an `add_comm_monoid` indexed by a `finset`
is in the `add_submonoid`."]
lemma prod_mem {M : Type*} [comm_monoid M] (S : submonoid M)
{ι : Type*} {t : finset ι} {f : ι → M} (h : ∀c ∈ t, f c ∈ S) :
∏ c in t, f c ∈ S :=
S.multiset_prod_mem (t.1.map f) $ λ x hx, let ⟨i, hi, hix⟩ := multiset.mem_map.1 hx in hix ▸ h i hi
lemma pow_mem {x : M} (hx : x ∈ S) (n : ℕ) : x ^ n ∈ S :=
by simpa only [coe_pow] using ((⟨x, hx⟩ : S) ^ n).coe_prop
end assoc
section non_assoc
variables [mul_one_class M] (S : submonoid M)
open set
@[to_additive]
lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → submonoid M} (hS : directed (≤) S)
{x : M} :
x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i :=
begin
refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩,
suffices : x ∈ closure (⋃ i, (S i : set M)) → ∃ i, x ∈ S i,
by simpa only [closure_Union, closure_eq (S _)] using this,
refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _),
{ exact hι.elim (λ i, ⟨i, (S i).one_mem⟩) },
{ rintros x y ⟨i, hi⟩ ⟨j, hj⟩,
rcases hS i j with ⟨k, hki, hkj⟩,
exact ⟨k, (S k).mul_mem (hki hi) (hkj hj)⟩ }
end
@[to_additive]
lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → submonoid M} (hS : directed (≤) S) :
((⨆ i, S i : submonoid M) : set M) = ⋃ i, ↑(S i) :=
set.ext $ λ x, by simp [mem_supr_of_directed hS]
@[to_additive]
lemma mem_Sup_of_directed_on {S : set (submonoid M)} (Sne : S.nonempty)
(hS : directed_on (≤) S) {x : M} :
x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s :=
begin
haveI : nonempty S := Sne.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk]
end
@[to_additive]
lemma coe_Sup_of_directed_on {S : set (submonoid M)} (Sne : S.nonempty) (hS : directed_on (≤) S) :
(↑(Sup S) : set M) = ⋃ s ∈ S, ↑s :=
set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS]
@[to_additive]
lemma mem_sup_left {S T : submonoid M} : ∀ {x : M}, x ∈ S → x ∈ S ⊔ T :=
show S ≤ S ⊔ T, from le_sup_left
@[to_additive]
lemma mem_sup_right {S T : submonoid M} : ∀ {x : M}, x ∈ T → x ∈ S ⊔ T :=
show T ≤ S ⊔ T, from le_sup_right
@[to_additive]
lemma mem_supr_of_mem {ι : Type*} {S : ι → submonoid M} (i : ι) :
∀ {x : M}, x ∈ S i → x ∈ supr S :=
show S i ≤ supr S, from le_supr _ _
@[to_additive]
lemma mem_Sup_of_mem {S : set (submonoid M)} {s : submonoid M}
(hs : s ∈ S) : ∀ {x : M}, x ∈ s → x ∈ Sup S :=
show s ≤ Sup S, from le_Sup hs
end non_assoc
end submonoid
namespace free_monoid
variables {α : Type*}
open submonoid
@[to_additive]
theorem closure_range_of : closure (set.range $ @of α) = ⊤ :=
eq_top_iff.2 $ λ x hx, free_monoid.rec_on x (one_mem _) $ λ x xs hxs,
mul_mem _ (subset_closure $ set.mem_range_self _) hxs
end free_monoid
namespace submonoid
variables [monoid M]
open monoid_hom
lemma closure_singleton_eq (x : M) : closure ({x} : set M) = (powers_hom M x).mrange :=
closure_eq_of_le (set.singleton_subset_iff.2 ⟨multiplicative.of_add 1, pow_one x⟩) $
λ x ⟨n, hn⟩, hn ▸ pow_mem _ (subset_closure $ set.mem_singleton _) _
/-- The submonoid generated by an element of a monoid equals the set of natural number powers of
the element. -/
lemma mem_closure_singleton {x y : M} : y ∈ closure ({x} : set M) ↔ ∃ n:ℕ, x^n=y :=
by rw [closure_singleton_eq, mem_mrange]; refl
lemma mem_closure_singleton_self {y : M} : y ∈ closure ({y} : set M) :=
mem_closure_singleton.2 ⟨1, pow_one y⟩
lemma closure_singleton_one : closure ({1} : set M) = ⊥ :=
by simp [eq_bot_iff_forall, mem_closure_singleton]
@[to_additive]
lemma closure_eq_mrange (s : set M) : closure s = (free_monoid.lift (coe : s → M)).mrange :=
by rw [mrange_eq_map, ← free_monoid.closure_range_of, map_mclosure, ← set.range_comp,
free_monoid.lift_comp_of, subtype.range_coe]
@[to_additive]
lemma exists_list_of_mem_closure {s : set M} {x : M} (hx : x ∈ closure s) :
∃ (l : list M) (hl : ∀ y ∈ l, y ∈ s), l.prod = x :=
begin
rw [closure_eq_mrange, mem_mrange] at hx,
rcases hx with ⟨l, hx⟩,
exact ⟨list.map coe l, λ y hy, let ⟨z, hz, hy⟩ := list.mem_map.1 hy in hy ▸ z.2, hx⟩
end
/-- The submonoid generated by an element. -/
def powers (n : M) : submonoid M :=
submonoid.copy (powers_hom M n).mrange (set.range ((^) n : ℕ → M)) $
set.ext (λ n, exists_congr $ λ i, by simp; refl)
@[simp] lemma mem_powers (n : M) : n ∈ powers n := ⟨1, pow_one _⟩
lemma powers_eq_closure (n : M) : powers n = closure {n} :=
by { ext, exact mem_closure_singleton.symm }
lemma powers_subset {n : M} {P : submonoid M} (h : n ∈ P) : powers n ≤ P :=
λ x hx, match x, hx with _, ⟨i, rfl⟩ := P.pow_mem h i end
end submonoid
namespace submonoid
variables {N : Type*} [comm_monoid N]
open monoid_hom
@[to_additive]
lemma sup_eq_range (s t : submonoid N) : s ⊔ t = (s.subtype.coprod t.subtype).mrange :=
by rw [mrange_eq_map, ← mrange_inl_sup_mrange_inr, map_sup, map_mrange, coprod_comp_inl,
map_mrange, coprod_comp_inr, range_subtype, range_subtype]
@[to_additive]
lemma mem_sup {s t : submonoid N} {x : N} :
x ∈ s ⊔ t ↔ ∃ (y ∈ s) (z ∈ t), y * z = x :=
by simp only [sup_eq_range, mem_mrange, coprod_apply, prod.exists, set_like.exists,
coe_subtype, subtype.coe_mk]
end submonoid
namespace add_submonoid
variables [add_monoid A]
open set
lemma nsmul_mem (S : add_submonoid A) {x : A} (hx : x ∈ S) :
∀ n : ℕ, n • x ∈ S
| 0 := by { rw zero_nsmul, exact S.zero_mem }
| (n+1) := by { rw [add_nsmul, one_nsmul], exact S.add_mem (nsmul_mem n) hx }
lemma closure_singleton_eq (x : A) : closure ({x} : set A) = (multiples_hom A x).mrange :=
closure_eq_of_le (set.singleton_subset_iff.2 ⟨1, one_nsmul x⟩) $
λ x ⟨n, hn⟩, hn ▸ nsmul_mem _ (subset_closure $ set.mem_singleton _) _
/-- The `add_submonoid` generated by an element of an `add_monoid` equals the set of
natural number multiples of the element. -/
lemma mem_closure_singleton {x y : A} :
y ∈ closure ({x} : set A) ↔ ∃ n:ℕ, n • x = y :=
by rw [closure_singleton_eq, add_monoid_hom.mem_mrange]; refl
lemma closure_singleton_zero : closure ({0} : set A) = ⊥ :=
by simp [eq_bot_iff_forall, mem_closure_singleton, nsmul_zero]
/-- The additive submonoid generated by an element. -/
def multiples (x : A) : add_submonoid A :=
add_submonoid.copy (multiples_hom A x).mrange (set.range (λ i, nsmul i x : ℕ → A)) $
set.ext (λ n, exists_congr $ λ i, by simp; refl)
@[simp] lemma mem_multiples (x : A) : x ∈ multiples x := ⟨1, one_nsmul _⟩
lemma multiples_eq_closure (x : A) : multiples x = closure {x} :=
by { ext, exact mem_closure_singleton.symm }
lemma multiples_subset {x : A} {P : add_submonoid A} (h : x ∈ P) : multiples x ≤ P :=
λ x hx, match x, hx with _, ⟨i, rfl⟩ := P.nsmul_mem h i end
attribute [to_additive add_submonoid.multiples] submonoid.powers
attribute [to_additive add_submonoid.mem_multiples] submonoid.mem_powers
attribute [to_additive add_submonoid.multiples_eq_closure] submonoid.powers_eq_closure
attribute [to_additive add_submonoid.multiples_subset] submonoid.powers_subset
end add_submonoid
/-! Lemmas about additive closures of `submonoid`. -/
namespace submonoid
variables {R : Type*} [semiring R] (S : submonoid R) {a b : R}
/-- The product of an element of the additive closure of a multiplicative submonoid `M`
and an element of `M` is contained in the additive closure of `M`. -/
lemma mul_right_mem_add_closure
(ha : a ∈ add_submonoid.closure (S : set R)) (hb : b ∈ S) :
a * b ∈ add_submonoid.closure (S : set R) :=
begin
revert b,
refine add_submonoid.closure_induction ha _ _ _; clear ha a,
{ exact λ r hr b hb, add_submonoid.mem_closure.mpr (λ y hy, hy (S.mul_mem hr hb)) },
{ exact λ b hb, by simp only [zero_mul, (add_submonoid.closure (S : set R)).zero_mem] },
{ simp_rw add_mul,
exact λ r s hr hs b hb, (add_submonoid.closure (S : set R)).add_mem (hr hb) (hs hb) }
end
/-- The product of two elements of the additive closure of a submonoid `M` is an element of the
additive closure of `M`. -/
lemma mul_mem_add_closure
(ha : a ∈ add_submonoid.closure (S : set R)) (hb : b ∈ add_submonoid.closure (S : set R)) :
a * b ∈ add_submonoid.closure (S : set R) :=
begin
revert a,
refine add_submonoid.closure_induction hb _ _ _; clear hb b,
{ exact λ r hr b hb, S.mul_right_mem_add_closure hb hr },
{ exact λ b hb, by simp only [mul_zero, (add_submonoid.closure (S : set R)).zero_mem] },
{ simp_rw mul_add,
exact λ r s hr hs b hb, (add_submonoid.closure (S : set R)).add_mem (hr hb) (hs hb) }
end
/-- The product of an element of `S` and an element of the additive closure of a multiplicative
submonoid `S` is contained in the additive closure of `S`. -/
lemma mul_left_mem_add_closure (ha : a ∈ S) (hb : b ∈ add_submonoid.closure (S : set R)) :
a * b ∈ add_submonoid.closure (S : set R) :=
S.mul_mem_add_closure (add_submonoid.mem_closure.mpr (λ sT hT, hT ha)) hb
@[to_additive]
lemma mem_closure_inv {G : Type*} [group G] (S : set G) (x : G) :
x ∈ submonoid.closure S⁻¹ ↔ x⁻¹ ∈ submonoid.closure S :=
begin
suffices : ∀ (S : set G) (x : G), x ∈ submonoid.closure S⁻¹ → x⁻¹ ∈ submonoid.closure S,
{ refine ⟨this S x, _⟩,
have := this S⁻¹ x⁻¹,
rw [inv_inv, set.inv_inv] at this,
exact this, },
intros S x hx,
refine submonoid.closure_induction hx (λ x hx, _) _ (λ x y hx hy, _),
{ exact submonoid.subset_closure (set.mem_inv.mp hx), },
{ rw one_inv,
exact submonoid.one_mem _ },
{ rw mul_inv_rev x y,
exact submonoid.mul_mem _ hy hx },
end
end submonoid
section mul_add
lemma of_mul_image_powers_eq_multiples_of_mul [monoid M] {x : M} :
additive.of_mul '' ((submonoid.powers x) : set M) = add_submonoid.multiples (additive.of_mul x) :=
begin
ext,
split,
{ rintros ⟨y, ⟨n, hy1⟩, hy2⟩,
use n,
simpa [← of_mul_pow, hy1] },
{ rintros ⟨n, hn⟩,
refine ⟨x ^ n, ⟨n, rfl⟩, _⟩,
rwa of_mul_pow }
end
lemma of_add_image_multiples_eq_powers_of_add [add_monoid A] {x : A} :
multiplicative.of_add '' ((add_submonoid.multiples x) : set A) =
submonoid.powers (multiplicative.of_add x) :=
begin
symmetry,
rw equiv.eq_image_iff_symm_image_eq,
exact of_mul_image_powers_eq_multiples_of_mul,
end
end mul_add
|
cd3ba710901f30f55b046693aaad469d9090b0c2 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/algebra/lie/quotient.lean | d387306e4bc65db801de83b4cd08f07e6b0ffdce | [
"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 | 6,553 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.submodule
import algebra.lie.of_associative
/-!
# Quotients of Lie algebras and Lie modules
Given a Lie submodule of a Lie module, the quotient carries a natural Lie module structure. In the
special case that the Lie module is the Lie algebra itself via the adjoint action, the submodule
is a Lie ideal and the quotient carries a natural Lie algebra structure.
We define these quotient structures here. A notable omission at the time of writing (February 2021)
is a statement and proof of the universal property of these quotients.
## Main definitions
* `lie_submodule.quotient.lie_quotient_lie_module`
* `lie_submodule.quotient.lie_quotient_lie_algebra`
## Tags
lie algebra, quotient
-/
universes u v w w₁ w₂
namespace lie_submodule
variables {R : Type u} {L : Type v} {M : Type w}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
variables (N N' : lie_submodule R L M) (I J : lie_ideal R L)
/-- The quotient of a Lie module by a Lie submodule. It is a Lie module. -/
abbreviation quotient := N.to_submodule.quotient
namespace quotient
variables {N I}
/-- Map sending an element of `M` to the corresponding element of `M/N`, when `N` is a
lie_submodule of the lie_module `N`. -/
abbreviation mk : M → N.quotient := submodule.quotient.mk
lemma is_quotient_mk (m : M) :
quotient.mk' m = (mk m : N.quotient) := rfl
/-- Given a Lie module `M` over a Lie algebra `L`, together with a Lie submodule `N ⊆ M`, there
is a natural linear map from `L` to the endomorphisms of `M` leaving `N` invariant. -/
def lie_submodule_invariant : L →ₗ[R] submodule.compatible_maps N.to_submodule N.to_submodule :=
linear_map.cod_restrict _ (lie_module.to_endomorphism R L M) N.lie_mem
variables (N)
/-- Given a Lie module `M` over a Lie algebra `L`, together with a Lie submodule `N ⊆ M`, there
is a natural Lie algebra morphism from `L` to the linear endomorphism of the quotient `M/N`. -/
def action_as_endo_map : L →ₗ⁅R⁆ module.End R N.quotient :=
{ map_lie' := λ x y, by { ext m,
change mk ⁅⁅x, y⁆, m⁆ = mk (⁅x, ⁅y, m⁆⁆ - ⁅y, ⁅x, m⁆⁆),
congr, apply lie_lie, },
..linear_map.comp (submodule.mapq_linear (N : submodule R M) ↑N) lie_submodule_invariant }
/-- Given a Lie module `M` over a Lie algebra `L`, together with a Lie submodule `N ⊆ M`, there is
a natural bracket action of `L` on the quotient `M/N`. -/
def action_as_endo_map_bracket : has_bracket L N.quotient := ⟨λ x n, action_as_endo_map N x n⟩
instance lie_quotient_lie_ring_module : lie_ring_module L N.quotient :=
{ bracket := λ x n, (action_as_endo_map N : L →ₗ[R] module.End R N.quotient) x n,
add_lie := λ x y n, by { simp only [linear_map.map_add, linear_map.add_apply], },
lie_add := λ x m n, by { simp only [linear_map.map_add, linear_map.add_apply], },
leibniz_lie := λ x y m, show action_as_endo_map _ _ _ = _,
{ simp only [lie_hom.map_lie, lie_ring.of_associative_ring_bracket, sub_add_cancel,
lie_hom.coe_to_linear_map, linear_map.mul_apply, linear_map.sub_apply], } }
/-- The quotient of a Lie module by a Lie submodule, is a Lie module. -/
instance lie_quotient_lie_module : lie_module R L N.quotient :=
{ smul_lie := λ t x m, show (_ : L →ₗ[R] module.End R N.quotient) _ _ = _,
{ simp only [linear_map.map_smul], refl, },
lie_smul := λ x t m, show (_ : L →ₗ[R] module.End R N.quotient) _ _ = _,
{ simp only [linear_map.map_smul], refl, }, }
instance lie_quotient_has_bracket : has_bracket (quotient I) (quotient I) :=
⟨begin
intros x y,
apply quotient.lift_on₂' x y (λ x' y', mk ⁅x', y'⁆),
intros x₁ x₂ y₁ y₂ h₁ h₂,
apply (submodule.quotient.eq I.to_submodule).2,
have h : ⁅x₁, x₂⁆ - ⁅y₁, y₂⁆ = ⁅x₁, x₂ - y₂⁆ + ⁅x₁ - y₁, y₂⁆,
by simp [-lie_skew, sub_eq_add_neg, add_assoc],
rw h,
apply submodule.add_mem,
{ apply lie_mem_right R L I x₁ (x₂ - y₂) h₂, },
{ apply lie_mem_left R L I (x₁ - y₁) y₂ h₁, },
end⟩
@[simp] lemma mk_bracket (x y : L) :
mk ⁅x, y⁆ = ⁅(mk x : quotient I), (mk y : quotient I)⁆ := rfl
instance lie_quotient_lie_ring : lie_ring (quotient I) :=
{ add_lie := by { intros x' y' z', apply quotient.induction_on₃' x' y' z', intros x y z,
repeat { rw is_quotient_mk <|>
rw ←mk_bracket <|>
rw ←submodule.quotient.mk_add, },
apply congr_arg, apply add_lie, },
lie_add := by { intros x' y' z', apply quotient.induction_on₃' x' y' z', intros x y z,
repeat { rw is_quotient_mk <|>
rw ←mk_bracket <|>
rw ←submodule.quotient.mk_add, },
apply congr_arg, apply lie_add, },
lie_self := by { intros x', apply quotient.induction_on' x', intros x,
rw [is_quotient_mk, ←mk_bracket],
apply congr_arg, apply lie_self, },
leibniz_lie := by { intros x' y' z', apply quotient.induction_on₃' x' y' z', intros x y z,
repeat { rw is_quotient_mk <|>
rw ←mk_bracket <|>
rw ←submodule.quotient.mk_add, },
apply congr_arg, apply leibniz_lie, } }
instance lie_quotient_lie_algebra : lie_algebra R (quotient I) :=
{ lie_smul := by { intros t x' y', apply quotient.induction_on₂' x' y', intros x y,
repeat { rw is_quotient_mk <|>
rw ←mk_bracket <|>
rw ←submodule.quotient.mk_smul, },
apply congr_arg, apply lie_smul, } }
/-- `lie_submodule.quotient.mk` as a `lie_module_hom`. -/
@[simps]
def mk' : M →ₗ⁅R,L⁆ quotient N :=
{ to_fun := mk, map_lie' := λ r m, rfl, ..N.to_submodule.mkq}
/-- Two `lie_module_hom`s from a quotient lie module are equal if their compositions with
`lie_submodule.quotient.mk'` are equal.
See note [partially-applied ext lemmas]. -/
@[ext]
lemma lie_module_hom_ext ⦃f g : quotient N →ₗ⁅R,L⁆ M⦄ (h : f.comp (mk' N) = g.comp (mk' N)) :
f = g :=
lie_module_hom.ext $ λ x, quotient.induction_on' x $ lie_module_hom.congr_fun h
end quotient
end lie_submodule
|
5bc87f3ab75444d2d7d412e6ceaa87109452d042 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/complex/upper_half_plane/manifold.lean | 0c070195cc5dda0274eeb69d30aaafc31aca3c6d | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 1,199 | lean | /-
Copyright (c) 2022 Chris Birkbeck. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Birkbeck
-/
import analysis.complex.upper_half_plane.topology
import geometry.manifold.cont_mdiff_mfderiv
/-!
# Manifold structure on the upper half plane.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define the complex manifold structure on the upper half-plane.
-/
open_locale upper_half_plane manifold
namespace upper_half_plane
noncomputable instance : charted_space ℂ ℍ :=
upper_half_plane.open_embedding_coe.singleton_charted_space
instance : smooth_manifold_with_corners 𝓘(ℂ) ℍ :=
upper_half_plane.open_embedding_coe.singleton_smooth_manifold_with_corners 𝓘(ℂ)
/-- The inclusion map `ℍ → ℂ` is a smooth map of manifolds. -/
lemma smooth_coe : smooth 𝓘(ℂ) 𝓘(ℂ) (coe : ℍ → ℂ) :=
λ x, cont_mdiff_at_ext_chart_at
/-- The inclusion map `ℍ → ℂ` is a differentiable map of manifolds. -/
lemma mdifferentiable_coe : mdifferentiable 𝓘(ℂ) 𝓘(ℂ) (coe : ℍ → ℂ) :=
smooth_coe.mdifferentiable
end upper_half_plane
|
5471d570c82e52cf66e467e240f93d40b154b531 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/special_functions/gamma/basic.lean | e8cdf1d2b63bab6f198c9363ed1ef300b73ef4cc | [
"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 | 24,387 | lean | /-
Copyright (c) 2022 David Loeffler. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Loeffler
-/
import measure_theory.integral.exp_decay
import analysis.special_functions.improper_integrals
import analysis.mellin_transform
/-!
# The Gamma function
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the `Γ` function (of a real or complex variable `s`). We define this by Euler's
integral `Γ(s) = ∫ x in Ioi 0, exp (-x) * x ^ (s - 1)` in the range where this integral converges
(i.e., for `0 < s` in the real case, and `0 < re s` in the complex case).
We show that this integral satisfies `Γ(1) = 1` and `Γ(s + 1) = s * Γ(s)`; hence we can define
`Γ(s)` for all `s` as the unique function satisfying this recurrence and agreeing with Euler's
integral in the convergence range. (If `s = -n` for `n ∈ ℕ`, then the function is undefined, and we
set it to be `0` by convention.)
## Gamma function: main statements (complex case)
* `complex.Gamma`: the `Γ` function (of a complex variable).
* `complex.Gamma_eq_integral`: for `0 < re s`, `Γ(s)` agrees with Euler's integral.
* `complex.Gamma_add_one`: for all `s : ℂ` with `s ≠ 0`, we have `Γ (s + 1) = s Γ(s)`.
* `complex.Gamma_nat_eq_factorial`: for all `n : ℕ` we have `Γ (n + 1) = n!`.
* `complex.differentiable_at_Gamma`: `Γ` is complex-differentiable at all `s : ℂ` with
`s ∉ {-n : n ∈ ℕ}`.
## Gamma function: main statements (real case)
* `real.Gamma`: the `Γ` function (of a real variable).
* Real counterparts of all the properties of the complex Gamma function listed above:
`real.Gamma_eq_integral`, `real.Gamma_add_one`, `real.Gamma_nat_eq_factorial`,
`real.differentiable_at_Gamma`.
## Tags
Gamma
-/
noncomputable theory
open filter interval_integral set real measure_theory asymptotics
open_locale nat topology complex_conjugate
namespace real
/-- Asymptotic bound for the `Γ` function integrand. -/
lemma Gamma_integrand_is_o (s : ℝ) :
(λ x:ℝ, exp (-x) * x ^ s) =o[at_top] (λ x:ℝ, exp (-(1/2) * x)) :=
begin
refine is_o_of_tendsto (λ x hx, _) _,
{ exfalso, exact (exp_pos (-(1 / 2) * x)).ne' hx },
have : (λ (x:ℝ), exp (-x) * x ^ s / exp (-(1 / 2) * x)) = (λ (x:ℝ), exp ((1 / 2) * x) / x ^ s )⁻¹,
{ ext1 x,
field_simp [exp_ne_zero, exp_neg, ← real.exp_add],
left,
ring },
rw this,
exact (tendsto_exp_mul_div_rpow_at_top s (1 / 2) one_half_pos).inv_tendsto_at_top,
end
/-- The Euler integral for the `Γ` function converges for positive real `s`. -/
lemma Gamma_integral_convergent {s : ℝ} (h : 0 < s) :
integrable_on (λ x:ℝ, exp (-x) * x ^ (s - 1)) (Ioi 0) :=
begin
rw [←Ioc_union_Ioi_eq_Ioi (@zero_le_one ℝ _ _ _ _), integrable_on_union],
split,
{ rw ←integrable_on_Icc_iff_integrable_on_Ioc,
refine integrable_on.continuous_on_mul continuous_on_id.neg.exp _ is_compact_Icc,
refine (interval_integrable_iff_integrable_Icc_of_le zero_le_one).mp _,
exact interval_integrable_rpow' (by linarith), },
{ refine integrable_of_is_O_exp_neg one_half_pos _ (Gamma_integrand_is_o _ ).is_O,
refine continuous_on_id.neg.exp.mul (continuous_on_id.rpow_const _),
intros x hx,
exact or.inl ((zero_lt_one : (0 : ℝ) < 1).trans_le hx).ne' }
end
end real
namespace complex
/- Technical note: In defining the Gamma integrand exp (-x) * x ^ (s - 1) for s complex, we have to
make a choice between ↑(real.exp (-x)), complex.exp (↑(-x)), and complex.exp (-↑x), all of which are
equal but not definitionally so. We use the first of these throughout. -/
/-- The integral defining the `Γ` function converges for complex `s` with `0 < re s`.
This is proved by reduction to the real case. -/
lemma Gamma_integral_convergent {s : ℂ} (hs : 0 < s.re) :
integrable_on (λ x, (-x).exp * x ^ (s - 1) : ℝ → ℂ) (Ioi 0) :=
begin
split,
{ refine continuous_on.ae_strongly_measurable _ measurable_set_Ioi,
apply (continuous_of_real.comp continuous_neg.exp).continuous_on.mul,
apply continuous_at.continuous_on,
intros x hx,
have : continuous_at (λ x:ℂ, x ^ (s - 1)) ↑x,
{ apply continuous_at_cpow_const, rw of_real_re, exact or.inl hx, },
exact continuous_at.comp this continuous_of_real.continuous_at },
{ rw ←has_finite_integral_norm_iff,
refine has_finite_integral.congr (real.Gamma_integral_convergent hs).2 _,
refine (ae_restrict_iff' measurable_set_Ioi).mpr (ae_of_all _ (λ x hx, _)),
dsimp only,
rw [norm_eq_abs, map_mul, abs_of_nonneg $ le_of_lt $ exp_pos $ -x,
abs_cpow_eq_rpow_re_of_pos hx _],
simp }
end
/-- Euler's integral for the `Γ` function (of a complex variable `s`), defined as
`∫ x in Ioi 0, exp (-x) * x ^ (s - 1)`.
See `complex.Gamma_integral_convergent` for a proof of the convergence of the integral for
`0 < re s`. -/
def Gamma_integral (s : ℂ) : ℂ := ∫ x in Ioi (0:ℝ), ↑(-x).exp * ↑x ^ (s - 1)
lemma Gamma_integral_conj (s : ℂ) : Gamma_integral (conj s) = conj (Gamma_integral s) :=
begin
rw [Gamma_integral, Gamma_integral, ←integral_conj],
refine set_integral_congr measurable_set_Ioi (λ x hx, _),
dsimp only,
rw [ring_hom.map_mul, conj_of_real, cpow_def_of_ne_zero (of_real_ne_zero.mpr (ne_of_gt hx)),
cpow_def_of_ne_zero (of_real_ne_zero.mpr (ne_of_gt hx)), ←exp_conj, ring_hom.map_mul,
←of_real_log (le_of_lt hx), conj_of_real, ring_hom.map_sub, ring_hom.map_one],
end
lemma Gamma_integral_of_real (s : ℝ) :
Gamma_integral ↑s = ↑(∫ x:ℝ in Ioi 0, real.exp (-x) * x ^ (s - 1)) :=
begin
rw [Gamma_integral, ←_root_.integral_of_real],
refine set_integral_congr measurable_set_Ioi _,
intros x hx, dsimp only,
rw [of_real_mul, of_real_cpow (mem_Ioi.mp hx).le],
simp,
end
lemma Gamma_integral_one : Gamma_integral 1 = 1 :=
by simpa only [←of_real_one, Gamma_integral_of_real, of_real_inj, sub_self,
rpow_zero, mul_one] using integral_exp_neg_Ioi_zero
end complex
/-! Now we establish the recurrence relation `Γ(s + 1) = s * Γ(s)` using integration by parts. -/
namespace complex
section Gamma_recurrence
/-- The indefinite version of the `Γ` function, `Γ(s, X) = ∫ x ∈ 0..X, exp(-x) x ^ (s - 1)`. -/
def partial_Gamma (s : ℂ) (X : ℝ) : ℂ := ∫ x in 0..X, (-x).exp * x ^ (s - 1)
lemma tendsto_partial_Gamma {s : ℂ} (hs: 0 < s.re) :
tendsto (λ X:ℝ, partial_Gamma s X) at_top (𝓝 $ Gamma_integral s) :=
interval_integral_tendsto_integral_Ioi 0 (Gamma_integral_convergent hs) tendsto_id
private lemma Gamma_integrand_interval_integrable (s : ℂ) {X : ℝ} (hs : 0 < s.re) (hX : 0 ≤ X):
interval_integrable (λ x, (-x).exp * x ^ (s - 1) : ℝ → ℂ) volume 0 X :=
begin
rw interval_integrable_iff_integrable_Ioc_of_le hX,
exact integrable_on.mono_set (Gamma_integral_convergent hs) Ioc_subset_Ioi_self
end
private lemma Gamma_integrand_deriv_integrable_A {s : ℂ} (hs : 0 < s.re) {X : ℝ} (hX : 0 ≤ X):
interval_integrable (λ x, -((-x).exp * x ^ s) : ℝ → ℂ) volume 0 X :=
begin
convert (Gamma_integrand_interval_integrable (s+1) _ hX).neg,
{ ext1, simp only [add_sub_cancel, pi.neg_apply] },
{ simp only [add_re, one_re], linarith,},
end
private lemma Gamma_integrand_deriv_integrable_B {s : ℂ} (hs : 0 < s.re) {Y : ℝ} (hY : 0 ≤ Y) :
interval_integrable (λ (x : ℝ), (-x).exp * (s * x ^ (s - 1)) : ℝ → ℂ) volume 0 Y :=
begin
have : (λ x, (-x).exp * (s * x ^ (s - 1)) : ℝ → ℂ) =
(λ x, s * ((-x).exp * x ^ (s - 1)) : ℝ → ℂ),
{ ext1, ring, },
rw [this, interval_integrable_iff_integrable_Ioc_of_le hY],
split,
{ refine (continuous_on_const.mul _).ae_strongly_measurable measurable_set_Ioc,
apply (continuous_of_real.comp continuous_neg.exp).continuous_on.mul,
apply continuous_at.continuous_on,
intros x hx,
refine (_ : continuous_at (λ x:ℂ, x ^ (s - 1)) _).comp continuous_of_real.continuous_at,
apply continuous_at_cpow_const, rw of_real_re, exact or.inl hx.1, },
rw ←has_finite_integral_norm_iff,
simp_rw [norm_eq_abs, map_mul],
refine (((real.Gamma_integral_convergent hs).mono_set
Ioc_subset_Ioi_self).has_finite_integral.congr _).const_mul _,
rw [eventually_eq, ae_restrict_iff'],
{ apply ae_of_all, intros x hx,
rw [abs_of_nonneg (exp_pos _).le,abs_cpow_eq_rpow_re_of_pos hx.1],
simp },
{ exact measurable_set_Ioc},
end
/-- The recurrence relation for the indefinite version of the `Γ` function. -/
lemma partial_Gamma_add_one {s : ℂ} (hs: 0 < s.re) {X : ℝ} (hX : 0 ≤ X) :
partial_Gamma (s + 1) X = s * partial_Gamma s X - (-X).exp * X ^ s :=
begin
rw [partial_Gamma, partial_Gamma, add_sub_cancel],
have F_der_I: (∀ (x:ℝ), (x ∈ Ioo 0 X) → has_deriv_at (λ x, (-x).exp * x ^ s : ℝ → ℂ)
( -((-x).exp * x ^ s) + (-x).exp * (s * x ^ (s - 1))) x),
{ intros x hx,
have d1 : has_deriv_at (λ (y: ℝ), (-y).exp) (-(-x).exp) x,
{ simpa using (has_deriv_at_neg x).exp },
have d2 : has_deriv_at (λ (y : ℝ), ↑y ^ s) (s * x ^ (s - 1)) x,
{ have t := @has_deriv_at.cpow_const _ _ _ s (has_deriv_at_id ↑x) _,
simpa only [mul_one] using t.comp_of_real,
simpa only [id.def, of_real_re, of_real_im,
ne.def, eq_self_iff_true, not_true, or_false, mul_one] using hx.1, },
simpa only [of_real_neg, neg_mul] using d1.of_real_comp.mul d2 },
have cont := (continuous_of_real.comp continuous_neg.exp).mul
(continuous_of_real_cpow_const hs),
have der_ible := (Gamma_integrand_deriv_integrable_A hs hX).add
(Gamma_integrand_deriv_integrable_B hs hX),
have int_eval := integral_eq_sub_of_has_deriv_at_of_le hX cont.continuous_on F_der_I der_ible,
-- We are basically done here but manipulating the output into the right form is fiddly.
apply_fun (λ x:ℂ, -x) at int_eval,
rw [interval_integral.integral_add (Gamma_integrand_deriv_integrable_A hs hX)
(Gamma_integrand_deriv_integrable_B hs hX), interval_integral.integral_neg, neg_add, neg_neg]
at int_eval,
rw [eq_sub_of_add_eq int_eval, sub_neg_eq_add, neg_sub, add_comm, add_sub],
simp only [sub_left_inj, add_left_inj],
have : (λ x, (-x).exp * (s * x ^ (s - 1)) : ℝ → ℂ) = (λ x, s * (-x).exp * x ^ (s - 1) : ℝ → ℂ),
{ ext1, ring,},
rw this,
have t := @integral_const_mul 0 X volume _ _ s (λ x:ℝ, (-x).exp * x ^ (s - 1)),
dsimp at t, rw [←t, of_real_zero, zero_cpow],
{ rw [mul_zero, add_zero], congr', ext1, ring },
{ contrapose! hs, rw [hs, zero_re] }
end
/-- The recurrence relation for the `Γ` integral. -/
theorem Gamma_integral_add_one {s : ℂ} (hs: 0 < s.re) :
Gamma_integral (s + 1) = s * Gamma_integral s :=
begin
suffices : tendsto (s+1).partial_Gamma at_top (𝓝 $ s * Gamma_integral s),
{ refine tendsto_nhds_unique _ this,
apply tendsto_partial_Gamma, rw [add_re, one_re], linarith, },
have : (λ X:ℝ, s * partial_Gamma s X - X ^ s * (-X).exp) =ᶠ[at_top] (s+1).partial_Gamma,
{ apply eventually_eq_of_mem (Ici_mem_at_top (0:ℝ)),
intros X hX,
rw partial_Gamma_add_one hs (mem_Ici.mp hX),
ring_nf, },
refine tendsto.congr' this _,
suffices : tendsto (λ X, -X ^ s * (-X).exp : ℝ → ℂ) at_top (𝓝 0),
{ simpa using tendsto.add (tendsto.const_mul s (tendsto_partial_Gamma hs)) this },
rw tendsto_zero_iff_norm_tendsto_zero,
have : (λ (e : ℝ), ‖-(e:ℂ) ^ s * (-e).exp‖ ) =ᶠ[at_top] (λ (e : ℝ), e ^ s.re * (-1 * e).exp ),
{ refine eventually_eq_of_mem (Ioi_mem_at_top 0) _,
intros x hx, dsimp only,
rw [norm_eq_abs, map_mul, abs.map_neg, abs_cpow_eq_rpow_re_of_pos hx,
abs_of_nonneg (exp_pos(-x)).le, neg_mul, one_mul],},
exact (tendsto_congr' this).mpr (tendsto_rpow_mul_exp_neg_mul_at_top_nhds_0 _ _ zero_lt_one),
end
end Gamma_recurrence
/-! Now we define `Γ(s)` on the whole complex plane, by recursion. -/
section Gamma_def
/-- The `n`th function in this family is `Γ(s)` if `-n < s.re`, and junk otherwise. -/
noncomputable def Gamma_aux : ℕ → (ℂ → ℂ)
| 0 := Gamma_integral
| (n+1) := λ s:ℂ, (Gamma_aux n (s+1)) / s
lemma Gamma_aux_recurrence1 (s : ℂ) (n : ℕ) (h1 : -s.re < ↑n) :
Gamma_aux n s = Gamma_aux n (s+1) / s :=
begin
induction n with n hn generalizing s,
{ simp only [nat.cast_zero, neg_lt_zero] at h1,
dsimp only [Gamma_aux], rw Gamma_integral_add_one h1,
rw [mul_comm, mul_div_cancel], contrapose! h1, rw h1,
simp },
{ dsimp only [Gamma_aux],
have hh1 : -(s+1).re < n,
{ rw [nat.succ_eq_add_one, nat.cast_add, nat.cast_one] at h1,
rw [add_re, one_re], linarith, },
rw ←(hn (s+1) hh1) }
end
lemma Gamma_aux_recurrence2 (s : ℂ) (n : ℕ) (h1 : -s.re < ↑n) :
Gamma_aux n s = Gamma_aux (n+1) s :=
begin
cases n,
{ simp only [nat.cast_zero, neg_lt_zero] at h1,
dsimp only [Gamma_aux],
rw [Gamma_integral_add_one h1, mul_div_cancel_left],
rintro rfl,
rw [zero_re] at h1,
exact h1.false },
{ dsimp only [Gamma_aux],
have : (Gamma_aux n (s + 1 + 1)) / (s+1) = Gamma_aux n (s + 1),
{ have hh1 : -(s+1).re < n,
{ rw [nat.succ_eq_add_one, nat.cast_add, nat.cast_one] at h1,
rw [add_re, one_re], linarith, },
rw Gamma_aux_recurrence1 (s+1) n hh1, },
rw this },
end
/-- The `Γ` function (of a complex variable `s`). -/
@[pp_nodot] def Gamma (s : ℂ) : ℂ := Gamma_aux ⌊1 - s.re⌋₊ s
lemma Gamma_eq_Gamma_aux (s : ℂ) (n : ℕ) (h1 : -s.re < ↑n) : Gamma s = Gamma_aux n s :=
begin
have u : ∀ (k : ℕ), Gamma_aux (⌊1 - s.re⌋₊ + k) s = Gamma s,
{ intro k, induction k with k hk,
{ simp [Gamma],},
{ rw [←hk, nat.succ_eq_add_one, ←add_assoc],
refine (Gamma_aux_recurrence2 s (⌊1 - s.re⌋₊ + k) _).symm,
rw nat.cast_add,
have i0 := nat.sub_one_lt_floor (1 - s.re),
simp only [sub_sub_cancel_left] at i0,
refine lt_add_of_lt_of_nonneg i0 _,
rw [←nat.cast_zero, nat.cast_le], exact nat.zero_le k, } },
convert (u $ n - ⌊1 - s.re⌋₊).symm, rw nat.add_sub_of_le,
by_cases (0 ≤ 1 - s.re),
{ apply nat.le_of_lt_succ,
exact_mod_cast lt_of_le_of_lt (nat.floor_le h) (by linarith : 1 - s.re < n + 1) },
{ rw nat.floor_of_nonpos, linarith, linarith },
end
/-- The recurrence relation for the `Γ` function. -/
theorem Gamma_add_one (s : ℂ) (h2 : s ≠ 0) : Gamma (s+1) = s * Gamma s :=
begin
let n := ⌊1 - s.re⌋₊,
have t1 : -s.re < n,
{ simpa only [sub_sub_cancel_left] using nat.sub_one_lt_floor (1 - s.re) },
have t2 : -(s+1).re < n,
{ rw [add_re, one_re], linarith, },
rw [Gamma_eq_Gamma_aux s n t1, Gamma_eq_Gamma_aux (s+1) n t2, Gamma_aux_recurrence1 s n t1],
field_simp, ring,
end
theorem Gamma_eq_integral {s : ℂ} (hs : 0 < s.re) : Gamma s = Gamma_integral s :=
Gamma_eq_Gamma_aux s 0 (by { norm_cast, linarith })
lemma Gamma_one : Gamma 1 = 1 :=
by { rw Gamma_eq_integral, simpa using Gamma_integral_one, simp }
theorem Gamma_nat_eq_factorial (n : ℕ) : Gamma (n+1) = n! :=
begin
induction n with n hn,
{ simpa using Gamma_one },
{ rw (Gamma_add_one n.succ $ nat.cast_ne_zero.mpr $ nat.succ_ne_zero n),
simp only [nat.cast_succ, nat.factorial_succ, nat.cast_mul], congr, exact hn },
end
/-- At `0` the Gamma function is undefined; by convention we assign it the value `0`. -/
lemma Gamma_zero : Gamma 0 = 0 :=
by simp_rw [Gamma, zero_re, sub_zero, nat.floor_one, Gamma_aux, div_zero]
/-- At `-n` for `n ∈ ℕ`, the Gamma function is undefined; by convention we assign it the value 0. -/
lemma Gamma_neg_nat_eq_zero (n : ℕ) : Gamma (-n) = 0 :=
begin
induction n with n IH,
{ rw [nat.cast_zero, neg_zero, Gamma_zero] },
{ have A : -(n.succ : ℂ) ≠ 0,
{ rw [neg_ne_zero, nat.cast_ne_zero],
apply nat.succ_ne_zero },
have : -(n:ℂ) = -↑n.succ + 1, by simp,
rw [this, Gamma_add_one _ A] at IH,
contrapose! IH,
exact mul_ne_zero A IH }
end
lemma Gamma_conj (s : ℂ) : Gamma (conj s) = conj (Gamma s) :=
begin
suffices : ∀ (n:ℕ) (s:ℂ) , Gamma_aux n (conj s) = conj (Gamma_aux n s), from this _ _,
intro n,
induction n with n IH,
{ rw Gamma_aux, exact Gamma_integral_conj, },
{ intro s,
rw Gamma_aux,
dsimp only,
rw [div_eq_mul_inv _ s, ring_hom.map_mul, conj_inv, ←div_eq_mul_inv],
suffices : conj s + 1 = conj (s + 1), by rw [this, IH],
rw [ring_hom.map_add, ring_hom.map_one] }
end
end Gamma_def
/-! Now check that the `Γ` function is differentiable, wherever this makes sense. -/
section Gamma_has_deriv
/-- Rewrite the Gamma integral as an example of a Mellin transform. -/
lemma Gamma_integral_eq_mellin : Gamma_integral = mellin (λ x, real.exp (-x)) :=
funext (λ s, by simp only [mellin, Gamma_integral, smul_eq_mul, mul_comm])
/-- The derivative of the `Γ` integral, at any `s ∈ ℂ` with `1 < re s`, is given by the Melllin
transform of `log t * exp (-t)`. -/
theorem has_deriv_at_Gamma_integral {s : ℂ} (hs : 0 < s.re) :
has_deriv_at Gamma_integral (∫ (t : ℝ) in Ioi 0, t ^ (s - 1) * (real.log t * real.exp (-t))) s :=
begin
rw Gamma_integral_eq_mellin,
convert (mellin_has_deriv_of_is_O_rpow _ _ (lt_add_one _) _ hs).2,
{ refine (continuous.continuous_on _).locally_integrable_on measurable_set_Ioi,
exact continuous_of_real.comp (real.continuous_exp.comp continuous_neg), },
{ rw [←is_O_norm_left],
simp_rw [complex.norm_eq_abs, abs_of_real, ←real.norm_eq_abs, is_O_norm_left],
simpa only [neg_one_mul] using (is_o_exp_neg_mul_rpow_at_top zero_lt_one _).is_O },
{ simp_rw [neg_zero, rpow_zero],
refine is_O_const_of_tendsto (_ : tendsto _ _ (𝓝 1)) one_ne_zero,
rw (by simp : (1 : ℂ) = real.exp (-0)),
exact (continuous_of_real.comp (real.continuous_exp.comp continuous_neg)).continuous_within_at }
end
lemma differentiable_at_Gamma_aux (s : ℂ) (n : ℕ) (h1 : (1 - s.re) < n ) (h2 : ∀ m : ℕ, s ≠ -m) :
differentiable_at ℂ (Gamma_aux n) s :=
begin
induction n with n hn generalizing s,
{ refine (has_deriv_at_Gamma_integral _).differentiable_at,
rw nat.cast_zero at h1, linarith },
{ dsimp only [Gamma_aux],
specialize hn (s + 1),
have a : 1 - (s + 1).re < ↑n,
{ rw nat.cast_succ at h1, rw [complex.add_re, complex.one_re], linarith },
have b : ∀ m : ℕ, s + 1 ≠ -m,
{ intro m, have := h2 (1 + m),
contrapose! this,
rw ←eq_sub_iff_add_eq at this,
simpa using this },
refine differentiable_at.div (differentiable_at.comp _ (hn a b) _) _ _,
simp, simp, simpa using h2 0 }
end
theorem differentiable_at_Gamma (s : ℂ) (hs : ∀ m : ℕ, s ≠ -m) : differentiable_at ℂ Gamma s :=
begin
let n := ⌊1 - s.re⌋₊ + 1,
have hn : 1 - s.re < n := by exact_mod_cast nat.lt_floor_add_one (1 - s.re),
apply (differentiable_at_Gamma_aux s n hn hs).congr_of_eventually_eq,
let S := { t : ℂ | 1 - t.re < n },
have : S ∈ 𝓝 s,
{ rw mem_nhds_iff, use S,
refine ⟨subset.rfl, _, hn⟩,
have : S = re⁻¹' Ioi (1 - n : ℝ),
{ ext, rw [preimage,Ioi, mem_set_of_eq, mem_set_of_eq, mem_set_of_eq], exact sub_lt_comm },
rw this,
refine continuous.is_open_preimage continuous_re _ is_open_Ioi, },
apply eventually_eq_of_mem this,
intros t ht, rw mem_set_of_eq at ht,
apply Gamma_eq_Gamma_aux, linarith,
end
end Gamma_has_deriv
/-- At `s = 0`, the Gamma function has a simple pole with residue 1. -/
lemma tendsto_self_mul_Gamma_nhds_zero : tendsto (λ z : ℂ, z * Gamma z) (𝓝[≠] 0) (𝓝 1) :=
begin
rw (show 𝓝 (1 : ℂ) = 𝓝 (Gamma (0 + 1)), by simp only [zero_add, complex.Gamma_one]),
convert (tendsto.mono_left _ nhds_within_le_nhds).congr'
(eventually_eq_of_mem self_mem_nhds_within complex.Gamma_add_one),
refine continuous_at.comp _ (continuous_id.add continuous_const).continuous_at,
refine (complex.differentiable_at_Gamma _ (λ m, _)).continuous_at,
rw [zero_add, ←of_real_nat_cast, ←of_real_neg, ←of_real_one, ne.def, of_real_inj],
refine (lt_of_le_of_lt _ zero_lt_one).ne',
exact neg_nonpos.mpr (nat.cast_nonneg _),
end
end complex
namespace real
/-- The `Γ` function (of a real variable `s`). -/
@[pp_nodot] def Gamma (s : ℝ) : ℝ := (complex.Gamma s).re
lemma Gamma_eq_integral {s : ℝ} (hs : 0 < s) : Gamma s = ∫ x in Ioi 0, exp (-x) * x ^ (s - 1) :=
begin
rw [Gamma, complex.Gamma_eq_integral (by rwa complex.of_real_re : 0 < complex.re s)],
dsimp only [complex.Gamma_integral],
simp_rw [←complex.of_real_one, ←complex.of_real_sub],
suffices : ∫ (x : ℝ) in Ioi 0, ↑(exp (-x)) * (x : ℂ) ^ ((s - 1 : ℝ) : ℂ) =
∫ (x : ℝ) in Ioi 0, ((exp (-x) * x ^ (s - 1) : ℝ) : ℂ),
{ rw [this, _root_.integral_of_real, complex.of_real_re], },
refine set_integral_congr measurable_set_Ioi (λ x hx, _),
push_cast,
rw complex.of_real_cpow (le_of_lt hx),
push_cast,
end
lemma Gamma_add_one {s : ℝ} (hs : s ≠ 0) : Gamma (s + 1) = s * Gamma s :=
begin
simp_rw Gamma,
rw [complex.of_real_add, complex.of_real_one, complex.Gamma_add_one, complex.of_real_mul_re],
rwa complex.of_real_ne_zero,
end
lemma Gamma_one : Gamma 1 = 1 :=
by rw [Gamma, complex.of_real_one, complex.Gamma_one, complex.one_re]
lemma _root_.complex.Gamma_of_real (s : ℝ) : complex.Gamma (s : ℂ) = Gamma s :=
by rw [Gamma, eq_comm, ←complex.conj_eq_iff_re, ←complex.Gamma_conj, complex.conj_of_real]
theorem Gamma_nat_eq_factorial (n : ℕ) : Gamma (n + 1) = n! :=
by rw [Gamma, complex.of_real_add, complex.of_real_nat_cast, complex.of_real_one,
complex.Gamma_nat_eq_factorial, ←complex.of_real_nat_cast, complex.of_real_re]
/-- At `0` the Gamma function is undefined; by convention we assign it the value `0`. -/
lemma Gamma_zero : Gamma 0 = 0 :=
by simpa only [←complex.of_real_zero, complex.Gamma_of_real, complex.of_real_inj]
using complex.Gamma_zero
/-- At `-n` for `n ∈ ℕ`, the Gamma function is undefined; by convention we assign it the value `0`.
-/
lemma Gamma_neg_nat_eq_zero (n : ℕ) : Gamma (-n) = 0 :=
begin
simpa only [←complex.of_real_nat_cast, ←complex.of_real_neg, complex.Gamma_of_real,
complex.of_real_eq_zero] using complex.Gamma_neg_nat_eq_zero n,
end
lemma Gamma_pos_of_pos {s : ℝ} (hs : 0 < s) : 0 < Gamma s :=
begin
rw Gamma_eq_integral hs,
have : function.support (λ (x : ℝ), exp (-x) * x ^ (s - 1)) ∩ Ioi 0 = Ioi 0,
{ rw inter_eq_right_iff_subset,
intros x hx,
rw function.mem_support,
exact mul_ne_zero (exp_pos _).ne' (rpow_pos_of_pos hx _).ne' },
rw set_integral_pos_iff_support_of_nonneg_ae,
{ rw [this, volume_Ioi, ←ennreal.of_real_zero],
exact ennreal.of_real_lt_top },
{ refine eventually_of_mem (self_mem_ae_restrict measurable_set_Ioi) _,
exact λ x hx, (mul_pos (exp_pos _) (rpow_pos_of_pos hx _)).le },
{ exact Gamma_integral_convergent hs },
end
/-- The Gamma function does not vanish on `ℝ` (except at non-positive integers, where the function
is mathematically undefined and we set it to `0` by convention). -/
lemma Gamma_ne_zero {s : ℝ} (hs : ∀ m : ℕ, s ≠ -m) : Gamma s ≠ 0 :=
begin
suffices : ∀ {n : ℕ}, (-(n:ℝ) < s) → Gamma s ≠ 0,
{ apply this,
swap, use (⌊-s⌋₊ + 1),
rw [neg_lt, nat.cast_add, nat.cast_one],
exact nat.lt_floor_add_one _ },
intro n,
induction n generalizing s,
{ intro hs,
refine (Gamma_pos_of_pos _).ne',
rwa [nat.cast_zero, neg_zero] at hs },
{ intro hs',
have : Gamma (s + 1) ≠ 0,
{ apply n_ih,
{ intro m,
specialize hs (1 + m),
contrapose! hs,
rw ←eq_sub_iff_add_eq at hs,
rw hs,
push_cast,
ring },
{ rw [nat.succ_eq_add_one, nat.cast_add, nat.cast_one, neg_add] at hs',
linarith } },
rw [Gamma_add_one, mul_ne_zero_iff] at this,
{ exact this.2 },
{ simpa using hs 0 } },
end
lemma Gamma_eq_zero_iff (s : ℝ) : Gamma s = 0 ↔ ∃ m : ℕ, s = -m :=
⟨by { contrapose!, exact Gamma_ne_zero }, by { rintro ⟨m, rfl⟩, exact Gamma_neg_nat_eq_zero m }⟩
lemma differentiable_at_Gamma {s : ℝ} (hs : ∀ m : ℕ, s ≠ -m) : differentiable_at ℝ Gamma s :=
begin
refine ((complex.differentiable_at_Gamma _ _).has_deriv_at).real_of_complex.differentiable_at,
simp_rw [←complex.of_real_nat_cast, ←complex.of_real_neg, ne.def, complex.of_real_inj],
exact hs,
end
end real
|
2a12dcc58bbf3c184c59523d8609c911adac1ab1 | ee8cdbabf07f77e7be63a449b8483ce308d37218 | /lean/src/valid/mathd-numbertheory-32.lean | 7f8364d96bee46524e086068898a6c4f87a5fdfd | [
"MIT",
"Apache-2.0"
] | permissive | zeta1999/miniF2F | 6d66c75d1c18152e224d07d5eed57624f731d4b7 | c1ba9629559c5273c92ec226894baa0c1ce27861 | refs/heads/main | 1,681,897,460,642 | 1,620,646,361,000 | 1,620,646,361,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 374 | lean | /-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kunhao Zheng
-/
import algebra.big_operators.basic
import data.pnat.basic
import data.finset.basic
open_locale big_operators
example (h₀ : fintype { n : ℕ | n ∣ 36}) : ∑ k in { n : ℕ | n ∣ 36}.to_finset, k = 91 :=
begin
sorry
end
|
b9f02b2d91621ff088d051bc9d9825e5df8a5b68 | e09201d437062e1f95e6e5360aab0c9f947901aa | /src/languages/basic.lean | a25b12547144cc8d9fed829dd830d1c57672bf03 | [] | no_license | VArtem/lean-regular-languages | 34f4b093f28ef2f09ba7e684e642a0f97c901560 | e877243188253d0ac17ccf0ae2da7bf608686ff0 | refs/heads/master | 1,683,590,111,306 | 1,622,307,234,000 | 1,622,307,234,000 | 284,232,653 | 7 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,979 | lean | import data.set
import logic.function.iterate
import algebra.group_power
import tactic.nth_rewrite
import data.list.basic
open set
namespace languages
variable {S : Type}
@[simp] def append_lang (L M: set (list S)) :=
{ w : list S | ∃ {left right}, left ∈ L ∧ right ∈ M ∧ w = left ++ right}
@[simp] lemma append_eps (A : set (list S)) : append_lang A {[]} = A :=
begin
apply subset.antisymm, {
rintro _ ⟨left, right, hleft, hright, rfl⟩,
rw mem_singleton_iff at hright,
rwa [hright, list.append_nil],
}, {
rintro x xa,
use [x, [], xa, mem_singleton [], (list.append_nil x).symm],
},
end
@[simp] lemma eps_append (A : set (list S)) : append_lang {[]} A = A :=
begin
apply subset.antisymm, {
rintro _ ⟨ left, right, hleft, hright, rfl ⟩,
rw mem_singleton_iff at hleft,
rwa [hleft, list.nil_append],
}, {
rintro x xa,
use [[], x, xa, (list.nil_append x).symm],
},
end
lemma append_assoc (A B C : set (list S)):
append_lang (append_lang A B) C = append_lang A (append_lang B C) :=
begin
apply subset.antisymm, {
rintro _ ⟨_, right, ⟨ left, mid, hleft, hmid, rfl ⟩, hright, rfl ⟩,
use [left, mid ++ right, hleft, mid, right, hmid, hright],
exact list.append_assoc left mid right,
}, {
rintro _ ⟨left, _, hleft, ⟨ mid, right, hmid, hright, rfl ⟩, rfl ⟩,
use [left ++ mid, right, left, mid, hleft, hmid, hright],
exact (list.append_assoc left mid right).symm,
},
end
instance : monoid (set (list S)) := {
mul := append_lang,
mul_assoc := append_assoc,
one := {[]},
one_mul := eps_append,
mul_one := append_eps,
}
@[simp] lemma one_def : (1 : set (list S)) = {list.nil} := rfl
lemma append_subset_of_subset {A B C D : set (list S)} : A ⊆ C → B ⊆ D → A * B ⊆ C * D :=
begin
rintro hAC hBD x ⟨left, right, hleft, hright, rfl⟩,
use [left, right, hAC hleft, hBD hright],
end
lemma power_subset_of_subset {A B : set (list S)} {n : ℕ} : A ⊆ B → A^n ⊆ B^n :=
begin
intro hAB,
induction n with n hyp, {
simp only [pow_zero],
}, {
rw pow_succ,
apply append_subset_of_subset;
assumption,
},
end
lemma contain_eps_subset_power {A : set (list S)} {n : ℕ} {heps : 1 ⊆ A} : A ⊆ A^n.succ :=
begin
induction n with n hyp, {
rw pow_one,
}, {
rw pow_succ,
nth_rewrite 0 ←one_mul A,
apply append_subset_of_subset heps hyp,
}
end
lemma power_eq_list_join {L : set (list S)} {w : list S} {n : ℕ} :
w ∈ L^n ↔ ∃ l (h : ∀ x, x ∈ l → x ∈ L), w = list.join l ∧ l.length = n :=
begin
split, {
rintro hw,
induction n with n hyp generalizing w hw, {
use list.nil,
simp only [mem_singleton_iff, one_def, pow_zero] at hw,
simp only [hw, list.not_mem_nil, list.join, forall_const, forall_prop_of_false, list.length, eq_self_iff_true, not_false_iff,
and_self],
}, {
rw pow_succ at hw,
rcases hw with ⟨left, right, hleft, hright, rfl⟩,
rcases hyp hright with ⟨l, h, rfl, rfl⟩,
use [left :: l],
simpa only [hleft, true_and, list.join, forall_eq_or_imp, and_true, list.mem_cons_iff, list.length, eq_self_iff_true],
}
}, {
rintro ⟨l, h, rfl, rfl⟩,
induction l with head tail hyp, {
simp only [list.join, list.length, one_def, pow_zero, mem_singleton],
}, {
use [head, tail.join],
split, {
apply h head,
apply list.mem_cons_self,
},
split, {
apply hyp,
intros x hx,
refine (h _ _),
simp only [hx, list.mem_cons_iff, or_true],
},
refl,
},
}
end
end languages |
003055323a57fe650fbf9c22700b73aa52bb3f34 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/implicitTypePos.lean | 5e071e238e23d523d0ab145954032d96274a1948 | [
"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 | 103 | lean | def f x y := 0
def g (x y z) := 0 + x + z
def h {α β} (a : α) := a
def r {{α β}} (a : α) := a
|
869fa47d80933e22908ed752c7c0090d89829c40 | f20db13587f4dd28a4b1fbd31953afd491691fa0 | /library/init/data/setoid.lean | f5bcbc14878643477c39c55b46335420e1a26acc | [
"Apache-2.0"
] | permissive | AHartNtkn/lean | 9a971edfc6857c63edcbf96bea6841b9a84cf916 | 0d83a74b26541421fc1aa33044c35b03759710ed | refs/heads/master | 1,620,592,591,236 | 1,516,749,881,000 | 1,516,749,881,000 | 118,697,288 | 1 | 0 | null | 1,516,759,470,000 | 1,516,759,470,000 | null | UTF-8 | Lean | false | false | 883 | 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
-/
prelude
import init.logic
universes u
class setoid (α : Sort u) :=
(r : α → α → Prop) (iseqv : equivalence r)
instance setoid_has_equiv {α : Sort u} [setoid α] : has_equiv α :=
⟨setoid.r⟩
namespace setoid
variable {α : Sort u}
variable [s : setoid α]
include s
@[refl] lemma refl [setoid α] (a : α) : a ≈ a :=
match setoid.iseqv α with
| ⟨h_refl, h_symm, h_trans⟩ := h_refl a
end
@[symm] lemma symm {a b : α} (hab : a ≈ b) : b ≈ a :=
match setoid.iseqv α with
| ⟨h_refl, h_symm, h_trans⟩ := h_symm hab
end
@[trans] lemma trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c :=
match setoid.iseqv α with
| ⟨h_refl, h_symm, h_trans⟩ := h_trans hab hbc
end
end setoid
|
ad28359340992579daa53bf337476c4c9a8d47c9 | 01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab | /categories/universal/complete/default.lean | 3ac2dff19693c448f49cd51fa27ed94f051d096b | [] | no_license | PatrickMassot/lean-category-theory | 0f56a83464396a253c28a42dece16c93baf8ad74 | ef239978e91f2e1c3b8e88b6e9c64c155dc56c99 | refs/heads/master | 1,629,739,187,316 | 1,512,422,659,000 | 1,512,422,659,000 | 113,098,786 | 0 | 0 | null | 1,512,424,022,000 | 1,512,424,022,000 | null | UTF-8 | Lean | false | false | 3,310 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import ..instances
import ...discrete_category
open categories
open categories.functor
open categories.natural_transformation
open categories.functor_categories
open categories.isomorphism
open categories.products
open categories.initial
open categories.types
open categories.util
namespace categories.universal
class {u v} Complete_for ( C : Category.{u v} ) ( p : Category.{u v} → Prop ) :=
( limitCone : Π { J : Category.{u v} } ( w : p J ) ( F : Functor J C ), LimitCone F )
class {u v} Complete ( C : Category.{u v} ) :=
( limitCone : Π { J : Category.{u v} } ( F : Functor J C ), LimitCone F )
definition {u v} limitCone { C : Category.{u v} } [ Complete.{u v} C ] { J : Category.{u v} } ( F : Functor J C ) := Complete.limitCone F
definition {u v} limit { C : Category.{u v} } [ Complete.{u v} C ] { J : Category.{u v} } ( F : Functor J C ) := (Complete.limitCone F).terminal_object.cone_point
@[applicable] private lemma {u v} uniqueness_of_morphism_to_limit
{ J C : Category.{u v} }
{ F : Functor J C }
{ L : LimitCone F }
{ X : Cone F }
{ g : C.Hom X.cone_point L.terminal_object.cone_point }
( w : ∀ j : J.Obj, C.compose g ((L.terminal_object).cone_maps j) = X.cone_maps j )
: (L.morphism_to_terminal_object_from X).cone_morphism = g :=
begin
let G : (Cones F).Hom X L.terminal_object := ⟨ g, w ⟩,
have q := L.uniqueness_of_morphisms_to_terminal_object _ (L.morphism_to_terminal_object_from X) G,
exact congr_arg ConeMorphism.cone_morphism q,
end
@[simp,ematch] private lemma {u v} morphism_to_terminal_object_composed_with_cone_map
{ J C : Category.{u v} }
{ F : Functor J C }
{ L : LimitCone F }
{ X : Cone F }
{ j : J.Obj }
: C.compose (L.morphism_to_terminal_object_from X).cone_morphism (L.terminal_object.cone_maps j) = X.cone_maps j :=
(L.morphism_to_terminal_object_from X).commutativity j
@[applicable] definition morphism_to_terminal_object_cone_point
{ J D : Category }
{ Z : D.Obj }
{ G : Functor J D }
{ L : LimitCone G }
( cone_maps : Π j : J.Obj, D.Hom Z (G.onObjects j) )
( commutativity : Π j k : J.Obj, Π f : J.Hom j k, D.compose (cone_maps j) (G.onMorphisms f) = cone_maps k )
: D.Hom Z L.terminal_object.cone_point :=
begin
let cone : Cone G := {
cone_point := Z,
cone_maps := cone_maps,
commutativity := commutativity
},
exact (L.morphism_to_terminal_object_from cone).cone_morphism,
end
definition {u v} Limit { J C : Category.{u v} } [ Complete C ] : Functor (FunctorCategory J C) C := {
onObjects := λ F, (limitCone F).terminal_object.cone_point,
onMorphisms := λ F G τ, let lim_F := (limitCone F) in
let lim_G := (limitCone G) in
(lim_G.morphism_to_terminal_object_from {
cone_point := _,
cone_maps := (λ j, C.compose (lim_F.terminal_object.cone_maps j) (τ.components j)),
commutativity := ♯
}).cone_morphism,
identities := ♯,
functoriality := ♯
}
end categories.universal |
3a83ba6b46139a99a102071f61ca0e52f3d67483 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/module/submodule/basic.lean | 6b5d2175764bbebb6c594a02620ac387d6fe896b | [
"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 | 18,523 | lean | /-
Copyright (c) 2015 Nathaniel Thomas. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro
-/
import algebra.module.linear_map
import algebra.module.equiv
import group_theory.group_action.sub_mul_action
import group_theory.submonoid.membership
/-!
# Submodules of a module
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define
* `submodule R M` : a subset of a `module` `M` that contains zero and is closed with respect to
addition and scalar multiplication.
* `subspace k M` : an abbreviation for `submodule` assuming that `k` is a `field`.
## Tags
submodule, subspace, linear map
-/
open function
open_locale big_operators
universes u'' u' u v w
variables {G : Type u''} {S : Type u'} {R : Type u} {M : Type v} {ι : Type w}
set_option old_structure_cmd true
/-- A submodule of a module is one which is closed under vector operations.
This is a sufficient condition for the subset of vectors in the submodule
to themselves form a module. -/
structure submodule (R : Type u) (M : Type v) [semiring R]
[add_comm_monoid M] [module R M] extends add_submonoid M, sub_mul_action R M : Type v.
/-- Reinterpret a `submodule` as an `add_submonoid`. -/
add_decl_doc submodule.to_add_submonoid
/-- Reinterpret a `submodule` as an `sub_mul_action`. -/
add_decl_doc submodule.to_sub_mul_action
namespace submodule
variables [semiring R] [add_comm_monoid M] [module R M]
instance : set_like (submodule R M) M :=
{ coe := submodule.carrier,
coe_injective' := λ p q h, by cases p; cases q; congr' }
instance : add_submonoid_class (submodule R M) M :=
{ zero_mem := zero_mem',
add_mem := add_mem' }
instance : smul_mem_class (submodule R M) R M :=
{ smul_mem := smul_mem' }
@[simp] theorem mem_to_add_submonoid (p : submodule R M) (x : M) : x ∈ p.to_add_submonoid ↔ x ∈ p :=
iff.rfl
variables {p q : submodule R M}
@[simp]
lemma mem_mk {S : set M} {x : M} (h₁ h₂ h₃) : x ∈ (⟨S, h₁, h₂, h₃⟩ : submodule R M) ↔ x ∈ S :=
iff.rfl
@[simp] lemma coe_set_mk (S : set M) (h₁ h₂ h₃) :
((⟨S, h₁, h₂, h₃⟩ : submodule R M) : set M) = S := rfl
@[simp]
lemma mk_le_mk {S S' : set M} (h₁ h₂ h₃ h₁' h₂' h₃') :
(⟨S, h₁, h₂, h₃⟩ : submodule R M) ≤ (⟨S', h₁', h₂', h₃'⟩ : submodule R M) ↔ S ⊆ S' := iff.rfl
@[ext] theorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := set_like.ext h
/-- Copy of a submodule with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (p : submodule R M) (s : set M) (hs : s = ↑p) : submodule R M :=
{ carrier := s,
zero_mem' := hs.symm ▸ p.zero_mem',
add_mem' := λ _ _, hs.symm ▸ p.add_mem',
smul_mem' := hs.symm ▸ p.smul_mem' }
@[simp] lemma coe_copy (S : submodule R M) (s : set M) (hs : s = ↑S) :
(S.copy s hs : set M) = s := rfl
lemma copy_eq (S : submodule R M) (s : set M) (hs : s = ↑S) : S.copy s hs = S :=
set_like.coe_injective hs
theorem to_add_submonoid_injective :
injective (to_add_submonoid : submodule R M → add_submonoid M) :=
λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h)
@[simp] theorem to_add_submonoid_eq : p.to_add_submonoid = q.to_add_submonoid ↔ p = q :=
to_add_submonoid_injective.eq_iff
@[mono] lemma to_add_submonoid_strict_mono :
strict_mono (to_add_submonoid : submodule R M → add_submonoid M) := λ _ _, id
lemma to_add_submonoid_le : p.to_add_submonoid ≤ q.to_add_submonoid ↔ p ≤ q := iff.rfl
@[mono]
lemma to_add_submonoid_mono : monotone (to_add_submonoid : submodule R M → add_submonoid M) :=
to_add_submonoid_strict_mono.monotone
@[simp] theorem coe_to_add_submonoid (p : submodule R M) :
(p.to_add_submonoid : set M) = p := rfl
theorem to_sub_mul_action_injective :
injective (to_sub_mul_action : submodule R M → sub_mul_action R M) :=
λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h)
@[simp] theorem to_sub_mul_action_eq : p.to_sub_mul_action = q.to_sub_mul_action ↔ p = q :=
to_sub_mul_action_injective.eq_iff
@[mono] lemma to_sub_mul_action_strict_mono :
strict_mono (to_sub_mul_action : submodule R M → sub_mul_action R M) := λ _ _, id
@[mono]
lemma to_sub_mul_action_mono : monotone (to_sub_mul_action : submodule R M → sub_mul_action R M) :=
to_sub_mul_action_strict_mono.monotone
@[simp] theorem coe_to_sub_mul_action (p : submodule R M) :
(p.to_sub_mul_action : set M) = p := rfl
end submodule
namespace smul_mem_class
variables [semiring R] [add_comm_monoid M] [module R M] {A : Type*} [set_like A M]
[add_submonoid_class A M] [hA : smul_mem_class A R M] (S' : A)
include hA
/-- A submodule of a `module` is a `module`. -/
@[priority 75] -- Prefer subclasses of `module` over `smul_mem_class`.
instance to_module : module R S' :=
subtype.coe_injective.module R (add_submonoid_class.subtype S') (set_like.coe_smul S')
/-- The natural `R`-linear map from a submodule of an `R`-module `M` to `M`. -/
protected def subtype : S' →ₗ[R] M := ⟨coe, λ _ _, rfl, λ _ _, rfl⟩
@[simp] protected theorem coe_subtype : (smul_mem_class.subtype S' : S' → M) = coe := rfl
end smul_mem_class
namespace submodule
section add_comm_monoid
variables [semiring R] [add_comm_monoid M]
-- We can infer the module structure implicitly from the bundled submodule,
-- rather than via typeclass resolution.
variables {module_M : module R M}
variables {p q : submodule R M}
variables {r : R} {x y : M}
variables (p)
@[simp] lemma mem_carrier : x ∈ p.carrier ↔ x ∈ (p : set M) := iff.rfl
@[simp] protected lemma zero_mem : (0 : M) ∈ p := zero_mem _
protected lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := add_mem h₁ h₂
lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h
lemma smul_of_tower_mem [has_smul S R] [has_smul S M] [is_scalar_tower S R M]
(r : S) (h : x ∈ p) : r • x ∈ p :=
p.to_sub_mul_action.smul_of_tower_mem r h
protected lemma sum_mem {t : finset ι} {f : ι → M} : (∀c∈t, f c ∈ p) → (∑ i in t, f i) ∈ p :=
sum_mem
lemma sum_smul_mem {t : finset ι} {f : ι → M} (r : ι → R)
(hyp : ∀ c ∈ t, f c ∈ p) : (∑ i in t, r i • f i) ∈ p :=
sum_mem (λ i hi, smul_mem _ _ (hyp i hi))
@[simp] lemma smul_mem_iff' [group G] [mul_action G M] [has_smul G R] [is_scalar_tower G R M]
(g : G) : g • x ∈ p ↔ x ∈ p :=
p.to_sub_mul_action.smul_mem_iff' g
instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem x.2 y.2⟩⟩
instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩
instance : inhabited p := ⟨0⟩
instance [has_smul S R] [has_smul S M] [is_scalar_tower S R M] :
has_smul S p := ⟨λ c x, ⟨c • x.1, smul_of_tower_mem _ c x.2⟩⟩
instance [has_smul S R] [has_smul S M] [is_scalar_tower S R M] : is_scalar_tower S R p :=
p.to_sub_mul_action.is_scalar_tower
instance is_scalar_tower' {S' : Type*}
[has_smul S R] [has_smul S M] [has_smul S' R] [has_smul S' M] [has_smul S S']
[is_scalar_tower S' R M] [is_scalar_tower S S' M] [is_scalar_tower S R M] :
is_scalar_tower S S' p :=
p.to_sub_mul_action.is_scalar_tower'
instance
[has_smul S R] [has_smul S M] [is_scalar_tower S R M]
[has_smul Sᵐᵒᵖ R] [has_smul Sᵐᵒᵖ M] [is_scalar_tower Sᵐᵒᵖ R M]
[is_central_scalar S M] : is_central_scalar S p :=
p.to_sub_mul_action.is_central_scalar
protected lemma nonempty : (p : set M).nonempty := ⟨0, p.zero_mem⟩
@[simp] lemma mk_eq_zero {x} (h : x ∈ p) : (⟨x, h⟩ : p) = 0 ↔ x = 0 := subtype.ext_iff_val
variables {p}
@[simp, norm_cast] lemma coe_eq_zero {x : p} : (x : M) = 0 ↔ x = 0 :=
(set_like.coe_eq_coe : (x : M) = (0 : p) ↔ x = 0)
@[simp, norm_cast] lemma coe_add (x y : p) : (↑(x + y) : M) = ↑x + ↑y := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : p) : M) = 0 := rfl
@[norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl
@[simp, norm_cast] lemma coe_smul_of_tower [has_smul S R] [has_smul S M] [is_scalar_tower S R M]
(r : S) (x : p) : ((r • x : p) : M) = r • ↑x := rfl
@[simp, norm_cast] lemma coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl
@[simp] lemma coe_mem (x : p) : (x : M) ∈ p := x.2
variables (p)
instance : add_comm_monoid p :=
{ add := (+), zero := 0, .. p.to_add_submonoid.to_add_comm_monoid }
instance module' [semiring S] [has_smul S R] [module S M] [is_scalar_tower S R M] : module S p :=
by refine {smul := (•), ..p.to_sub_mul_action.mul_action', ..};
{ intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] }
instance : module R p := p.module'
instance no_zero_smul_divisors [no_zero_smul_divisors R M] : no_zero_smul_divisors R p :=
⟨λ c x h,
have c = 0 ∨ (x : M) = 0,
from eq_zero_or_eq_zero_of_smul_eq_zero (congr_arg coe h),
this.imp_right (@subtype.ext_iff _ _ x 0).mpr⟩
/-- Embedding of a submodule `p` to the ambient space `M`. -/
protected def subtype : p →ₗ[R] M :=
by refine {to_fun := coe, ..}; simp [coe_smul]
theorem subtype_apply (x : p) : p.subtype x = x := rfl
@[simp] lemma coe_subtype : ((submodule.subtype p) : p → M) = coe := rfl
lemma injective_subtype : injective p.subtype := subtype.coe_injective
/-- Note the `add_submonoid` version of this lemma is called `add_submonoid.coe_finset_sum`. -/
@[simp] lemma coe_sum (x : ι → p) (s : finset ι) : ↑(∑ i in s, x i) = ∑ i in s, (x i : M) :=
map_sum p.subtype _ _
section add_action
/-! ### Additive actions by `submodule`s
These instances transfer the action by an element `m : M` of a `R`-module `M` written as `m +ᵥ a`
onto the action by an element `s : S` of a submodule `S : submodule R M` such that
`s +ᵥ a = (s : M) +ᵥ a`.
These instances work particularly well in conjunction with `add_group.to_add_action`, enabling
`s +ᵥ m` as an alias for `↑s + m`.
-/
variables {α β : Type*}
instance [has_vadd M α] : has_vadd p α := p.to_add_submonoid.has_vadd
instance vadd_comm_class [has_vadd M β] [has_vadd α β] [vadd_comm_class M α β] :
vadd_comm_class p α β := ⟨λ a, (vadd_comm (a : M) : _)⟩
instance [has_vadd M α] [has_faithful_vadd M α] :
has_faithful_vadd p α := ⟨λ x y h, subtype.ext $ eq_of_vadd_eq_vadd h⟩
/-- The action by a submodule is the action by the underlying module. -/
instance [add_action M α] : add_action p α := add_action.comp_hom _ p.subtype.to_add_monoid_hom
variable {p}
lemma vadd_def [has_vadd M α] (g : p) (m : α) : g +ᵥ m = (g : M) +ᵥ m := rfl
end add_action
section restrict_scalars
variables (S) [semiring S] [module S M] [module R M] [has_smul S R] [is_scalar_tower S R M]
/--
`V.restrict_scalars S` is the `S`-submodule of the `S`-module given by restriction of scalars,
corresponding to `V`, an `R`-submodule of the original `R`-module.
-/
def restrict_scalars (V : submodule R M) : submodule S M :=
{ carrier := V,
zero_mem' := V.zero_mem,
smul_mem' := λ c m h, V.smul_of_tower_mem c h,
add_mem' := λ x y hx hy, V.add_mem hx hy }
@[simp]
lemma coe_restrict_scalars (V : submodule R M) : (V.restrict_scalars S : set M) = V :=
rfl
@[simp]
lemma restrict_scalars_mem (V : submodule R M) (m : M) : m ∈ V.restrict_scalars S ↔ m ∈ V :=
iff.refl _
@[simp]
lemma restrict_scalars_self (V : submodule R M) : V.restrict_scalars R = V :=
set_like.coe_injective rfl
variables (R S M)
lemma restrict_scalars_injective :
function.injective (restrict_scalars S : submodule R M → submodule S M) :=
λ V₁ V₂ h, ext $ set.ext_iff.1 (set_like.ext'_iff.1 h : _)
@[simp] lemma restrict_scalars_inj {V₁ V₂ : submodule R M} :
restrict_scalars S V₁ = restrict_scalars S V₂ ↔ V₁ = V₂ :=
(restrict_scalars_injective S _ _).eq_iff
/-- Even though `p.restrict_scalars S` has type `submodule S M`, it is still an `R`-module. -/
instance restrict_scalars.orig_module (p : submodule R M) :
module R (p.restrict_scalars S) :=
(by apply_instance : module R p)
instance (p : submodule R M) : is_scalar_tower S R (p.restrict_scalars S) :=
{ smul_assoc := λ r s x, subtype.ext $ smul_assoc r s (x : M) }
/-- `restrict_scalars S` is an embedding of the lattice of `R`-submodules into
the lattice of `S`-submodules. -/
@[simps]
def restrict_scalars_embedding : submodule R M ↪o submodule S M :=
{ to_fun := restrict_scalars S,
inj' := restrict_scalars_injective S R M,
map_rel_iff' := λ p q, by simp [set_like.le_def] }
/-- Turning `p : submodule R M` into an `S`-submodule gives the same module structure
as turning it into a type and adding a module structure. -/
@[simps {simp_rhs := tt}]
def restrict_scalars_equiv (p : submodule R M) : p.restrict_scalars S ≃ₗ[R] p :=
{ to_fun := id, inv_fun := id, map_smul' := λ c x, rfl, .. add_equiv.refl p }
end restrict_scalars
end add_comm_monoid
section add_comm_group
variables [ring R] [add_comm_group M]
variables {module_M : module R M}
variables (p p' : submodule R M)
variables {r : R} {x y : M}
instance [module R M] : add_subgroup_class (submodule R M) M :=
{ neg_mem := λ p x, p.to_sub_mul_action.neg_mem,
.. submodule.add_submonoid_class }
protected lemma neg_mem (hx : x ∈ p) : -x ∈ p := neg_mem hx
/-- Reinterpret a submodule as an additive subgroup. -/
def to_add_subgroup : add_subgroup M :=
{ neg_mem' := λ _, p.neg_mem , .. p.to_add_submonoid }
@[simp] lemma coe_to_add_subgroup : (p.to_add_subgroup : set M) = p := rfl
@[simp] lemma mem_to_add_subgroup : x ∈ p.to_add_subgroup ↔ x ∈ p := iff.rfl
include module_M
theorem to_add_subgroup_injective : injective (to_add_subgroup : submodule R M → add_subgroup M)
| p q h := set_like.ext (set_like.ext_iff.1 h : _)
@[simp] theorem to_add_subgroup_eq : p.to_add_subgroup = p'.to_add_subgroup ↔ p = p' :=
to_add_subgroup_injective.eq_iff
@[mono] lemma to_add_subgroup_strict_mono :
strict_mono (to_add_subgroup : submodule R M → add_subgroup M) := λ _ _, id
lemma to_add_subgroup_le : p.to_add_subgroup ≤ p'.to_add_subgroup ↔ p ≤ p' := iff.rfl
@[mono] lemma to_add_subgroup_mono : monotone (to_add_subgroup : submodule R M → add_subgroup M) :=
to_add_subgroup_strict_mono.monotone
omit module_M
protected lemma sub_mem : x ∈ p → y ∈ p → x - y ∈ p := sub_mem
protected lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := neg_mem_iff
protected lemma add_mem_iff_left : y ∈ p → (x + y ∈ p ↔ x ∈ p) := add_mem_cancel_right
protected lemma add_mem_iff_right : x ∈ p → (x + y ∈ p ↔ y ∈ p) := add_mem_cancel_left
protected lemma coe_neg (x : p) : ((-x : p) : M) = -x := add_subgroup_class.coe_neg _
protected lemma coe_sub (x y : p) : (↑(x - y) : M) = ↑x - ↑y := add_subgroup_class.coe_sub _ _
lemma sub_mem_iff_left (hy : y ∈ p) : (x - y) ∈ p ↔ x ∈ p :=
by rw [sub_eq_add_neg, p.add_mem_iff_left (p.neg_mem hy)]
lemma sub_mem_iff_right (hx : x ∈ p) : (x - y) ∈ p ↔ y ∈ p :=
by rw [sub_eq_add_neg, p.add_mem_iff_right hx, p.neg_mem_iff]
instance : add_comm_group p :=
{ add := (+), zero := 0, neg := has_neg.neg, ..p.to_add_subgroup.to_add_comm_group }
end add_comm_group
section is_domain
variables [ring R] [is_domain R]
variables [add_comm_group M] [module R M] {b : ι → M}
lemma not_mem_of_ortho {x : M} {N : submodule R M}
(ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) :
x ∉ N :=
by { intro hx, simpa using ortho (-1) x hx }
lemma ne_zero_of_ortho {x : M} {N : submodule R M}
(ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) :
x ≠ 0 :=
mt (λ h, show x ∈ N, from h.symm ▸ N.zero_mem) (not_mem_of_ortho ortho)
end is_domain
section ordered_monoid
variables [semiring R]
/-- A submodule of an `ordered_add_comm_monoid` is an `ordered_add_comm_monoid`. -/
instance to_ordered_add_comm_monoid
{M} [ordered_add_comm_monoid M] [module R M] (S : submodule R M) :
ordered_add_comm_monoid S :=
subtype.coe_injective.ordered_add_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl)
/-- A submodule of a `linear_ordered_add_comm_monoid` is a `linear_ordered_add_comm_monoid`. -/
instance to_linear_ordered_add_comm_monoid
{M} [linear_ordered_add_comm_monoid M] [module R M] (S : submodule R M) :
linear_ordered_add_comm_monoid S :=
subtype.coe_injective.linear_ordered_add_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
(λ _ _, rfl)
/-- A submodule of an `ordered_cancel_add_comm_monoid` is an `ordered_cancel_add_comm_monoid`. -/
instance to_ordered_cancel_add_comm_monoid
{M} [ordered_cancel_add_comm_monoid M] [module R M] (S : submodule R M) :
ordered_cancel_add_comm_monoid S :=
subtype.coe_injective.ordered_cancel_add_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl)
/-- A submodule of a `linear_ordered_cancel_add_comm_monoid` is a
`linear_ordered_cancel_add_comm_monoid`. -/
instance to_linear_ordered_cancel_add_comm_monoid
{M} [linear_ordered_cancel_add_comm_monoid M] [module R M] (S : submodule R M) :
linear_ordered_cancel_add_comm_monoid S :=
subtype.coe_injective.linear_ordered_cancel_add_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl)
(λ _ _, rfl) (λ _ _, rfl)
end ordered_monoid
section ordered_group
variables [ring R]
/-- A submodule of an `ordered_add_comm_group` is an `ordered_add_comm_group`. -/
instance to_ordered_add_comm_group
{M} [ordered_add_comm_group M] [module R M] (S : submodule R M) :
ordered_add_comm_group S :=
subtype.coe_injective.ordered_add_comm_group coe
rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
/-- A submodule of a `linear_ordered_add_comm_group` is a
`linear_ordered_add_comm_group`. -/
instance to_linear_ordered_add_comm_group
{M} [linear_ordered_add_comm_group M] [module R M] (S : submodule R M) :
linear_ordered_add_comm_group S :=
subtype.coe_injective.linear_ordered_add_comm_group coe
rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
end ordered_group
end submodule
namespace submodule
variables [division_ring S] [semiring R] [add_comm_monoid M] [module R M]
variables [has_smul S R] [module S M] [is_scalar_tower S R M]
variables (p : submodule R M) {s : S} {x y : M}
theorem smul_mem_iff (s0 : s ≠ 0) : s • x ∈ p ↔ x ∈ p :=
p.to_sub_mul_action.smul_mem_iff s0
end submodule
/-- Subspace of a vector space. Defined to equal `submodule`. -/
abbreviation subspace (R : Type u) (M : Type v)
[division_ring R] [add_comm_group M] [module R M] :=
submodule R M
|
5d8581f55e54a70da319c0c44756a8adaa3f19df | 94e33a31faa76775069b071adea97e86e218a8ee | /src/order/atoms.lean | d200acc5025f18a5532a0bca2715b059345af0a6 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 26,541 | lean | /-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import order.complete_boolean_algebra
import order.cover
import order.modular_lattice
import data.fintype.basic
/-!
# Atoms, Coatoms, and Simple Lattices
This module defines atoms, which are minimal non-`⊥` elements in bounded lattices, simple lattices,
which are lattices with only two elements, and related ideas.
## Main definitions
### Atoms and Coatoms
* `is_atom a` indicates that the only element below `a` is `⊥`.
* `is_coatom a` indicates that the only element above `a` is `⊤`.
### Atomic and Atomistic Lattices
* `is_atomic` indicates that every element other than `⊥` is above an atom.
* `is_coatomic` indicates that every element other than `⊤` is below a coatom.
* `is_atomistic` indicates that every element is the `Sup` of a set of atoms.
* `is_coatomistic` indicates that every element is the `Inf` of a set of coatoms.
### Simple Lattices
* `is_simple_order` indicates that an order has only two unique elements, `⊥` and `⊤`.
* `is_simple_order.bounded_order`
* `is_simple_order.distrib_lattice`
* Given an instance of `is_simple_order`, we provide the following definitions. These are not
made global instances as they contain data :
* `is_simple_order.boolean_algebra`
* `is_simple_order.complete_lattice`
* `is_simple_order.complete_boolean_algebra`
## Main results
* `is_atom_dual_iff_is_coatom` and `is_coatom_dual_iff_is_atom` express the (definitional) duality
of `is_atom` and `is_coatom`.
* `is_simple_order_iff_is_atom_top` and `is_simple_order_iff_is_coatom_bot` express the
connection between atoms, coatoms, and simple lattices
* `is_compl.is_atom_iff_is_coatom` and `is_compl.is_coatom_if_is_atom`: In a modular
bounded lattice, a complement of an atom is a coatom and vice versa.
* `is_atomic_iff_is_coatomic`: A modular complemented lattice is atomic iff it is coatomic.
* `fintype.to_is_atomic`, `fintype.to_is_coatomic`: Finite partial orders with bottom resp. top
are atomic resp. coatomic.
-/
variable {α : Type*}
section atoms
section is_atom
section preorder
variables [preorder α] [order_bot α] {a b x : α}
/-- An atom of an `order_bot` is an element with no other element between it and `⊥`,
which is not `⊥`. -/
def is_atom (a : α) : Prop := a ≠ ⊥ ∧ (∀ b, b < a → b = ⊥)
lemma is_atom.Iic (ha : is_atom a) (hax : a ≤ x) : is_atom (⟨a, hax⟩ : set.Iic x) :=
⟨λ con, ha.1 (subtype.mk_eq_mk.1 con), λ ⟨b, hb⟩ hba, subtype.mk_eq_mk.2 (ha.2 b hba)⟩
lemma is_atom.of_is_atom_coe_Iic {a : set.Iic x} (ha : is_atom a) : is_atom (a : α) :=
⟨λ con, ha.1 (subtype.ext con), λ b hba, subtype.mk_eq_mk.1 (ha.2 ⟨b, hba.le.trans a.prop⟩ hba)⟩
end preorder
variables [partial_order α] [order_bot α] {a b x : α}
lemma is_atom.lt_iff (h : is_atom a) : x < a ↔ x = ⊥ := ⟨h.2 x, λ hx, hx.symm ▸ h.1.bot_lt⟩
lemma is_atom.le_iff (h : is_atom a) : x ≤ a ↔ x = ⊥ ∨ x = a :=
by rw [le_iff_lt_or_eq, h.lt_iff]
lemma is_atom.Iic_eq (h : is_atom a) : set.Iic a = {⊥, a} := set.ext $ λ x, h.le_iff
@[simp] lemma bot_covby_iff : ⊥ ⋖ a ↔ is_atom a :=
by simp only [covby, bot_lt_iff_ne_bot, is_atom, not_imp_not]
alias bot_covby_iff ↔ covby.is_atom is_atom.bot_covby
end is_atom
section is_coatom
section preorder
variables [preorder α]
/-- A coatom of an `order_top` is an element with no other element between it and `⊤`,
which is not `⊤`. -/
def is_coatom [order_top α] (a : α) : Prop := a ≠ ⊤ ∧ (∀ b, a < b → b = ⊤)
@[simp] lemma is_coatom_dual_iff_is_atom [order_bot α] {a : α}:
is_coatom (order_dual.to_dual a) ↔ is_atom a :=
iff.rfl
@[simp] lemma is_atom_dual_iff_is_coatom [order_top α] {a : α} :
is_atom (order_dual.to_dual a) ↔ is_coatom a :=
iff.rfl
alias is_coatom_dual_iff_is_atom ↔ _ is_atom.dual
alias is_atom_dual_iff_is_coatom ↔ _ is_coatom.dual
variables [order_top α] {a x : α}
lemma is_coatom.Ici (ha : is_coatom a) (hax : x ≤ a) : is_coatom (⟨a, hax⟩ : set.Ici x) :=
ha.dual.Iic hax
lemma is_coatom.of_is_coatom_coe_Ici {a : set.Ici x} (ha : is_coatom a) :
is_coatom (a : α) :=
@is_atom.of_is_atom_coe_Iic αᵒᵈ _ _ x a ha
end preorder
variables [partial_order α] [order_top α] {a b x : α}
lemma is_coatom.lt_iff (h : is_coatom a) : a < x ↔ x = ⊤ := h.dual.lt_iff
lemma is_coatom.le_iff (h : is_coatom a) : a ≤ x ↔ x = ⊤ ∨ x = a := h.dual.le_iff
lemma is_coatom.Ici_eq (h : is_coatom a) : set.Ici a = {⊤, a} := h.dual.Iic_eq
@[simp] lemma covby_top_iff : a ⋖ ⊤ ↔ is_coatom a :=
to_dual_covby_to_dual_iff.symm.trans bot_covby_iff
alias covby_top_iff ↔ covby.is_coatom is_coatom.covby_top
end is_coatom
section pairwise
lemma is_atom.inf_eq_bot_of_ne [semilattice_inf α] [order_bot α] {a b : α}
(ha : is_atom a) (hb : is_atom b) (hab : a ≠ b) : a ⊓ b = ⊥ :=
hab.not_le_or_not_le.elim (ha.lt_iff.1 ∘ inf_lt_left.2) (hb.lt_iff.1 ∘ inf_lt_right.2)
lemma is_atom.disjoint_of_ne [semilattice_inf α] [order_bot α] {a b : α}
(ha : is_atom a) (hb : is_atom b) (hab : a ≠ b) : disjoint a b :=
disjoint_iff.mpr (is_atom.inf_eq_bot_of_ne ha hb hab)
lemma is_coatom.sup_eq_top_of_ne [semilattice_sup α] [order_top α] {a b : α}
(ha : is_coatom a) (hb : is_coatom b) (hab : a ≠ b) : a ⊔ b = ⊤ :=
ha.dual.inf_eq_bot_of_ne hb.dual hab
end pairwise
end atoms
section atomic
variables [partial_order α] (α)
/-- A lattice is atomic iff every element other than `⊥` has an atom below it. -/
class is_atomic [order_bot α] : Prop :=
(eq_bot_or_exists_atom_le : ∀ (b : α), b = ⊥ ∨ ∃ (a : α), is_atom a ∧ a ≤ b)
/-- A lattice is coatomic iff every element other than `⊤` has a coatom above it. -/
class is_coatomic [order_top α] : Prop :=
(eq_top_or_exists_le_coatom : ∀ (b : α), b = ⊤ ∨ ∃ (a : α), is_coatom a ∧ b ≤ a)
export is_atomic (eq_bot_or_exists_atom_le) is_coatomic (eq_top_or_exists_le_coatom)
variable {α}
@[simp] lemma is_coatomic_dual_iff_is_atomic [order_bot α] : is_coatomic αᵒᵈ ↔ is_atomic α :=
⟨λ h, ⟨λ b, by apply h.eq_top_or_exists_le_coatom⟩, λ h, ⟨λ b, by apply h.eq_bot_or_exists_atom_le⟩⟩
@[simp] lemma is_atomic_dual_iff_is_coatomic [order_top α] : is_atomic αᵒᵈ ↔ is_coatomic α :=
⟨λ h, ⟨λ b, by apply h.eq_bot_or_exists_atom_le⟩, λ h, ⟨λ b, by apply h.eq_top_or_exists_le_coatom⟩⟩
namespace is_atomic
variables [order_bot α] [is_atomic α]
instance is_coatomic_dual : is_coatomic αᵒᵈ := is_coatomic_dual_iff_is_atomic.2 ‹is_atomic α›
instance {x : α} : is_atomic (set.Iic x) :=
⟨λ ⟨y, hy⟩, (eq_bot_or_exists_atom_le y).imp subtype.mk_eq_mk.2
(λ ⟨a, ha, hay⟩, ⟨⟨a, hay.trans hy⟩, ha.Iic (hay.trans hy), hay⟩)⟩
end is_atomic
namespace is_coatomic
variables [order_top α] [is_coatomic α]
instance is_coatomic : is_atomic αᵒᵈ := is_atomic_dual_iff_is_coatomic.2 ‹is_coatomic α›
instance {x : α} : is_coatomic (set.Ici x) :=
⟨λ ⟨y, hy⟩, (eq_top_or_exists_le_coatom y).imp subtype.mk_eq_mk.2
(λ ⟨a, ha, hay⟩, ⟨⟨a, le_trans hy hay⟩, ha.Ici (le_trans hy hay), hay⟩)⟩
end is_coatomic
theorem is_atomic_iff_forall_is_atomic_Iic [order_bot α] :
is_atomic α ↔ ∀ (x : α), is_atomic (set.Iic x) :=
⟨@is_atomic.set.Iic.is_atomic _ _ _, λ h, ⟨λ x, ((@eq_bot_or_exists_atom_le _ _ _ (h x))
(⊤ : set.Iic x)).imp subtype.mk_eq_mk.1 (exists_imp_exists' coe
(λ ⟨a, ha⟩, and.imp_left (is_atom.of_is_atom_coe_Iic)))⟩⟩
theorem is_coatomic_iff_forall_is_coatomic_Ici [order_top α] :
is_coatomic α ↔ ∀ (x : α), is_coatomic (set.Ici x) :=
is_atomic_dual_iff_is_coatomic.symm.trans $ is_atomic_iff_forall_is_atomic_Iic.trans $ forall_congr
(λ x, is_coatomic_dual_iff_is_atomic.symm.trans iff.rfl)
section well_founded
lemma is_atomic_of_order_bot_well_founded_lt [order_bot α]
(h : well_founded ((<) : α → α → Prop)) : is_atomic α :=
⟨λ a, or_iff_not_imp_left.2 $
λ ha, let ⟨b, hb, hm⟩ := h.has_min { b | b ≠ ⊥ ∧ b ≤ a } ⟨a, ha, le_rfl⟩ in
⟨b, ⟨hb.1, λ c, not_imp_not.1 $ λ hc hl, hm c ⟨hc, hl.le.trans hb.2⟩ hl⟩, hb.2⟩⟩
lemma is_coatomic_of_order_top_gt_well_founded [order_top α]
(h : well_founded ((>) : α → α → Prop)) : is_coatomic α :=
is_atomic_dual_iff_is_coatomic.1 (@is_atomic_of_order_bot_well_founded_lt αᵒᵈ _ _ h)
end well_founded
end atomic
section atomistic
variables (α) [complete_lattice α]
/-- A lattice is atomistic iff every element is a `Sup` of a set of atoms. -/
class is_atomistic : Prop :=
(eq_Sup_atoms : ∀ (b : α), ∃ (s : set α), b = Sup s ∧ ∀ a, a ∈ s → is_atom a)
/-- A lattice is coatomistic iff every element is an `Inf` of a set of coatoms. -/
class is_coatomistic : Prop :=
(eq_Inf_coatoms : ∀ (b : α), ∃ (s : set α), b = Inf s ∧ ∀ a, a ∈ s → is_coatom a)
export is_atomistic (eq_Sup_atoms) is_coatomistic (eq_Inf_coatoms)
variable {α}
@[simp]
theorem is_coatomistic_dual_iff_is_atomistic : is_coatomistic αᵒᵈ ↔ is_atomistic α :=
⟨λ h, ⟨λ b, by apply h.eq_Inf_coatoms⟩, λ h, ⟨λ b, by apply h.eq_Sup_atoms⟩⟩
@[simp]
theorem is_atomistic_dual_iff_is_coatomistic : is_atomistic αᵒᵈ ↔ is_coatomistic α :=
⟨λ h, ⟨λ b, by apply h.eq_Sup_atoms⟩, λ h, ⟨λ b, by apply h.eq_Inf_coatoms⟩⟩
namespace is_atomistic
instance is_coatomistic_dual [h : is_atomistic α] : is_coatomistic αᵒᵈ :=
is_coatomistic_dual_iff_is_atomistic.2 h
variable [is_atomistic α]
@[priority 100]
instance : is_atomic α :=
⟨λ b, by { rcases eq_Sup_atoms b with ⟨s, rfl, hs⟩,
cases s.eq_empty_or_nonempty with h h,
{ simp [h] },
{ exact or.intro_right _ ⟨h.some, hs _ h.some_spec, le_Sup h.some_spec⟩ } } ⟩
end is_atomistic
section is_atomistic
variables [is_atomistic α]
@[simp]
theorem Sup_atoms_le_eq (b : α) : Sup {a : α | is_atom a ∧ a ≤ b} = b :=
begin
rcases eq_Sup_atoms b with ⟨s, rfl, hs⟩,
exact le_antisymm (Sup_le (λ _, and.right)) (Sup_le_Sup (λ a ha, ⟨hs a ha, le_Sup ha⟩)),
end
@[simp]
theorem Sup_atoms_eq_top : Sup {a : α | is_atom a} = ⊤ :=
begin
refine eq.trans (congr rfl (set.ext (λ x, _))) (Sup_atoms_le_eq ⊤),
exact (and_iff_left le_top).symm,
end
theorem le_iff_atom_le_imp {a b : α} :
a ≤ b ↔ ∀ c : α, is_atom c → c ≤ a → c ≤ b :=
⟨λ ab c hc ca, le_trans ca ab, λ h, begin
rw [← Sup_atoms_le_eq a, ← Sup_atoms_le_eq b],
exact Sup_le_Sup (λ c hc, ⟨hc.1, h c hc.1 hc.2⟩),
end⟩
end is_atomistic
namespace is_coatomistic
instance is_atomistic_dual [h : is_coatomistic α] : is_atomistic αᵒᵈ :=
is_atomistic_dual_iff_is_coatomistic.2 h
variable [is_coatomistic α]
@[priority 100]
instance : is_coatomic α :=
⟨λ b, by { rcases eq_Inf_coatoms b with ⟨s, rfl, hs⟩,
cases s.eq_empty_or_nonempty with h h,
{ simp [h] },
{ exact or.intro_right _ ⟨h.some, hs _ h.some_spec, Inf_le h.some_spec⟩ } } ⟩
end is_coatomistic
end atomistic
/-- An order is simple iff it has exactly two elements, `⊥` and `⊤`. -/
class is_simple_order (α : Type*) [has_le α] [bounded_order α] extends nontrivial α : Prop :=
(eq_bot_or_eq_top : ∀ (a : α), a = ⊥ ∨ a = ⊤)
export is_simple_order (eq_bot_or_eq_top)
theorem is_simple_order_iff_is_simple_order_order_dual [has_le α] [bounded_order α] :
is_simple_order α ↔ is_simple_order αᵒᵈ :=
begin
split; intro i; haveI := i,
{ exact { exists_pair_ne := @exists_pair_ne α _,
eq_bot_or_eq_top := λ a, or.symm (eq_bot_or_eq_top ((order_dual.of_dual a)) : _ ∨ _) } },
{ exact { exists_pair_ne := @exists_pair_ne αᵒᵈ _,
eq_bot_or_eq_top := λ a, or.symm (eq_bot_or_eq_top (order_dual.to_dual a)) } }
end
lemma is_simple_order.bot_ne_top [has_le α] [bounded_order α] [is_simple_order α] :
(⊥ : α) ≠ (⊤ : α) :=
begin
obtain ⟨a, b, h⟩ := exists_pair_ne α,
rcases eq_bot_or_eq_top a with rfl|rfl;
rcases eq_bot_or_eq_top b with rfl|rfl;
simpa <|> simpa using h.symm
end
section is_simple_order
variables [partial_order α] [bounded_order α] [is_simple_order α]
instance {α} [has_le α] [bounded_order α] [is_simple_order α] : is_simple_order αᵒᵈ :=
is_simple_order_iff_is_simple_order_order_dual.1 (by apply_instance)
/-- A simple `bounded_order` induces a preorder. This is not an instance to prevent loops. -/
protected def is_simple_order.preorder {α} [has_le α] [bounded_order α] [is_simple_order α] :
preorder α :=
{ le := (≤),
le_refl := λ a, by rcases eq_bot_or_eq_top a with rfl|rfl; simp,
le_trans := λ a b c, begin
rcases eq_bot_or_eq_top a with rfl|rfl,
{ simp },
{ rcases eq_bot_or_eq_top b with rfl|rfl,
{ rcases eq_bot_or_eq_top c with rfl|rfl; simp },
{ simp } }
end }
/-- A simple partial ordered `bounded_order` induces a linear order.
This is not an instance to prevent loops. -/
protected def is_simple_order.linear_order [decidable_eq α] : linear_order α :=
{ le_total := λ a b, by rcases eq_bot_or_eq_top a with rfl|rfl; simp,
decidable_le := λ a b, if ha : a = ⊥ then is_true (ha.le.trans bot_le) else
if hb : b = ⊤ then is_true (le_top.trans hb.ge) else
is_false (λ H, hb (top_unique
(le_trans (top_le_iff.mpr (or.resolve_left (eq_bot_or_eq_top a) ha)) H))),
decidable_eq := by assumption,
..(infer_instance : partial_order α) }
@[simp] lemma is_atom_top : is_atom (⊤ : α) :=
⟨top_ne_bot, λ a ha, or.resolve_right (eq_bot_or_eq_top a) (ne_of_lt ha)⟩
@[simp] lemma is_coatom_bot : is_coatom (⊥ : α) := is_atom_dual_iff_is_coatom.1 is_atom_top
lemma bot_covby_top : (⊥ : α) ⋖ ⊤ := is_atom_top.bot_covby
end is_simple_order
namespace is_simple_order
section preorder
variables [preorder α] [bounded_order α] [is_simple_order α] {a b : α} (h : a < b)
lemma eq_bot_of_lt : a = ⊥ := (is_simple_order.eq_bot_or_eq_top _).resolve_right h.ne_top
lemma eq_top_of_lt : b = ⊤ := (is_simple_order.eq_bot_or_eq_top _).resolve_left h.ne_bot
alias eq_bot_of_lt ← has_lt.lt.eq_bot
alias eq_top_of_lt ← has_lt.lt.eq_top
end preorder
section bounded_order
variables [lattice α] [bounded_order α] [is_simple_order α]
/-- A simple partial ordered `bounded_order` induces a lattice.
This is not an instance to prevent loops -/
protected def lattice {α} [decidable_eq α] [partial_order α] [bounded_order α]
[is_simple_order α] : lattice α :=
@linear_order.to_lattice α (is_simple_order.linear_order)
/-- A lattice that is a `bounded_order` is a distributive lattice.
This is not an instance to prevent loops -/
protected def distrib_lattice : distrib_lattice α :=
{ le_sup_inf := λ x y z, by { rcases eq_bot_or_eq_top x with rfl | rfl; simp },
.. (infer_instance : lattice α) }
@[priority 100] -- see Note [lower instance priority]
instance : is_atomic α :=
⟨λ b, (eq_bot_or_eq_top b).imp_right (λ h, ⟨⊤, ⟨is_atom_top, ge_of_eq h⟩⟩)⟩
@[priority 100] -- see Note [lower instance priority]
instance : is_coatomic α := is_atomic_dual_iff_is_coatomic.1 is_simple_order.is_atomic
end bounded_order
/- It is important that in this section `is_simple_order` is the last type-class argument. -/
section decidable_eq
variables [decidable_eq α] [partial_order α] [bounded_order α] [is_simple_order α]
/-- Every simple lattice is isomorphic to `bool`, regardless of order. -/
@[simps] def equiv_bool {α} [decidable_eq α] [has_le α] [bounded_order α] [is_simple_order α] :
α ≃ bool :=
{ to_fun := λ x, x = ⊤,
inv_fun := λ x, cond x ⊤ ⊥,
left_inv := λ x, by { rcases (eq_bot_or_eq_top x) with rfl | rfl; simp [bot_ne_top] },
right_inv := λ x, by { cases x; simp [bot_ne_top] } }
/-- Every simple lattice over a partial order is order-isomorphic to `bool`. -/
def order_iso_bool : α ≃o bool :=
{ map_rel_iff' := λ a b, begin
rcases (eq_bot_or_eq_top a) with rfl | rfl,
{ simp [bot_ne_top] },
{ rcases (eq_bot_or_eq_top b) with rfl | rfl,
{ simp [bot_ne_top.symm, bot_ne_top, bool.ff_lt_tt] },
{ simp [bot_ne_top] } }
end,
..equiv_bool }
/- It is important that `is_simple_order` is the last type-class argument of this instance,
so that type-class inference fails quickly if it doesn't apply. -/
@[priority 200]
instance {α} [decidable_eq α] [has_le α] [bounded_order α] [is_simple_order α] : fintype α :=
fintype.of_equiv bool equiv_bool.symm
/-- A simple `bounded_order` is also a `boolean_algebra`. -/
protected def boolean_algebra {α} [decidable_eq α] [lattice α] [bounded_order α]
[is_simple_order α] : boolean_algebra α :=
{ compl := λ x, if x = ⊥ then ⊤ else ⊥,
sdiff := λ x y, if x = ⊤ ∧ y = ⊥ then ⊤ else ⊥,
sdiff_eq := λ x y, by rcases eq_bot_or_eq_top x with rfl | rfl;
simp [bot_ne_top, has_sdiff.sdiff, compl],
inf_compl_le_bot := λ x, begin
rcases eq_bot_or_eq_top x with rfl | rfl,
{ simp },
{ simp only [top_inf_eq],
split_ifs with h h;
simp [h] }
end,
top_le_sup_compl := λ x, by rcases eq_bot_or_eq_top x with rfl | rfl; simp,
sup_inf_sdiff := λ x y, by rcases eq_bot_or_eq_top x with rfl | rfl;
rcases eq_bot_or_eq_top y with rfl | rfl; simp [bot_ne_top],
inf_inf_sdiff := λ x y, begin
rcases eq_bot_or_eq_top x with rfl | rfl,
{ simpa },
rcases eq_bot_or_eq_top y with rfl | rfl,
{ simpa },
{ simp only [true_and, top_inf_eq, eq_self_iff_true],
split_ifs with h h;
simpa [h] }
end,
.. (show bounded_order α, by apply_instance),
.. is_simple_order.distrib_lattice }
end decidable_eq
variables [lattice α] [bounded_order α] [is_simple_order α]
open_locale classical
/-- A simple `bounded_order` is also complete. -/
protected noncomputable def complete_lattice : complete_lattice α :=
{ Sup := λ s, if ⊤ ∈ s then ⊤ else ⊥,
Inf := λ s, if ⊥ ∈ s then ⊥ else ⊤,
le_Sup := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl,
{ exact bot_le },
{ rw if_pos h } },
Sup_le := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl,
{ rw if_neg,
intro con,
exact bot_ne_top (eq_top_iff.2 (h ⊤ con)) },
{ exact le_top } },
Inf_le := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl,
{ rw if_pos h },
{ exact le_top } },
le_Inf := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl,
{ exact bot_le },
{ rw if_neg,
intro con,
exact top_ne_bot (eq_bot_iff.2 (h ⊥ con)) } },
.. (infer_instance : lattice α),
.. (infer_instance : bounded_order α) }
/-- A simple `bounded_order` is also a `complete_boolean_algebra`. -/
protected noncomputable def complete_boolean_algebra : complete_boolean_algebra α :=
{ infi_sup_le_sup_Inf := λ x s, by { rcases eq_bot_or_eq_top x with rfl | rfl,
{ simp only [bot_sup_eq, ← Inf_eq_infi], exact le_rfl },
{ simp only [top_sup_eq, le_top] }, },
inf_Sup_le_supr_inf := λ x s, by { rcases eq_bot_or_eq_top x with rfl | rfl,
{ simp only [bot_inf_eq, bot_le] },
{ simp only [top_inf_eq, ← Sup_eq_supr], exact le_rfl } },
.. is_simple_order.complete_lattice,
.. is_simple_order.boolean_algebra }
end is_simple_order
namespace is_simple_order
variables [complete_lattice α] [is_simple_order α]
set_option default_priority 100
instance : is_atomistic α :=
⟨λ b, (eq_bot_or_eq_top b).elim
(λ h, ⟨∅, ⟨h.trans Sup_empty.symm, λ a ha, false.elim (set.not_mem_empty _ ha)⟩⟩)
(λ h, ⟨{⊤}, h.trans Sup_singleton.symm, λ a ha, (set.mem_singleton_iff.1 ha).symm ▸ is_atom_top⟩)⟩
instance : is_coatomistic α := is_atomistic_dual_iff_is_coatomistic.1 is_simple_order.is_atomistic
end is_simple_order
namespace fintype
namespace is_simple_order
variables [partial_order α] [bounded_order α] [is_simple_order α] [decidable_eq α]
lemma univ : (finset.univ : finset α) = {⊤, ⊥} :=
begin
change finset.map _ (finset.univ : finset bool) = _,
rw fintype.univ_bool,
simp only [finset.map_insert, function.embedding.coe_fn_mk, finset.map_singleton],
refl,
end
lemma card : fintype.card α = 2 :=
(fintype.of_equiv_card _).trans fintype.card_bool
end is_simple_order
end fintype
namespace bool
instance : is_simple_order bool :=
⟨λ a, begin
rw [← finset.mem_singleton, or.comm, ← finset.mem_insert,
top_eq_tt, bot_eq_ff, ← fintype.univ_bool],
apply finset.mem_univ,
end⟩
end bool
theorem is_simple_order_iff_is_atom_top [partial_order α] [bounded_order α] :
is_simple_order α ↔ is_atom (⊤ : α) :=
⟨λ h, @is_atom_top _ _ _ h, λ h,
{ exists_pair_ne := ⟨⊤, ⊥, h.1⟩,
eq_bot_or_eq_top := λ a, ((eq_or_lt_of_le le_top).imp_right (h.2 a)).symm }⟩
theorem is_simple_order_iff_is_coatom_bot [partial_order α] [bounded_order α] :
is_simple_order α ↔ is_coatom (⊥ : α) :=
is_simple_order_iff_is_simple_order_order_dual.trans is_simple_order_iff_is_atom_top
namespace set
theorem is_simple_order_Iic_iff_is_atom [partial_order α] [order_bot α] {a : α} :
is_simple_order (Iic a) ↔ is_atom a :=
is_simple_order_iff_is_atom_top.trans $ and_congr (not_congr subtype.mk_eq_mk)
⟨λ h b ab, subtype.mk_eq_mk.1 (h ⟨b, le_of_lt ab⟩ ab),
λ h ⟨b, hab⟩ hbotb, subtype.mk_eq_mk.2 (h b (subtype.mk_lt_mk.1 hbotb))⟩
theorem is_simple_order_Ici_iff_is_coatom [partial_order α] [order_top α] {a : α} :
is_simple_order (Ici a) ↔ is_coatom a :=
is_simple_order_iff_is_coatom_bot.trans $ and_congr (not_congr subtype.mk_eq_mk)
⟨λ h b ab, subtype.mk_eq_mk.1 (h ⟨b, le_of_lt ab⟩ ab),
λ h ⟨b, hab⟩ hbotb, subtype.mk_eq_mk.2 (h b (subtype.mk_lt_mk.1 hbotb))⟩
end set
namespace order_iso
variables {β : Type*}
@[simp] lemma is_atom_iff [partial_order α] [order_bot α] [partial_order β] [order_bot β]
(f : α ≃o β) (a : α) :
is_atom (f a) ↔ is_atom a :=
and_congr (not_congr ⟨λ h, f.injective (f.map_bot.symm ▸ h), λ h, f.map_bot ▸ (congr rfl h)⟩)
⟨λ h b hb, f.injective ((h (f b) ((f : α ↪o β).lt_iff_lt.2 hb)).trans f.map_bot.symm),
λ h b hb, f.symm.injective begin
rw f.symm.map_bot,
apply h,
rw [← f.symm_apply_apply a],
exact (f.symm : β ↪o α).lt_iff_lt.2 hb,
end⟩
@[simp] lemma is_coatom_iff [partial_order α] [order_top α] [partial_order β] [order_top β]
(f : α ≃o β) (a : α) :
is_coatom (f a) ↔ is_coatom a :=
f.dual.is_atom_iff a
lemma is_simple_order_iff [partial_order α] [bounded_order α] [partial_order β] [bounded_order β]
(f : α ≃o β) :
is_simple_order α ↔ is_simple_order β :=
by rw [is_simple_order_iff_is_atom_top, is_simple_order_iff_is_atom_top,
← f.is_atom_iff ⊤, f.map_top]
lemma is_simple_order [partial_order α] [bounded_order α] [partial_order β] [bounded_order β]
[h : is_simple_order β] (f : α ≃o β) :
is_simple_order α :=
f.is_simple_order_iff.mpr h
lemma is_atomic_iff [partial_order α] [order_bot α] [partial_order β] [order_bot β] (f : α ≃o β) :
is_atomic α ↔ is_atomic β :=
begin
suffices : (∀ b : α, b = ⊥ ∨ ∃ (a : α), is_atom a ∧ a ≤ b) ↔
(∀ b : β, b = ⊥ ∨ ∃ (a : β), is_atom a ∧ a ≤ b),
from ⟨λ ⟨p⟩, ⟨this.mp p⟩, λ ⟨p⟩, ⟨this.mpr p⟩⟩,
apply f.to_equiv.forall_congr,
simp_rw [rel_iso.coe_fn_to_equiv],
intro b, apply or_congr,
{ rw [f.apply_eq_iff_eq_symm_apply, map_bot], },
{ split,
{ exact λ ⟨a, ha⟩, ⟨f a, ⟨(f.is_atom_iff a).mpr ha.1, f.le_iff_le.mpr ha.2⟩⟩, },
{ rintros ⟨b, ⟨hb1, hb2⟩⟩,
refine ⟨f.symm b, ⟨(f.symm.is_atom_iff b).mpr hb1, _⟩⟩,
rwa [←f.le_iff_le, f.apply_symm_apply], }, },
end
lemma is_coatomic_iff [partial_order α] [order_top α] [partial_order β] [order_top β] (f : α ≃o β) :
is_coatomic α ↔ is_coatomic β :=
by { rw [←is_atomic_dual_iff_is_coatomic, ←is_atomic_dual_iff_is_coatomic],
exact f.dual.is_atomic_iff }
end order_iso
section is_modular_lattice
variables [lattice α] [bounded_order α] [is_modular_lattice α]
namespace is_compl
variables {a b : α} (hc : is_compl a b)
include hc
lemma is_atom_iff_is_coatom : is_atom a ↔ is_coatom b :=
set.is_simple_order_Iic_iff_is_atom.symm.trans $ hc.Iic_order_iso_Ici.is_simple_order_iff.trans
set.is_simple_order_Ici_iff_is_coatom
lemma is_coatom_iff_is_atom : is_coatom a ↔ is_atom b := hc.symm.is_atom_iff_is_coatom.symm
end is_compl
variables [is_complemented α]
lemma is_coatomic_of_is_atomic_of_is_complemented_of_is_modular [is_atomic α] : is_coatomic α :=
⟨λ x, begin
rcases exists_is_compl x with ⟨y, xy⟩,
apply (eq_bot_or_exists_atom_le y).imp _ _,
{ rintro rfl,
exact eq_top_of_is_compl_bot xy },
{ rintro ⟨a, ha, ay⟩,
rcases exists_is_compl (xy.symm.Iic_order_iso_Ici ⟨a, ay⟩) with ⟨⟨b, xb⟩, hb⟩,
refine ⟨↑(⟨b, xb⟩ : set.Ici x), is_coatom.of_is_coatom_coe_Ici _, xb⟩,
rw [← hb.is_atom_iff_is_coatom, order_iso.is_atom_iff],
apply ha.Iic }
end⟩
lemma is_atomic_of_is_coatomic_of_is_complemented_of_is_modular [is_coatomic α] : is_atomic α :=
is_coatomic_dual_iff_is_atomic.1 is_coatomic_of_is_atomic_of_is_complemented_of_is_modular
theorem is_atomic_iff_is_coatomic : is_atomic α ↔ is_coatomic α :=
⟨λ h, @is_coatomic_of_is_atomic_of_is_complemented_of_is_modular _ _ _ _ _ h,
λ h, @is_atomic_of_is_coatomic_of_is_complemented_of_is_modular _ _ _ _ _ h⟩
end is_modular_lattice
section fintype
open finset
@[priority 100] -- see Note [lower instance priority]
instance fintype.to_is_coatomic [partial_order α] [order_top α] [fintype α] : is_coatomic α :=
begin
refine is_coatomic.mk (λ b, or_iff_not_imp_left.2 (λ ht, _)),
obtain ⟨c, hc, hmax⟩ := set.finite.exists_maximal_wrt id { x : α | b ≤ x ∧ x ≠ ⊤ }
(set.to_finite _) ⟨b, le_rfl, ht⟩,
refine ⟨c, ⟨hc.2, λ y hcy, _⟩, hc.1⟩,
by_contra hyt,
obtain rfl : c = y := hmax y ⟨hc.1.trans hcy.le, hyt⟩ hcy.le,
exact (lt_self_iff_false _).mp hcy
end
@[priority 100] -- see Note [lower instance priority]
instance fintype.to_is_atomic [partial_order α] [order_bot α] [fintype α] : is_atomic α :=
is_coatomic_dual_iff_is_atomic.mp fintype.to_is_coatomic
end fintype
|
9d088b7e96ce1e89786ebfee8a6a51e0f688138c | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/linear_algebra/basic.lean | d4fb7038ff70eb811eacbd95a4620c0462738d7d | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 115,771 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov
-/
import algebra.big_operators.pi
import algebra.module.hom
import algebra.module.pi
import algebra.module.prod
import algebra.module.submodule
import algebra.module.submodule_lattice
import algebra.group.prod
import data.finsupp.basic
import data.dfinsupp
import algebra.pointwise
import order.compactly_generated
import order.omega_complete_partial_order
/-!
# Linear algebra
This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of
modules over a ring, submodules, and linear maps.
Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in
`src/algebra/module`.
## Main definitions
* Many constructors for linear maps
* `submodule.span s` is defined to be the smallest submodule containing the set `s`.
* If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`:
that is, elements of `M` are identified if their difference is in `p`. This is itself a module.
* The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain
respectively.
* The general linear group is defined to be the group of invertible linear maps from `M` to itself.
## Main statements
* The first, second and third isomorphism laws for modules are proved as
`linear_map.quot_ker_equiv_range`, `linear_map.quotient_inf_equiv_sup_quotient` and
`submodule.quotient_quotient_equiv_quotient`.
## Notations
* We continue to use the notation `M →ₗ[R] M₂` for the type of linear maps from `M` to `M₂` over the
ring `R`.
* We introduce the notations `M ≃ₗ M₂` and `M ≃ₗ[R] M₂` for `linear_equiv M M₂`. In the first, the
ring `R` is implicit.
* We introduce the notation `R ∙ v` for the span of a singleton, `submodule.span R {v}`. This is
`\.`, not the same as the scalar multiplication `•`/`\bub`.
## Implementation notes
We note that, when constructing linear maps, it is convenient to use operations defined on bundled
maps (`linear_map.prod`, `linear_map.coprod`, arithmetic operations like `+`) instead of defining a
function and proving it is linear.
## Tags
linear algebra, vector space, module
-/
open function
open_locale big_operators
universes u v w x y z u' v' w' y'
variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'}
variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x}
namespace finsupp
lemma smul_sum {α : Type u} {β : Type v} {R : Type w} {M : Type y}
[has_zero β] [monoid R] [add_comm_monoid M] [distrib_mul_action R M]
{v : α →₀ β} {c : R} {h : α → β → M} :
c • (v.sum h) = v.sum (λa b, c • h a b) :=
finset.smul_sum
@[simp]
lemma sum_smul_index_linear_map' {α : Type u} {R : Type v} {M : Type w} {M₂ : Type x}
[semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂]
{v : α →₀ M} {c : R} {h : α → M →ₗ[R] M₂} :
(c • v).sum (λ a, h a) = c • (v.sum (λ a, h a)) :=
begin
rw [finsupp.sum_smul_index', finsupp.smul_sum],
{ simp only [linear_map.map_smul], },
{ intro i, exact (h i).map_zero },
end
variable (R)
/-- Given `fintype α`, `linear_equiv_fun_on_fintype R` is the natural `R`-linear equivalence between
`α →₀ β` and `α → β`. -/
@[simps apply] noncomputable def linear_equiv_fun_on_fintype {α} [fintype α] [add_comm_monoid M]
[semiring R] [module R M] :
(α →₀ M) ≃ₗ[R] (α → M) :=
{ to_fun := coe_fn,
map_add' := λ f g, by { ext, refl },
map_smul' := λ c f, by { ext, refl },
.. equiv_fun_on_fintype }
@[simp] lemma linear_equiv_fun_on_fintype_single {α} [decidable_eq α] [fintype α]
[add_comm_monoid M] [semiring R] [module R M] (x : α) (m : M) :
(@linear_equiv_fun_on_fintype R M α _ _ _ _) (single x m) = pi.single x m :=
begin
ext a,
change (equiv_fun_on_fintype (single x m)) a = _,
convert _root_.congr_fun (equiv_fun_on_fintype_single x m) a,
end
@[simp] lemma linear_equiv_fun_on_fintype_symm_single {α} [decidable_eq α] [fintype α]
[add_comm_monoid M] [semiring R] [module R M] (x : α) (m : M) :
(@linear_equiv_fun_on_fintype R M α _ _ _ _).symm (pi.single x m) = single x m :=
begin
ext a,
change (equiv_fun_on_fintype.symm (pi.single x m)) a = _,
convert congr_fun (equiv_fun_on_fintype_symm_single x m) a,
end
end finsupp
section
open_locale classical
/-- decomposing `x : ι → R` as a sum along the canonical basis -/
lemma pi_eq_sum_univ {ι : Type u} [fintype ι] {R : Type v} [semiring R] (x : ι → R) :
x = ∑ i, x i • (λj, if i = j then 1 else 0) :=
by { ext, simp }
end
/-! ### Properties of linear maps -/
namespace linear_map
section add_comm_monoid
variables [semiring R]
variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄]
variables [module R M] [module R M₂] [module R M₃] [module R M₄]
variables (f g : M →ₗ[R] M₂)
include R
theorem comp_assoc (g : M₂ →ₗ[R] M₃) (h : M₃ →ₗ[R] M₄) : (h.comp g).comp f = h.comp (g.comp f) :=
rfl
/-- The restriction of a linear map `f : M → M₂` to a submodule `p ⊆ M` gives a linear map
`p → M₂`. -/
def dom_restrict (f : M →ₗ[R] M₂) (p : submodule R M) : p →ₗ[R] M₂ := f.comp p.subtype
@[simp] lemma dom_restrict_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) :
f.dom_restrict p x = f x := rfl
/-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a
linear map M₂ → p. -/
def cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h : ∀c, f c ∈ p) : M₂ →ₗ[R] p :=
by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp
@[simp] theorem cod_restrict_apply (p : submodule R M) (f : M₂ →ₗ[R] M) {h} (x : M₂) :
(cod_restrict p f h x : M) = f x := rfl
@[simp] lemma comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) (g : M₃ →ₗ[R] M) :
(cod_restrict p f h).comp g = cod_restrict p (f.comp g) (assume b, h _) :=
ext $ assume b, rfl
@[simp] lemma subtype_comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) :
p.subtype.comp (cod_restrict p f h) = f :=
ext $ assume b, rfl
/-- Restrict domain and codomain of an endomorphism. -/
def restrict (f : M →ₗ[R] M) {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p →ₗ[R] p :=
(f.dom_restrict p).cod_restrict p $ set_like.forall.2 hf
lemma restrict_apply
{f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) (x : p) :
f.restrict hf x = ⟨f x, hf x.1 x.2⟩ := rfl
lemma subtype_comp_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) :
p.subtype.comp (f.restrict hf) = f.dom_restrict p := rfl
lemma restrict_eq_cod_restrict_dom_restrict
{f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) :
f.restrict hf = (f.dom_restrict p).cod_restrict p (λ x, hf x.1 x.2) := rfl
lemma restrict_eq_dom_restrict_cod_restrict
{f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x, f x ∈ p) :
f.restrict (λ x _, hf x) = (f.cod_restrict p hf).dom_restrict p := rfl
/-- The constant 0 map is linear. -/
instance : has_zero (M →ₗ[R] M₂) :=
⟨{ to_fun := 0, map_add' := by simp, map_smul' := by simp }⟩
instance : inhabited (M →ₗ[R] M₂) := ⟨0⟩
@[simp] lemma zero_apply (x : M) : (0 : M →ₗ[R] M₂) x = 0 := rfl
@[simp] lemma default_def : default (M →ₗ[R] M₂) = 0 := rfl
instance unique_of_left [subsingleton M] : unique (M →ₗ[R] M₂) :=
{ uniq := λ f, ext $ λ x, by rw [subsingleton.elim x 0, map_zero, map_zero],
.. linear_map.inhabited }
instance unique_of_right [subsingleton M₂] : unique (M →ₗ[R] M₂) :=
coe_injective.unique
/-- The sum of two linear maps is linear. -/
instance : has_add (M →ₗ[R] M₂) :=
⟨λ f g, { to_fun := f + g,
map_add' := by simp [add_comm, add_left_comm], map_smul' := by simp [smul_add] }⟩
@[simp] lemma add_apply (x : M) : (f + g) x = f x + g x := rfl
/-- The type of linear maps is an additive monoid. -/
instance : add_comm_monoid (M →ₗ[R] M₂) :=
{ zero := 0,
add := (+),
add_assoc := by intros; ext; simp [add_comm, add_left_comm],
zero_add := by intros; ext; simp [add_comm, add_left_comm],
add_zero := by intros; ext; simp [add_comm, add_left_comm],
add_comm := by intros; ext; simp [add_comm, add_left_comm],
nsmul := λ n f, {
to_fun := λ x, n • (f x),
map_add' := λ x y, by rw [f.map_add, smul_add],
map_smul' := λ c x, by rw [f.map_smul, smul_comm n c (f x)] },
nsmul_zero' := λ f, by { ext x, simp },
nsmul_succ' := λ n f, by { ext x, simp [nat.succ_eq_one_add, add_nsmul] } }
/-- Evaluation of an `R`-linear map at a fixed `a`, as an `add_monoid_hom`. -/
def eval_add_monoid_hom (a : M) : (M →ₗ[R] M₂) →+ M₂ :=
{ to_fun := λ f, f a,
map_add' := λ f g, linear_map.add_apply f g a,
map_zero' := rfl }
lemma add_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) :
(h + g).comp f = h.comp f + g.comp f := rfl
lemma comp_add (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) :
h.comp (f + g) = h.comp f + h.comp g := by { ext, simp }
/-- `linear_map.to_add_monoid_hom` promoted to an `add_monoid_hom` -/
def to_add_monoid_hom' : (M →ₗ[R] M₂) →+ (M →+ M₂) :=
{ to_fun := to_add_monoid_hom,
map_zero' := by ext; refl,
map_add' := by intros; ext; refl }
lemma sum_apply (t : finset ι) (f : ι → M →ₗ[R] M₂) (b : M) :
(∑ d in t, f d) b = ∑ d in t, f d b :=
add_monoid_hom.map_sum ((add_monoid_hom.eval b).comp to_add_monoid_hom') f _
section smul_right
variables {S : Type*} [semiring S] [module R S] [module S M] [is_scalar_tower R S M]
/-- When `f` is an `R`-linear map taking values in `S`, then `λb, f b • x` is an `R`-linear map. -/
def smul_right (f : M₂ →ₗ[R] S) (x : M) : M₂ →ₗ[R] M :=
{ to_fun := λb, f b • x,
map_add' := λ x y, by rw [f.map_add, add_smul],
map_smul' := λ b y, by rw [f.map_smul, smul_assoc] }
@[simp] theorem coe_smul_right (f : M₂ →ₗ[R] S) (x : M) :
(smul_right f x : M₂ → M) = λ c, f c • x := rfl
theorem smul_right_apply (f : M₂ →ₗ[R] S) (x : M) (c : M₂) :
smul_right f x c = f c • x := rfl
end smul_right
instance : has_one (M →ₗ[R] M) := ⟨linear_map.id⟩
instance : has_mul (M →ₗ[R] M) := ⟨linear_map.comp⟩
lemma one_eq_id : (1 : M →ₗ[R] M) = id := rfl
lemma mul_eq_comp (f g : M →ₗ[R] M) : f * g = f.comp g := rfl
@[simp] lemma one_apply (x : M) : (1 : M →ₗ[R] M) x = x := rfl
@[simp] lemma mul_apply (f g : M →ₗ[R] M) (x : M) : (f * g) x = f (g x) := rfl
lemma coe_one : ⇑(1 : M →ₗ[R] M) = _root_.id := rfl
lemma coe_mul (f g : M →ₗ[R] M) : ⇑(f * g) = f ∘ g := rfl
instance [nontrivial M] : nontrivial (module.End R M) :=
begin
obtain ⟨m, ne⟩ := (nontrivial_iff_exists_ne (0 : M)).mp infer_instance,
exact nontrivial_of_ne 1 0 (λ p, ne (linear_map.congr_fun p m)),
end
@[simp] theorem comp_zero : f.comp (0 : M₃ →ₗ[R] M) = 0 :=
ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero]
@[simp] theorem zero_comp : (0 : M₂ →ₗ[R] M₃).comp f = 0 :=
rfl
@[simp, norm_cast] lemma coe_fn_sum {ι : Type*} (t : finset ι) (f : ι → M →ₗ[R] M₂) :
⇑(∑ i in t, f i) = ∑ i in t, (f i : M → M₂) :=
add_monoid_hom.map_sum ⟨@to_fun R M M₂ _ _ _ _ _, rfl, λ x y, rfl⟩ _ _
instance : monoid (M →ₗ[R] M) :=
by refine_struct { mul := (*), one := (1 : M →ₗ[R] M), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩ };
intros; try { refl }; apply linear_map.ext; simp {proj := ff}
@[simp] lemma pow_apply (f : M →ₗ[R] M) (n : ℕ) (m : M) :
(f^n) m = (f^[n] m) :=
begin
induction n with n ih,
{ refl, },
{ simp only [function.comp_app, function.iterate_succ, linear_map.mul_apply, pow_succ, ih],
exact (function.commute.iterate_self _ _ m).symm, },
end
lemma pow_map_zero_of_le
{f : module.End R M} {m : M} {k l : ℕ} (hk : k ≤ l) (hm : (f^k) m = 0) : (f^l) m = 0 :=
by rw [← nat.sub_add_cancel hk, pow_add, mul_apply, hm, map_zero]
lemma commute_pow_left_of_commute
{f : M →ₗ[R] M₂} {g : module.End R M} {g₂ : module.End R M₂} (h : g₂.comp f = f.comp g) (k : ℕ) :
(g₂^k).comp f = f.comp (g^k) :=
begin
induction k with k ih,
{ simpa only [pow_zero], },
{ rw [pow_succ, pow_succ, linear_map.mul_eq_comp, linear_map.comp_assoc, ih,
← linear_map.comp_assoc, h, linear_map.comp_assoc, linear_map.mul_eq_comp], },
end
lemma submodule_pow_eq_zero_of_pow_eq_zero {N : submodule R M}
{g : module.End R N} {G : module.End R M} (h : G.comp N.subtype = N.subtype.comp g)
{k : ℕ} (hG : G^k = 0) : g^k = 0 :=
begin
ext m,
have hg : N.subtype.comp (g^k) m = 0,
{ rw [← commute_pow_left_of_commute h, hG, zero_comp, zero_apply], },
simp only [submodule.subtype_apply, comp_app, submodule.coe_eq_zero, coe_comp] at hg,
rw [hg, linear_map.zero_apply],
end
lemma coe_pow (f : M →ₗ[R] M) (n : ℕ) : ⇑(f^n) = (f^[n]) :=
by { ext m, apply pow_apply, }
@[simp] lemma id_pow (n : ℕ) : (id : M →ₗ[R] M)^n = id := one_pow n
section
variables {f' : M →ₗ[R] M}
lemma iterate_succ (n : ℕ) : (f' ^ (n + 1)) = comp (f' ^ n) f' :=
by rw [pow_succ', mul_eq_comp]
lemma iterate_surjective (h : surjective f') : ∀ n : ℕ, surjective ⇑(f' ^ n)
| 0 := surjective_id
| (n + 1) := by { rw [iterate_succ], exact surjective.comp (iterate_surjective n) h, }
lemma iterate_injective (h : injective f') : ∀ n : ℕ, injective ⇑(f' ^ n)
| 0 := injective_id
| (n + 1) := by { rw [iterate_succ], exact injective.comp (iterate_injective n) h, }
lemma iterate_bijective (h : bijective f') : ∀ n : ℕ, bijective ⇑(f' ^ n)
| 0 := bijective_id
| (n + 1) := by { rw [iterate_succ], exact bijective.comp (iterate_bijective n) h, }
lemma injective_of_iterate_injective {n : ℕ} (hn : n ≠ 0) (h : injective ⇑(f' ^ n)) :
injective f' :=
begin
rw [← nat.succ_pred_eq_of_pos (pos_iff_ne_zero.mpr hn), iterate_succ, coe_comp] at h,
exact injective.of_comp h,
end
end
section
open_locale classical
/-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements
of the canonical basis. -/
lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) :
f x = ∑ i, x i • (f (λj, if i = j then 1 else 0)) :=
begin
conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] },
apply finset.sum_congr rfl (λl hl, _),
rw f.map_smul
end
end
end add_comm_monoid
section add_comm_group
variables [semiring R]
[add_comm_monoid M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄]
[module R M] [module R M₂] [module R M₃] [module R M₄]
(f g : M →ₗ[R] M₂)
/-- The negation of a linear map is linear. -/
instance : has_neg (M →ₗ[R] M₂) :=
⟨λ f, { to_fun := -f, map_add' := by simp [add_comm], map_smul' := by simp }⟩
@[simp] lemma neg_apply (x : M) : (- f) x = - f x := rfl
@[simp] lemma comp_neg (g : M₂ →ₗ[R] M₃) : g.comp (- f) = - g.comp f := by { ext, simp }
/-- The negation of a linear map is linear. -/
instance : has_sub (M →ₗ[R] M₂) :=
⟨λ f g, { to_fun := f - g,
map_add' := λ x y, by simp only [pi.sub_apply, map_add, add_sub_comm],
map_smul' := λ r x, by simp only [pi.sub_apply, map_smul, smul_sub] }⟩
@[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl
lemma sub_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) :
(g - h).comp f = g.comp f - h.comp f := rfl
lemma comp_sub (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) :
h.comp (g - f) = h.comp g - h.comp f := by { ext, simp }
/-- The type of linear maps is an additive group. -/
instance : add_comm_group (M →ₗ[R] M₂) :=
by refine
{ zero := 0,
add := (+),
neg := has_neg.neg,
sub := has_sub.sub,
sub_eq_add_neg := _,
add_left_neg := _,
nsmul := λ n f, {
to_fun := λ x, n • (f x),
map_add' := λ x y, by rw [f.map_add, smul_add],
map_smul' := λ c x, by rw [f.map_smul, smul_comm n c (f x)] },
gsmul := λ n f, {
to_fun := λ x, n • (f x),
map_add' := λ x y, by rw [f.map_add, smul_add],
map_smul' := λ c x, by rw [f.map_smul, smul_comm n c (f x)] },
gsmul_zero' := _,
gsmul_succ' := _,
gsmul_neg' := _,
.. linear_map.add_comm_monoid };
intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg, add_smul, nat.succ_eq_add_one]
end add_comm_group
section has_scalar
variables {S : Type*} [semiring R] [monoid S]
[add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
[module R M] [module R M₂] [module R M₃]
[distrib_mul_action S M₂] [smul_comm_class R S M₂]
(f : M →ₗ[R] M₂)
instance : has_scalar S (M →ₗ[R] M₂) :=
⟨λ a f, { to_fun := a • f,
map_add' := λ x y, by simp only [pi.smul_apply, f.map_add, smul_add],
map_smul' := λ c x, by simp only [pi.smul_apply, f.map_smul, smul_comm c] }⟩
@[simp] lemma smul_apply (a : S) (x : M) : (a • f) x = a • f x := rfl
instance {T : Type*} [monoid T] [distrib_mul_action T M₂] [smul_comm_class R T M₂]
[smul_comm_class S T M₂] :
smul_comm_class S T (M →ₗ[R] M₂) :=
⟨λ a b f, ext $ λ x, smul_comm _ _ _⟩
-- example application of this instance: if S -> T -> R are homomorphisms of commutative rings and
-- M and M₂ are R-modules then the S-module and T-module structures on Hom_R(M,M₂) are compatible.
instance {T : Type*} [monoid T] [has_scalar S T] [distrib_mul_action T M₂] [smul_comm_class R T M₂]
[is_scalar_tower S T M₂] :
is_scalar_tower S T (M →ₗ[R] M₂) :=
{ smul_assoc := λ _ _ _, ext $ λ _, smul_assoc _ _ _ }
instance : distrib_mul_action S (M →ₗ[R] M₂) :=
{ one_smul := λ f, ext $ λ _, one_smul _ _,
mul_smul := λ c c' f, ext $ λ _, mul_smul _ _ _,
smul_add := λ c f g, ext $ λ x, smul_add _ _ _,
smul_zero := λ c, ext $ λ x, smul_zero _ }
theorem smul_comp (a : S) (g : M₃ →ₗ[R] M₂) (f : M →ₗ[R] M₃) : (a • g).comp f = a • (g.comp f) :=
rfl
end has_scalar
section module
variables {S : Type*} [semiring R] [semiring S]
[add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
[module R M] [module R M₂] [module R M₃]
[module S M₂] [module S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃]
(f : M →ₗ[R] M₂)
instance : module S (M →ₗ[R] M₂) :=
{ add_smul := λ a b f, ext $ λ x, add_smul _ _ _,
zero_smul := λ f, ext $ λ x, zero_smul _ _ }
variable (S)
/-- Applying a linear map at `v : M`, seen as `S`-linear map from `M →ₗ[R] M₂` to `M₂`.
See `linear_map.applyₗ` for a version where `S = R`. -/
@[simps]
def applyₗ' : M →+ (M →ₗ[R] M₂) →ₗ[S] M₂ :=
{ to_fun := λ v,
{ to_fun := λ f, f v,
map_add' := λ f g, f.add_apply g v,
map_smul' := λ x f, f.smul_apply x v },
map_zero' := linear_map.ext $ λ f, f.map_zero,
map_add' := λ x y, linear_map.ext $ λ f, f.map_add _ _ }
section
variables (R M)
/--
The equivalence between R-linear maps from `R` to `M`, and points of `M` itself.
This says that the forgetful functor from `R`-modules to types is representable, by `R`.
This as an `S`-linear equivalence, under the assumption that `S` acts on `M` commuting with `R`.
When `R` is commutative, we can take this to be the usual action with `S = R`.
Otherwise, `S = ℕ` shows that the equivalence is additive.
See note [bundled maps over different rings].
-/
@[simps]
def ring_lmap_equiv_self [module S M] [smul_comm_class R S M] : (R →ₗ[R] M) ≃ₗ[S] M :=
{ to_fun := λ f, f 1,
inv_fun := smul_right (1 : R →ₗ[R] R),
left_inv := λ f, by { ext, simp },
right_inv := λ x, by simp,
.. applyₗ' S (1 : R) }
end
end module
section comm_semiring
variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
variables [module R M] [module R M₂] [module R M₃]
variables (f g : M →ₗ[R] M₂)
include R
theorem comp_smul (g : M₂ →ₗ[R] M₃) (a : R) : g.comp (a • f) = a • (g.comp f) :=
ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl
/-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂`
to the space of linear maps `M₂ → M₃`. -/
def comp_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) :=
{ to_fun := f.comp,
map_add' := λ _ _, linear_map.ext $ λ _, f.map_add _ _,
map_smul' := λ _ _, linear_map.ext $ λ _, f.map_smul _ _ }
/-- Applying a linear map at `v : M`, seen as a linear map from `M →ₗ[R] M₂` to `M₂`.
See also `linear_map.applyₗ'` for a version that works with two different semirings.
This is the `linear_map` version of `add_monoid_hom.eval`. -/
@[simps]
def applyₗ : M →ₗ[R] (M →ₗ[R] M₂) →ₗ[R] M₂ :=
{ to_fun := λ v, { to_fun := λ f, f v, ..applyₗ' R v },
map_smul' := λ x y, linear_map.ext $ λ f, f.map_smul _ _,
..applyₗ' R }
/-- Alternative version of `dom_restrict` as a linear map. -/
def dom_restrict'
(p : submodule R M) : (M →ₗ[R] M₂) →ₗ[R] (p →ₗ[R] M₂) :=
{ to_fun := λ φ, φ.dom_restrict p,
map_add' := by simp [linear_map.ext_iff],
map_smul' := by simp [linear_map.ext_iff] }
@[simp] lemma dom_restrict'_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) :
dom_restrict' p f x = f x := rfl
end comm_semiring
section semiring
variables [semiring R] [add_comm_monoid M] [module R M]
instance endomorphism_semiring : semiring (M →ₗ[R] M) :=
by refine_struct
{ mul := (*),
one := (1 : M →ₗ[R] M),
zero := 0,
add := (+),
npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩,
.. linear_map.add_comm_monoid, .. };
intros; try { refl }; apply linear_map.ext; simp {proj := ff}
end semiring
section ring
variables [ring R] [add_comm_group M] [module R M]
instance endomorphism_ring : ring (M →ₗ[R] M) :=
{ ..linear_map.endomorphism_semiring, ..linear_map.add_comm_group }
end ring
section comm_ring
variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
/--
The family of linear maps `M₂ → M` parameterised by `f ∈ M₂ → R`, `x ∈ M`, is linear in `f`, `x`.
-/
def smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M :=
{ to_fun := λ f, {
to_fun := linear_map.smul_right f,
map_add' := λ m m', by { ext, apply smul_add, },
map_smul' := λ c m, by { ext, apply smul_comm, } },
map_add' := λ f f', by { ext, apply add_smul, },
map_smul' := λ c f, by { ext, apply mul_smul, } }
@[simp] lemma smul_rightₗ_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) :
(smul_rightₗ : (M₂ →ₗ R) →ₗ M →ₗ M₂ →ₗ M) f x c = (f c) • x := rfl
end comm_ring
end linear_map
/--
The `ℕ`-linear equivalence between additive morphisms `A →+ B` and `ℕ`-linear morphisms `A →ₗ[ℕ] B`.
-/
@[simps]
def add_monoid_hom_lequiv_nat {A B : Type*} [add_comm_monoid A] [add_comm_monoid B] :
(A →+ B) ≃ₗ[ℕ] (A →ₗ[ℕ] B) :=
{ to_fun := add_monoid_hom.to_nat_linear_map,
inv_fun := linear_map.to_add_monoid_hom,
map_add' := by { intros, ext, refl },
map_smul' := by { intros, ext, refl },
left_inv := by { intros f, ext, refl },
right_inv := by { intros f, ext, refl } }
/--
The `ℤ`-linear equivalence between additive morphisms `A →+ B` and `ℤ`-linear morphisms `A →ₗ[ℤ] B`.
-/
@[simps]
def add_monoid_hom_lequiv_int {A B : Type*} [add_comm_group A] [add_comm_group B] :
(A →+ B) ≃ₗ[ℤ] (A →ₗ[ℤ] B) :=
{ to_fun := add_monoid_hom.to_int_linear_map,
inv_fun := linear_map.to_add_monoid_hom,
map_add' := by { intros, ext, refl },
map_smul' := by { intros, ext, refl },
left_inv := by { intros f, ext, refl },
right_inv := by { intros f, ext, refl } }
/-! ### Properties of submodules -/
namespace submodule
section add_comm_monoid
variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
variables [module R M] [module R M₂] [module R M₃]
variables (p p' : submodule R M) (q q' : submodule R M₂)
variables {r : R} {x y : M}
open set
variables {p p'}
/-- If two submodules `p` and `p'` satisfy `p ⊆ p'`, then `of_le p p'` is the linear map version of
this inclusion. -/
def of_le (h : p ≤ p') : p →ₗ[R] p' :=
p.subtype.cod_restrict p' $ λ ⟨x, hx⟩, h hx
@[simp] theorem coe_of_le (h : p ≤ p') (x : p) :
(of_le h x : M) = x := rfl
theorem of_le_apply (h : p ≤ p') (x : p) : of_le h x = ⟨x, h x.2⟩ := rfl
variables (p p')
lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) :
q.subtype.comp (of_le h) = p.subtype :=
by { ext ⟨b, hb⟩, refl }
instance add_comm_monoid_submodule : add_comm_monoid (submodule R M) :=
{ add := (⊔),
add_assoc := λ _ _ _, sup_assoc,
zero := ⊥,
zero_add := λ _, bot_sup_eq,
add_zero := λ _, sup_bot_eq,
add_comm := λ _ _, sup_comm }
@[simp] lemma add_eq_sup (p q : submodule R M) : p + q = p ⊔ q := rfl
@[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl
variables (R)
lemma subsingleton_iff : subsingleton M ↔ subsingleton (submodule R M) :=
add_submonoid.subsingleton_iff.trans $ begin
rw [←subsingleton_iff_bot_eq_top, ←subsingleton_iff_bot_eq_top],
convert to_add_submonoid_eq; refl
end
lemma nontrivial_iff : nontrivial M ↔ nontrivial (submodule R M) :=
not_iff_not.mp (
(not_nontrivial_iff_subsingleton.trans $ subsingleton_iff R).trans
not_nontrivial_iff_subsingleton.symm)
variables {R}
instance [subsingleton M] : unique (submodule R M) :=
⟨⟨⊥⟩, λ a, @subsingleton.elim _ ((subsingleton_iff R).mp ‹_›) a _⟩
instance unique' [subsingleton R] : unique (submodule R M) :=
by haveI := module.subsingleton R M; apply_instance
instance [nontrivial M] : nontrivial (submodule R M) := (nontrivial_iff R).mp ‹_›
theorem disjoint_def {p p' : submodule R M} :
disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) :=
show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp
theorem disjoint_def' {p p' : submodule R M} :
disjoint p p' ↔ ∀ (x ∈ p) (y ∈ p'), x = y → x = (0:M) :=
disjoint_def.trans ⟨λ h x hx y hy hxy, h x hx $ hxy.symm ▸ hy,
λ h x hx hx', h _ hx x hx' rfl⟩
theorem mem_right_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p} :
(x:M) ∈ p' ↔ x = 0 :=
⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x x.2 hx, λ h, h.symm ▸ p'.zero_mem⟩
theorem mem_left_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p'} :
(x:M) ∈ p ↔ x = 0 :=
⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x hx x.2, λ h, h.symm ▸ p.zero_mem⟩
/-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/
def map (f : M →ₗ[R] M₂) (p : submodule R M) : submodule R M₂ :=
{ carrier := f '' p,
smul_mem' := by rintro a _ ⟨b, hb, rfl⟩; exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩,
.. p.to_add_submonoid.map f.to_add_monoid_hom }
@[simp] lemma map_coe (f : M →ₗ[R] M₂) (p : submodule R M) :
(map f p : set M₂) = f '' p := rfl
@[simp] lemma mem_map {f : M →ₗ[R] M₂} {p : submodule R M} {x : M₂} :
x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl
theorem mem_map_of_mem {f : M →ₗ[R] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p :=
set.mem_image_of_mem _ h
lemma apply_coe_mem_map (f : M →ₗ[R] M₂) {p : submodule R M} (r : p) : f r ∈ map f p :=
mem_map_of_mem r.prop
@[simp] lemma map_id : map linear_map.id p = p :=
submodule.ext $ λ a, by simp
lemma map_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M) :
map (g.comp f) p = map g (map f p) :=
set_like.coe_injective $ by simp [map_coe]; rw ← image_comp
lemma map_mono {f : M →ₗ[R] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' :=
image_subset _
@[simp] lemma map_zero : map (0 : M →ₗ[R] M₂) p = ⊥ :=
have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩,
ext $ by simp [this, eq_comm]
lemma range_map_nonempty (N : submodule R M) :
(set.range (λ ϕ, submodule.map ϕ N : (M →ₗ[R] M₂) → submodule R M₂)).nonempty :=
⟨_, set.mem_range.mpr ⟨0, rfl⟩⟩
/-- The pushforward of a submodule by an injective linear map is
linearly equivalent to the original submodule. -/
noncomputable def equiv_map_of_injective (f : M →ₗ[R] M₂) (i : injective f) (p : submodule R M) :
p ≃ₗ[R] p.map f :=
{ map_add' := by { intros, simp, refl, },
map_smul' := by { intros, simp, refl, },
..(equiv.set.image f p i) }
@[simp] lemma coe_equiv_map_of_injective_apply (f : M →ₗ[R] M₂) (i : injective f)
(p : submodule R M) (x : p) :
(equiv_map_of_injective f i p x : M₂) = f x := rfl
/-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/
def comap (f : M →ₗ[R] M₂) (p : submodule R M₂) : submodule R M :=
{ carrier := f ⁻¹' p,
smul_mem' := λ a x h, by simp [p.smul_mem _ h],
.. p.to_add_submonoid.comap f.to_add_monoid_hom }
@[simp] lemma comap_coe (f : M →ₗ[R] M₂) (p : submodule R M₂) :
(comap f p : set M) = f ⁻¹' p := rfl
@[simp] lemma mem_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} :
x ∈ comap f p ↔ f x ∈ p := iff.rfl
lemma comap_id : comap linear_map.id p = p :=
set_like.coe_injective rfl
lemma comap_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M₃) :
comap (g.comp f) p = comap f (comap g p) := rfl
lemma comap_mono {f : M →ₗ[R] M₂} {q q' : submodule R M₂} : q ≤ q' → comap f q ≤ comap f q' :=
preimage_mono
lemma map_le_iff_le_comap {f : M →ₗ[R] M₂} {p : submodule R M} {q : submodule R M₂} :
map f p ≤ q ↔ p ≤ comap f q := image_subset_iff
lemma gc_map_comap (f : M →ₗ[R] M₂) : galois_connection (map f) (comap f)
| p q := map_le_iff_le_comap
@[simp] lemma map_bot (f : M →ₗ[R] M₂) : map f ⊥ = ⊥ :=
(gc_map_comap f).l_bot
@[simp] lemma map_sup (f : M →ₗ[R] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' :=
(gc_map_comap f).l_sup
@[simp] lemma map_supr {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M) :
map f (⨆i, p i) = (⨆i, map f (p i)) :=
(gc_map_comap f).l_supr
@[simp] lemma comap_top (f : M →ₗ[R] M₂) : comap f ⊤ = ⊤ := rfl
@[simp] lemma comap_inf (f : M →ₗ[R] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl
@[simp] lemma comap_infi {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M₂) :
comap f (⨅i, p i) = (⨅i, comap f (p i)) :=
(gc_map_comap f).u_infi
@[simp] lemma comap_zero : comap (0 : M →ₗ[R] M₂) q = ⊤ :=
ext $ by simp
lemma map_comap_le (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) ≤ q :=
(gc_map_comap f).l_u_le _
lemma le_comap_map (f : M →ₗ[R] M₂) (p : submodule R M) : p ≤ comap f (map f p) :=
(gc_map_comap f).le_u_l _
section galois_coinsertion
variables {f : M →ₗ[R] M₂} (hf : injective f)
include hf
/-- `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. -/
def gci_map_comap : galois_coinsertion (map f) (comap f) :=
(gc_map_comap f).to_galois_coinsertion
(λ S x, by simp [mem_comap, mem_map, hf.eq_iff])
lemma comap_map_eq_of_injective (p : submodule R M) : (p.map f).comap f = p :=
(gci_map_comap hf).u_l_eq _
lemma comap_surjective_of_injective : function.surjective (comap f) :=
(gci_map_comap hf).u_surjective
lemma map_injective_of_injective : function.injective (map f) :=
(gci_map_comap hf).l_injective
lemma comap_inf_map_of_injective (p q : submodule R M) : (p.map f ⊓ q.map f).comap f = p ⊓ q :=
(gci_map_comap hf).u_inf_l _ _
lemma comap_infi_map_of_injective (S : ι → submodule R M) : (⨅ i, (S i).map f).comap f = infi S :=
(gci_map_comap hf).u_infi_l _
lemma comap_sup_map_of_injective (p q : submodule R M) : (p.map f ⊔ q.map f).comap f = p ⊔ q :=
(gci_map_comap hf).u_sup_l _ _
lemma comap_supr_map_of_injective (S : ι → submodule R M) : (⨆ i, (S i).map f).comap f = supr S :=
(gci_map_comap hf).u_supr_l _
lemma map_le_map_iff_of_injective (p q : submodule R M) : p.map f ≤ q.map f ↔ p ≤ q :=
(gci_map_comap hf).l_le_l_iff
lemma map_strict_mono_of_injective : strict_mono (map f) :=
(gci_map_comap hf).strict_mono_l
end galois_coinsertion
--TODO(Mario): is there a way to prove this from order properties?
lemma map_inf_eq_map_inf_comap {f : M →ₗ[R] M₂}
{p : submodule R M} {p' : submodule R M₂} :
map f p ⊓ p' = map f (p ⊓ comap f p') :=
le_antisymm
(by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩)
(le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right))
lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' :=
ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩
lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0
| ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb
section
variables (R)
/-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/
def span (s : set M) : submodule R M := Inf {p | s ⊆ p}
end
variables {s t : set M}
lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p :=
mem_bInter_iff
lemma subset_span : s ⊆ span R s :=
λ x h, mem_span.2 $ λ p hp, hp h
lemma span_le {p} : span R s ≤ p ↔ s ⊆ p :=
⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩
lemma span_mono (h : s ⊆ t) : span R s ≤ span R t :=
span_le.2 $ subset.trans h subset_span
lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p :=
le_antisymm (span_le.2 h₁) h₂
@[simp] lemma span_eq : span R (p : set M) = p :=
span_eq_of_le _ (subset.refl _) subset_span
lemma map_span (f : M →ₗ[R] M₂) (s : set M) :
(span R s).map f = span R (f '' s) :=
eq.symm $ span_eq_of_le _ (set.image_subset f subset_span) $
map_le_iff_le_comap.2 $ span_le.2 $ λ x hx, subset_span ⟨x, hx, rfl⟩
alias submodule.map_span ← linear_map.map_span
lemma map_span_le {R M M₂ : Type*} [semiring R] [add_comm_monoid M]
[add_comm_monoid M₂] [module R M] [module R M₂] (f : M →ₗ[R] M₂)
(s : set M) (N : submodule R M₂) : map f (span R s) ≤ N ↔ ∀ m ∈ s, f m ∈ N :=
begin
rw [f.map_span, span_le, set.image_subset_iff],
exact iff.rfl
end
alias submodule.map_span_le ← linear_map.map_span_le
/- See also `span_preimage_eq` below. -/
lemma span_preimage_le (f : M →ₗ[R] M₂) (s : set M₂) :
span R (f ⁻¹' s) ≤ (span R s).comap f :=
by { rw [span_le, comap_coe], exact preimage_mono (subset_span), }
alias submodule.span_preimage_le ← linear_map.span_preimage_le
/-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is
preserved under addition and scalar multiplication, then `p` holds for all elements of the span of
`s`. -/
@[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s)
(Hs : ∀ x ∈ s, p x) (H0 : p 0)
(H1 : ∀ x y, p x → p y → p (x + y))
(H2 : ∀ (a:R) x, p x → p (a • x)) : p x :=
(@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h
lemma span_nat_eq_add_submonoid_closure (s : set M) :
(span ℕ s).to_add_submonoid = add_submonoid.closure s :=
begin
refine eq.symm (add_submonoid.closure_eq_of_le subset_span _),
apply add_submonoid.to_nat_submodule.symm.to_galois_connection.l_le _,
rw span_le,
exact add_submonoid.subset_closure,
end
@[simp] lemma span_nat_eq (s : add_submonoid M) : (span ℕ (s : set M)).to_add_submonoid = s :=
by rw [span_nat_eq_add_submonoid_closure, s.closure_eq]
lemma span_int_eq_add_subgroup_closure {M : Type*} [add_comm_group M] (s : set M) :
(span ℤ s).to_add_subgroup = add_subgroup.closure s :=
eq.symm $ add_subgroup.closure_eq_of_le _ subset_span $ λ x hx, span_induction hx
(λ x hx, add_subgroup.subset_closure hx) (add_subgroup.zero_mem _)
(λ _ _, add_subgroup.add_mem _) (λ _ _ _, add_subgroup.gsmul_mem _ ‹_› _)
@[simp] lemma span_int_eq {M : Type*} [add_comm_group M] (s : add_subgroup M) :
(span ℤ (s : set M)).to_add_subgroup = s :=
by rw [span_int_eq_add_subgroup_closure, s.closure_eq]
section
variables (R M)
/-- `span` forms a Galois insertion with the coercion from submodule to set. -/
protected def gi : galois_insertion (@span R M _ _ _) coe :=
{ choice := λ s _, span R s,
gc := λ s t, span_le,
le_l_u := λ s, subset_span,
choice_eq := λ s h, rfl }
end
@[simp] lemma span_empty : span R (∅ : set M) = ⊥ :=
(submodule.gi R M).gc.l_bot
@[simp] lemma span_univ : span R (univ : set M) = ⊤ :=
eq_top_iff.2 $ set_like.le_def.2 $ subset_span
lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t :=
(submodule.gi R M).gc.l_sup
lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) :=
(submodule.gi R M).gc.l_supr
lemma span_eq_supr_of_singleton_spans (s : set M) : span R s = ⨆ x ∈ s, span R {x} :=
by simp only [←span_Union, set.bUnion_of_singleton s]
@[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι]
(S : ι → submodule R M) (H : directed (≤) S) :
((supr S : submodule R M) : set M) = ⋃ i, S i :=
begin
refine subset.antisymm _ (Union_subset $ le_supr S),
suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i),
by simpa only [span_Union, span_eq] using this,
refine (λ x hx, span_induction hx (λ _, id) _ _ _);
simp only [mem_Union, exists_imp_distrib],
{ exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) },
{ intros x y i hi j hj,
rcases H i j with ⟨k, ik, jk⟩,
exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ },
{ exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ },
end
lemma sum_mem_bsupr {ι : Type*} {s : finset ι} {f : ι → M} {p : ι → submodule R M}
(h : ∀ i ∈ s, f i ∈ p i) :
∑ i in s, f i ∈ ⨆ i ∈ s, p i :=
sum_mem _ $ λ i hi, mem_supr_of_mem i $ mem_supr_of_mem hi (h i hi)
lemma sum_mem_supr {ι : Type*} [fintype ι] {f : ι → M} {p : ι → submodule R M}
(h : ∀ i, f i ∈ p i) :
∑ i, f i ∈ ⨆ i, p i :=
sum_mem _ $ λ i hi, mem_supr_of_mem i (h i)
@[simp] theorem mem_supr_of_directed {ι} [nonempty ι]
(S : ι → submodule R M) (H : directed (≤) S) {x} :
x ∈ supr S ↔ ∃ i, x ∈ S i :=
by { rw [← set_like.mem_coe, coe_supr_of_directed S H, mem_Union], refl }
theorem mem_Sup_of_directed {s : set (submodule R M)}
{z} (hs : s.nonempty) (hdir : directed_on (≤) s) :
z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y :=
begin
haveI : nonempty s := hs.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed _ hdir.directed_coe, set_coe.exists, subtype.coe_mk]
end
@[norm_cast, simp] lemma coe_supr_of_chain (a : ℕ →ₘ submodule R M) :
(↑(⨆ k, a k) : set M) = ⋃ k, (a k : set M) :=
coe_supr_of_directed a a.monotone.directed_le
/-- We can regard `coe_supr_of_chain` as the statement that `coe : (submodule R M) → set M` is
Scott continuous for the ω-complete partial order induced by the complete lattice structures. -/
lemma coe_scott_continuous : omega_complete_partial_order.continuous'
(coe : submodule R M → set M) :=
⟨set_like.coe_mono, coe_supr_of_chain⟩
@[simp] lemma mem_supr_of_chain (a : ℕ →ₘ submodule R M) (m : M) : m ∈ (⨆ k, a k) ↔ ∃ k, m ∈ a k :=
mem_supr_of_directed a a.monotone.directed_le
section
variables {p p'}
lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x :=
⟨λ h, begin
rw [← span_eq p, ← span_eq p', ← span_union] at h,
apply span_induction h,
{ rintro y (h | h),
{ exact ⟨y, h, 0, by simp, by simp⟩ },
{ exact ⟨0, by simp, y, h, by simp⟩ } },
{ exact ⟨0, by simp, 0, by simp⟩ },
{ rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩,
exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp [add_assoc]; cc⟩ },
{ rintro a _ ⟨y, hy, z, hz, rfl⟩,
exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ }
end,
by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _
((le_sup_left : p ≤ p ⊔ p') hy)
((le_sup_right : p' ≤ p ⊔ p') hz)⟩
lemma mem_sup' : x ∈ p ⊔ p' ↔ ∃ (y : p) (z : p'), (y:M) + z = x :=
mem_sup.trans $ by simp only [set_like.exists, coe_mk]
lemma coe_sup : ↑(p ⊔ p') = (p + p' : set M) :=
by { ext, rw [set_like.mem_coe, mem_sup, set.mem_add], simp, }
end
/- This is the character `∙`, with escape sequence `\.`, and is thus different from the scalar
multiplication character `•`, with escape sequence `\bub`. -/
notation R`∙`:1000 x := span R (@singleton _ _ set.has_singleton x)
lemma mem_span_singleton_self (x : M) : x ∈ R ∙ x := subset_span rfl
lemma nontrivial_span_singleton {x : M} (h : x ≠ 0) : nontrivial (R ∙ x) :=
⟨begin
use [0, x, submodule.mem_span_singleton_self x],
intros H,
rw [eq_comm, submodule.mk_eq_zero] at H,
exact h H
end⟩
lemma mem_span_singleton {y : M} : x ∈ (R ∙ y) ↔ ∃ a:R, a • y = x :=
⟨λ h, begin
apply span_induction h,
{ rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ },
{ exact ⟨0, by simp⟩ },
{ rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩,
exact ⟨a + b, by simp [add_smul]⟩ },
{ rintro a _ ⟨b, rfl⟩,
exact ⟨a * b, by simp [smul_smul]⟩ }
end,
by rintro ⟨a, y, rfl⟩; exact
smul_mem _ _ (subset_span $ by simp)⟩
lemma le_span_singleton_iff {s : submodule R M} {v₀ : M} :
s ≤ (R ∙ v₀) ↔ ∀ v ∈ s, ∃ r : R, r • v₀ = v :=
by simp_rw [set_like.le_def, mem_span_singleton]
lemma span_singleton_eq_top_iff (x : M) : (R ∙ x) = ⊤ ↔ ∀ v, ∃ r : R, r • x = v :=
begin
rw [eq_top_iff, le_span_singleton_iff],
finish,
end
@[simp] lemma span_zero_singleton : (R ∙ (0:M)) = ⊥ :=
by { ext, simp [mem_span_singleton, eq_comm] }
lemma span_singleton_eq_range (y : M) : ↑(R ∙ y) = range ((• y) : R → M) :=
set.ext $ λ x, mem_span_singleton
lemma span_singleton_smul_le (r : R) (x : M) : (R ∙ (r • x)) ≤ R ∙ x :=
begin
rw [span_le, set.singleton_subset_iff, set_like.mem_coe],
exact smul_mem _ _ (mem_span_singleton_self _)
end
lemma span_singleton_smul_eq {K E : Type*} [division_ring K] [add_comm_group E] [module K E]
{r : K} (x : E) (hr : r ≠ 0) : (K ∙ (r • x)) = K ∙ x :=
begin
refine le_antisymm (span_singleton_smul_le r x) _,
convert span_singleton_smul_le r⁻¹ (r • x),
exact (inv_smul_smul' hr _).symm
end
lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E]
{s : submodule K E} {x : E} :
disjoint s (K ∙ x) ↔ (x ∈ s → x = 0) :=
begin
refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩,
assume H y hy hyx,
obtain ⟨c, hc⟩ := mem_span_singleton.1 hyx,
subst y,
classical, by_cases hc : c = 0, by simp only [hc, zero_smul],
rw [s.smul_mem_iff hc] at hy,
rw [H hy, smul_zero]
end
lemma disjoint_span_singleton' {K E : Type*} [division_ring K] [add_comm_group E] [module K E]
{p : submodule K E} {x : E} (x0 : x ≠ 0) :
disjoint p (K ∙ x) ↔ x ∉ p :=
disjoint_span_singleton.trans ⟨λ h₁ h₂, x0 (h₁ h₂), λ h₁ h₂, (h₁ h₂).elim⟩
lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z :=
begin
simp only [← union_singleton, span_union, mem_sup, mem_span_singleton, exists_prop,
exists_exists_eq_and],
rw [exists_comm],
simp only [eq_comm, add_comm, exists_and_distrib_left]
end
lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s :=
span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _)
lemma span_span : span R (span R s : set M) = span R s := span_eq _
lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 :=
eq_bot_iff.trans ⟨
λ H x h, (mem_bot R).1 $ H $ subset_span h,
λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩
@[simp] lemma span_singleton_eq_bot : (R ∙ x) = ⊥ ↔ x = 0 :=
span_eq_bot.trans $ by simp
@[simp] lemma span_zero : span R (0 : set M) = ⊥ := by rw [←singleton_zero, span_singleton_eq_bot]
@[simp] lemma span_image (f : M →ₗ[R] M₂) : span R (f '' s) = map f (span R s) :=
span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $
span_le.2 $ image_subset_iff.1 subset_span
lemma apply_mem_span_image_of_mem_span
(f : M →ₗ[R] M₂) {x : M} {s : set M} (h : x ∈ submodule.span R s) :
f x ∈ submodule.span R (f '' s) :=
begin
rw submodule.span_image,
exact submodule.mem_map_of_mem h
end
/-- `f` is an explicit argument so we can `apply` this theorem and obtain `h` as a new goal. -/
lemma not_mem_span_of_apply_not_mem_span_image
(f : M →ₗ[R] M₂) {x : M} {s : set M} (h : f x ∉ submodule.span R (f '' s)) :
x ∉ submodule.span R s :=
not.imp h (apply_mem_span_image_of_mem_span f)
lemma supr_eq_span {ι : Sort w} (p : ι → submodule R M) :
(⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) :=
le_antisymm
(supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span)
(span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem i hm)
lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : (R ∙ m) ≤ p ↔ m ∈ p :=
by rw [span_le, singleton_subset_iff, set_like.mem_coe]
lemma singleton_span_is_compact_element (x : M) :
complete_lattice.is_compact_element (span R {x} : submodule R M) :=
begin
rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le,
intros d hemp hdir hsup,
have : x ∈ Sup d, from (set_like.le_def.mp hsup) (mem_span_singleton_self x),
obtain ⟨y, ⟨hyd, hxy⟩⟩ := (mem_Sup_of_directed hemp hdir).mp this,
exact ⟨y, ⟨hyd, by simpa only [span_le, singleton_subset_iff]⟩⟩,
end
instance : is_compactly_generated (submodule R M) :=
⟨λ s, ⟨(λ x, span R {x}) '' s, ⟨λ t ht, begin
rcases (set.mem_image _ _ _).1 ht with ⟨x, hx, rfl⟩,
apply singleton_span_is_compact_element,
end, by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, span_eq]⟩⟩⟩
lemma lt_add_iff_not_mem {I : submodule R M} {a : M} : I < I + (R ∙ a) ↔ a ∉ I :=
begin
split,
{ intro h,
by_contra akey,
have h1 : I + (R ∙ a) ≤ I,
{ simp only [add_eq_sup, sup_le_iff],
split,
{ exact le_refl I, },
{ exact (span_singleton_le_iff_mem a I).mpr akey, } },
have h2 := gt_of_ge_of_gt h1 h,
exact lt_irrefl I h2, },
{ intro h,
apply set_like.lt_iff_le_and_exists.mpr, split,
simp only [add_eq_sup, le_sup_left],
use a,
split, swap, { assumption, },
{ have : (R ∙ a) ≤ I + (R ∙ a) := le_sup_right,
exact this (mem_span_singleton_self a), } },
end
lemma mem_supr {ι : Sort w} (p : ι → submodule R M) {m : M} :
(m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) :=
begin
rw [← span_singleton_le_iff_mem, le_supr_iff],
simp only [span_singleton_le_iff_mem],
end
section
open_locale classical
/-- For every element in the span of a set, there exists a finite subset of the set
such that the element is contained in the span of the subset. -/
lemma mem_span_finite_of_mem_span {S : set M} {x : M} (hx : x ∈ span R S) :
∃ T : finset M, ↑T ⊆ S ∧ x ∈ span R (T : set M) :=
begin
refine span_induction hx (λ x hx, _) _ _ _,
{ refine ⟨{x}, _, _⟩,
{ rwa [finset.coe_singleton, set.singleton_subset_iff] },
{ rw finset.coe_singleton,
exact submodule.mem_span_singleton_self x } },
{ use ∅, simp },
{ rintros x y ⟨X, hX, hxX⟩ ⟨Y, hY, hyY⟩,
refine ⟨X ∪ Y, _, _⟩,
{ rw finset.coe_union,
exact set.union_subset hX hY },
rw [finset.coe_union, span_union, mem_sup],
exact ⟨x, hxX, y, hyY, rfl⟩, },
{ rintros a x ⟨T, hT, h2⟩,
exact ⟨T, hT, smul_mem _ _ h2⟩ }
end
end
/-- The product of two submodules is a submodule. -/
def prod : submodule R (M × M₂) :=
{ carrier := set.prod p q,
smul_mem' := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩,
.. p.to_add_submonoid.prod q.to_add_submonoid }
@[simp] lemma prod_coe :
(prod p q : set (M × M₂)) = set.prod p q := rfl
@[simp] lemma mem_prod {p : submodule R M} {q : submodule R M₂} {x : M × M₂} :
x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod
lemma span_prod_le (s : set M) (t : set M₂) :
span R (set.prod s t) ≤ prod (span R s) (span R t) :=
span_le.2 $ set.prod_mono subset_span subset_span
@[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M₂)) = ⊤ :=
by ext; simp
@[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M₂)) = ⊥ :=
by ext ⟨x, y⟩; simp [prod.zero_eq_mk]
lemma prod_mono {p p' : submodule R M} {q q' : submodule R M₂} :
p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono
@[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') :=
set_like.coe_injective set.prod_inter_prod
@[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') :=
begin
refine le_antisymm (sup_le
(prod_mono le_sup_left le_sup_left)
(prod_mono le_sup_right le_sup_right)) _,
simp [set_like.le_def], intros xx yy hxx hyy,
rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩,
rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩,
refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩
end
end add_comm_monoid
variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
variables (p p' : submodule R M) (q q' : submodule R M₂)
variables {r : R} {x y : M}
open set
@[simp] lemma neg_coe : -(p : set M) = p := set.ext $ λ x, p.neg_mem_iff
@[simp] protected lemma map_neg (f : M →ₗ[R] M₂) : map (-f) p = map f p :=
ext $ λ y, ⟨λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, f.map_neg x⟩,
λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, ((-f).map_neg _).trans (neg_neg (f x))⟩⟩
@[simp] lemma span_neg (s : set M) : span R (-s) = span R s :=
calc span R (-s) = span R ((-linear_map.id : M →ₗ[R] M) '' s) : by simp
... = map (-linear_map.id) (span R s) : ((-linear_map.id).map_span _).symm
... = span R s : by simp
lemma mem_span_insert' {y} {s : set M} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s :=
begin
rw mem_span_insert, split,
{ rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz, add_assoc]⟩ },
{ rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ }
end
-- TODO(Mario): Factor through add_subgroup
/-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/
def quotient_rel : setoid M :=
⟨λ x y, x - y ∈ p, λ x, by simp,
λ x y h, by simpa using neg_mem _ h,
λ x y z h₁ h₂, by simpa [sub_eq_add_neg, add_left_comm, add_assoc] using add_mem _ h₁ h₂⟩
/-- The quotient of a module `M` by a submodule `p ⊆ M`. -/
def quotient : Type* := quotient (quotient_rel p)
namespace quotient
/-- Map associating to an element of `M` the corresponding element of `M/p`,
when `p` is a submodule of `M`. -/
def mk {p : submodule R M} : M → quotient p := quotient.mk'
@[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (quotient.mk x : quotient p) = mk x := rfl
@[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl
@[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl
protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq'
instance : has_zero (quotient p) := ⟨mk 0⟩
instance : inhabited (quotient p) := ⟨0⟩
@[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl
@[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p :=
by simpa using (quotient.eq p : mk x = 0 ↔ _)
instance : has_add (quotient p) :=
⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $
λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $
by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ h₂⟩
@[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl
instance : has_neg (quotient p) :=
⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $
λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩
@[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl
instance : has_sub (quotient p) :=
⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a - b)) $
λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $
by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ (neg_mem p h₂)⟩
@[simp] theorem mk_sub : (mk (x - y) : quotient p) = mk x - mk y := rfl
instance : add_comm_group (quotient p) :=
{ zero := (0 : quotient p),
add := (+),
neg := has_neg.neg,
sub := has_sub.sub,
add_assoc := by { rintros ⟨x⟩ ⟨y⟩ ⟨z⟩, simp only [←mk_add p, quot_mk_eq_mk, add_assoc] },
zero_add := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, quot_mk_eq_mk, zero_add] },
add_zero := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, add_zero, quot_mk_eq_mk] },
add_comm := by { rintros ⟨x⟩ ⟨y⟩, simp only [←mk_add p, quot_mk_eq_mk, add_comm] },
add_left_neg := by { rintro ⟨x⟩,
simp only [←mk_zero p, ←mk_add p, ←mk_neg p, quot_mk_eq_mk, add_left_neg] },
sub_eq_add_neg := by { rintros ⟨x⟩ ⟨y⟩,
simp only [←mk_add p, ←mk_neg p, ←mk_sub p, sub_eq_add_neg, quot_mk_eq_mk] },
nsmul := λ n x, quotient.lift_on' x (λ x, mk (n • x)) $
λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_of_tower_mem p n h,
nsmul_zero' := by { rintros ⟨⟩, simp only [mk_zero, quot_mk_eq_mk, zero_smul], refl },
nsmul_succ' := by { rintros n ⟨⟩,
simp only [nat.succ_eq_one_add, add_nsmul, mk_add, quot_mk_eq_mk, one_nsmul], refl },
gsmul := λ n x, quotient.lift_on' x (λ x, mk (n • x)) $
λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_of_tower_mem p n h,
gsmul_zero' := by { rintros ⟨⟩, simp only [mk_zero, quot_mk_eq_mk, zero_smul], refl },
gsmul_succ' := by { rintros n ⟨⟩,
simp [nat.succ_eq_add_one, add_nsmul, mk_add, quot_mk_eq_mk, one_nsmul, add_smul, add_comm],
refl },
gsmul_neg' := by { rintros n ⟨x⟩, simp_rw [gsmul_neg_succ_of_nat, gsmul_coe_nat], refl }, }
instance : has_scalar R (quotient p) :=
⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $
λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_mem p a h⟩
@[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl
@[simp] theorem mk_nsmul (n : ℕ) : (mk (n • x) : quotient p) = n • mk x := rfl
instance : module R (quotient p) :=
module.of_core $ by refine {smul := (•), ..};
repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul,
-mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm]
lemma mk_surjective : function.surjective (@mk _ _ _ _ _ p) :=
by { rintros ⟨x⟩, exact ⟨x, rfl⟩ }
lemma nontrivial_of_lt_top (h : p < ⊤) : nontrivial (p.quotient) :=
begin
obtain ⟨x, _, not_mem_s⟩ := set_like.exists_of_lt h,
refine ⟨⟨mk x, 0, _⟩⟩,
simpa using not_mem_s
end
end quotient
lemma quot_hom_ext ⦃f g : quotient p →ₗ[R] M₂⦄ (h : ∀ x, f (quotient.mk x) = g (quotient.mk x)) :
f = g :=
linear_map.ext $ λ x, quotient.induction_on' x h
end submodule
namespace submodule
variables [field K]
variables [add_comm_group V] [module K V]
variables [add_comm_group V₂] [module K V₂]
lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) :
p.comap (a • f) = p.comap f :=
by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply]
lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) :
p.map (a • f) = p.map f :=
le_antisymm
begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end
begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end
lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) :
p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) :=
by classical; by_cases a = 0; simp [h, comap_smul]
lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) :
p.map (a • f) = (⨆ h : a ≠ 0, p.map f) :=
by classical; by_cases a = 0; simp [h, map_smul]
end submodule
/-! ### Properties of linear maps -/
namespace linear_map
section add_comm_monoid
variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
variables [module R M] [module R M₂] [module R M₃]
include R
open submodule
/-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`.
See also `linear_map.eq_on_span'` for a version using `set.eq_on`. -/
lemma eq_on_span {s : set M} {f g : M →ₗ[R] M₂} (H : set.eq_on f g s) ⦃x⦄ (h : x ∈ span R s) :
f x = g x :=
by apply span_induction h H; simp {contextual := tt}
/-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`.
This version uses `set.eq_on`, and the hidden argument will expand to `h : x ∈ (span R s : set M)`.
See `linear_map.eq_on_span` for a version that takes `h : x ∈ span R s` as an argument. -/
lemma eq_on_span' {s : set M} {f g : M →ₗ[R] M₂} (H : set.eq_on f g s) :
set.eq_on f g (span R s : set M) :=
eq_on_span H
/-- If `s` generates the whole module and linear maps `f`, `g` are equal on `s`, then they are
equal. -/
lemma ext_on {s : set M} {f g : M →ₗ[R] M₂} (hv : span R s = ⊤) (h : set.eq_on f g s) :
f = g :=
linear_map.ext (λ x, eq_on_span h (eq_top_iff'.1 hv _))
/-- If the range of `v : ι → M` generates the whole module and linear maps `f`, `g` are equal at
each `v i`, then they are equal. -/
lemma ext_on_range {v : ι → M} {f g : M →ₗ[R] M₂} (hv : span R (set.range v) = ⊤)
(h : ∀i, f (v i) = g (v i)) : f = g :=
ext_on hv (set.forall_range_iff.2 h)
section finsupp
variables {γ : Type*} [has_zero γ]
@[simp] lemma map_finsupp_sum (f : M →ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} :
f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum
lemma coe_finsupp_sum (t : ι →₀ γ) (g : ι → γ → M →ₗ[R] M₂) :
⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _
@[simp] lemma finsupp_sum_apply (t : ι →₀ γ) (g : ι → γ → M →ₗ[R] M₂) (b : M) :
(t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _
end finsupp
section dfinsupp
open dfinsupp
variables {γ : ι → Type*} [decidable_eq ι]
section sum
variables [Π i, has_zero (γ i)] [Π i (x : γ i), decidable (x ≠ 0)]
@[simp] lemma map_dfinsupp_sum (f : M →ₗ[R] M₂) {t : Π₀ i, γ i} {g : Π i, γ i → M} :
f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum
lemma coe_dfinsupp_sum (t : Π₀ i, γ i) (g : Π i, γ i → M →ₗ[R] M₂) :
⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _
@[simp] lemma dfinsupp_sum_apply (t : Π₀ i, γ i) (g : Π i, γ i → M →ₗ[R] M₂) (b : M) :
(t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _
end sum
section sum_add_hom
variables [Π i, add_zero_class (γ i)]
@[simp] lemma map_dfinsupp_sum_add_hom (f : M →ₗ[R] M₂) {t : Π₀ i, γ i} {g : Π i, γ i →+ M} :
f (sum_add_hom g t) = sum_add_hom (λ i, f.to_add_monoid_hom.comp (g i)) t :=
f.to_add_monoid_hom.map_dfinsupp_sum_add_hom _ _
end sum_add_hom
end dfinsupp
theorem map_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h p') :
submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) :=
submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.ext_iff_val]
theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf p') :
submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') :=
submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩
/-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. See Note [range copy pattern]. -/
def range (f : M →ₗ[R] M₂) : submodule R M₂ :=
(map f ⊤).copy (set.range f) set.image_univ.symm
theorem range_coe (f : M →ₗ[R] M₂) : (range f : set M₂) = set.range f := rfl
@[simp] theorem mem_range {f : M →ₗ[R] M₂} {x} : x ∈ range f ↔ ∃ y, f y = x :=
iff.rfl
lemma range_eq_map (f : M →ₗ[R] M₂) : f.range = map f ⊤ :=
by { ext, simp }
theorem mem_range_self (f : M →ₗ[R] M₂) (x : M) : f x ∈ f.range := ⟨x, rfl⟩
@[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ :=
set_like.coe_injective set.range_id
theorem range_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) = map g (range f) :=
set_like.coe_injective (set.range_comp g f)
theorem range_comp_le_range (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) ≤ range g :=
set_like.coe_mono (set.range_comp_subset_range f g)
theorem range_eq_top {f : M →ₗ[R] M₂} : range f = ⊤ ↔ surjective f :=
by rw [set_like.ext'_iff, range_coe, top_coe, set.range_iff_surjective]
lemma range_le_iff_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : range f ≤ p ↔ comap f p = ⊤ :=
by rw [range_eq_map, map_le_iff_le_comap, eq_top_iff]
lemma map_le_range {f : M →ₗ[R] M₂} {p : submodule R M} : map f p ≤ range f :=
set_like.coe_mono (set.image_subset_range f p)
/--
The decreasing sequence of submodules consisting of the ranges of the iterates of a linear map.
-/
@[simps]
def iterate_range {R M} [ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M) :
ℕ →ₘ order_dual (submodule R M) :=
⟨λ n, (f ^ n).range, λ n m w x h, begin
obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w,
rw linear_map.mem_range at h,
obtain ⟨m, rfl⟩ := h,
rw linear_map.mem_range,
use (f ^ c) m,
rw [pow_add, linear_map.mul_apply],
end⟩
/-- Restrict the codomain of a linear map `f` to `f.range`.
This is the bundled version of `set.range_factorization`. -/
@[reducible] def range_restrict (f : M →ₗ[R] M₂) : M →ₗ[R] f.range :=
f.cod_restrict f.range f.mem_range_self
/-- The range of a linear map is finite if the domain is finite.
Note: this instance can form a diamond with `subtype.fintype` in the
presence of `fintype M₂`. -/
instance fintype_range [fintype M] [decidable_eq M₂] (f : M →ₗ[R] M₂) : fintype (range f) :=
set.fintype_range f
section
variables (R) (M)
/-- Given an element `x` of a module `M` over `R`, the natural map from
`R` to scalar multiples of `x`.-/
def to_span_singleton (x : M) : R →ₗ[R] M := linear_map.id.smul_right x
/-- The range of `to_span_singleton x` is the span of `x`.-/
lemma span_singleton_eq_range (x : M) : (R ∙ x) = (to_span_singleton R M x).range :=
submodule.ext $ λ y, by {refine iff.trans _ mem_range.symm, exact mem_span_singleton }
lemma to_span_singleton_one (x : M) : to_span_singleton R M x 1 = x := one_smul _ _
end
/-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the
set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/
def ker (f : M →ₗ[R] M₂) : submodule R M := comap f ⊥
@[simp] theorem mem_ker {f : M →ₗ[R] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R
@[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl
@[simp] theorem map_coe_ker (f : M →ₗ[R] M₂) (x : ker f) : f x = 0 := mem_ker.1 x.2
lemma comp_ker_subtype (f : M →ₗ[R] M₂) : f.comp f.ker.subtype = 0 :=
linear_map.ext $ λ x, suffices f x = 0, by simp [this], mem_ker.1 x.2
theorem ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker (g.comp f) = comap f (ker g) := rfl
theorem ker_le_ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker f ≤ ker (g.comp f) :=
by rw ker_comp; exact comap_mono bot_le
theorem disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} :
disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 :=
by simp [disjoint_def]
theorem ker_eq_bot' {f : M →ₗ[R] M₂} :
ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) :=
by simpa [disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤
theorem ker_eq_bot_of_inverse {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M} (h : g.comp f = id) :
ker f = ⊥ :=
ker_eq_bot'.2 $ λ m hm, by rw [← id_apply m, ← h, comp_apply, hm, g.map_zero]
lemma le_ker_iff_map {f : M →ₗ[R] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ :=
by rw [ker, eq_bot_iff, map_le_iff_le_comap]
lemma ker_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) :
ker (cod_restrict p f hf) = ker f :=
by rw [ker, comap_cod_restrict, map_bot]; refl
lemma range_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) :
range (cod_restrict p f hf) = comap p.subtype f.range :=
by simpa only [range_eq_map] using map_cod_restrict _ _ _ _
lemma ker_restrict {p : submodule R M} {f : M →ₗ[R] M} (hf : ∀ x : M, x ∈ p → f x ∈ p) :
ker (f.restrict hf) = (f.dom_restrict p).ker :=
by rw [restrict_eq_cod_restrict_dom_restrict, ker_cod_restrict]
lemma map_comap_eq (f : M →ₗ[R] M₂) (q : submodule R M₂) :
map f (comap f q) = range f ⊓ q :=
le_antisymm (le_inf map_le_range (map_comap_le _ _)) $
by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩
lemma map_comap_eq_self {f : M →ₗ[R] M₂} {q : submodule R M₂} (h : q ≤ range f) :
map f (comap f q) = q :=
by rwa [map_comap_eq, inf_eq_right]
@[simp] theorem ker_zero : ker (0 : M →ₗ[R] M₂) = ⊤ :=
eq_top_iff'.2 $ λ x, by simp
@[simp] theorem range_zero : range (0 : M →ₗ[R] M₂) = ⊥ :=
by simpa only [range_eq_map] using submodule.map_zero _
theorem ker_eq_top {f : M →ₗ[R] M₂} : ker f = ⊤ ↔ f = 0 :=
⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩
lemma range_le_bot_iff (f : M →ₗ[R] M₂) : range f ≤ ⊥ ↔ f = 0 :=
by rw [range_le_iff_comap]; exact ker_eq_top
theorem range_eq_bot {f : M →ₗ[R] M₂} : range f = ⊥ ↔ f = 0 :=
by rw [← range_le_bot_iff, le_bot_iff]
lemma range_le_ker_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : range f ≤ ker g ↔ g.comp f = 0 :=
⟨λ h, ker_eq_top.1 $ eq_top_iff'.2 $ λ x, h $ ⟨_, rfl⟩,
λ h x hx, mem_ker.2 $ exists.elim hx $ λ y hy, by rw [←hy, ←comp_apply, h, zero_apply]⟩
theorem comap_le_comap_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p p'} :
comap f p ≤ comap f p' ↔ p ≤ p' :=
⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩
theorem comap_injective {f : M →ₗ[R] M₂} (hf : range f = ⊤) : injective (comap f) :=
λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h))
((comap_le_comap_iff hf).1 (ge_of_eq h))
theorem ker_eq_bot_of_injective {f : M →ₗ[R] M₂} (hf : injective f) : ker f = ⊥ :=
begin
have : disjoint ⊤ f.ker, by { rw [disjoint_ker, ← map_zero f], exact λ x hx H, hf H },
simpa [disjoint]
end
/--
The increasing sequence of submodules consisting of the kernels of the iterates of a linear map.
-/
@[simps]
def iterate_ker {R M} [ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M) :
ℕ →ₘ submodule R M :=
⟨λ n, (f ^ n).ker, λ n m w x h, begin
obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w,
rw linear_map.mem_ker at h,
rw [linear_map.mem_ker, add_comm, pow_add, linear_map.mul_apply, h, linear_map.map_zero],
end⟩
end add_comm_monoid
section add_comm_group
variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
include R
open submodule
lemma comap_map_eq (f : M →ₗ[R] M₂) (p : submodule R M) :
comap f (map f p) = p ⊔ ker f :=
begin
refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)),
rintro x ⟨y, hy, e⟩,
exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩
end
lemma comap_map_eq_self {f : M →ₗ[R] M₂} {p : submodule R M} (h : ker f ≤ p) :
comap f (map f p) = p :=
by rw [comap_map_eq, sup_of_le_left h]
theorem map_le_map_iff (f : M →ₗ[R] M₂) {p p'} : map f p ≤ map f p' ↔ p ≤ p' ⊔ ker f :=
by rw [map_le_iff_le_comap, comap_map_eq]
theorem map_le_map_iff' {f : M →ₗ[R] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' :=
by rw [map_le_map_iff, hf, sup_bot_eq]
theorem map_injective {f : M →ₗ[R] M₂} (hf : ker f = ⊥) : injective (map f) :=
λ p p' h, le_antisymm ((map_le_map_iff' hf).1 (le_of_eq h)) ((map_le_map_iff' hf).1 (ge_of_eq h))
theorem map_eq_top_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p : submodule R M} :
p.map f = ⊤ ↔ p ⊔ f.ker = ⊤ :=
by simp_rw [← top_le_iff, ← hf, range_eq_map, map_le_map_iff]
end add_comm_group
section ring
variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
variables {f : M →ₗ[R] M₂}
include R
open submodule
theorem sub_mem_ker_iff {x y} : x - y ∈ f.ker ↔ f x = f y :=
by rw [mem_ker, map_sub, sub_eq_zero]
theorem disjoint_ker' {p : submodule R M} :
disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y :=
disjoint_ker.trans
⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]),
λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩
theorem inj_of_disjoint_ker {p : submodule R M}
{s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) :
∀ x y ∈ s, f x = f y → x = y :=
λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy)
theorem ker_eq_bot : ker f = ⊥ ↔ injective f :=
by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤
lemma ker_le_iff {p : submodule R M} : ker f ≤ p ↔ ∃ (y ∈ range f), f ⁻¹' {y} ⊆ p :=
begin
split,
{ intros h, use 0, rw [← set_like.mem_coe, f.range_coe], exact ⟨⟨0, map_zero f⟩, h⟩, },
{ rintros ⟨y, h₁, h₂⟩,
rw set_like.le_def, intros z hz, simp only [mem_ker, set_like.mem_coe] at hz,
rw [← set_like.mem_coe, f.range_coe, set.mem_range] at h₁, obtain ⟨x, hx⟩ := h₁,
have hx' : x ∈ p, { exact h₂ hx, },
have hxz : z + x ∈ p, { apply h₂, simp [hx, hz], },
suffices : z + x - x ∈ p, { simpa only [this, add_sub_cancel], },
exact p.sub_mem hxz hx', },
end
end ring
section field
variables [field K]
variables [add_comm_group V] [module K V]
variables [add_comm_group V₂] [module K V₂]
lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f :=
submodule.comap_smul f _ a h
lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f :=
submodule.comap_smul' f _ a
lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f :=
by simpa only [range_eq_map] using submodule.map_smul f _ a h
lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f :=
by simpa only [range_eq_map] using submodule.map_smul' f _ a
lemma span_singleton_sup_ker_eq_top (f : V →ₗ[K] K) {x : V} (hx : f x ≠ 0) :
(K ∙ x) ⊔ f.ker = ⊤ :=
eq_top_iff.2 (λ y hy, submodule.mem_sup.2 ⟨(f y * (f x)⁻¹) • x,
submodule.mem_span_singleton.2 ⟨f y * (f x)⁻¹, rfl⟩,
⟨y - (f y * (f x)⁻¹) • x,
by rw [linear_map.mem_ker, f.map_sub, f.map_smul, smul_eq_mul, mul_assoc,
inv_mul_cancel hx, mul_one, sub_self],
by simp only [add_sub_cancel'_right]⟩⟩)
end field
end linear_map
namespace is_linear_map
lemma is_linear_map_add [semiring R] [add_comm_monoid M] [module R M] :
is_linear_map R (λ (x : M × M), x.1 + x.2) :=
begin
apply is_linear_map.mk,
{ intros x y,
simp, cc },
{ intros x y,
simp [smul_add] }
end
lemma is_linear_map_sub {R M : Type*} [semiring R] [add_comm_group M] [module R M]:
is_linear_map R (λ (x : M × M), x.1 - x.2) :=
begin
apply is_linear_map.mk,
{ intros x y,
simp [add_comm, add_left_comm, sub_eq_add_neg] },
{ intros x y,
simp [smul_sub] }
end
end is_linear_map
namespace submodule
section add_comm_monoid
variables {T : semiring R} [add_comm_monoid M] [add_comm_monoid M₂]
variables [module R M] [module R M₂]
variables (p p' : submodule R M) (q : submodule R M₂)
include T
open linear_map
@[simp] theorem map_top (f : M →ₗ[R] M₂) : map f ⊤ = range f := f.range_eq_map.symm
@[simp] theorem comap_bot (f : M →ₗ[R] M₂) : comap f ⊥ = ker f := rfl
@[simp] theorem ker_subtype : p.subtype.ker = ⊥ :=
ker_eq_bot_of_injective $ λ x y, subtype.ext_val
@[simp] theorem range_subtype : p.subtype.range = p :=
by simpa using map_comap_subtype p ⊤
lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p :=
by simpa using (map_le_range : map p.subtype p' ≤ p.subtype.range)
/-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the
maximal submodule of `p` is just `p `. -/
@[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p :=
by simp
@[simp] lemma comap_subtype_eq_top {p p' : submodule R M} :
comap p.subtype p' = ⊤ ↔ p ≤ p' :=
eq_top_iff.trans $ map_le_iff_le_comap.symm.trans $ by rw [map_subtype_top]
@[simp] lemma comap_subtype_self : comap p.subtype p = ⊤ :=
comap_subtype_eq_top.2 (le_refl _)
@[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ :=
by rw [of_le, ker_cod_restrict, ker_subtype]
lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p :=
by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype]
end add_comm_monoid
section ring
variables {T : ring R} [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂]
variables (p p' : submodule R M) (q : submodule R M₂)
include T
open linear_map
lemma disjoint_iff_comap_eq_bot {p q : submodule R M} :
disjoint p q ↔ comap p.subtype q = ⊥ :=
by rw [eq_bot_iff, ← map_le_map_iff' p.ker_subtype, map_bot, map_comap_subtype, disjoint]
/-- If `N ⊆ M` then submodules of `N` are the same as submodules of `M` contained in `N` -/
def map_subtype.rel_iso :
submodule R p ≃o {p' : submodule R M // p' ≤ p} :=
{ to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩,
inv_fun := λ q, comap p.subtype q,
left_inv := λ p', comap_map_eq_self $ by simp,
right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simp [map_comap_subtype p, inf_of_le_right hq],
map_rel_iff' := λ p₁ p₂, map_le_map_iff' (ker_subtype p) }
/-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of
submodules of `M`. -/
def map_subtype.order_embedding :
submodule R p ↪o submodule R M :=
(rel_iso.to_rel_embedding $ map_subtype.rel_iso p).trans (subtype.rel_embedding _ _)
@[simp] lemma map_subtype_embedding_eq (p' : submodule R p) :
map_subtype.order_embedding p p' = map p.subtype p' := rfl
/-- The map from a module `M` to the quotient of `M` by a submodule `p` as a linear map. -/
def mkq : M →ₗ[R] p.quotient :=
{ to_fun := quotient.mk, map_add' := by simp, map_smul' := by simp }
@[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl
/-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂`
vanishing on `p`, as a linear map. -/
def liftq (f : M →ₗ[R] M₂) (h : p ≤ f.ker) : p.quotient →ₗ[R] M₂ :=
{ to_fun := λ x, _root_.quotient.lift_on' x f $
λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab,
map_add' := by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y,
map_smul' := by rintro a ⟨x⟩; exact f.map_smul a x }
@[simp] theorem liftq_apply (f : M →ₗ[R] M₂) {h} (x : M) :
p.liftq f h (quotient.mk x) = f x := rfl
@[simp] theorem liftq_mkq (f : M →ₗ[R] M₂) (h) : (p.liftq f h).comp p.mkq = f :=
by ext; refl
@[simp] theorem range_mkq : p.mkq.range = ⊤ :=
eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, rfl⟩
@[simp] theorem ker_mkq : p.mkq.ker = p :=
by ext; simp
lemma le_comap_mkq (p' : submodule R p.quotient) : p ≤ comap p.mkq p' :=
by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p')
@[simp] theorem mkq_map_self : map p.mkq p = ⊥ :=
by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _
@[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' :=
by simp [comap_map_eq, sup_comm]
@[simp] theorem map_mkq_eq_top : map p.mkq p' = ⊤ ↔ p ⊔ p' = ⊤ :=
by simp only [map_eq_top_iff p.range_mkq, sup_comm, ker_mkq]
/-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along
`f : M → M₂` is linear. -/
def mapq (f : M →ₗ[R] M₂) (h : p ≤ comap f q) : p.quotient →ₗ[R] q.quotient :=
p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h
@[simp] theorem mapq_apply (f : M →ₗ[R] M₂) {h} (x : M) :
mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl
theorem mapq_mkq (f : M →ₗ[R] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f :=
by ext x; refl
theorem comap_liftq (f : M →ₗ[R] M₂) (h) :
q.comap (p.liftq f h) = (q.comap f).map (mkq p) :=
le_antisymm
(by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩)
(by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _)
theorem map_liftq (f : M →ₗ[R] M₂) (h) (q : submodule R (quotient p)) :
q.map (p.liftq f h) = (q.comap p.mkq).map f :=
le_antisymm
(by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩)
(by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩)
theorem ker_liftq (f : M →ₗ[R] M₂) (h) :
ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _
theorem range_liftq (f : M →ₗ[R] M₂) (h) :
range (p.liftq f h) = range f :=
by simpa only [range_eq_map] using map_liftq _ _ _ _
theorem ker_liftq_eq_bot (f : M →ₗ[R] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ :=
by rw [ker_liftq, le_antisymm h h', mkq_map_self]
/-- The correspondence theorem for modules: there is an order isomorphism between submodules of the
quotient of `M` by `p`, and submodules of `M` larger than `p`. -/
def comap_mkq.rel_iso :
submodule R p.quotient ≃o {p' : submodule R M // p ≤ p'} :=
{ to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩,
inv_fun := λ q, map p.mkq q,
left_inv := λ p', map_comap_eq_self $ by simp,
right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simpa [comap_map_mkq p],
map_rel_iff' := λ p₁ p₂, comap_le_comap_iff $ range_mkq _ }
/-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules
of `M`. -/
def comap_mkq.order_embedding :
submodule R p.quotient ↪o submodule R M :=
(rel_iso.to_rel_embedding $ comap_mkq.rel_iso p).trans (subtype.rel_embedding _ _)
@[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) :
comap_mkq.order_embedding p p' = comap p.mkq p' := rfl
lemma span_preimage_eq {f : M →ₗ[R] M₂} {s : set M₂} (h₀ : s.nonempty) (h₁ : s ⊆ range f) :
span R (f ⁻¹' s) = (span R s).comap f :=
begin
suffices : (span R s).comap f ≤ span R (f ⁻¹' s),
{ exact le_antisymm (span_preimage_le f s) this, },
have hk : ker f ≤ span R (f ⁻¹' s),
{ let y := classical.some h₀, have hy : y ∈ s, { exact classical.some_spec h₀, },
rw ker_le_iff, use [y, h₁ hy], rw ← set.singleton_subset_iff at hy,
exact set.subset.trans subset_span (span_mono (set.preimage_mono hy)), },
rw ← left_eq_sup at hk, rw f.range_coe at h₁,
rw [hk, ← map_le_map_iff, map_span, map_comap_eq, set.image_preimage_eq_of_subset h₁],
exact inf_le_right,
end
end ring
end submodule
namespace linear_map
section semiring
variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
variables [module R M] [module R M₂] [module R M₃]
/-- A monomorphism is injective. -/
lemma ker_eq_bot_of_cancel {f : M →ₗ[R] M₂}
(h : ∀ (u v : f.ker →ₗ[R] M), f.comp u = f.comp v → u = v) : f.ker = ⊥ :=
begin
have h₁ : f.comp (0 : f.ker →ₗ[R] M) = 0 := comp_zero _,
rw [←submodule.range_subtype f.ker, ←h 0 f.ker.subtype (eq.trans h₁ (comp_ker_subtype f).symm)],
exact range_zero
end
lemma range_comp_of_range_eq_top {f : M →ₗ[R] M₂} (g : M₂ →ₗ[R] M₃) (hf : range f = ⊤) :
range (g.comp f) = range g :=
by rw [range_comp, hf, submodule.map_top]
lemma ker_comp_of_ker_eq_bot (f : M →ₗ[R] M₂) {g : M₂ →ₗ[R] M₃} (hg : ker g = ⊥) :
ker (g.comp f) = ker f :=
by rw [ker_comp, hg, submodule.comap_bot]
end semiring
section ring
variables [ring R] [add_comm_monoid M] [add_comm_group M₂] [add_comm_monoid M₃]
variables [module R M] [module R M₂] [module R M₃]
lemma range_mkq_comp (f : M →ₗ[R] M₂) : f.range.mkq.comp f = 0 :=
linear_map.ext $ λ x, by simp
lemma ker_le_range_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} :
g.ker ≤ f.range ↔ f.range.mkq.comp g.ker.subtype = 0 :=
by rw [←range_le_ker_iff, submodule.ker_mkq, submodule.range_subtype]
/-- An epimorphism is surjective. -/
lemma range_eq_top_of_cancel {f : M →ₗ[R] M₂}
(h : ∀ (u v : M₂ →ₗ[R] f.range.quotient), u.comp f = v.comp f → u = v) : f.range = ⊤ :=
begin
have h₁ : (0 : M₂ →ₗ[R] f.range.quotient).comp f = 0 := zero_comp _,
rw [←submodule.ker_mkq f.range, ←h 0 f.range.mkq (eq.trans h₁ (range_mkq_comp _).symm)],
exact ker_zero
end
end ring
end linear_map
@[simp] lemma linear_map.range_range_restrict [semiring R] [add_comm_monoid M] [add_comm_monoid M₂]
[module R M] [module R M₂] (f : M →ₗ[R] M₂) :
f.range_restrict.range = ⊤ :=
by simp [f.range_cod_restrict _]
/-! ### Linear equivalences -/
namespace linear_equiv
section add_comm_monoid
variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂]
[add_comm_monoid M₃] [add_comm_monoid M₄]
section subsingleton
variables [module R M] [module R M₂] [subsingleton M] [subsingleton M₂]
/-- Between two zero modules, the zero map is an equivalence. -/
instance : has_zero (M ≃ₗ[R] M₂) :=
⟨{ to_fun := 0,
inv_fun := 0,
right_inv := λ x, subsingleton.elim _ _,
left_inv := λ x, subsingleton.elim _ _,
..(0 : M →ₗ[R] M₂)}⟩
-- Even though these are implied by `subsingleton.elim` via the `unique` instance below, they're
-- nice to have as `rfl`-lemmas for `dsimp`.
@[simp] lemma zero_symm : (0 : M ≃ₗ[R] M₂).symm = 0 := rfl
@[simp] lemma coe_zero : ⇑(0 : M ≃ₗ[R] M₂) = 0 := rfl
lemma zero_apply (x : M) : (0 : M ≃ₗ[R] M₂) x = 0 := rfl
/-- Between two zero modules, the zero map is the only equivalence. -/
instance : unique (M ≃ₗ[R] M₂) :=
{ uniq := λ f, to_linear_map_injective (subsingleton.elim _ _),
default := 0 }
end subsingleton
section
variables {module_M : module R M} {module_M₂ : module R M₂}
variables (e e' : M ≃ₗ[R] M₂)
lemma map_eq_comap {p : submodule R M} : (p.map e : submodule R M₂) = p.comap e.symm :=
set_like.coe_injective $ by simp [e.image_eq_preimage]
/-- A linear equivalence of two modules restricts to a linear equivalence from any submodule
`p` of the domain onto the image of that submodule.
This is `linear_equiv.of_submodule'` but with `map` on the right instead of `comap` on the left. -/
def of_submodule (p : submodule R M) : p ≃ₗ[R] ↥(p.map ↑e : submodule R M₂) :=
{ inv_fun := λ y, ⟨e.symm y, by {
rcases y with ⟨y', hy⟩, rw submodule.mem_map at hy, rcases hy with ⟨x, hx, hxy⟩, subst hxy,
simp only [symm_apply_apply, submodule.coe_mk, coe_coe, hx], }⟩,
left_inv := λ x, by simp,
right_inv := λ y, by { apply set_coe.ext, simp, },
..((e : M →ₗ[R] M₂).dom_restrict p).cod_restrict (p.map ↑e) (λ x, ⟨x, by simp⟩) }
@[simp] lemma of_submodule_apply (p : submodule R M) (x : p) :
↑(e.of_submodule p x) = e x := rfl
@[simp] lemma of_submodule_symm_apply (p : submodule R M) (x : (p.map ↑e : submodule R M₂)) :
↑((e.of_submodule p).symm x) = e.symm x := rfl
end
section finsupp
variables {γ : Type*} [module R M] [module R M₂] [has_zero γ]
@[simp] lemma map_finsupp_sum (f : M ≃ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} :
f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum _
end finsupp
section dfinsupp
open dfinsupp
variables {γ : ι → Type*} [decidable_eq ι] [module R M] [module R M₂]
@[simp] lemma map_dfinsupp_sum [Π i, has_zero (γ i)] [Π i (x : γ i), decidable (x ≠ 0)]
(f : M ≃ₗ[R] M₂) (t : Π₀ i, γ i) (g : Π i, γ i → M) :
f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum _
@[simp] lemma map_dfinsupp_sum_add_hom [Π i, add_zero_class (γ i)] (f : M ≃ₗ[R] M₂) (t : Π₀ i, γ i)
(g : Π i, γ i →+ M) :
f (sum_add_hom g t) = sum_add_hom (λ i, f.to_add_equiv.to_add_monoid_hom.comp (g i)) t :=
f.to_add_equiv.map_dfinsupp_sum_add_hom _ _
end dfinsupp
section uncurry
variables (V V₂ R)
/-- Linear equivalence between a curried and uncurried function.
Differs from `tensor_product.curry`. -/
protected def curry :
(V × V₂ → R) ≃ₗ[R] (V → V₂ → R) :=
{ map_add' := λ _ _, by { ext, refl },
map_smul' := λ _ _, by { ext, refl },
.. equiv.curry _ _ _ }
@[simp] lemma coe_curry : ⇑(linear_equiv.curry R V V₂) = curry := rfl
@[simp] lemma coe_curry_symm : ⇑(linear_equiv.curry R V V₂).symm = uncurry := rfl
end uncurry
section
variables {module_M : module R M} {module_M₂ : module R M₂}
{module_M₃ : module R M₃}
variables (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) (e : M ≃ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) (l : M₃ →ₗ[R] M)
variables (p q : submodule R M)
/-- Linear equivalence between two equal submodules. -/
def of_eq (h : p = q) : p ≃ₗ[R] q :=
{ map_smul' := λ _ _, rfl, map_add' := λ _ _, rfl, .. equiv.set.of_eq (congr_arg _ h) }
variables {p q}
@[simp] lemma coe_of_eq_apply (h : p = q) (x : p) : (of_eq p q h x : M) = x := rfl
@[simp] lemma of_eq_symm (h : p = q) : (of_eq p q h).symm = of_eq q p h.symm := rfl
/-- A linear equivalence which maps a submodule of one module onto another, restricts to a linear
equivalence of the two submodules. -/
def of_submodules (p : submodule R M) (q : submodule R M₂) (h : p.map ↑e = q) : p ≃ₗ[R] q :=
(e.of_submodule p).trans (linear_equiv.of_eq _ _ h)
@[simp] lemma of_submodules_apply {p : submodule R M} {q : submodule R M₂}
(h : p.map ↑e = q) (x : p) : ↑(e.of_submodules p q h x) = e x := rfl
@[simp] lemma of_submodules_symm_apply {p : submodule R M} {q : submodule R M₂}
(h : p.map ↑e = q) (x : q) : ↑((e.of_submodules p q h).symm x) = e.symm x := rfl
/-- A linear equivalence of two modules restricts to a linear equivalence from the preimage of any
submodule to that submodule.
This is `linear_equiv.of_submodule` but with `comap` on the left instead of `map` on the right. -/
def of_submodule' [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) :
U.comap (f : M →ₗ[R] M₂) ≃ₗ[R] U :=
(f.symm.of_submodules _ _ f.symm.map_eq_comap).symm
lemma of_submodule'_to_linear_map [module R M] [module R M₂]
(f : M ≃ₗ[R] M₂) (U : submodule R M₂) :
(f.of_submodule' U).to_linear_map =
(f.to_linear_map.dom_restrict _).cod_restrict _ subtype.prop :=
by { ext, refl }
@[simp]
lemma of_submodule'_apply [module R M] [module R M₂]
(f : M ≃ₗ[R] M₂) (U : submodule R M₂) (x : U.comap (f : M →ₗ[R] M₂)) :
(f.of_submodule' U x : M₂) = f (x : M) := rfl
@[simp]
lemma of_submodule'_symm_apply [module R M] [module R M₂]
(f : M ≃ₗ[R] M₂) (U : submodule R M₂) (x : U) :
((f.of_submodule' U).symm x : M) = f.symm (x : M₂) := rfl
variable (p)
/-- The top submodule of `M` is linearly equivalent to `M`. -/
def of_top (h : p = ⊤) : p ≃ₗ[R] M :=
{ inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩,
left_inv := λ ⟨x, h⟩, rfl,
right_inv := λ x, rfl,
.. p.subtype }
@[simp] theorem of_top_apply {h} (x : p) : of_top p h x = x := rfl
@[simp] theorem coe_of_top_symm_apply {h} (x : M) : ((of_top p h).symm x : M) = x := rfl
theorem of_top_symm_apply {h} (x : M) : (of_top p h).symm x = ⟨x, h.symm ▸ trivial⟩ := rfl
/-- If a linear map has an inverse, it is a linear equivalence. -/
def of_linear (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₗ[R] M₂ :=
{ inv_fun := g,
left_inv := linear_map.ext_iff.1 h₂,
right_inv := linear_map.ext_iff.1 h₁,
..f }
@[simp] theorem of_linear_apply {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl
@[simp] theorem of_linear_symm_apply {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl
@[simp] protected theorem range : (e : M →ₗ[R] M₂).range = ⊤ :=
linear_map.range_eq_top.2 e.to_equiv.surjective
lemma eq_bot_of_equiv [module R M₂] (e : p ≃ₗ[R] (⊥ : submodule R M₂)) : p = ⊥ :=
begin
refine bot_unique (set_like.le_def.2 $ assume b hb, (submodule.mem_bot R).2 _),
rw [← p.mk_eq_zero hb, ← e.map_eq_zero_iff],
apply submodule.eq_zero_of_bot_submodule
end
@[simp] protected theorem ker : (e : M →ₗ[R] M₂).ker = ⊥ :=
linear_map.ker_eq_bot_of_injective e.to_equiv.injective
@[simp] theorem range_comp : (h.comp (e : M →ₗ[R] M₂)).range = h.range :=
linear_map.range_comp_of_range_eq_top _ e.range
@[simp] theorem ker_comp : ((e : M →ₗ[R] M₂).comp l).ker = l.ker :=
linear_map.ker_comp_of_ker_eq_bot _ e.ker
variables {f g}
/-- An linear map `f : M →ₗ[R] M₂` with a left-inverse `g : M₂ →ₗ[R] M` defines a linear equivalence
between `M` and `f.range`.
This is a computable alternative to `linear_equiv.of_injective`, and a bidirectional version of
`linear_map.range_restrict`. -/
def of_left_inverse {g : M₂ → M} (h : function.left_inverse g f) : M ≃ₗ[R] f.range :=
{ to_fun := f.range_restrict,
inv_fun := g ∘ f.range.subtype,
left_inv := h,
right_inv := λ x, subtype.ext $
let ⟨x', hx'⟩ := linear_map.mem_range.mp x.prop in
show f (g x) = x, by rw [←hx', h x'],
.. f.range_restrict }
@[simp] lemma of_left_inverse_apply
(h : function.left_inverse g f) (x : M) :
↑(of_left_inverse h x) = f x := rfl
@[simp] lemma of_left_inverse_symm_apply
(h : function.left_inverse g f) (x : f.range) :
(of_left_inverse h).symm x = g x := rfl
end
end add_comm_monoid
section add_comm_group
variables [semiring R]
variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄]
variables {module_M : module R M} {module_M₂ : module R M₂}
variables {module_M₃ : module R M₃} {module_M₄ : module R M₄}
variables (e e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄)
@[simp] theorem map_neg (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a
@[simp] theorem map_sub (a b : M) : e (a - b) = e a - e b :=
e.to_linear_map.map_sub a b
end add_comm_group
section neg
variables (R) [semiring R] [add_comm_group M] [module R M]
/-- `x ↦ -x` as a `linear_equiv` -/
def neg : M ≃ₗ[R] M := { .. equiv.neg M, .. (-linear_map.id : M →ₗ[R] M) }
variable {R}
@[simp] lemma coe_neg : ⇑(neg R : M ≃ₗ[R] M) = -id := rfl
lemma neg_apply (x : M) : neg R x = -x := by simp
@[simp] lemma symm_neg : (neg R : M ≃ₗ[R] M).symm = neg R := rfl
end neg
section ring
variables [ring R] [add_comm_group M] [add_comm_group M₂]
variables {module_M : module R M} {module_M₂ : module R M₂}
variables (f : M →ₗ[R] M₂) (e : M ≃ₗ[R] M₂)
/-- An `injective` linear map `f : M →ₗ[R] M₂` defines a linear equivalence
between `M` and `f.range`. See also `linear_map.of_left_inverse`. -/
noncomputable def of_injective (h : f.ker = ⊥) : M ≃ₗ[R] f.range :=
of_left_inverse $ classical.some_spec (linear_map.ker_eq_bot.1 h).has_left_inverse
@[simp] theorem of_injective_apply {h : f.ker = ⊥} (x : M) :
↑(of_injective f h x) = f x := rfl
/-- A bijective linear map is a linear equivalence. Here, bijectivity is described by saying that
the kernel of `f` is `{0}` and the range is the universal set. -/
noncomputable def of_bijective (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : M ≃ₗ[R] M₂ :=
(of_injective f hf₁).trans (of_top _ hf₂)
@[simp] theorem of_bijective_apply {hf₁ hf₂} (x : M) :
of_bijective f hf₁ hf₂ x = f x := rfl
end ring
section comm_ring
variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
open linear_map
/-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/
def smul_of_unit (a : units R) : M ≃ₗ[R] M :=
of_linear ((a:R) • 1 : M →ₗ M) (((a⁻¹ : units R) : R) • 1 : M →ₗ M)
(by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl)
(by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl)
/-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a
linear isomorphism between the two function spaces. -/
def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R]
[add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂]
[module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂]
(e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) :
(M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) :=
{ to_fun := λ f, (e₂ : M₂₁ →ₗ[R] M₂₂).comp $ f.comp e₁.symm,
inv_fun := λ f, (e₂.symm : M₂₂ →ₗ[R] M₂₁).comp $ f.comp e₁,
left_inv := λ f, by { ext x, simp },
right_inv := λ f, by { ext x, simp },
map_add' := λ f g, by { ext x, simp },
map_smul' := λ c f, by { ext x, simp } }
@[simp] lemma arrow_congr_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R]
[add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂]
[module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂]
(e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₁ →ₗ[R] M₂₁) (x : M₂) :
arrow_congr e₁ e₂ f x = e₂ (f (e₁.symm x)) :=
rfl
@[simp] lemma arrow_congr_symm_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R]
[add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂]
[module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂]
(e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₂ →ₗ[R] M₂₂) (x : M₁) :
(arrow_congr e₁ e₂).symm f x = e₂.symm (f (e₁ x)) :=
rfl
lemma arrow_congr_comp {N N₂ N₃ : Sort*}
[add_comm_group N] [add_comm_group N₂] [add_comm_group N₃]
[module R N] [module R N₂] [module R N₃]
(e₁ : M ≃ₗ[R] N) (e₂ : M₂ ≃ₗ[R] N₂) (e₃ : M₃ ≃ₗ[R] N₃) (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) :
arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) :=
by { ext, simp only [symm_apply_apply, arrow_congr_apply, linear_map.comp_apply], }
lemma arrow_congr_trans {M₁ M₂ M₃ N₁ N₂ N₃ : Sort*}
[add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂]
[add_comm_group M₃] [module R M₃] [add_comm_group N₁] [module R N₁]
[add_comm_group N₂] [module R N₂] [add_comm_group N₃] [module R N₃]
(e₁ : M₁ ≃ₗ[R] M₂) (e₂ : N₁ ≃ₗ[R] N₂) (e₃ : M₂ ≃ₗ[R] M₃) (e₄ : N₂ ≃ₗ[R] N₃) :
(arrow_congr e₁ e₂).trans (arrow_congr e₃ e₄) = arrow_congr (e₁.trans e₃) (e₂.trans e₄) :=
rfl
/-- If `M₂` and `M₃` are linearly isomorphic then the two spaces of linear maps from `M` into `M₂`
and `M` into `M₃` are linearly isomorphic. -/
def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ (M →ₗ M₃) :=
arrow_congr (linear_equiv.refl R M) f
/-- If `M` and `M₂` are linearly isomorphic then the two spaces of linear maps from `M` and `M₂` to
themselves are linearly isomorphic. -/
def conj (e : M ≃ₗ[R] M₂) : (module.End R M) ≃ₗ[R] (module.End R M₂) := arrow_congr e e
lemma conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M) :
e.conj f = ((↑e : M →ₗ[R] M₂).comp f).comp e.symm := rfl
lemma symm_conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M₂) :
e.symm.conj f = ((↑e.symm : M₂ →ₗ[R] M).comp f).comp e := rfl
lemma conj_comp (e : M ≃ₗ[R] M₂) (f g : module.End R M) :
e.conj (g.comp f) = (e.conj g).comp (e.conj f) :=
arrow_congr_comp e e e f g
lemma conj_trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) :
e₁.conj.trans e₂.conj = (e₁.trans e₂).conj :=
by { ext f x, refl, }
@[simp] lemma conj_id (e : M ≃ₗ[R] M₂) : e.conj linear_map.id = linear_map.id :=
by { ext, simp [conj_apply], }
end comm_ring
section field
variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module K M] [module K M₂] [module K M₃]
variables (K) (M)
open linear_map
/-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/
def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M :=
smul_of_unit $ units.mk0 a ha
section
noncomputable theory
open_locale classical
lemma ker_to_span_singleton {x : M} (h : x ≠ 0) : (to_span_singleton K M x).ker = ⊥ :=
begin
ext c, split,
{ intros hc, rw submodule.mem_bot, rw mem_ker at hc, by_contra hc',
have : x = 0,
calc x = c⁻¹ • (c • x) : by rw [← mul_smul, inv_mul_cancel hc', one_smul]
... = c⁻¹ • ((to_span_singleton K M x) c) : rfl
... = 0 : by rw [hc, smul_zero],
tauto },
{ rw [mem_ker, submodule.mem_bot], intros h, rw h, simp }
end
/-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural
map from `K` to the span of `x`, with invertibility check to consider it as an
isomorphism.-/
def to_span_nonzero_singleton (x : M) (h : x ≠ 0) : K ≃ₗ[K] (K ∙ x) :=
linear_equiv.trans
(linear_equiv.of_injective (to_span_singleton K M x) (ker_to_span_singleton K M h))
(of_eq (to_span_singleton K M x).range (K ∙ x)
(span_singleton_eq_range K M x).symm)
lemma to_span_nonzero_singleton_one (x : M) (h : x ≠ 0) : to_span_nonzero_singleton K M x h 1
= (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) :=
begin
apply set_like.coe_eq_coe.mp,
have : ↑(to_span_nonzero_singleton K M x h 1) = to_span_singleton K M x 1 := rfl,
rw [this, to_span_singleton_one, submodule.coe_mk],
end
/-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map
from the span of `x` to `K`.-/
abbreviation coord (x : M) (h : x ≠ 0) : (K ∙ x) ≃ₗ[K] K :=
(to_span_nonzero_singleton K M x h).symm
lemma coord_self (x : M) (h : x ≠ 0) :
(coord K M x h) (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) = 1 :=
by rw [← to_span_nonzero_singleton_one K M x h, symm_apply_apply]
end
end field
end linear_equiv
namespace submodule
section module
variables [semiring R] [add_comm_monoid M] [module R M]
/-- Given `p` a submodule of the module `M` and `q` a submodule of `p`, `p.equiv_subtype_map q`
is the natural `linear_equiv` between `q` and `q.map p.subtype`. -/
def equiv_subtype_map (p : submodule R M) (q : submodule R p) :
q ≃ₗ[R] q.map p.subtype :=
{ inv_fun :=
begin
rintro ⟨x, hx⟩,
refine ⟨⟨x, _⟩, _⟩;
rcases hx with ⟨⟨_, h⟩, _, rfl⟩;
assumption
end,
left_inv := λ ⟨⟨_, _⟩, _⟩, rfl,
right_inv := λ ⟨x, ⟨_, h⟩, _, rfl⟩, rfl,
.. (p.subtype.dom_restrict q).cod_restrict _
begin
rintro ⟨x, hx⟩,
refine ⟨x, hx, rfl⟩,
end }
@[simp]
lemma equiv_subtype_map_apply {p : submodule R M} {q : submodule R p} (x : q) :
(p.equiv_subtype_map q x : M) = p.subtype.dom_restrict q x :=
rfl
@[simp]
lemma equiv_subtype_map_symm_apply {p : submodule R M} {q : submodule R p} (x : q.map p.subtype) :
((p.equiv_subtype_map q).symm x : M) = x :=
by { cases x, refl }
/-- If `s ≤ t`, then we can view `s` as a submodule of `t` by taking the comap
of `t.subtype`. -/
def comap_subtype_equiv_of_le {p q : submodule R M} (hpq : p ≤ q) :
comap q.subtype p ≃ₗ[R] p :=
{ to_fun := λ x, ⟨x, x.2⟩,
inv_fun := λ x, ⟨⟨x, hpq x.2⟩, x.2⟩,
left_inv := λ x, by simp only [coe_mk, set_like.eta, coe_coe],
right_inv := λ x, by simp only [subtype.coe_mk, set_like.eta, coe_coe],
map_add' := λ x y, rfl,
map_smul' := λ c x, rfl }
end module
variables [ring R] [add_comm_group M] [module R M]
variables (p : submodule R M)
open linear_map
/-- If `p = ⊥`, then `M / p ≃ₗ[R] M`. -/
def quot_equiv_of_eq_bot (hp : p = ⊥) : p.quotient ≃ₗ[R] M :=
linear_equiv.of_linear (p.liftq id $ hp.symm ▸ bot_le) p.mkq (liftq_mkq _ _ _) $
p.quot_hom_ext $ λ x, rfl
@[simp] lemma quot_equiv_of_eq_bot_apply_mk (hp : p = ⊥) (x : M) :
p.quot_equiv_of_eq_bot hp (quotient.mk x) = x := rfl
@[simp] lemma quot_equiv_of_eq_bot_symm_apply (hp : p = ⊥) (x : M) :
(p.quot_equiv_of_eq_bot hp).symm x = quotient.mk x := rfl
@[simp] lemma coe_quot_equiv_of_eq_bot_symm (hp : p = ⊥) :
((p.quot_equiv_of_eq_bot hp).symm : M →ₗ[R] p.quotient) = p.mkq := rfl
variables (q : submodule R M)
/-- Quotienting by equal submodules gives linearly equivalent quotients. -/
def quot_equiv_of_eq (h : p = q) : p.quotient ≃ₗ[R] q.quotient :=
{ map_add' := by { rintros ⟨x⟩ ⟨y⟩, refl }, map_smul' := by { rintros x ⟨y⟩, refl },
..@quotient.congr _ _ (quotient_rel p) (quotient_rel q) (equiv.refl _) $
λ a b, by { subst h, refl } }
end submodule
namespace submodule
variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂]
variables (p : submodule R M) (q : submodule R M₂)
@[simp] lemma mem_map_equiv {e : M ≃ₗ[R] M₂} {x : M₂} : x ∈ p.map (e : M →ₗ[R] M₂) ↔ e.symm x ∈ p :=
begin
rw submodule.mem_map, split,
{ rintros ⟨y, hy, hx⟩, simp [←hx, hy], },
{ intros hx, refine ⟨e.symm x, hx, by simp⟩, },
end
lemma map_equiv_eq_comap_symm (e : M ≃ₗ[R] M₂) (K : submodule R M) :
K.map (e : M →ₗ[R] M₂) = K.comap e.symm :=
submodule.ext (λ _, by rw [mem_map_equiv, mem_comap, linear_equiv.coe_coe])
lemma comap_equiv_eq_map_symm (e : M ≃ₗ[R] M₂) (K : submodule R M₂) :
K.comap (e : M →ₗ[R] M₂) = K.map e.symm :=
(map_equiv_eq_comap_symm e.symm K).symm
lemma comap_le_comap_smul (f : M →ₗ[R] M₂) (c : R) :
comap f q ≤ comap (c • f) q :=
begin
rw set_like.le_def,
intros m h,
change c • (f m) ∈ q,
change f m ∈ q at h,
apply q.smul_mem _ h,
end
lemma inf_comap_le_comap_add (f₁ f₂ : M →ₗ[R] M₂) :
comap f₁ q ⊓ comap f₂ q ≤ comap (f₁ + f₂) q :=
begin
rw set_like.le_def,
intros m h,
change f₁ m + f₂ m ∈ q,
change f₁ m ∈ q ∧ f₂ m ∈ q at h,
apply q.add_mem h.1 h.2,
end
/-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the
set of maps $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \}$ is a submodule of `Hom(M, M₂)`. -/
def compatible_maps : submodule R (M →ₗ[R] M₂) :=
{ carrier := {f | p ≤ comap f q},
zero_mem' := by { change p ≤ comap 0 q, rw comap_zero, refine le_top, },
add_mem' := λ f₁ f₂ h₁ h₂, by { apply le_trans _ (inf_comap_le_comap_add q f₁ f₂), rw le_inf_iff,
exact ⟨h₁, h₂⟩, },
smul_mem' := λ c f h, le_trans h (comap_le_comap_smul q f c), }
/-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the
natural map $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \} \to Hom(M/p, M₂/q)$ is linear. -/
def mapq_linear : compatible_maps p q →ₗ[R] p.quotient →ₗ[R] q.quotient :=
{ to_fun := λ f, mapq _ _ f.val f.property,
map_add' := λ x y, by { ext m', apply quotient.induction_on' m', intros m, refl, },
map_smul' := λ c f, by { ext m', apply quotient.induction_on' m', intros m, refl, } }
end submodule
namespace equiv
variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂]
/-- An equivalence whose underlying function is linear is a linear equivalence. -/
def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ :=
{ .. e, .. h.mk' e}
end equiv
namespace add_equiv
variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂]
/-- An additive equivalence whose underlying function preserves `smul` is a linear equivalence. -/
def to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : M ≃ₗ[R] M₂ :=
{ map_smul' := h, .. e, }
@[simp] lemma coe_to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) :
⇑(e.to_linear_equiv h) = e :=
rfl
@[simp] lemma coe_to_linear_equiv_symm (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) :
⇑(e.to_linear_equiv h).symm = e.symm :=
rfl
end add_equiv
namespace linear_map
open submodule
section isomorphism_laws
variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
variables (f : M →ₗ[R] M₂)
/-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly
equivalent to the range of `f`. -/
noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[R] f.range :=
(linear_equiv.of_injective (f.ker.liftq f $ le_refl _) $
submodule.ker_liftq_eq_bot _ _ _ (le_refl f.ker)).trans
(linear_equiv.of_eq _ _ $ submodule.range_liftq _ _ _)
/-- The first isomorphism theorem for surjective linear maps. -/
noncomputable def quot_ker_equiv_of_surjective
(f : M →ₗ[R] M₂) (hf : function.surjective f) : f.ker.quotient ≃ₗ[R] M₂ :=
f.quot_ker_equiv_range.trans
(linear_equiv.of_top f.range (linear_map.range_eq_top.2 hf))
@[simp] lemma quot_ker_equiv_range_apply_mk (x : M) :
(f.quot_ker_equiv_range (submodule.quotient.mk x) : M₂) = f x :=
rfl
@[simp] lemma quot_ker_equiv_range_symm_apply_image (x : M) (h : f x ∈ f.range) :
f.quot_ker_equiv_range.symm ⟨f x, h⟩ = f.ker.mkq x :=
f.quot_ker_equiv_range.symm_apply_apply (f.ker.mkq x)
/--
Canonical linear map from the quotient `p/(p ∩ p')` to `(p+p')/p'`, mapping `x + (p ∩ p')`
to `x + p'`, where `p` and `p'` are submodules of an ambient module.
-/
def quotient_inf_to_sup_quotient (p p' : submodule R M) :
(comap p.subtype (p ⊓ p')).quotient →ₗ[R] (comap (p ⊔ p').subtype p').quotient :=
(comap p.subtype (p ⊓ p')).liftq
((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin
rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype],
exact comap_mono (inf_le_inf_right _ le_sup_left) end
/--
Second Isomorphism Law : the canonical map from `p/(p ∩ p')` to `(p+p')/p'` as a linear isomorphism.
-/
noncomputable def quotient_inf_equiv_sup_quotient (p p' : submodule R M) :
(comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient :=
linear_equiv.of_bijective (quotient_inf_to_sup_quotient p p')
begin
rw [quotient_inf_to_sup_quotient, ker_liftq_eq_bot],
rw [ker_comp, ker_mkq],
exact λ ⟨x, hx1⟩ hx2, ⟨hx1, hx2⟩
end
begin
rw [quotient_inf_to_sup_quotient, range_liftq, eq_top_iff'],
rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩,
use [⟨y, hy⟩], apply (submodule.quotient.eq _).2,
change y - (y + z) ∈ p',
rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff]
end
@[simp] lemma coe_quotient_inf_to_sup_quotient (p p' : submodule R M) :
⇑(quotient_inf_to_sup_quotient p p') = quotient_inf_equiv_sup_quotient p p' := rfl
@[simp] lemma quotient_inf_equiv_sup_quotient_apply_mk (p p' : submodule R M) (x : p) :
quotient_inf_equiv_sup_quotient p p' (submodule.quotient.mk x) =
submodule.quotient.mk (of_le (le_sup_left : p ≤ p ⊔ p') x) :=
rfl
lemma quotient_inf_equiv_sup_quotient_symm_apply_left (p p' : submodule R M)
(x : p ⊔ p') (hx : (x:M) ∈ p) :
(quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) =
submodule.quotient.mk ⟨x, hx⟩ :=
(linear_equiv.symm_apply_eq _).2 $ by simp [of_le_apply]
@[simp] lemma quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff {p p' : submodule R M}
{x : p ⊔ p'} :
(quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 ↔ (x:M) ∈ p' :=
(linear_equiv.symm_apply_eq _).trans $ by simp [of_le_apply]
lemma quotient_inf_equiv_sup_quotient_symm_apply_right (p p' : submodule R M) {x : p ⊔ p'}
(hx : (x:M) ∈ p') :
(quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 :=
quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff.2 hx
end isomorphism_laws
section fun_left
variables (R M) [semiring R] [add_comm_monoid M] [module R M]
variables {m n p : Type*}
/-- Given an `R`-module `M` and a function `m → n` between arbitrary types,
construct a linear map `(n → M) →ₗ[R] (m → M)` -/
def fun_left (f : m → n) : (n → M) →ₗ[R] (m → M) :=
{ to_fun := (∘ f), map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl }
@[simp] theorem fun_left_apply (f : m → n) (g : n → M) (i : m) : fun_left R M f g i = g (f i) :=
rfl
@[simp] theorem fun_left_id (g : n → M) : fun_left R M _root_.id g = g :=
rfl
theorem fun_left_comp (f₁ : n → p) (f₂ : m → n) :
fun_left R M (f₁ ∘ f₂) = (fun_left R M f₂).comp (fun_left R M f₁) :=
rfl
theorem fun_left_surjective_of_injective (f : m → n) (hf : injective f) :
surjective (fun_left R M f) :=
begin
classical,
intro g,
refine ⟨λ x, if h : ∃ y, f y = x then g h.some else 0, _⟩,
{ ext,
dsimp only [fun_left_apply],
split_ifs with w,
{ congr,
exact hf w.some_spec, },
{ simpa only [not_true, exists_apply_eq_apply] using w } },
end
theorem fun_left_injective_of_surjective (f : m → n) (hf : surjective f) :
injective (fun_left R M f) :=
begin
obtain ⟨g, hg⟩ := hf.has_right_inverse,
suffices : left_inverse (fun_left R M g) (fun_left R M f),
{ exact this.injective },
intro x,
simp only [← linear_map.comp_apply, ← fun_left_comp, hg.id, fun_left_id]
end
/-- Given an `R`-module `M` and an equivalence `m ≃ n` between arbitrary types,
construct a linear equivalence `(n → M) ≃ₗ[R] (m → M)` -/
def fun_congr_left (e : m ≃ n) : (n → M) ≃ₗ[R] (m → M) :=
linear_equiv.of_linear (fun_left R M e) (fun_left R M e.symm)
(ext $ λ x, funext $ λ i,
by rw [id_apply, ← fun_left_comp, equiv.symm_comp_self, fun_left_id])
(ext $ λ x, funext $ λ i,
by rw [id_apply, ← fun_left_comp, equiv.self_comp_symm, fun_left_id])
@[simp] theorem fun_congr_left_apply (e : m ≃ n) (x : n → M) :
fun_congr_left R M e x = fun_left R M e x :=
rfl
@[simp] theorem fun_congr_left_id :
fun_congr_left R M (equiv.refl n) = linear_equiv.refl R (n → M) :=
rfl
@[simp] theorem fun_congr_left_comp (e₁ : m ≃ n) (e₂ : n ≃ p) :
fun_congr_left R M (equiv.trans e₁ e₂) =
linear_equiv.trans (fun_congr_left R M e₂) (fun_congr_left R M e₁) :=
rfl
@[simp] lemma fun_congr_left_symm (e : m ≃ n) :
(fun_congr_left R M e).symm = fun_congr_left R M e.symm :=
rfl
end fun_left
universe i
variables [semiring R] [add_comm_monoid M] [module R M]
variables (R M)
instance automorphism_group : group (M ≃ₗ[R] M) :=
{ mul := λ f g, g.trans f,
one := linear_equiv.refl R M,
inv := λ f, f.symm,
mul_assoc := λ f g h, by {ext, refl},
mul_one := λ f, by {ext, refl},
one_mul := λ f, by {ext, refl},
mul_left_inv := λ f, by {ext, exact f.left_inv x} }
/-- Restriction from `R`-linear automorphisms of `M` to `R`-linearendomorphisms of `M`,
promoted to a monoid hom. -/
def automorphism_group.to_linear_map_monoid_hom :
(M ≃ₗ[R] M) →* (M →ₗ[R] M) :=
{ to_fun := coe,
map_one' := rfl,
map_mul' := λ _ _, rfl }
/-- The group of invertible linear maps from `M` to itself -/
@[reducible] def general_linear_group := units (M →ₗ[R] M)
namespace general_linear_group
variables {R M}
instance : has_coe_to_fun (general_linear_group R M) := by apply_instance
/-- An invertible linear map `f` determines an equivalence from `M` to itself. -/
def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) :=
{ inv_fun := f.inv.to_fun,
left_inv := λ m, show (f.inv * f.val) m = m,
by erw f.inv_val; simp,
right_inv := λ m, show (f.val * f.inv) m = m,
by erw f.val_inv; simp,
..f.val }
/-- An equivalence from `M` to itself determines an invertible linear map. -/
def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M :=
{ val := f,
inv := f.symm,
val_inv := linear_map.ext $ λ _, f.apply_symm_apply _,
inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ }
variables (R M)
/-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear
equivalences between `M` and itself. -/
def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) :=
{ to_fun := to_linear_equiv,
inv_fun := of_linear_equiv,
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, refl },
map_mul' := λ x y, by {ext, refl} }
@[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) :
(general_linear_equiv R M f : M →ₗ[R] M) = f :=
by {ext, refl}
end general_linear_group
end linear_map
namespace submodule
variables [ring R] [add_comm_group M] [module R M]
instance : is_modular_lattice (submodule R M) :=
⟨λ x y z xz a ha, begin
rw [mem_inf, mem_sup] at ha,
rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩,
rw mem_sup,
refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩,
rw [← add_sub_cancel c b, add_comm],
apply z.sub_mem haz (xz hb),
end⟩
section third_iso_thm
variables (S T : submodule R M) (h : S ≤ T)
/-- The map from the third isomorphism theorem for modules: `(M / S) / (T / S) → M / T`. -/
def quotient_quotient_equiv_quotient_aux :
quotient (T.map S.mkq) →ₗ[R] quotient T :=
liftq _ (mapq S T linear_map.id h)
(by { rintro _ ⟨x, hx, rfl⟩, rw [linear_map.mem_ker, mkq_apply, mapq_apply],
exact (quotient.mk_eq_zero _).mpr hx })
@[simp] lemma quotient_quotient_equiv_quotient_aux_mk (x : S.quotient) :
quotient_quotient_equiv_quotient_aux S T h (quotient.mk x) = mapq S T linear_map.id h x :=
liftq_apply _ _ _
@[simp] lemma quotient_quotient_equiv_quotient_aux_mk_mk (x : M) :
quotient_quotient_equiv_quotient_aux S T h (quotient.mk (quotient.mk x)) = quotient.mk x :=
by rw [quotient_quotient_equiv_quotient_aux_mk, mapq_apply, linear_map.id_apply]
/-- **Noether's third isomorphism theorem** for modules: `(M / S) / (T / S) ≃ M / T`. -/
def quotient_quotient_equiv_quotient :
quotient (T.map S.mkq) ≃ₗ[R] quotient T :=
{ to_fun := quotient_quotient_equiv_quotient_aux S T h,
inv_fun := mapq _ _ (mkq S) (le_comap_map _ _),
left_inv := λ x, quotient.induction_on' x $ λ x, quotient.induction_on' x $ λ x, by simp,
right_inv := λ x, quotient.induction_on' x $ λ x, by simp,
.. quotient_quotient_equiv_quotient_aux S T h }
end third_iso_thm
end submodule
|
eb71c65a54bea91d87200d3136119e1a799e2ffa | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/gcd_monoid/basic.lean | b9d1989f192fc3da7be880e071b214b8e588e798 | [
"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 | 49,318 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jens Wagemaker
-/
import algebra.associated
import algebra.group_power.lemmas
/-!
# Monoids with normalization functions, `gcd`, and `lcm`
This file defines extra structures on `cancel_comm_monoid_with_zero`s, including `is_domain`s.
## Main Definitions
* `normalization_monoid`
* `gcd_monoid`
* `normalized_gcd_monoid`
* `gcd_monoid_of_gcd`, `gcd_monoid_of_exists_gcd`, `normalized_gcd_monoid_of_gcd`,
`normalized_gcd_monoid_of_exists_gcd`
* `gcd_monoid_of_lcm`, `gcd_monoid_of_exists_lcm`, `normalized_gcd_monoid_of_lcm`,
`normalized_gcd_monoid_of_exists_lcm`
For the `normalized_gcd_monoid` instances on `ℕ` and `ℤ`, see `ring_theory.int.basic`.
## Implementation Notes
* `normalization_monoid` is defined by assigning to each element a `norm_unit` such that multiplying
by that unit normalizes the monoid, and `normalize` is an idempotent monoid homomorphism. This
definition as currently implemented does casework on `0`.
* `gcd_monoid` contains the definitions of `gcd` and `lcm` with the usual properties. They are
both determined up to a unit.
* `normalized_gcd_monoid` extends `normalization_monoid`, so the `gcd` and `lcm` are always
normalized. This makes `gcd`s of polynomials easier to work with, but excludes Euclidean domains,
and monoids without zero.
* `gcd_monoid_of_gcd` and `normalized_gcd_monoid_of_gcd` noncomputably construct a `gcd_monoid`
(resp. `normalized_gcd_monoid`) structure just from the `gcd` and its properties.
* `gcd_monoid_of_exists_gcd` and `normalized_gcd_monoid_of_exists_gcd` noncomputably construct a
`gcd_monoid` (resp. `normalized_gcd_monoid`) structure just from a proof that any two elements
have a (not necessarily normalized) `gcd`.
* `gcd_monoid_of_lcm` and `normalized_gcd_monoid_of_lcm` noncomputably construct a `gcd_monoid`
(resp. `normalized_gcd_monoid`) structure just from the `lcm` and its properties.
* `gcd_monoid_of_exists_lcm` and `normalized_gcd_monoid_of_exists_lcm` noncomputably construct a
`gcd_monoid` (resp. `normalized_gcd_monoid`) structure just from a proof that any two elements
have a (not necessarily normalized) `lcm`.
## TODO
* Port GCD facts about nats, definition of coprime
* Generalize normalization monoids to commutative (cancellative) monoids with or without zero
## Tags
divisibility, gcd, lcm, normalize
-/
variables {α : Type*}
/-- Normalization monoid: multiplying with `norm_unit` gives a normal form for associated
elements. -/
@[protect_proj] class normalization_monoid (α : Type*)
[cancel_comm_monoid_with_zero α] :=
(norm_unit : α → αˣ)
(norm_unit_zero : norm_unit 0 = 1)
(norm_unit_mul : ∀{a b}, a ≠ 0 → b ≠ 0 → norm_unit (a * b) = norm_unit a * norm_unit b)
(norm_unit_coe_units : ∀(u : αˣ), norm_unit u = u⁻¹)
export normalization_monoid (norm_unit norm_unit_zero norm_unit_mul norm_unit_coe_units)
attribute [simp] norm_unit_coe_units norm_unit_zero norm_unit_mul
section normalization_monoid
variables [cancel_comm_monoid_with_zero α] [normalization_monoid α]
@[simp] theorem norm_unit_one : norm_unit (1:α) = 1 :=
norm_unit_coe_units 1
/-- Chooses an element of each associate class, by multiplying by `norm_unit` -/
def normalize : α →*₀ α :=
{ to_fun := λ x, x * norm_unit x,
map_zero' := by simp,
map_one' := by rw [norm_unit_one, units.coe_one, mul_one],
map_mul' := λ x y,
classical.by_cases (λ hx : x = 0, by rw [hx, zero_mul, zero_mul, zero_mul]) $ λ hx,
classical.by_cases (λ hy : y = 0, by rw [hy, mul_zero, zero_mul, mul_zero]) $ λ hy,
by simp only [norm_unit_mul hx hy, units.coe_mul]; simp only [mul_assoc, mul_left_comm y], }
theorem associated_normalize (x : α) : associated x (normalize x) :=
⟨_, rfl⟩
theorem normalize_associated (x : α) : associated (normalize x) x :=
(associated_normalize _).symm
lemma associated_normalize_iff {x y : α} :
associated x (normalize y) ↔ associated x y :=
⟨λ h, h.trans (normalize_associated y), λ h, h.trans (associated_normalize y)⟩
lemma normalize_associated_iff {x y : α} :
associated (normalize x) y ↔ associated x y :=
⟨λ h, (associated_normalize _).trans h, λ h, (normalize_associated _).trans h⟩
lemma associates.mk_normalize (x : α) : associates.mk (normalize x) = associates.mk x :=
associates.mk_eq_mk_iff_associated.2 (normalize_associated _)
@[simp] lemma normalize_apply (x : α) : normalize x = x * norm_unit x := rfl
@[simp] lemma normalize_zero : normalize (0 : α) = 0 := normalize.map_zero
@[simp] lemma normalize_one : normalize (1 : α) = 1 := normalize.map_one
lemma normalize_coe_units (u : αˣ) : normalize (u : α) = 1 := by simp
lemma normalize_eq_zero {x : α} : normalize x = 0 ↔ x = 0 :=
⟨λ hx, (associated_zero_iff_eq_zero x).1 $ hx ▸ associated_normalize _,
by rintro rfl; exact normalize_zero⟩
lemma normalize_eq_one {x : α} : normalize x = 1 ↔ is_unit x :=
⟨λ hx, is_unit_iff_exists_inv.2 ⟨_, hx⟩, λ ⟨u, hu⟩, hu ▸ normalize_coe_units u⟩
@[simp] theorem norm_unit_mul_norm_unit (a : α) : norm_unit (a * norm_unit a) = 1 :=
begin
nontriviality α using [subsingleton.elim a 0],
obtain rfl|h := eq_or_ne a 0,
{ rw [norm_unit_zero, zero_mul, norm_unit_zero] },
{ rw [norm_unit_mul h (units.ne_zero _), norm_unit_coe_units, mul_inv_eq_one] }
end
theorem normalize_idem (x : α) : normalize (normalize x) = normalize x := by simp
theorem normalize_eq_normalize {a b : α}
(hab : a ∣ b) (hba : b ∣ a) : normalize a = normalize b :=
begin
nontriviality α,
rcases associated_of_dvd_dvd hab hba with ⟨u, rfl⟩,
refine classical.by_cases (by rintro rfl; simp only [zero_mul]) (assume ha : a ≠ 0, _),
suffices : a * ↑(norm_unit a) = a * ↑u * ↑(norm_unit a) * ↑u⁻¹,
by simpa only [normalize_apply, mul_assoc, norm_unit_mul ha u.ne_zero, norm_unit_coe_units],
calc a * ↑(norm_unit a) = a * ↑(norm_unit a) * ↑u * ↑u⁻¹:
(units.mul_inv_cancel_right _ _).symm
... = a * ↑u * ↑(norm_unit a) * ↑u⁻¹ : by rw mul_right_comm a
end
lemma normalize_eq_normalize_iff {x y : α} : normalize x = normalize y ↔ x ∣ y ∧ y ∣ x :=
⟨λ h, ⟨units.dvd_mul_right.1 ⟨_, h.symm⟩, units.dvd_mul_right.1 ⟨_, h⟩⟩,
λ ⟨hxy, hyx⟩, normalize_eq_normalize hxy hyx⟩
theorem dvd_antisymm_of_normalize_eq {a b : α}
(ha : normalize a = a) (hb : normalize b = b) (hab : a ∣ b) (hba : b ∣ a) :
a = b :=
ha ▸ hb ▸ normalize_eq_normalize hab hba
--can be proven by simp
lemma dvd_normalize_iff {a b : α} : a ∣ normalize b ↔ a ∣ b :=
units.dvd_mul_right
--can be proven by simp
lemma normalize_dvd_iff {a b : α} : normalize a ∣ b ↔ a ∣ b :=
units.mul_right_dvd
end normalization_monoid
namespace associates
variables [cancel_comm_monoid_with_zero α] [normalization_monoid α]
local attribute [instance] associated.setoid
/-- Maps an element of `associates` back to the normalized element of its associate class -/
protected def out : associates α → α :=
quotient.lift (normalize : α → α) $ λ a b ⟨u, hu⟩, hu ▸
normalize_eq_normalize ⟨_, rfl⟩ (units.mul_right_dvd.2 $ dvd_refl a)
@[simp] lemma out_mk (a : α) : (associates.mk a).out = normalize a := rfl
@[simp] lemma out_one : (1 : associates α).out = 1 :=
normalize_one
lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out :=
quotient.induction_on₂ a b $ assume a b,
by simp only [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk, normalize.map_mul]
lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b :=
quotient.induction_on b $
by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff]
lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a :=
quotient.induction_on b $
by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff]
@[simp] lemma out_top : (⊤ : associates α).out = 0 :=
normalize_zero
@[simp] lemma normalize_out (a : associates α) : normalize a.out = a.out :=
quotient.induction_on a normalize_idem
@[simp] lemma mk_out (a : associates α) : associates.mk (a.out) = a :=
quotient.induction_on a mk_normalize
lemma out_injective : function.injective (associates.out : _ → α) :=
function.left_inverse.injective mk_out
end associates
/-- GCD monoid: a `cancel_comm_monoid_with_zero` with `gcd` (greatest common divisor) and
`lcm` (least common multiple) operations, determined up to a unit. The type class focuses on `gcd`
and we derive the corresponding `lcm` facts from `gcd`.
-/
@[protect_proj] class gcd_monoid (α : Type*) [cancel_comm_monoid_with_zero α] :=
(gcd : α → α → α)
(lcm : α → α → α)
(gcd_dvd_left : ∀a b, gcd a b ∣ a)
(gcd_dvd_right : ∀a b, gcd a b ∣ b)
(dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b)
(gcd_mul_lcm : ∀a b, associated (gcd a b * lcm a b) (a * b))
(lcm_zero_left : ∀a, lcm 0 a = 0)
(lcm_zero_right : ∀a, lcm a 0 = 0)
/-- Normalized GCD monoid: a `cancel_comm_monoid_with_zero` with normalization and `gcd`
(greatest common divisor) and `lcm` (least common multiple) operations. In this setting `gcd` and
`lcm` form a bounded lattice on the associated elements where `gcd` is the infimum, `lcm` is the
supremum, `1` is bottom, and `0` is top. The type class focuses on `gcd` and we derive the
corresponding `lcm` facts from `gcd`.
-/
class normalized_gcd_monoid (α : Type*) [cancel_comm_monoid_with_zero α]
extends normalization_monoid α, gcd_monoid α :=
(normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b)
(normalize_lcm : ∀a b, normalize (lcm a b) = lcm a b)
export gcd_monoid (gcd lcm gcd_dvd_left gcd_dvd_right dvd_gcd lcm_zero_left lcm_zero_right)
attribute [simp] lcm_zero_left lcm_zero_right
section gcd_monoid
variables [cancel_comm_monoid_with_zero α]
@[simp] theorem normalize_gcd [normalized_gcd_monoid α] : ∀a b:α, normalize (gcd a b) = gcd a b :=
normalized_gcd_monoid.normalize_gcd
theorem gcd_mul_lcm [gcd_monoid α] : ∀a b:α, associated (gcd a b * lcm a b) (a * b) :=
gcd_monoid.gcd_mul_lcm
section gcd
theorem dvd_gcd_iff [gcd_monoid α] (a b c : α) : a ∣ gcd b c ↔ (a ∣ b ∧ a ∣ c) :=
iff.intro
(assume h, ⟨h.trans (gcd_dvd_left _ _), h.trans (gcd_dvd_right _ _)⟩)
(assume ⟨hab, hac⟩, dvd_gcd hab hac)
theorem gcd_comm [normalized_gcd_monoid α] (a b : α) : gcd a b = gcd b a :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _)
(dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _))
(dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _))
theorem gcd_comm' [gcd_monoid α] (a b : α) : associated (gcd a b) (gcd b a) :=
associated_of_dvd_dvd
(dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _))
(dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _))
theorem gcd_assoc [normalized_gcd_monoid α] (m n k : α) : gcd (gcd m n) k = gcd m (gcd n k) :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _)
(dvd_gcd
((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_left m n))
(dvd_gcd ((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_right m n))
(gcd_dvd_right (gcd m n) k)))
(dvd_gcd
(dvd_gcd (gcd_dvd_left m (gcd n k)) ((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_left n k)))
((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_right n k)))
theorem gcd_assoc' [gcd_monoid α] (m n k : α) : associated (gcd (gcd m n) k) (gcd m (gcd n k)) :=
associated_of_dvd_dvd
(dvd_gcd
((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_left m n))
(dvd_gcd ((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_right m n))
(gcd_dvd_right (gcd m n) k)))
(dvd_gcd
(dvd_gcd (gcd_dvd_left m (gcd n k)) ((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_left n k)))
((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_right n k)))
instance [normalized_gcd_monoid α] : is_commutative α gcd := ⟨gcd_comm⟩
instance [normalized_gcd_monoid α] : is_associative α gcd := ⟨gcd_assoc⟩
theorem gcd_eq_normalize [normalized_gcd_monoid α] {a b c : α}
(habc : gcd a b ∣ c) (hcab : c ∣ gcd a b) :
gcd a b = normalize c :=
normalize_gcd a b ▸ normalize_eq_normalize habc hcab
@[simp] theorem gcd_zero_left [normalized_gcd_monoid α] (a : α) : gcd 0 a = normalize a :=
gcd_eq_normalize (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a))
theorem gcd_zero_left' [gcd_monoid α] (a : α) : associated (gcd 0 a) a :=
associated_of_dvd_dvd (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a))
@[simp] theorem gcd_zero_right [normalized_gcd_monoid α] (a : α) : gcd a 0 = normalize a :=
gcd_eq_normalize (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero _))
theorem gcd_zero_right' [gcd_monoid α] (a : α) : associated (gcd a 0) a :=
associated_of_dvd_dvd (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero _))
@[simp] theorem gcd_eq_zero_iff [gcd_monoid α] (a b : α) : gcd a b = 0 ↔ a = 0 ∧ b = 0 :=
iff.intro
(assume h, let ⟨ca, ha⟩ := gcd_dvd_left a b, ⟨cb, hb⟩ := gcd_dvd_right a b in
by rw [h, zero_mul] at ha hb; exact ⟨ha, hb⟩)
(assume ⟨ha, hb⟩, by
{ rw [ha, hb, ←zero_dvd_iff],
apply dvd_gcd; refl })
@[simp] theorem gcd_one_left [normalized_gcd_monoid α] (a : α) : gcd 1 a = 1 :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_left _ _) (one_dvd _)
@[simp] theorem gcd_one_left' [gcd_monoid α] (a : α) : associated (gcd 1 a) 1 :=
associated_of_dvd_dvd (gcd_dvd_left _ _) (one_dvd _)
@[simp] theorem gcd_one_right [normalized_gcd_monoid α] (a : α) : gcd a 1 = 1 :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_right _ _) (one_dvd _)
@[simp] theorem gcd_one_right' [gcd_monoid α] (a : α) : associated (gcd a 1) 1 :=
associated_of_dvd_dvd (gcd_dvd_right _ _) (one_dvd _)
theorem gcd_dvd_gcd [gcd_monoid α] {a b c d: α} (hab : a ∣ b) (hcd : c ∣ d) : gcd a c ∣ gcd b d :=
dvd_gcd ((gcd_dvd_left _ _).trans hab) ((gcd_dvd_right _ _).trans hcd)
@[simp] theorem gcd_same [normalized_gcd_monoid α] (a : α) : gcd a a = normalize a :=
gcd_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_refl a))
@[simp] theorem gcd_mul_left [normalized_gcd_monoid α] (a b c : α) :
gcd (a * b) (a * c) = normalize a * gcd b c :=
classical.by_cases (by rintro rfl; simp only [zero_mul, gcd_zero_left, normalize_zero]) $
assume ha : a ≠ 0,
suffices gcd (a * b) (a * c) = normalize (a * gcd b c),
by simpa only [normalize.map_mul, normalize_gcd],
let ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c) in
gcd_eq_normalize
(eq.symm ▸ mul_dvd_mul_left a $ show d ∣ gcd b c, from
dvd_gcd
((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_left _ _)
((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_right _ _))
(dvd_gcd
(mul_dvd_mul_left a $ gcd_dvd_left _ _)
(mul_dvd_mul_left a $ gcd_dvd_right _ _))
theorem gcd_mul_left' [gcd_monoid α] (a b c : α) : associated (gcd (a * b) (a * c)) (a * gcd b c) :=
begin
obtain rfl|ha := eq_or_ne a 0,
{ simp only [zero_mul, gcd_zero_left'] },
obtain ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c),
apply associated_of_dvd_dvd,
{ rw eq,
apply mul_dvd_mul_left,
exact dvd_gcd
((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_left _ _)
((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_right _ _) },
{ exact (dvd_gcd
(mul_dvd_mul_left a $ gcd_dvd_left _ _)
(mul_dvd_mul_left a $ gcd_dvd_right _ _)) },
end
@[simp] theorem gcd_mul_right [normalized_gcd_monoid α] (a b c : α) :
gcd (b * a) (c * a) = gcd b c * normalize a :=
by simp only [mul_comm, gcd_mul_left]
@[simp] theorem gcd_mul_right' [gcd_monoid α] (a b c : α) :
associated (gcd (b * a) (c * a)) (gcd b c * a) :=
by simp only [mul_comm, gcd_mul_left']
theorem gcd_eq_left_iff [normalized_gcd_monoid α] (a b : α) (h : normalize a = a) :
gcd a b = a ↔ a ∣ b :=
iff.intro (assume eq, eq ▸ gcd_dvd_right _ _) $
assume hab, dvd_antisymm_of_normalize_eq (normalize_gcd _ _) h (gcd_dvd_left _ _)
(dvd_gcd (dvd_refl a) hab)
theorem gcd_eq_right_iff [normalized_gcd_monoid α] (a b : α) (h : normalize b = b) :
gcd a b = b ↔ b ∣ a :=
by simpa only [gcd_comm a b] using gcd_eq_left_iff b a h
theorem gcd_dvd_gcd_mul_left [gcd_monoid α] (m n k : α) : gcd m n ∣ gcd (k * m) n :=
gcd_dvd_gcd (dvd_mul_left _ _) dvd_rfl
theorem gcd_dvd_gcd_mul_right [gcd_monoid α] (m n k : α) : gcd m n ∣ gcd (m * k) n :=
gcd_dvd_gcd (dvd_mul_right _ _) dvd_rfl
theorem gcd_dvd_gcd_mul_left_right [gcd_monoid α] (m n k : α) : gcd m n ∣ gcd m (k * n) :=
gcd_dvd_gcd dvd_rfl (dvd_mul_left _ _)
theorem gcd_dvd_gcd_mul_right_right [gcd_monoid α] (m n k : α) : gcd m n ∣ gcd m (n * k) :=
gcd_dvd_gcd dvd_rfl (dvd_mul_right _ _)
theorem associated.gcd_eq_left [normalized_gcd_monoid α] {m n : α} (h : associated m n) (k : α) :
gcd m k = gcd n k :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _)
(gcd_dvd_gcd h.dvd dvd_rfl)
(gcd_dvd_gcd h.symm.dvd dvd_rfl)
theorem associated.gcd_eq_right [normalized_gcd_monoid α] {m n : α} (h : associated m n) (k : α) :
gcd k m = gcd k n :=
dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _)
(gcd_dvd_gcd dvd_rfl h.dvd)
(gcd_dvd_gcd dvd_rfl h.symm.dvd)
lemma dvd_gcd_mul_of_dvd_mul [gcd_monoid α] {m n k : α} (H : k ∣ m * n) : k ∣ (gcd k m) * n :=
(dvd_gcd (dvd_mul_right _ n) H).trans (gcd_mul_right' n k m).dvd
lemma dvd_mul_gcd_of_dvd_mul [gcd_monoid α] {m n k : α} (H : k ∣ m * n) : k ∣ m * gcd k n :=
by { rw mul_comm at H ⊢, exact dvd_gcd_mul_of_dvd_mul H }
/-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`.
Note: In general, this representation is highly non-unique. -/
lemma exists_dvd_and_dvd_of_dvd_mul [gcd_monoid α] {m n k : α} (H : k ∣ m * n) :
∃ d₁ (hd₁ : d₁ ∣ m) d₂ (hd₂ : d₂ ∣ n), k = d₁ * d₂ :=
begin
by_cases h0 : gcd k m = 0,
{ rw gcd_eq_zero_iff at h0,
rcases h0 with ⟨rfl, rfl⟩,
refine ⟨0, dvd_refl 0, n, dvd_refl n, _⟩,
simp },
{ obtain ⟨a, ha⟩ := gcd_dvd_left k m,
refine ⟨gcd k m, gcd_dvd_right _ _, a, _, ha⟩,
suffices h : gcd k m * a ∣ gcd k m * n,
{ cases h with b hb,
use b,
rw mul_assoc at hb,
apply mul_left_cancel₀ h0 hb },
rw ← ha,
exact dvd_gcd_mul_of_dvd_mul H }
end
theorem gcd_mul_dvd_mul_gcd [gcd_monoid α] (k m n : α) : gcd k (m * n) ∣ gcd k m * gcd k n :=
begin
obtain ⟨m', hm', n', hn', h⟩ := (exists_dvd_and_dvd_of_dvd_mul $ gcd_dvd_right k (m * n)),
replace h : gcd k (m * n) = m' * n' := h,
rw h,
have hm'n' : m' * n' ∣ k := h ▸ gcd_dvd_left _ _,
apply mul_dvd_mul,
{ have hm'k : m' ∣ k := (dvd_mul_right m' n').trans hm'n',
exact dvd_gcd hm'k hm' },
{ have hn'k : n' ∣ k := (dvd_mul_left n' m').trans hm'n',
exact dvd_gcd hn'k hn' }
end
theorem gcd_pow_right_dvd_pow_gcd [gcd_monoid α] {a b : α} {k : ℕ} :
gcd a (b ^ k) ∣ (gcd a b) ^ k :=
begin
by_cases hg : gcd a b = 0,
{ rw gcd_eq_zero_iff at hg,
rcases hg with ⟨rfl, rfl⟩,
exact (gcd_zero_left' (0 ^ k : α)).dvd.trans
(pow_dvd_pow_of_dvd (gcd_zero_left' (0 : α)).symm.dvd _) },
{ induction k with k hk,
{ simp only [pow_zero],
exact (gcd_one_right' a).dvd, },
rw [pow_succ, pow_succ],
transitivity gcd a b * gcd a (b ^ k),
apply gcd_mul_dvd_mul_gcd a b (b ^ k),
exact (mul_dvd_mul_iff_left hg).mpr hk }
end
theorem gcd_pow_left_dvd_pow_gcd [gcd_monoid α] {a b : α} {k : ℕ} :
gcd (a ^ k) b ∣ (gcd a b) ^ k :=
calc gcd (a ^ k) b
∣ gcd b (a ^ k) : (gcd_comm' _ _).dvd
... ∣ (gcd b a) ^ k : gcd_pow_right_dvd_pow_gcd
... ∣ (gcd a b) ^ k : pow_dvd_pow_of_dvd (gcd_comm' _ _).dvd _
theorem pow_dvd_of_mul_eq_pow [gcd_monoid α] {a b c d₁ d₂ : α} (ha : a ≠ 0)
(hab : is_unit (gcd a b)) {k : ℕ} (h : a * b = c ^ k) (hc : c = d₁ * d₂)
(hd₁ : d₁ ∣ a) : d₁ ^ k ≠ 0 ∧ d₁ ^ k ∣ a :=
begin
have h1 : is_unit (gcd (d₁ ^ k) b),
{ apply is_unit_of_dvd_one,
transitivity (gcd d₁ b) ^ k,
{ exact gcd_pow_left_dvd_pow_gcd },
{ apply is_unit.dvd, apply is_unit.pow, apply is_unit_of_dvd_one,
apply dvd_trans _ hab.dvd,
apply gcd_dvd_gcd hd₁ (dvd_refl b) } },
have h2 : d₁ ^ k ∣ a * b, { use d₂ ^ k, rw [h, hc], exact mul_pow d₁ d₂ k },
rw mul_comm at h2,
have h3 : d₁ ^ k ∣ a,
{ apply (dvd_gcd_mul_of_dvd_mul h2).trans,
rw is_unit.mul_left_dvd _ _ _ h1 },
have h4 : d₁ ^ k ≠ 0,
{ intro hdk, rw hdk at h3, apply absurd (zero_dvd_iff.mp h3) ha },
exact ⟨h4, h3⟩,
end
theorem exists_associated_pow_of_mul_eq_pow [gcd_monoid α] {a b c : α}
(hab : is_unit (gcd a b)) {k : ℕ}
(h : a * b = c ^ k) : ∃ (d : α), associated (d ^ k) a :=
begin
casesI subsingleton_or_nontrivial α,
{ use 0, rw [subsingleton.elim a (0 ^ k)] },
by_cases ha : a = 0,
{ use 0, rw ha,
obtain (rfl | hk) := k.eq_zero_or_pos,
{ exfalso, revert h, rw [ha, zero_mul, pow_zero], apply zero_ne_one },
{ rw zero_pow hk } },
by_cases hb : b = 0,
{ use 1, rw [one_pow],
apply (associated_one_iff_is_unit.mpr hab).symm.trans,
rw hb,
exact gcd_zero_right' a },
obtain (rfl | hk) := k.eq_zero_or_pos,
{ use 1, rw pow_zero at h ⊢, use units.mk_of_mul_eq_one _ _ h,
rw [units.coe_mk_of_mul_eq_one, one_mul] },
have hc : c ∣ a * b, { rw h, exact dvd_pow_self _ hk.ne' },
obtain ⟨d₁, hd₁, d₂, hd₂, hc⟩ := exists_dvd_and_dvd_of_dvd_mul hc,
use d₁,
obtain ⟨h0₁, ⟨a', ha'⟩⟩ := pow_dvd_of_mul_eq_pow ha hab h hc hd₁,
rw [mul_comm] at h hc,
rw (gcd_comm' a b).is_unit_iff at hab,
obtain ⟨h0₂, ⟨b', hb'⟩⟩ := pow_dvd_of_mul_eq_pow hb hab h hc hd₂,
rw [ha', hb', hc, mul_pow] at h,
have h' : a' * b' = 1,
{ apply (mul_right_inj' h0₁).mp, rw mul_one,
apply (mul_right_inj' h0₂).mp, rw ← h,
rw [mul_assoc, mul_comm a', ← mul_assoc _ b', ← mul_assoc b', mul_comm b'] },
use units.mk_of_mul_eq_one _ _ h',
rw [units.coe_mk_of_mul_eq_one, ha']
end
theorem exists_eq_pow_of_mul_eq_pow [gcd_monoid α] [unique αˣ] {a b c : α}
(hab : is_unit (gcd a b)) {k : ℕ}
(h : a * b = c ^ k) : ∃ (d : α), a = d ^ k :=
let ⟨d, hd⟩ := exists_associated_pow_of_mul_eq_pow hab h in ⟨d, (associated_iff_eq.mp hd).symm⟩
lemma gcd_greatest {α : Type*} [cancel_comm_monoid_with_zero α] [normalized_gcd_monoid α]
{a b d : α} (hda : d ∣ a) (hdb : d ∣ b)
(hd : ∀ e : α, e ∣ a → e ∣ b → e ∣ d) : gcd_monoid.gcd a b = normalize d :=
begin
have h := hd _ (gcd_monoid.gcd_dvd_left a b) (gcd_monoid.gcd_dvd_right a b),
exact gcd_eq_normalize h (gcd_monoid.dvd_gcd hda hdb),
end
lemma gcd_greatest_associated {α : Type*} [cancel_comm_monoid_with_zero α] [gcd_monoid α]
{a b d : α} (hda : d ∣ a) (hdb : d ∣ b)
(hd : ∀ e : α, e ∣ a → e ∣ b → e ∣ d) : associated d (gcd_monoid.gcd a b) :=
begin
have h := hd _ (gcd_monoid.gcd_dvd_left a b) (gcd_monoid.gcd_dvd_right a b),
exact associated_of_dvd_dvd (gcd_monoid.dvd_gcd hda hdb) h,
end
lemma is_unit_gcd_of_eq_mul_gcd {α : Type*} [cancel_comm_monoid_with_zero α] [gcd_monoid α]
{x y x' y' : α} (ex : x = gcd x y * x') (ey : y = gcd x y * y') (h : gcd x y ≠ 0) :
is_unit (gcd x' y') :=
begin
rw ← associated_one_iff_is_unit,
refine associated.of_mul_left _ (associated.refl $ gcd x y) h,
convert (gcd_mul_left' _ _ _).symm using 1,
rw [← ex, ← ey, mul_one],
end
lemma extract_gcd {α : Type*} [cancel_comm_monoid_with_zero α] [gcd_monoid α] (x y : α) :
∃ x' y' d : α, x = d * x' ∧ y = d * y' ∧ is_unit (gcd x' y') :=
begin
cases eq_or_ne (gcd x y) 0 with h h,
{ obtain ⟨rfl, rfl⟩ := (gcd_eq_zero_iff x y).1 h,
simp_rw ← associated_one_iff_is_unit,
exact ⟨1, 1, 0, (zero_mul 1).symm, (zero_mul 1).symm, gcd_one_left' 1⟩ },
obtain ⟨x', ex⟩ := gcd_dvd_left x y,
obtain ⟨y', ey⟩ := gcd_dvd_right x y,
exact ⟨x', y', gcd x y, ex, ey, is_unit_gcd_of_eq_mul_gcd ex ey h⟩,
end
end gcd
section lcm
lemma lcm_dvd_iff [gcd_monoid α] {a b c : α} : lcm a b ∣ c ↔ a ∣ c ∧ b ∣ c :=
begin
by_cases this : a = 0 ∨ b = 0,
{ rcases this with rfl | rfl;
simp only [iff_def, lcm_zero_left, lcm_zero_right, zero_dvd_iff, dvd_zero,
eq_self_iff_true, and_true, imp_true_iff] {contextual:=tt} },
{ obtain ⟨h1, h2⟩ := not_or_distrib.1 this,
have h : gcd a b ≠ 0, from λ H, h1 ((gcd_eq_zero_iff _ _).1 H).1,
rw [← mul_dvd_mul_iff_left h, (gcd_mul_lcm a b).dvd_iff_dvd_left,
←(gcd_mul_right' c a b).dvd_iff_dvd_right, dvd_gcd_iff, mul_comm b c,
mul_dvd_mul_iff_left h1, mul_dvd_mul_iff_right h2, and_comm] }
end
lemma dvd_lcm_left [gcd_monoid α] (a b : α) : a ∣ lcm a b :=
(lcm_dvd_iff.1 (dvd_refl (lcm a b))).1
lemma dvd_lcm_right [gcd_monoid α] (a b : α) : b ∣ lcm a b :=
(lcm_dvd_iff.1 (dvd_refl (lcm a b))).2
lemma lcm_dvd [gcd_monoid α] {a b c : α} (hab : a ∣ b) (hcb : c ∣ b) : lcm a c ∣ b :=
lcm_dvd_iff.2 ⟨hab, hcb⟩
@[simp] theorem lcm_eq_zero_iff [gcd_monoid α] (a b : α) : lcm a b = 0 ↔ a = 0 ∨ b = 0 :=
iff.intro
(assume h : lcm a b = 0,
have associated (a * b) 0 := (gcd_mul_lcm a b).symm.trans $
by rw [h, mul_zero],
by simpa only [associated_zero_iff_eq_zero, mul_eq_zero])
(by rintro (rfl | rfl); [apply lcm_zero_left, apply lcm_zero_right])
@[simp] lemma normalize_lcm [normalized_gcd_monoid α] (a b : α) : normalize (lcm a b) = lcm a b :=
normalized_gcd_monoid.normalize_lcm a b
theorem lcm_comm [normalized_gcd_monoid α] (a b : α) : lcm a b = lcm b a :=
dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _)
(lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _))
(lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _))
theorem lcm_comm' [gcd_monoid α] (a b : α) : associated (lcm a b) (lcm b a) :=
associated_of_dvd_dvd
(lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _))
(lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _))
theorem lcm_assoc [normalized_gcd_monoid α] (m n k : α) : lcm (lcm m n) k = lcm m (lcm n k) :=
dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _)
(lcm_dvd
(lcm_dvd (dvd_lcm_left _ _) ((dvd_lcm_left _ _).trans (dvd_lcm_right _ _)))
((dvd_lcm_right _ _).trans (dvd_lcm_right _ _)))
(lcm_dvd
((dvd_lcm_left _ _).trans (dvd_lcm_left _ _))
(lcm_dvd ((dvd_lcm_right _ _).trans (dvd_lcm_left _ _)) (dvd_lcm_right _ _)))
theorem lcm_assoc' [gcd_monoid α] (m n k : α) : associated (lcm (lcm m n) k) (lcm m (lcm n k)) :=
associated_of_dvd_dvd
(lcm_dvd
(lcm_dvd (dvd_lcm_left _ _) ((dvd_lcm_left _ _).trans (dvd_lcm_right _ _)))
((dvd_lcm_right _ _).trans (dvd_lcm_right _ _)))
(lcm_dvd
((dvd_lcm_left _ _).trans (dvd_lcm_left _ _))
(lcm_dvd ((dvd_lcm_right _ _).trans (dvd_lcm_left _ _)) (dvd_lcm_right _ _)))
instance [normalized_gcd_monoid α] : is_commutative α lcm := ⟨lcm_comm⟩
instance [normalized_gcd_monoid α] : is_associative α lcm := ⟨lcm_assoc⟩
lemma lcm_eq_normalize [normalized_gcd_monoid α] {a b c : α}
(habc : lcm a b ∣ c) (hcab : c ∣ lcm a b) :
lcm a b = normalize c :=
normalize_lcm a b ▸ normalize_eq_normalize habc hcab
theorem lcm_dvd_lcm [gcd_monoid α] {a b c d : α} (hab : a ∣ b) (hcd : c ∣ d) :
lcm a c ∣ lcm b d :=
lcm_dvd (hab.trans (dvd_lcm_left _ _)) (hcd.trans (dvd_lcm_right _ _))
@[simp] theorem lcm_units_coe_left [normalized_gcd_monoid α] (u : αˣ) (a : α) :
lcm ↑u a = normalize a :=
lcm_eq_normalize (lcm_dvd units.coe_dvd dvd_rfl) (dvd_lcm_right _ _)
@[simp] theorem lcm_units_coe_right [normalized_gcd_monoid α] (a : α) (u : αˣ) :
lcm a ↑u = normalize a :=
(lcm_comm a u).trans $ lcm_units_coe_left _ _
@[simp] theorem lcm_one_left [normalized_gcd_monoid α] (a : α) : lcm 1 a = normalize a :=
lcm_units_coe_left 1 a
@[simp] theorem lcm_one_right [normalized_gcd_monoid α] (a : α) : lcm a 1 = normalize a :=
lcm_units_coe_right a 1
@[simp] theorem lcm_same [normalized_gcd_monoid α] (a : α) : lcm a a = normalize a :=
lcm_eq_normalize (lcm_dvd dvd_rfl dvd_rfl) (dvd_lcm_left _ _)
@[simp] theorem lcm_eq_one_iff [normalized_gcd_monoid α] (a b : α) : lcm a b = 1 ↔ a ∣ 1 ∧ b ∣ 1 :=
iff.intro
(assume eq, eq ▸ ⟨dvd_lcm_left _ _, dvd_lcm_right _ _⟩)
(assume ⟨⟨c, hc⟩, ⟨d, hd⟩⟩,
show lcm (units.mk_of_mul_eq_one a c hc.symm : α) (units.mk_of_mul_eq_one b d hd.symm) = 1,
by rw [lcm_units_coe_left, normalize_coe_units])
@[simp] theorem lcm_mul_left [normalized_gcd_monoid α] (a b c : α) :
lcm (a * b) (a * c) = normalize a * lcm b c :=
classical.by_cases (by rintro rfl; simp only [zero_mul, lcm_zero_left, normalize_zero]) $
assume ha : a ≠ 0,
suffices lcm (a * b) (a * c) = normalize (a * lcm b c),
by simpa only [normalize.map_mul, normalize_lcm],
have a ∣ lcm (a * b) (a * c), from (dvd_mul_right _ _).trans (dvd_lcm_left _ _),
let ⟨d, eq⟩ := this in
lcm_eq_normalize
(lcm_dvd (mul_dvd_mul_left a (dvd_lcm_left _ _)) (mul_dvd_mul_left a (dvd_lcm_right _ _)))
(eq.symm ▸ (mul_dvd_mul_left a $ lcm_dvd
((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_left _ _)
((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_right _ _)))
@[simp] theorem lcm_mul_right [normalized_gcd_monoid α] (a b c : α) :
lcm (b * a) (c * a) = lcm b c * normalize a :=
by simp only [mul_comm, lcm_mul_left]
theorem lcm_eq_left_iff [normalized_gcd_monoid α] (a b : α) (h : normalize a = a) :
lcm a b = a ↔ b ∣ a :=
iff.intro (assume eq, eq ▸ dvd_lcm_right _ _) $
assume hab, dvd_antisymm_of_normalize_eq (normalize_lcm _ _) h (lcm_dvd (dvd_refl a) hab)
(dvd_lcm_left _ _)
theorem lcm_eq_right_iff [normalized_gcd_monoid α] (a b : α) (h : normalize b = b) :
lcm a b = b ↔ a ∣ b :=
by simpa only [lcm_comm b a] using lcm_eq_left_iff b a h
theorem lcm_dvd_lcm_mul_left [gcd_monoid α] (m n k : α) : lcm m n ∣ lcm (k * m) n :=
lcm_dvd_lcm (dvd_mul_left _ _) dvd_rfl
theorem lcm_dvd_lcm_mul_right [gcd_monoid α] (m n k : α) : lcm m n ∣ lcm (m * k) n :=
lcm_dvd_lcm (dvd_mul_right _ _) dvd_rfl
theorem lcm_dvd_lcm_mul_left_right [gcd_monoid α] (m n k : α) : lcm m n ∣ lcm m (k * n) :=
lcm_dvd_lcm dvd_rfl (dvd_mul_left _ _)
theorem lcm_dvd_lcm_mul_right_right [gcd_monoid α] (m n k : α) : lcm m n ∣ lcm m (n * k) :=
lcm_dvd_lcm dvd_rfl (dvd_mul_right _ _)
theorem lcm_eq_of_associated_left [normalized_gcd_monoid α] {m n : α}
(h : associated m n) (k : α) : lcm m k = lcm n k :=
dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _)
(lcm_dvd_lcm h.dvd dvd_rfl)
(lcm_dvd_lcm h.symm.dvd dvd_rfl)
theorem lcm_eq_of_associated_right [normalized_gcd_monoid α] {m n : α}
(h : associated m n) (k : α) : lcm k m = lcm k n :=
dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _)
(lcm_dvd_lcm dvd_rfl h.dvd)
(lcm_dvd_lcm dvd_rfl h.symm.dvd)
end lcm
namespace gcd_monoid
theorem prime_of_irreducible [gcd_monoid α] {x : α} (hi: irreducible x) : prime x :=
⟨hi.ne_zero, ⟨hi.1, λ a b h,
begin
cases gcd_dvd_left x a with y hy,
cases hi.is_unit_or_is_unit hy with hu hu,
{ right, transitivity (gcd (x * b) (a * b)), apply dvd_gcd (dvd_mul_right x b) h,
rw (gcd_mul_right' b x a).dvd_iff_dvd_left,
exact (associated_unit_mul_left _ _ hu).dvd },
{ left,
rw hy,
exact dvd_trans (associated_mul_unit_left _ _ hu).dvd (gcd_dvd_right x a) }
end ⟩⟩
theorem irreducible_iff_prime [gcd_monoid α] {p : α} : irreducible p ↔ prime p :=
⟨prime_of_irreducible, prime.irreducible⟩
end gcd_monoid
end gcd_monoid
section unique_unit
variables [cancel_comm_monoid_with_zero α] [unique αˣ]
@[priority 100] -- see Note [lower instance priority]
instance normalization_monoid_of_unique_units : normalization_monoid α :=
{ norm_unit := λ x, 1,
norm_unit_zero := rfl,
norm_unit_mul := λ x y hx hy, (mul_one 1).symm,
norm_unit_coe_units := λ u, subsingleton.elim _ _ }
@[simp] lemma norm_unit_eq_one (x : α) : norm_unit x = 1 := rfl
@[simp] lemma normalize_eq (x : α) : normalize x = x := mul_one x
/-- If a monoid's only unit is `1`, then it is isomorphic to its associates. -/
@[simps]
def associates_equiv_of_unique_units : associates α ≃* α :=
{ to_fun := associates.out,
inv_fun := associates.mk,
left_inv := associates.mk_out,
right_inv := λ t, (associates.out_mk _).trans $ normalize_eq _,
map_mul' := associates.out_mul }
end unique_unit
section is_domain
variables [comm_ring α] [is_domain α] [normalized_gcd_monoid α]
lemma gcd_eq_of_dvd_sub_right {a b c : α} (h : a ∣ b - c) : gcd a b = gcd a c :=
begin
apply dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _);
rw dvd_gcd_iff; refine ⟨gcd_dvd_left _ _, _⟩,
{ rcases h with ⟨d, hd⟩,
rcases gcd_dvd_right a b with ⟨e, he⟩,
rcases gcd_dvd_left a b with ⟨f, hf⟩,
use e - f * d,
rw [mul_sub, ← he, ← mul_assoc, ← hf, ← hd, sub_sub_cancel] },
{ rcases h with ⟨d, hd⟩,
rcases gcd_dvd_right a c with ⟨e, he⟩,
rcases gcd_dvd_left a c with ⟨f, hf⟩,
use e + f * d,
rw [mul_add, ← he, ← mul_assoc, ← hf, ← hd, ← add_sub_assoc, add_comm c b, add_sub_cancel] }
end
lemma gcd_eq_of_dvd_sub_left {a b c : α} (h : a ∣ b - c) : gcd b a = gcd c a :=
by rw [gcd_comm _ a, gcd_comm _ a, gcd_eq_of_dvd_sub_right h]
end is_domain
section constructors
noncomputable theory
open associates
variables [cancel_comm_monoid_with_zero α]
private lemma map_mk_unit_aux [decidable_eq α] {f : associates α →* α}
(hinv : function.right_inverse f associates.mk) (a : α) :
a * ↑(classical.some (associated_map_mk hinv a)) = f (associates.mk a) :=
classical.some_spec (associated_map_mk hinv a)
/-- Define `normalization_monoid` on a structure from a `monoid_hom` inverse to `associates.mk`. -/
def normalization_monoid_of_monoid_hom_right_inverse [decidable_eq α] (f : associates α →* α)
(hinv : function.right_inverse f associates.mk) :
normalization_monoid α :=
{ norm_unit := λ a, if a = 0 then 1 else
classical.some (associates.mk_eq_mk_iff_associated.1 (hinv (associates.mk a)).symm),
norm_unit_zero := if_pos rfl,
norm_unit_mul := λ a b ha hb, by
{ rw [if_neg (mul_ne_zero ha hb), if_neg ha, if_neg hb, units.ext_iff, units.coe_mul],
suffices : (a * b) * ↑(classical.some (associated_map_mk hinv (a * b))) =
(a * ↑(classical.some (associated_map_mk hinv a))) *
(b * ↑(classical.some (associated_map_mk hinv b))),
{ apply mul_left_cancel₀ (mul_ne_zero ha hb) _,
simpa only [mul_assoc, mul_comm, mul_left_comm] using this },
rw [map_mk_unit_aux hinv a, map_mk_unit_aux hinv (a * b), map_mk_unit_aux hinv b,
← monoid_hom.map_mul, associates.mk_mul_mk] },
norm_unit_coe_units := λ u, by
{ nontriviality α,
rw [if_neg (units.ne_zero u), units.ext_iff],
apply mul_left_cancel₀ (units.ne_zero u),
rw [units.mul_inv, map_mk_unit_aux hinv u,
associates.mk_eq_mk_iff_associated.2 (associated_one_iff_is_unit.2 ⟨u, rfl⟩),
associates.mk_one, monoid_hom.map_one] } }
/-- Define `gcd_monoid` on a structure just from the `gcd` and its properties. -/
noncomputable def gcd_monoid_of_gcd [decidable_eq α] (gcd : α → α → α)
(gcd_dvd_left : ∀a b, gcd a b ∣ a)
(gcd_dvd_right : ∀a b, gcd a b ∣ b)
(dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b) :
gcd_monoid α :=
{ gcd := gcd,
gcd_dvd_left := gcd_dvd_left,
gcd_dvd_right := gcd_dvd_right,
dvd_gcd := λ a b c, dvd_gcd,
lcm := λ a b, if a = 0 then 0 else classical.some ((gcd_dvd_left a b).trans (dvd.intro b rfl)),
gcd_mul_lcm := λ a b, by
{ split_ifs with a0,
{ rw [mul_zero, a0, zero_mul] },
{ rw ←classical.some_spec ((gcd_dvd_left a b).trans (dvd.intro b rfl)) } },
lcm_zero_left := λ a, if_pos rfl,
lcm_zero_right := λ a, by
{ split_ifs with a0, { refl },
have h := (classical.some_spec ((gcd_dvd_left a 0).trans (dvd.intro 0 rfl))).symm,
have a0' : gcd a 0 ≠ 0,
{ contrapose! a0,
rw [←associated_zero_iff_eq_zero, ←a0],
exact associated_of_dvd_dvd (dvd_gcd (dvd_refl a) (dvd_zero a)) (gcd_dvd_left _ _) },
apply or.resolve_left (mul_eq_zero.1 _) a0',
rw [h, mul_zero] } }
/-- Define `normalized_gcd_monoid` on a structure just from the `gcd` and its properties. -/
noncomputable def normalized_gcd_monoid_of_gcd [normalization_monoid α] [decidable_eq α]
(gcd : α → α → α)
(gcd_dvd_left : ∀a b, gcd a b ∣ a)
(gcd_dvd_right : ∀a b, gcd a b ∣ b)
(dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b)
(normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b) :
normalized_gcd_monoid α :=
{ gcd := gcd,
gcd_dvd_left := gcd_dvd_left,
gcd_dvd_right := gcd_dvd_right,
dvd_gcd := λ a b c, dvd_gcd,
normalize_gcd := normalize_gcd,
lcm := λ a b, if a = 0 then 0 else classical.some (dvd_normalize_iff.2
((gcd_dvd_left a b).trans (dvd.intro b rfl))),
normalize_lcm := λ a b, by
{ dsimp [normalize],
split_ifs with a0,
{ exact @normalize_zero α _ _ },
{ have := (classical.some_spec (dvd_normalize_iff.2
((gcd_dvd_left a b).trans (dvd.intro b rfl)))).symm,
set l := classical.some (dvd_normalize_iff.2
((gcd_dvd_left a b).trans (dvd.intro b rfl))),
obtain rfl|hb := eq_or_ne b 0,
{ simp only [normalize_zero, mul_zero, mul_eq_zero] at this,
obtain ha|hl := this,
{ apply (a0 _).elim,
rw [←zero_dvd_iff, ←ha],
exact gcd_dvd_left _ _ },
{ convert @normalize_zero α _ _ } },
have h1 : gcd a b ≠ 0,
{ have hab : a * b ≠ 0 := mul_ne_zero a0 hb,
contrapose! hab,
rw [←normalize_eq_zero, ←this, hab, zero_mul] },
have h2 : normalize (gcd a b * l) = gcd a b * l,
{ rw [this, normalize_idem] },
rw ←normalize_gcd at this,
rwa [normalize.map_mul, normalize_gcd, mul_right_inj' h1] at h2 } },
gcd_mul_lcm := λ a b, by
{ split_ifs with a0,
{ rw [mul_zero, a0, zero_mul] },
{ rw ←classical.some_spec (dvd_normalize_iff.2 ((gcd_dvd_left a b).trans (dvd.intro b rfl))),
exact normalize_associated (a * b) } },
lcm_zero_left := λ a, if_pos rfl,
lcm_zero_right := λ a, by
{ split_ifs with a0, { refl },
rw ← normalize_eq_zero at a0,
have h := (classical.some_spec (dvd_normalize_iff.2
((gcd_dvd_left a 0).trans (dvd.intro 0 rfl)))).symm,
have gcd0 : gcd a 0 = normalize a,
{ rw ← normalize_gcd,
exact normalize_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_zero a)) },
rw ← gcd0 at a0,
apply or.resolve_left (mul_eq_zero.1 _) a0,
rw [h, mul_zero, normalize_zero] },
.. (infer_instance : normalization_monoid α) }
/-- Define `gcd_monoid` on a structure just from the `lcm` and its properties. -/
noncomputable def gcd_monoid_of_lcm [decidable_eq α] (lcm : α → α → α)
(dvd_lcm_left : ∀a b, a ∣ lcm a b)
(dvd_lcm_right : ∀a b, b ∣ lcm a b)
(lcm_dvd : ∀{a b c}, c ∣ a → b ∣ a → lcm c b ∣ a):
gcd_monoid α :=
let exists_gcd := λ a b, lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl) in
{ lcm := lcm,
gcd := λ a b, if a = 0 then b else (if b = 0 then a else
classical.some (exists_gcd a b)),
gcd_mul_lcm := λ a b, by
{ split_ifs,
{ rw [h, eq_zero_of_zero_dvd (dvd_lcm_left _ _), mul_zero, zero_mul] },
{ rw [h_1, eq_zero_of_zero_dvd (dvd_lcm_right _ _), mul_zero] },
rw [mul_comm, ←classical.some_spec (exists_gcd a b)] },
lcm_zero_left := λ a, eq_zero_of_zero_dvd (dvd_lcm_left _ _),
lcm_zero_right := λ a, eq_zero_of_zero_dvd (dvd_lcm_right _ _),
gcd_dvd_left := λ a b, by
{ split_ifs with h h_1,
{ rw h, apply dvd_zero },
{ exact dvd_rfl },
have h0 : lcm a b ≠ 0,
{ intro con,
have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl),
rw [con, zero_dvd_iff, mul_eq_zero] at h,
cases h; tauto },
rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b),
mul_comm, mul_dvd_mul_iff_right h],
apply dvd_lcm_right },
gcd_dvd_right := λ a b, by
{ split_ifs with h h_1,
{ exact dvd_rfl },
{ rw h_1, apply dvd_zero },
have h0 : lcm a b ≠ 0,
{ intro con,
have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl),
rw [con, zero_dvd_iff, mul_eq_zero] at h,
cases h; tauto },
rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b),
mul_dvd_mul_iff_right h_1],
apply dvd_lcm_left },
dvd_gcd := λ a b c ac ab, by
{ split_ifs,
{ exact ab },
{ exact ac },
have h0 : lcm c b ≠ 0,
{ intro con,
have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left c rfl),
rw [con, zero_dvd_iff, mul_eq_zero] at h,
cases h; tauto },
rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd c b)],
rcases ab with ⟨d, rfl⟩,
rw mul_eq_zero at h_1,
push_neg at h_1,
rw [mul_comm a, ← mul_assoc, mul_dvd_mul_iff_right h_1.1],
apply lcm_dvd (dvd.intro d rfl),
rw [mul_comm, mul_dvd_mul_iff_right h_1.2],
apply ac } }
/-- Define `normalized_gcd_monoid` on a structure just from the `lcm` and its properties. -/
noncomputable def normalized_gcd_monoid_of_lcm [normalization_monoid α] [decidable_eq α]
(lcm : α → α → α)
(dvd_lcm_left : ∀a b, a ∣ lcm a b)
(dvd_lcm_right : ∀a b, b ∣ lcm a b)
(lcm_dvd : ∀{a b c}, c ∣ a → b ∣ a → lcm c b ∣ a)
(normalize_lcm : ∀a b, normalize (lcm a b) = lcm a b) :
normalized_gcd_monoid α :=
let exists_gcd := λ a b, dvd_normalize_iff.2 (lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl)) in
{ lcm := lcm,
gcd := λ a b, if a = 0 then normalize b else (if b = 0 then normalize a else
classical.some (exists_gcd a b)),
gcd_mul_lcm := λ a b, by
{ split_ifs with h h_1,
{ rw [h, eq_zero_of_zero_dvd (dvd_lcm_left _ _), mul_zero, zero_mul] },
{ rw [h_1, eq_zero_of_zero_dvd (dvd_lcm_right _ _), mul_zero, mul_zero] },
rw [mul_comm, ←classical.some_spec (exists_gcd a b)],
exact normalize_associated (a * b) },
normalize_lcm := normalize_lcm,
normalize_gcd := λ a b, by
{ dsimp [normalize],
split_ifs with h h_1,
{ apply normalize_idem },
{ apply normalize_idem },
have h0 : lcm a b ≠ 0,
{ intro con,
have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl),
rw [con, zero_dvd_iff, mul_eq_zero] at h,
cases h; tauto },
apply mul_left_cancel₀ h0,
refine trans _ (classical.some_spec (exists_gcd a b)),
conv_lhs { congr, rw [← normalize_lcm a b] },
erw [← normalize.map_mul, ← classical.some_spec (exists_gcd a b), normalize_idem] },
lcm_zero_left := λ a, eq_zero_of_zero_dvd (dvd_lcm_left _ _),
lcm_zero_right := λ a, eq_zero_of_zero_dvd (dvd_lcm_right _ _),
gcd_dvd_left := λ a b, by
{ split_ifs,
{ rw h, apply dvd_zero },
{ exact (normalize_associated _).dvd },
have h0 : lcm a b ≠ 0,
{ intro con,
have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl),
rw [con, zero_dvd_iff, mul_eq_zero] at h,
cases h; tauto },
rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b),
normalize_dvd_iff, mul_comm, mul_dvd_mul_iff_right h],
apply dvd_lcm_right },
gcd_dvd_right := λ a b, by
{ split_ifs,
{ exact (normalize_associated _).dvd },
{ rw h_1, apply dvd_zero },
have h0 : lcm a b ≠ 0,
{ intro con,
have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl),
rw [con, zero_dvd_iff, mul_eq_zero] at h,
cases h; tauto },
rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b),
normalize_dvd_iff, mul_dvd_mul_iff_right h_1],
apply dvd_lcm_left },
dvd_gcd := λ a b c ac ab, by
{ split_ifs,
{ apply dvd_normalize_iff.2 ab },
{ apply dvd_normalize_iff.2 ac },
have h0 : lcm c b ≠ 0,
{ intro con,
have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left c rfl),
rw [con, zero_dvd_iff, mul_eq_zero] at h,
cases h; tauto },
rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (dvd_normalize_iff.2
(lcm_dvd (dvd.intro b rfl) (dvd.intro_left c rfl))), dvd_normalize_iff],
rcases ab with ⟨d, rfl⟩,
rw mul_eq_zero at h_1,
push_neg at h_1,
rw [mul_comm a, ← mul_assoc, mul_dvd_mul_iff_right h_1.1],
apply lcm_dvd (dvd.intro d rfl),
rw [mul_comm, mul_dvd_mul_iff_right h_1.2],
apply ac },
.. (infer_instance : normalization_monoid α) }
/-- Define a `gcd_monoid` structure on a monoid just from the existence of a `gcd`. -/
noncomputable def gcd_monoid_of_exists_gcd [decidable_eq α]
(h : ∀ a b : α, ∃ c : α, ∀ d : α, d ∣ a ∧ d ∣ b ↔ d ∣ c) :
gcd_monoid α :=
gcd_monoid_of_gcd
(λ a b, (classical.some (h a b)))
(λ a b,
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).1)
(λ a b,
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).2)
(λ a b c ac ab, ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩))
/-- Define a `normalized_gcd_monoid` structure on a monoid just from the existence of a `gcd`. -/
noncomputable def normalized_gcd_monoid_of_exists_gcd [normalization_monoid α] [decidable_eq α]
(h : ∀ a b : α, ∃ c : α, ∀ d : α, d ∣ a ∧ d ∣ b ↔ d ∣ c) :
normalized_gcd_monoid α :=
normalized_gcd_monoid_of_gcd
(λ a b, normalize (classical.some (h a b)))
(λ a b, normalize_dvd_iff.2
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).1)
(λ a b, normalize_dvd_iff.2
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).2)
(λ a b c ac ab, dvd_normalize_iff.2 ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩))
(λ a b, normalize_idem _)
/-- Define a `gcd_monoid` structure on a monoid just from the existence of an `lcm`. -/
noncomputable def gcd_monoid_of_exists_lcm [decidable_eq α]
(h : ∀ a b : α, ∃ c : α, ∀ d : α, a ∣ d ∧ b ∣ d ↔ c ∣ d) :
gcd_monoid α :=
gcd_monoid_of_lcm
(λ a b, (classical.some (h a b)))
(λ a b,
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).1)
(λ a b,
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).2)
(λ a b c ac ab, ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩))
/-- Define a `normalized_gcd_monoid` structure on a monoid just from the existence of an `lcm`. -/
noncomputable def normalized_gcd_monoid_of_exists_lcm [normalization_monoid α] [decidable_eq α]
(h : ∀ a b : α, ∃ c : α, ∀ d : α, a ∣ d ∧ b ∣ d ↔ c ∣ d) :
normalized_gcd_monoid α :=
normalized_gcd_monoid_of_lcm
(λ a b, normalize (classical.some (h a b)))
(λ a b, dvd_normalize_iff.2
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).1)
(λ a b, dvd_normalize_iff.2
(((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).2)
(λ a b c ac ab, normalize_dvd_iff.2 ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩))
(λ a b, normalize_idem _)
end constructors
namespace comm_group_with_zero
variables (G₀ : Type*) [comm_group_with_zero G₀] [decidable_eq G₀]
@[priority 100] -- see Note [lower instance priority]
instance : normalized_gcd_monoid G₀ :=
{ norm_unit := λ x, if h : x = 0 then 1 else (units.mk0 x h)⁻¹,
norm_unit_zero := dif_pos rfl,
norm_unit_mul := λ x y x0 y0, units.eq_iff.1 (by simp [x0, y0, mul_comm]),
norm_unit_coe_units := λ u, by { rw [dif_neg (units.ne_zero _), units.mk0_coe], apply_instance },
gcd := λ a b, if a = 0 ∧ b = 0 then 0 else 1,
lcm := λ a b, if a = 0 ∨ b = 0 then 0 else 1,
gcd_dvd_left := λ a b, by { split_ifs with h, { rw h.1 }, { exact one_dvd _ } },
gcd_dvd_right := λ a b, by { split_ifs with h, { rw h.2 }, { exact one_dvd _ } },
dvd_gcd := λ a b c hac hab, begin
split_ifs with h, { apply dvd_zero },
cases not_and_distrib.mp h with h h;
refine is_unit_iff_dvd_one.mp (is_unit_of_dvd_unit _ (is_unit.mk0 _ h));
assumption
end,
gcd_mul_lcm := λ a b, begin
by_cases ha : a = 0, { simp [ha] },
by_cases hb : b = 0, { simp [hb] },
rw [if_neg (not_and_of_not_left _ ha), one_mul, if_neg (not_or ha hb)],
exact (associated_one_iff_is_unit.mpr ((is_unit.mk0 _ ha).mul (is_unit.mk0 _ hb))).symm
end,
lcm_zero_left := λ b, if_pos (or.inl rfl),
lcm_zero_right := λ a, if_pos (or.inr rfl),
-- `split_ifs` wants to split `normalize`, so handle the cases manually
normalize_gcd := λ a b, if h : a = 0 ∧ b = 0 then by simp [if_pos h] else by simp [if_neg h],
normalize_lcm := λ a b, if h : a = 0 ∨ b = 0 then by simp [if_pos h] else by simp [if_neg h] }
@[simp]
lemma coe_norm_unit {a : G₀} (h0 : a ≠ 0) : (↑(norm_unit a) : G₀) = a⁻¹ :=
by simp [norm_unit, h0]
lemma normalize_eq_one {a : G₀} (h0 : a ≠ 0) : normalize a = 1 :=
by simp [normalize_apply, h0]
end comm_group_with_zero
|
3865a4c416d28c85615377a24bba5b81c21c08c9 | 5c7fe6c4a9d4079b5457ffa5f061797d42a1cd65 | /src/exercises/src_40_sequences.lean | 6ae35d47ddbae3eee7898872b07bc997a54eef85 | [] | no_license | gihanmarasingha/mth1001_tutorial | 8e0817feeb96e7c1bb3bac49b63e3c9a3a329061 | bb277eebd5013766e1418365b91416b406275130 | refs/heads/master | 1,675,008,746,310 | 1,607,993,443,000 | 1,607,993,443,000 | 321,511,270 | 3 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,140 | lean | import data.real.basic
import data.set.basic
import tactic
namespace mth1001
/-
We'll only deal with real-valued sequences. Such a sequence is merely a function from `ℕ` to `ℝ`
We'll use the Lean built-in real number type rather than the type we've constructed.
-/
section convergence
-- `convergesto f a` means
def convergesto (f : ℕ → ℝ) (a : ℝ) := ∀ ε > 0, ∃ N, ∀ n ≥ N, abs (f n - a) < ε
/-
We'll prove that the sequence `f₁ : ℕ → R` given by `f₁(n) = 5` converges to `5`.
-/
def f₁ : ℕ → ℝ := λ n, (5 : ℝ)
example : convergesto f₁ 5 :=
begin
assume ε : ℝ,
assume εpos : ε > 0, -- It suffices to prove `∃ N, ∀ n ≥ N, abs (f₁ n - 5) < ε`.
use 1, -- Take `N := 1`.
assume n : ℕ,
assume hn : n ≥ 1,
unfold f₁, -- By unfolding, it suffices to show `abs (5 - 5) < ε`.
rw sub_self, -- That is, to prove `abs 0 < ε`.
rw abs_zero, -- But `abs 0 = 0`, so it suffices to prove `0 < ε`.
exact εpos, -- This holds by `εpos`.
end
/-
More generally, we'll show a constant sequence converges.
-/
-- Exercise 219:
lemma convergesto_const (c : ℝ) : convergesto (λ n, c) c :=
begin
assume ε : ℝ,
assume εpos : ε > 0,
sorry
end
end convergence
section uniqueness_of_limits
variables {f : ℕ → ℝ} {a b : ℝ}
-- We proved the following result earlier for our own real number type.
lemma zero_of_non_neg_of_lt_pos' {a : ℝ} (h : 0 ≤ a) (h₂ : ∀ ε > 0, a < ε) : a = 0 :=
begin
apply eq_of_le_of_forall_le_of_dense h,
intros ε εpos,
specialize h₂ ε εpos,
exact le_of_lt h₂,
end
-- We'll need the following results for the proof of the next lemma.
example (x y : ℝ) : abs (x + y) ≤ abs x + abs y := abs_add x y
example (x : ℝ) : abs (-x) = abs x := abs_neg x
example (a b c : ℝ) (h : a < b) : a + c < b + c := add_lt_add_right h c
example (a b c : ℝ) (h : a < b) : c + a < c + b := add_lt_add_left h c
-- Exercise 220:
lemma convergesto_unique (h₁ : convergesto f a) (h₂ : convergesto f b) : a = b :=
begin
suffices h : abs (a - b) = 0,
{ rwa [←sub_eq_zero, ←abs_eq_zero] },
have k₁ : abs (a - b) ≥ 0, from abs_nonneg (a - b),
suffices h : ∀ ε > 0, abs (a - b) < ε, from zero_of_non_neg_of_lt_pos' k₁ h,
sorry
end
end uniqueness_of_limits
section algebra_of_limits
variables (f g : ℕ → ℝ) -- `f` and `g` are sequences
variables (a b c : ℝ)
-- The following result will often come in handy!
lemma div_abs_pos_of_pos_of_non_zero {ε c : ℝ} (εpos : ε > 0) (h : c ≠ 0) : ε / abs c > 0 :=
begin
have h₂ : 0 < abs c, from abs_pos_iff.mpr h,
have h₃ : 0 < (abs c)⁻¹, from inv_pos.mpr h₂,
exact mul_pos εpos h₃,
end
example (a b c : ℝ) (h₁ : a < b / c) (h₂ : 0 < c): a * c < b := (lt_div_iff h₂).mp h₁
example (a b : ℝ) : abs (a*b) = abs a * abs b := abs_mul a b
example (x y : ℝ) : x ≤ max x y := le_max_left x y
example (x y : ℝ) : y ≤ max x y := le_max_right x y
theorem convergesto_scalar_mul (h : convergesto f a) : convergesto (λ n, c * (f n)) (c * a) :=
begin
by_cases h₂ : c = 0,
{ simp only [h₂, zero_mul], -- `simp` is a simiplying tactic.
exact convergesto_const 0, },
{ assume ε : ℝ,
assume εpos : ε > 0,
have h₃ : ε / abs c > 0, from div_abs_pos_of_pos_of_non_zero εpos h₂,
cases h (ε/ abs c) h₃ with N hN,
use N,
intros n hn,
specialize hN n hn,
have h₄ : abs c > 0, from abs_pos_iff.mpr h₂,
have h₅ : abs (f n -a) * abs c < ε, from (lt_div_iff h₄).mp hN,
have h₆ : abs ((f n - a)* c) < ε, { rwa abs_mul, },
rwa [←mul_sub, mul_comm], },
end
theorem convergesto_add (h₁ : convergesto f a) (h₂ : convergesto g b )
: convergesto (λ n, f n + g n) (a + b) :=
begin
assume ε : ℝ,
assume εpos : ε > 0,
cases h₁ (ε/2) (by linarith) with N₁ hN₁,
cases h₂ (ε/2) (by linarith) with N₂ hN₂,
use (max N₁ N₂),
intros n hn,
have k₁ : n ≥ N₁, from le_trans (le_max_left N₁ N₂) hn,
have k₂ : n ≥ N₂, from le_trans (le_max_right N₁ N₂) hn,
have m₁ : abs (f n - a) < ε/2, from hN₁ n k₁,
have m₂ : abs (g n - b) < ε/2, from hN₂ n k₂,
have h₃ : (f n + g n) - (a + b) = (f n - a) + (g n - b), ring,
rw h₃,
calc abs (f n - a + (g n - b))
≤ abs (f n - a) + abs (g n - b) : abs_add _ _
... < ε/2 + ε/2 : by linarith
... = ε : by linarith,
end
-- The same proof can be written more briefly using `congr'` and by giving arguments to `linarith`.
example (h₁ : convergesto f a) (h₂ : convergesto g b ) : convergesto (λ n, f n + g n) (a + b) :=
begin
intros ε εpos,
cases h₁ (ε/2) (by linarith) with N₁ hN₁,
cases h₂ (ε/2) (by linarith) with N₂ hN₂,
use (max N₁ N₂),
intros n hn,
have k₁ : n ≥ N₁, from le_trans (le_max_left N₁ N₂) hn,
have k₂ : n ≥ N₂, from le_trans (le_max_right N₁ N₂) hn,
calc abs ((f n + g n) - (a + b))
= abs (f n - a + (g n - b)) : by {congr', ring}
... ≤ abs (f n - a) + abs (g n - b) : abs_add _ _
... < ε/2 + ε/2 : by linarith [hN₁ n k₁, hN₂ n k₂]
... = ε : by linarith,
end
end algebra_of_limits
section specific_example
/-
In Lean, it's often harder to work with particular examples than with general theorems.
Here, we show convergence of a particular sequence.
We'll need the corollorary to the Archimedean property. In Lean,this is `exists_nat_one_div_lt`.
Note the use of `↑n` to indicate the embedding (or coercion) of the natural number `n`
as a real number.
-/
example (ε : ℝ) (h : 0 < ε) : ∃ n : ℕ, 1/(↑n + 1) < ε := exists_nat_one_div_lt h
example (x : ℝ) (h : x > 0) : abs x = x := abs_of_pos h
example (x : ℝ) (h : 0 < x) : 0 < x⁻¹ := by {rwa inv_pos}
example (x : ℝ) (h : 0 < x) : x⁻¹ = (1 : ℝ) / x := inv_eq_one_div x
-- Now we'll show the sequence given by `λ n, 3 + 1/n` converges to `3`.
example : convergesto (λ n, 3 + 1/n) 3 :=
begin
unfold convergesto,
assume ε εpos,
have h : ∃ N : ℕ, 1/(↑N + 1) < ε, from exists_nat_one_div_lt εpos,
cases h with N hN, -- By `∃` elim. on `h`, STP the goal assuming `N : ℕ` and `hN : 1/(↑N+1) < ε`.
use N + 1, -- By `∃` intro on `N + 1`, it suffices to prove
-- `∀ n ≥ N + 1, n ≥ N + 1 → abs (3 + 1/↑n - 3) < ε`.
assume n hn, -- assume `n : ℕ` and `hn : n ≥ N`.
have h₂ : abs ((3 : ℝ) + 1 / ↑n - 3) = abs (↑n)⁻¹, ring,
rw h₂,
have : N + 1 > 0, linarith,
have : n > 0, linarith,
have : (0 : ℝ) < ↑n, { rwa nat.cast_pos },
have : (0 : ℝ) < N + 1, {change (0 : ℝ) < ↑(N + 1), rw nat.cast_pos, linarith, },
have : (0 : ℝ) < (↑n)⁻¹, { rwa inv_pos },
rw abs_of_pos this,
have : (↑n)⁻¹ ≤ (↑N + (1 : ℝ))⁻¹,
{ rw inv_le_inv,
change ↑(N + 1) ≤ ↑n,
rwa nat.cast_le,
repeat { assumption }, },
apply lt_of_le_of_lt,
{ assumption, },
{ rwa inv_eq_one_div, },
end
end specific_example
end mth1001
|
cf445dbeb86517516af47d2c0dc4019bd29ab75a | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/char_p/mixed_char_zero.lean | 0c17a7d83dc45c7f83bd877cefd5449b1da02c06 | [
"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 | 14,952 | lean | /-
Copyright (c) 2022 Jon Eugster. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jon Eugster
-/
import algebra.char_p.algebra
import algebra.char_p.local_ring
import ring_theory.ideal.quotient
import tactic.field_simp
/-!
# Equal and mixed characteristic
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In commutative algebra, some statments are simpler when working over a `ℚ`-algebra `R`, in which
case one also says that the ring has "equal characteristic zero". A ring that is not a
`ℚ`-algebra has either positive characteristic or there exists a prime ideal `I ⊂ R` such that
the quotient `R ⧸ I` has positive characteristic `p > 0`. In this case one speaks of
"mixed characteristic `(0, p)`", where `p` is only unique if `R` is local.
Examples of mixed characteristic rings are `ℤ` or the `p`-adic integers/numbers.
This file provides the main theorem `split_by_characteristic` that splits any proposition `P` into
the following three cases:
1) Positive characteristic: `char_p R p` (where `p ≠ 0`)
2) Equal characteristic zero: `algebra ℚ R`
3) Mixed characteristic: `mixed_char_zero R p` (where `p` is prime)
## Main definitions
- `mixed_char_zero` : A ring has mixed characteristic `(0, p)` if it has characteristic zero
and there exists an ideal such that the quotient `R ⧸ I` has characteristic `p`.
## Main results
- `split_equal_mixed_char` : Split a statement into equal/mixed characteristic zero.
This main theorem has the following three corollaries which include the positive
characteristic case for convenience:
- `split_by_characteristic` : Generally consider positive char `p ≠ 0`.
- `split_by_characteristic_domain` : In a domain we can assume that `p` is prime.
- `split_by_characteristic_local_ring` : In a local ring we can assume that `p` is a prime power.
## TODO
- Relate mixed characteristic in a local ring to p-adic numbers [number_theory.padics].
-/
variables (R : Type*) [comm_ring R]
/-!
### Mixed characteristic
-/
/--
A ring of characteristic zero is of "mixed characteristic `(0, p)`" if there exists an ideal
such that the quotient `R ⧸ I` has caracteristic `p`.
**Remark:** For `p = 0`, `mixed_char R 0` is a meaningless definition as `R ⧸ ⊥ ≅ R` has by
definition always characteristic zero.
One could require `(I ≠ ⊥)` in the definition, but then `mixed_char R 0` would mean something
like `ℤ`-algebra of extension degree `≥ 1` and would be completely independent from
whether something is a `ℚ`-algebra or not (e.g. `ℚ[X]` would satisfy it but `ℚ` wouldn't).
-/
class mixed_char_zero (p : ℕ) : Prop :=
[to_char_zero : char_zero R]
(char_p_quotient : ∃ (I : ideal R), (I ≠ ⊤) ∧ char_p (R ⧸ I) p)
namespace mixed_char_zero
/--
Reduction to `p` prime: When proving any statement `P` about mixed characteristic rings we
can always assume that `p` is prime.
-/
lemma reduce_to_p_prime {P : Prop} :
(∀ p > 0, mixed_char_zero R p → P) ↔
(∀ (p : ℕ), p.prime → mixed_char_zero R p → P) :=
begin
split,
{ intros h q q_prime q_mixed_char,
exact h q (nat.prime.pos q_prime) q_mixed_char },
{ intros h q q_pos q_mixed_char,
rcases q_mixed_char.char_p_quotient with ⟨I, hI_ne_top, hI_char⟩,
-- Krull's Thm: There exists a prime ideal `P` such that `I ≤ P`
rcases ideal.exists_le_maximal I hI_ne_top with ⟨M, hM_max, h_IM⟩,
resetI, -- make `hI_char : char_p (R ⧸ I) q` an instance.
let r := ring_char (R ⧸ M),
have r_pos : r ≠ 0,
{ have q_zero := congr_arg (ideal.quotient.factor I M h_IM) (char_p.cast_eq_zero (R ⧸ I) q),
simp only [map_nat_cast, map_zero] at q_zero,
apply ne_zero_of_dvd_ne_zero (ne_of_gt q_pos),
exact (char_p.cast_eq_zero_iff (R ⧸ M) r q).mp q_zero },
have r_prime : nat.prime r :=
or_iff_not_imp_right.1 (char_p.char_is_prime_or_zero (R ⧸ M) r) r_pos,
apply h r r_prime,
haveI : char_zero R := q_mixed_char.to_char_zero,
exact ⟨⟨M, hM_max.ne_top, ring_char.of_eq rfl⟩⟩ }
end
/--
Reduction to `I` prime ideal: When proving statements about mixed characteristic rings,
after we reduced to `p` prime, we can assume that the ideal `I` in the definition is maximal.
-/
lemma reduce_to_maximal_ideal {p : ℕ} (hp : nat.prime p) :
(∃ (I : ideal R), (I ≠ ⊤) ∧ char_p (R ⧸ I) p) ↔
(∃ (I : ideal R), (I.is_maximal) ∧ char_p (R ⧸ I) p) :=
begin
split,
{ intro g,
rcases g with ⟨I, ⟨hI_not_top, hI⟩⟩,
-- Krull's Thm: There exists a prime ideal `M` such that `I ≤ M`.
rcases ideal.exists_le_maximal I hI_not_top with ⟨M, ⟨hM_max, hM⟩⟩,
use M,
split,
exact hM_max,
{ cases char_p.exists (R ⧸ M) with r hr,
convert hr,
resetI, -- make `hr : char_p (R ⧸ M) r` an instance.
have r_dvd_p : r ∣ p,
{ rw ←char_p.cast_eq_zero_iff (R ⧸ M) r p,
convert congr_arg (ideal.quotient.factor I M hM) (char_p.cast_eq_zero (R ⧸ I) p) },
symmetry,
apply (nat.prime.eq_one_or_self_of_dvd hp r r_dvd_p).resolve_left,
exact char_p.char_ne_one (R ⧸ M) r }},
{ rintro ⟨I, hI_max, hI⟩,
use I,
exact ⟨ideal.is_maximal.ne_top hI_max, hI⟩ }
end
end mixed_char_zero
/-!
### Equal characteristic zero
A commutative ring `R` has "equal characteristic zero" if it satisfies one of the following
equivalent properties:
1) `R` is a `ℚ`-algebra.
2) The quotient `R ⧸ I` has characteristic zero for any proper ideal `I ⊂ R`.
3) `R` has characteristic zero and does not have mixed characteristic for any prime `p`.
We show `(1) ↔ (2) ↔ (3)`, and most of the following is concerned with constructing
an explicit algebra map `ℚ →+* R` (given by `x ↦ (x.num : R) /ₚ ↑x.pnat_denom`)
for the direction `(1) ← (2)`.
Note: Property `(2)` is denoted as `equal_char_zero` in the statement names below.
-/
section equal_char_zero
/--
`ℚ`-algebra implies equal characteristic.
-/
@[nolint unused_arguments] -- argument `[nontrivial R]` is used in the first line of the proof.
lemma Q_algebra_to_equal_char_zero [nontrivial R] [algebra ℚ R] :
∀ (I : ideal R), I ≠ ⊤ → char_zero (R ⧸ I) :=
begin
haveI : char_zero R := algebra_rat.char_zero R,
intros I hI,
constructor,
intros a b h_ab,
contrapose! hI,
-- `↑a - ↑b` is a unit contained in `I`, which contradicts `I ≠ ⊤`.
refine I.eq_top_of_is_unit_mem _ (is_unit.map (algebra_map ℚ R) (is_unit.mk0 (a - b : ℚ) _)),
{ simpa only [← ideal.quotient.eq_zero_iff_mem, map_sub, sub_eq_zero, map_nat_cast] },
simpa only [ne.def, sub_eq_zero] using (@nat.cast_injective ℚ _ _).ne hI
end
section construction_of_Q_algebra
/-- Internal: Not intended to be used outside this local construction. -/
lemma equal_char_zero.pnat_coe_is_unit [h : fact (∀ (I : ideal R), I ≠ ⊤ → char_zero (R ⧸ I))]
(n : ℕ+) : is_unit (n : R) :=
begin
-- `n : R` is a unit iff `(n)` is not a proper ideal in `R`.
rw ← ideal.span_singleton_eq_top,
-- So by contrapositive, we should show the quotient does not have characteristic zero.
apply not_imp_comm.mp (h.elim (ideal.span {n})),
unfreezingI { intro h_char_zero },
-- In particular, the image of `n` in the quotient should be nonzero.
apply (h_char_zero.cast_injective).ne n.ne_zero,
-- But `n` generates the ideal, so its image is clearly zero.
rw [←map_nat_cast (ideal.quotient.mk _), nat.cast_zero, ideal.quotient.eq_zero_iff_mem],
exact ideal.subset_span (set.mem_singleton _)
end
/-- Internal: Not intended to be used outside this local construction. -/
noncomputable instance equal_char_zero.pnat_has_coe_units
[fact (∀ (I : ideal R), I ≠ ⊤ → char_zero (R ⧸ I))] : has_coe_t ℕ+ Rˣ :=
⟨λn, (equal_char_zero.pnat_coe_is_unit R n).unit⟩
/-- Internal: Not intended to be used outside this local construction. -/
lemma equal_char_zero.pnat_coe_units_eq_one [fact (∀ (I : ideal R), I ≠ ⊤ → char_zero (R ⧸ I))] :
((1 : ℕ+) : Rˣ) = 1 :=
begin
apply units.ext,
rw units.coe_one,
change ((equal_char_zero.pnat_coe_is_unit R 1).unit : R) = 1,
rw is_unit.unit_spec (equal_char_zero.pnat_coe_is_unit R 1),
rw [coe_coe, pnat.one_coe, nat.cast_one],
end
/-- Internal: Not intended to be used outside this local construction. -/
lemma equal_char_zero.pnat_coe_units_coe_eq_coe
[fact (∀ (I : ideal R), I ≠ ⊤ → char_zero (R ⧸ I))] (n : ℕ+) :
((n : Rˣ) : R) = ↑n :=
begin
change ((equal_char_zero.pnat_coe_is_unit R n).unit : R) = ↑n,
simp only [is_unit.unit_spec],
end
/--
Equal characteristic implies `ℚ`-algebra.
-/
noncomputable def equal_char_zero_to_Q_algebra (h : ∀ (I : ideal R), I ≠ ⊤ → char_zero (R ⧸ I)) :
algebra ℚ R :=
by haveI : fact (∀ (I : ideal R), I ≠ ⊤ → char_zero (R ⧸ I)) := ⟨h⟩; exact
ring_hom.to_algebra
{ to_fun := λ x, x.num /ₚ ↑(x.pnat_denom),
map_zero' := by simp [divp],
map_one' := by simp [equal_char_zero.pnat_coe_units_eq_one],
map_mul' :=
begin
intros a b,
field_simp,
repeat { rw equal_char_zero.pnat_coe_units_coe_eq_coe R },
transitivity (↑((a * b).num * (a.denom) * (b.denom)) : R),
{ simp_rw [int.cast_mul, int.cast_coe_nat, coe_coe, rat.coe_pnat_denom],
ring },
rw rat.mul_num_denom' a b,
simp
end,
map_add' :=
begin
intros a b,
field_simp,
repeat { rw equal_char_zero.pnat_coe_units_coe_eq_coe R },
transitivity (↑((a + b).num * a.denom * b.denom) : R),
{ simp_rw [int.cast_mul, int.cast_coe_nat, coe_coe, rat.coe_pnat_denom],
ring },
rw rat.add_num_denom' a b,
simp
end }
end construction_of_Q_algebra
end equal_char_zero
/--
Not mixed characteristic implies equal characteristic.
-/
lemma not_mixed_char_to_equal_char_zero [char_zero R] (h : ∀ p > 0, ¬mixed_char_zero R p) :
∀ (I : ideal R), I ≠ ⊤ → char_zero (R ⧸ I) :=
begin
intros I hI_ne_top,
apply char_p.char_p_to_char_zero _,
cases char_p.exists (R ⧸ I) with p hp,
cases p,
{ exact hp },
{ have h_mixed : mixed_char_zero R p.succ := ⟨⟨I, ⟨hI_ne_top, hp⟩⟩⟩,
exact absurd h_mixed (h p.succ p.succ_pos) }
end
/--
Equal characteristic implies not mixed characteristic.
-/
lemma equal_char_zero_to_not_mixed_char (h : ∀ (I : ideal R), I ≠ ⊤ → char_zero (R ⧸ I)) :
∀ p > 0, ¬mixed_char_zero R p :=
begin
intros p p_pos,
by_contradiction hp_mixed_char,
rcases hp_mixed_char.char_p_quotient with ⟨I, hI_ne_top, hI_p⟩,
replace hI_zero : char_p (R ⧸ I) 0 := @char_p.of_char_zero _ _ (h I hI_ne_top),
exact absurd (char_p.eq (R ⧸ I) hI_p hI_zero) (ne_of_gt p_pos),
end
/--
A ring of characteristic zero has equal characteristic iff it does not
have mixed characteristic for any `p`.
-/
lemma equal_char_zero_iff_not_mixed_char [char_zero R] :
(∀ (I : ideal R), I ≠ ⊤ → char_zero (R ⧸ I)) ↔ (∀ p > 0, ¬mixed_char_zero R p) :=
⟨equal_char_zero_to_not_mixed_char R, not_mixed_char_to_equal_char_zero R⟩
/--
A ring is a `ℚ`-algebra iff it has equal characteristic zero.
-/
theorem Q_algebra_iff_equal_char_zero [nontrivial R] :
nonempty (algebra ℚ R) ↔ ∀ (I : ideal R), I ≠ ⊤ → char_zero (R ⧸ I) :=
begin
split,
{ intro h_alg,
haveI h_alg' : algebra ℚ R := h_alg.some,
apply Q_algebra_to_equal_char_zero },
{ intro h,
apply nonempty.intro,
exact equal_char_zero_to_Q_algebra R h }
end
/--
A ring of characteristic zero is not a `ℚ`-algebra iff it has mixed characteristic for some `p`.
-/
theorem not_Q_algebra_iff_not_equal_char_zero [char_zero R] :
is_empty (algebra ℚ R) ↔ (∃ p > 0, mixed_char_zero R p) :=
begin
rw ←not_iff_not,
push_neg,
rw [not_is_empty_iff, ←equal_char_zero_iff_not_mixed_char],
apply Q_algebra_iff_equal_char_zero,
end
/-!
# Splitting statements into different characteristic
Statements to split a proof by characteristic. There are 3 theorems here that are very
similar. They only differ in the assumptions we can make on the positive characteristic
case:
Generally we need to consider all `p ≠ 0`, but if `R` is a local ring, we can assume
that `p` is a prime power. And if `R` is a domain, we can even assume that `p` is prime.
-/
section main_statements
variable {P : Prop}
/--
Split a `Prop` in characteristic zero into equal and mixed characteristic.
-/
theorem split_equal_mixed_char [char_zero R]
(h_equal : algebra ℚ R → P)
(h_mixed : ∀ (p : ℕ), (nat.prime p → mixed_char_zero R p → P)) : P :=
begin
by_cases h : ∃ p > 0, mixed_char_zero R p,
{ rcases h with ⟨p, ⟨H, hp⟩⟩,
rw ←mixed_char_zero.reduce_to_p_prime at h_mixed,
exact h_mixed p H hp },
{ apply h_equal,
rw [←not_Q_algebra_iff_not_equal_char_zero, not_is_empty_iff] at h,
exact h.some },
end
example (n : ℕ) (h : n ≠ 0) :0 < n := zero_lt_iff.mpr h
/-- Split any `Prop` over `R` into the three cases:
- positive characteristic.
- equal characteristic zero.
- mixed characteristic `(0, p)`.
-/
theorem split_by_characteristic
(h_pos : ∀ (p : ℕ), (p ≠ 0 → char_p R p → P))
(h_equal : algebra ℚ R → P)
(h_mixed : ∀ (p : ℕ), (nat.prime p → mixed_char_zero R p → P)) : P :=
begin
cases char_p.exists R with p p_char,
by_cases p = 0,
{ rw h at p_char,
resetI, -- make `p_char : char_p R 0` an instance.
haveI h0 : char_zero R := char_p.char_p_to_char_zero R,
exact split_equal_mixed_char R h_equal h_mixed },
exact h_pos p h p_char,
end
/-- In a `is_domain R`, split any `Prop` over `R` into the three cases:
- *prime* characteristic.
- equal characteristic zero.
- mixed characteristic `(0, p)`.
-/
theorem split_by_characteristic_domain [is_domain R]
(h_pos : ∀ (p : ℕ), (nat.prime p → char_p R p → P))
(h_equal : algebra ℚ R → P)
(h_mixed : ∀ (p : ℕ), (nat.prime p → mixed_char_zero R p → P)) : P :=
begin
refine split_by_characteristic R _ h_equal h_mixed,
introsI p p_pos p_char,
have p_prime : nat.prime p :=
or_iff_not_imp_right.mp (char_p.char_is_prime_or_zero R p) p_pos,
exact h_pos p p_prime p_char,
end
/-- In a `local_ring R`, split any `Prop` over `R` into the three cases:
- *prime power* characteristic.
- equal characteristic zero.
- mixed characteristic `(0, p)`.
-/
theorem split_by_characteristic_local_ring [local_ring R]
(h_pos : ∀ (p : ℕ), (is_prime_pow p → char_p R p → P))
(h_equal : algebra ℚ R → P)
(h_mixed : ∀ (p : ℕ), (nat.prime p → mixed_char_zero R p → P)) : P :=
begin
refine split_by_characteristic R _ h_equal h_mixed,
introsI p p_pos p_char,
have p_ppow : is_prime_pow (p : ℕ) :=
or_iff_not_imp_left.mp (char_p_zero_or_prime_power R p) p_pos,
exact h_pos p p_ppow p_char,
end
end main_statements
|
742157ef628063bcfdfc07e0f96347a72e3a3d28 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/algebra/ring/basic.lean | 9bacb50ec849feafd6ccabe53b22f6a87f475d11 | [
"Apache-2.0"
] | permissive | anthony2698/mathlib | 03cd69fe5c280b0916f6df2d07c614c8e1efe890 | 407615e05814e98b24b2ff322b14e8e3eb5e5d67 | refs/heads/master | 1,678,792,774,873 | 1,614,371,563,000 | 1,614,371,563,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 42,007 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Amelia Livingston, Yury Kudryashov,
Neil Strickland
-/
import algebra.divisibility
import data.set.basic
/-!
# Properties and homomorphisms of semirings and rings
This file proves simple properties of semirings, rings and domains and their unit groups. It also
defines bundled homomorphisms of semirings and rings. As with monoid and groups, we use the same
structure `ring_hom a β`, a.k.a. `α →+* β`, for both homomorphism types.
The unbundled homomorphisms are defined in `deprecated/ring`. They are deprecated and the plan is to
slowly remove them from mathlib.
## Main definitions
ring_hom, nonzero, domain, integral_domain
## Notations
→+* for bundled ring homs (also use for semiring homs)
## Implementation notes
There's a coercion from bundled homs to fun, and the canonical
notation is to use the bundled hom as a function via this coercion.
There is no `semiring_hom` -- the idea is that `ring_hom` is used.
The constructor for a `ring_hom` between semirings needs a proof of `map_zero`, `map_one` and
`map_add` as well as `map_mul`; a separate constructor `ring_hom.mk'` will construct ring homs
between rings from monoid homs given only a proof that addition is preserved.
## Tags
`ring_hom`, `semiring_hom`, `semiring`, `comm_semiring`, `ring`, `comm_ring`, `domain`,
`integral_domain`, `nonzero`, `units`
-/
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {R : Type x}
set_option old_structure_cmd true
open function
/-!
### `distrib` class
-/
/-- A typeclass stating that multiplication is left and right distributive
over addition. -/
@[protect_proj, ancestor has_mul has_add]
class distrib (R : Type*) extends has_mul R, has_add R :=
(left_distrib : ∀ a b c : R, a * (b + c) = (a * b) + (a * c))
(right_distrib : ∀ a b c : R, (a + b) * c = (a * c) + (b * c))
lemma left_distrib [distrib R] (a b c : R) : a * (b + c) = a * b + a * c :=
distrib.left_distrib a b c
alias left_distrib ← mul_add
lemma right_distrib [distrib R] (a b c : R) : (a + b) * c = a * c + b * c :=
distrib.right_distrib a b c
alias right_distrib ← add_mul
/-- Pullback a `distrib` instance along an injective function. -/
protected def function.injective.distrib {S} [has_mul R] [has_add R] [distrib S]
(f : R → S) (hf : injective f) (add : ∀ x y, f (x + y) = f x + f y)
(mul : ∀ x y, f (x * y) = f x * f y) :
distrib R :=
{ mul := (*),
add := (+),
left_distrib := λ x y z, hf $ by simp only [*, left_distrib],
right_distrib := λ x y z, hf $ by simp only [*, right_distrib] }
/-- Pushforward a `distrib` instance along a surjective function. -/
protected def function.surjective.distrib {S} [distrib R] [has_add S] [has_mul S]
(f : R → S) (hf : surjective f) (add : ∀ x y, f (x + y) = f x + f y)
(mul : ∀ x y, f (x * y) = f x * f y) :
distrib S :=
{ mul := (*),
add := (+),
left_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, left_distrib],
right_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, right_distrib] }
/-!
### Semirings
-/
/-- A semiring is a type with the following structures: additive commutative monoid
(`add_comm_monoid`), multiplicative monoid (`monoid`), distributive laws (`distrib`), and
multiplication by zero law (`mul_zero_class`). The actual definition extends `monoid_with_zero`
instead of `monoid` and `mul_zero_class`. -/
@[protect_proj, ancestor add_comm_monoid monoid_with_zero distrib]
class semiring (α : Type u) extends add_comm_monoid α, monoid_with_zero α, distrib α
section semiring
variables [semiring α]
/-- Pullback a `semiring` instance along an injective function. -/
protected def function.injective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β]
(f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) :
semiring β :=
{ .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add,
.. hf.distrib f add mul }
/-- Pullback a `semiring` instance along an injective function. -/
protected def function.surjective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β]
(f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) :
semiring β :=
{ .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add,
.. hf.distrib f add mul }
lemma one_add_one_eq_two : 1 + 1 = (2 : α) :=
by unfold bit0
theorem two_mul (n : α) : 2 * n = n + n :=
eq.trans (right_distrib 1 1 n) (by simp)
lemma distrib_three_right (a b c d : α) : (a + b + c) * d = a * d + b * d + c * d :=
by simp [right_distrib]
theorem mul_two (n : α) : n * 2 = n + n :=
(left_distrib n 1 1).trans (by simp)
theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n :=
(two_mul _).symm
@[to_additive] lemma mul_ite {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) :
a * (if P then b else c) = if P then a * b else a * c :=
by split_ifs; refl
@[to_additive] lemma ite_mul {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) :
(if P then a else b) * c = if P then a * c else b * c :=
by split_ifs; refl
-- We make `mul_ite` and `ite_mul` simp lemmas,
-- but not `add_ite` or `ite_add`.
-- The problem we're trying to avoid is dealing with
-- summations of the form `∑ x in s, (f x + ite P 1 0)`,
-- in which `add_ite` followed by `sum_ite` would needlessly slice up
-- the `f x` terms according to whether `P` holds at `x`.
-- There doesn't appear to be a corresponding difficulty so far with
-- `mul_ite` and `ite_mul`.
attribute [simp] mul_ite ite_mul
@[simp] lemma mul_boole {α} [semiring α] (P : Prop) [decidable P] (a : α) :
a * (if P then 1 else 0) = if P then a else 0 :=
by simp
@[simp] lemma boole_mul {α} [semiring α] (P : Prop) [decidable P] (a : α) :
(if P then 1 else 0) * a = if P then a else 0 :=
by simp
lemma ite_mul_zero_left {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) :
ite P (a * b) 0 = ite P a 0 * b :=
by { by_cases h : P; simp [h], }
lemma ite_mul_zero_right {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) :
ite P (a * b) 0 = a * ite P b 0 :=
by { by_cases h : P; simp [h], }
/-- An element `a` of a semiring is even if there exists `k` such `a = 2*k`. -/
def even (a : α) : Prop := ∃ k, a = 2*k
lemma even_iff_two_dvd {a : α} : even a ↔ 2 ∣ a := iff.rfl
/-- An element `a` of a semiring is odd if there exists `k` such `a = 2*k + 1`. -/
def odd (a : α) : Prop := ∃ k, a = 2*k + 1
theorem dvd_add {a b c : α} (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c :=
dvd.elim h₁ (λ d hd, dvd.elim h₂ (λ e he, dvd.intro (d + e) (by simp [left_distrib, hd, he])))
end semiring
namespace add_monoid_hom
/-- Left multiplication by an element of a (semi)ring is an `add_monoid_hom` -/
def mul_left {R : Type*} [semiring R] (r : R) : R →+ R :=
{ to_fun := (*) r,
map_zero' := mul_zero r,
map_add' := mul_add r }
@[simp] lemma coe_mul_left {R : Type*} [semiring R] (r : R) : ⇑(mul_left r) = (*) r := rfl
/-- Right multiplication by an element of a (semi)ring is an `add_monoid_hom` -/
def mul_right {R : Type*} [semiring R] (r : R) : R →+ R :=
{ to_fun := λ a, a * r,
map_zero' := zero_mul r,
map_add' := λ _ _, add_mul _ _ r }
@[simp] lemma coe_mul_right {R : Type*} [semiring R] (r : R) :
⇑(mul_right r) = (* r) := rfl
lemma mul_right_apply {R : Type*} [semiring R] (a r : R) :
mul_right r a = a * r := rfl
end add_monoid_hom
/-- Bundled semiring homomorphisms; use this for bundled ring homomorphisms too.
This extends from both `monoid_hom` and `monoid_with_zero_hom` in order to put the fields in a
sensible order, even though `monoid_with_zero_hom` already extends `monoid_hom`. -/
structure ring_hom (α : Type*) (β : Type*) [semiring α] [semiring β]
extends monoid_hom α β, add_monoid_hom α β, monoid_with_zero_hom α β
infixr ` →+* `:25 := ring_hom
/-- Reinterpret a ring homomorphism `f : R →+* S` as a `monoid_with_zero_hom R S`.
The `simp`-normal form is `(f : monoid_with_zero_hom R S)`. -/
add_decl_doc ring_hom.to_monoid_with_zero_hom
/-- Reinterpret a ring homomorphism `f : R →+* S` as a monoid homomorphism `R →* S`.
The `simp`-normal form is `(f : R →* S)`. -/
add_decl_doc ring_hom.to_monoid_hom
/-- Reinterpret a ring homomorphism `f : R →+* S` as an additive monoid homomorphism `R →+ S`.
The `simp`-normal form is `(f : R →+ S)`. -/
add_decl_doc ring_hom.to_add_monoid_hom
namespace ring_hom
section coe
/-!
Throughout this section, some `semiring` arguments are specified with `{}` instead of `[]`.
See note [implicit instance arguments].
-/
variables {rα : semiring α} {rβ : semiring β}
include rα rβ
instance : has_coe_to_fun (α →+* β) := ⟨_, ring_hom.to_fun⟩
initialize_simps_projections ring_hom (to_fun → apply)
@[simp] lemma to_fun_eq_coe (f : α →+* β) : f.to_fun = f := rfl
@[simp] lemma coe_mk (f : α → β) (h₁ h₂ h₃ h₄) : ⇑(⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) = f := rfl
instance has_coe_monoid_hom : has_coe (α →+* β) (α →* β) := ⟨ring_hom.to_monoid_hom⟩
@[simp, norm_cast] lemma coe_monoid_hom (f : α →+* β) : ⇑(f : α →* β) = f := rfl
@[simp] lemma to_monoid_hom_eq_coe (f : α →+* β) : f.to_monoid_hom = f := rfl
@[simp] lemma coe_monoid_hom_mk (f : α → β) (h₁ h₂ h₃ h₄) :
((⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) : α →* β) = ⟨f, h₁, h₂⟩ :=
rfl
instance has_coe_add_monoid_hom : has_coe (α →+* β) (α →+ β) := ⟨ring_hom.to_add_monoid_hom⟩
@[simp, norm_cast] lemma coe_add_monoid_hom (f : α →+* β) : ⇑(f : α →+ β) = f := rfl
@[simp] lemma to_add_monoid_hom_eq_coe (f : α →+* β) : f.to_add_monoid_hom = f := rfl
@[simp] lemma coe_add_monoid_hom_mk (f : α → β) (h₁ h₂ h₃ h₄) :
((⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) : α →+ β) = ⟨f, h₃, h₄⟩ :=
rfl
end coe
variables [rα : semiring α] [rβ : semiring β]
section
include rα rβ
variables (f : α →+* β) {x y : α} {rα rβ}
theorem congr_fun {f g : α →+* β} (h : f = g) (x : α) : f x = g x :=
congr_arg (λ h : α →+* β, h x) h
theorem congr_arg (f : α →+* β) {x y : α} (h : x = y) : f x = f y :=
congr_arg (λ x : α, f x) h
theorem coe_inj ⦃f g : α →+* β⦄ (h : (f : α → β) = g) : f = g :=
by cases f; cases g; cases h; refl
@[ext] theorem ext ⦃f g : α →+* β⦄ (h : ∀ x, f x = g x) : f = g :=
coe_inj (funext h)
theorem ext_iff {f g : α →+* β} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, ext h⟩
@[simp] lemma mk_coe (f : α →+* β) (h₁ h₂ h₃ h₄) : ring_hom.mk f h₁ h₂ h₃ h₄ = f :=
ext $ λ _, rfl
theorem coe_add_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →+ β)) :=
λ f g h, ext (λ x, add_monoid_hom.congr_fun h x)
theorem coe_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →* β)) :=
λ f g h, ext (λ x, monoid_hom.congr_fun h x)
/-- Ring homomorphisms map zero to zero. -/
@[simp] lemma map_zero (f : α →+* β) : f 0 = 0 := f.map_zero'
/-- Ring homomorphisms map one to one. -/
@[simp] lemma map_one (f : α →+* β) : f 1 = 1 := f.map_one'
/-- Ring homomorphisms preserve addition. -/
@[simp] lemma map_add (f : α →+* β) (a b : α) : f (a + b) = f a + f b := f.map_add' a b
/-- Ring homomorphisms preserve multiplication. -/
@[simp] lemma map_mul (f : α →+* β) (a b : α) : f (a * b) = f a * f b := f.map_mul' a b
/-- Ring homomorphisms preserve `bit0`. -/
@[simp] lemma map_bit0 (f : α →+* β) (a : α) : f (bit0 a) = bit0 (f a) := map_add _ _ _
/-- Ring homomorphisms preserve `bit1`. -/
@[simp] lemma map_bit1 (f : α →+* β) (a : α) : f (bit1 a) = bit1 (f a) :=
by simp [bit1]
/-- `f : R →+* S` has a trivial codomain iff `f 1 = 0`. -/
lemma codomain_trivial_iff_map_one_eq_zero : (0 : β) = 1 ↔ f 1 = 0 :=
by rw [map_one, eq_comm]
/-- `f : R →+* S` has a trivial codomain iff it has a trivial range. -/
lemma codomain_trivial_iff_range_trivial : (0 : β) = 1 ↔ (∀ x, f x = 0) :=
f.codomain_trivial_iff_map_one_eq_zero.trans
⟨λ h x, by rw [←mul_one x, map_mul, h, mul_zero], λ h, h 1⟩
/-- `f : R →+* S` has a trivial codomain iff its range is `{0}`. -/
lemma codomain_trivial_iff_range_eq_singleton_zero : (0 : β) = 1 ↔ set.range f = {0} :=
f.codomain_trivial_iff_range_trivial.trans
⟨ λ h, set.ext (λ y, ⟨λ ⟨x, hx⟩, by simp [←hx, h x], λ hy, ⟨0, by simpa using hy.symm⟩⟩),
λ h x, set.mem_singleton_iff.mp (h ▸ set.mem_range_self x)⟩
/-- `f : R →+* S` doesn't map `1` to `0` if `S` is nontrivial -/
lemma map_one_ne_zero [nontrivial β] : f 1 ≠ 0 :=
mt f.codomain_trivial_iff_map_one_eq_zero.mpr zero_ne_one
/-- If there is a homomorphism `f : R →+* S` and `S` is nontrivial, then `R` is nontrivial. -/
lemma domain_nontrivial [nontrivial β] : nontrivial α :=
⟨⟨1, 0, mt (λ h, show f 1 = 0, by rw [h, map_zero]) f.map_one_ne_zero⟩⟩
lemma is_unit_map (f : α →+* β) {a : α} (h : is_unit a) : is_unit (f a) :=
h.map (f.to_monoid_hom)
end
/-- The identity ring homomorphism from a semiring to itself. -/
def id (α : Type*) [semiring α] : α →+* α :=
by refine {to_fun := id, ..}; intros; refl
include rα
instance : inhabited (α →+* α) := ⟨id α⟩
@[simp] lemma id_apply (x : α) : ring_hom.id α x = x := rfl
variable {rγ : semiring γ}
include rβ rγ
/-- Composition of ring homomorphisms is a ring homomorphism. -/
def comp (hnp : β →+* γ) (hmn : α →+* β) : α →+* γ :=
{ to_fun := hnp ∘ hmn,
map_zero' := by simp,
map_one' := by simp,
map_add' := λ x y, by simp,
map_mul' := λ x y, by simp}
/-- Composition of semiring homomorphisms is associative. -/
lemma comp_assoc {δ} {rδ: semiring δ} (f : α →+* β) (g : β →+* γ) (h : γ →+* δ) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[simp] lemma coe_comp (hnp : β →+* γ) (hmn : α →+* β) : (hnp.comp hmn : α → γ) = hnp ∘ hmn := rfl
lemma comp_apply (hnp : β →+* γ) (hmn : α →+* β) (x : α) : (hnp.comp hmn : α → γ) x =
(hnp (hmn x)) := rfl
omit rγ
@[simp] lemma comp_id (f : α →+* β) : f.comp (id α) = f := ext $ λ x, rfl
@[simp] lemma id_comp (f : α →+* β) : (id β).comp f = f := ext $ λ x, rfl
omit rβ
instance : monoid (α →+* α) :=
{ one := id α,
mul := comp,
mul_one := comp_id,
one_mul := id_comp,
mul_assoc := λ f g h, comp_assoc _ _ _ }
lemma one_def : (1 : α →+* α) = id α := rfl
@[simp] lemma coe_one : ⇑(1 : α →+* α) = _root_.id := rfl
lemma mul_def (f g : α →+* α) : f * g = f.comp g := rfl
@[simp] lemma coe_mul (f g : α →+* α) : ⇑(f * g) = f ∘ g := rfl
include rβ rγ
lemma cancel_right {g₁ g₂ : β →+* γ} {f : α →+* β} (hf : surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, ring_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩
lemma cancel_left {g : β →+* γ} {f₁ f₂ : α →+* β} (hg : injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, ring_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩
omit rα rβ rγ
end ring_hom
/-- A commutative semiring is a `semiring` with commutative multiplication. In other words, it is a
type with the following structures: additive commutative monoid (`add_comm_monoid`), multiplicative
commutative monoid (`comm_monoid`), distributive laws (`distrib`), and multiplication by zero law
(`mul_zero_class`). -/
@[protect_proj, ancestor semiring comm_monoid]
class comm_semiring (α : Type u) extends semiring α, comm_monoid α
@[priority 100] -- see Note [lower instance priority]
instance comm_semiring.to_comm_monoid_with_zero [comm_semiring α] : comm_monoid_with_zero α :=
{ .. comm_semiring.to_comm_monoid α, .. comm_semiring.to_semiring α }
section comm_semiring
variables [comm_semiring α] [comm_semiring β] {a b c : α}
/-- Pullback a `semiring` instance along an injective function. -/
protected def function.injective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ]
(f : γ → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) :
comm_semiring γ :=
{ .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul }
/-- Pullback a `semiring` instance along an injective function. -/
protected def function.surjective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ]
(f : α → γ) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) :
comm_semiring γ :=
{ .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul }
lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b :=
by simp only [two_mul, add_mul, mul_add, add_assoc, mul_comm b]
@[simp] theorem two_dvd_bit0 : 2 ∣ bit0 a := ⟨a, bit0_eq_two_mul _⟩
lemma ring_hom.map_dvd (f : α →+* β) {a b : α} : a ∣ b → f a ∣ f b :=
λ ⟨z, hz⟩, ⟨f z, by rw [hz, f.map_mul]⟩
end comm_semiring
/-!
### Rings
-/
/-- A ring is a type with the following structures: additive commutative group (`add_comm_group`),
multiplicative monoid (`monoid`), and distributive laws (`distrib`). Equivalently, a ring is a
`semiring` with a negation operation making it an additive group. -/
@[protect_proj, ancestor add_comm_group monoid distrib]
class ring (α : Type u) extends add_comm_group α, monoid α, distrib α
section ring
variables [ring α] {a b c d e : α}
/- The instance from `ring` to `semiring` happens often in linear algebra, for which all the basic
definitions are given in terms of semirings, but many applications use rings or fields. We increase
a little bit its priority above 100 to try it quickly, but remaining below the default 1000 so that
more specific instances are tried first. -/
@[priority 200]
instance ring.to_semiring : semiring α :=
{ zero_mul := λ a, add_left_cancel $ show 0 * a + 0 * a = 0 * a + 0,
by rw [← add_mul, zero_add, add_zero],
mul_zero := λ a, add_left_cancel $ show a * 0 + a * 0 = a * 0 + 0,
by rw [← mul_add, add_zero, add_zero],
..‹ring α› }
/-- Pullback a `ring` instance along an injective function. -/
protected def function.injective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β]
(f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) :
ring β :=
{ .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul }
/-- Pullback a `ring` instance along an injective function,
with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/
protected def function.injective.ring_sub
[has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β]
(f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) :
ring β :=
{ .. hf.add_comm_group_sub f zero add neg sub, .. hf.monoid f one mul, .. hf.distrib f add mul }
/-- Pullback a `ring` instance along an injective function. -/
protected def function.surjective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β]
(f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) :
ring β :=
{ .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul }
/-- Pullback a `ring` instance along an injective function,
with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/
protected def function.surjective.ring_sub
[has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β]
(f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) :
ring β :=
{ .. hf.add_comm_group_sub f zero add neg sub, .. hf.monoid f one mul, .. hf.distrib f add mul }
lemma neg_mul_eq_neg_mul (a b : α) : -(a * b) = -a * b :=
neg_eq_of_add_eq_zero
begin rw [← right_distrib, add_right_neg, zero_mul] end
lemma neg_mul_eq_mul_neg (a b : α) : -(a * b) = a * -b :=
neg_eq_of_add_eq_zero
begin rw [← left_distrib, add_right_neg, mul_zero] end
@[simp] lemma neg_mul_eq_neg_mul_symm (a b : α) : - a * b = - (a * b) :=
eq.symm (neg_mul_eq_neg_mul a b)
@[simp] lemma mul_neg_eq_neg_mul_symm (a b : α) : a * - b = - (a * b) :=
eq.symm (neg_mul_eq_mul_neg a b)
lemma neg_mul_neg (a b : α) : -a * -b = a * b :=
by simp
lemma neg_mul_comm (a b : α) : -a * b = a * -b :=
by simp
theorem neg_eq_neg_one_mul (a : α) : -a = -1 * a :=
by simp
lemma mul_sub_left_distrib (a b c : α) : a * (b - c) = a * b - a * c :=
by simpa only [sub_eq_add_neg, neg_mul_eq_mul_neg] using mul_add a b (-c)
alias mul_sub_left_distrib ← mul_sub
lemma mul_sub_right_distrib (a b c : α) : (a - b) * c = a * c - b * c :=
by simpa only [sub_eq_add_neg, neg_mul_eq_neg_mul] using add_mul a (-b) c
alias mul_sub_right_distrib ← sub_mul
/-- An element of a ring multiplied by the additive inverse of one is the element's additive
inverse. -/
lemma mul_neg_one (a : α) : a * -1 = -a := by simp
/-- The additive inverse of one multiplied by an element of a ring is the element's additive
inverse. -/
lemma neg_one_mul (a : α) : -1 * a = -a := by simp
/-- An iff statement following from right distributivity in rings and the definition
of subtraction. -/
theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d :=
calc
a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp [add_comm]
... ↔ a * e + c - b * e = d : iff.intro (λ h, begin rw h, simp end) (λ h,
begin rw ← h, simp end)
... ↔ (a - b) * e + c = d : begin simp [sub_mul, sub_add_eq_add_sub] end
/-- A simplification of one side of an equation exploiting right distributivity in rings
and the definition of subtraction. -/
theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d :=
assume h,
calc
(a - b) * e + c = (a * e + c) - b * e : begin simp [sub_mul, sub_add_eq_add_sub] end
... = d : begin rw h, simp [@add_sub_cancel α] end
end ring
namespace units
variables [ring α] {a b : α}
/-- Each element of the group of units of a ring has an additive inverse. -/
instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩
/-- Representing an element of a ring's unit group as an element of the ring commutes with
mapping this element to its additive inverse. -/
@[simp, norm_cast] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl
@[simp, norm_cast] protected theorem coe_neg_one : ((-1 : units α) : α) = -1 := rfl
/-- Mapping an element of a ring's unit group to its inverse commutes with mapping this element
to its additive inverse. -/
@[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl
/-- An element of a ring's unit group equals the additive inverse of its additive inverse. -/
@[simp] protected theorem neg_neg (u : units α) : - -u = u :=
units.ext $ neg_neg _
/-- Multiplication of elements of a ring's unit group commutes with mapping the first
argument to its additive inverse. -/
@[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) :=
units.ext $ neg_mul_eq_neg_mul_symm _ _
/-- Multiplication of elements of a ring's unit group commutes with mapping the second argument
to its additive inverse. -/
@[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) :=
units.ext $ (neg_mul_eq_mul_neg _ _).symm
/-- Multiplication of the additive inverses of two elements of a ring's unit group equals
multiplication of the two original elements. -/
@[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp
/-- The additive inverse of an element of a ring's unit group equals the additive inverse of
one times the original element. -/
protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp
end units
namespace ring_hom
/-- Ring homomorphisms preserve additive inverse. -/
@[simp] theorem map_neg {α β} [ring α] [ring β] (f : α →+* β) (x : α) : f (-x) = -(f x) :=
(f : α →+ β).map_neg x
/-- Ring homomorphisms preserve subtraction. -/
@[simp] theorem map_sub {α β} [ring α] [ring β] (f : α →+* β) (x y : α) :
f (x - y) = (f x) - (f y) := (f : α →+ β).map_sub x y
/-- A ring homomorphism is injective iff its kernel is trivial. -/
theorem injective_iff {α β} [ring α] [semiring β] (f : α →+* β) :
function.injective f ↔ (∀ a, f a = 0 → a = 0) :=
(f : α →+ β).injective_iff
/-- Makes a ring homomorphism from a monoid homomorphism of rings which preserves addition. -/
def mk' {γ} [semiring α] [ring γ] (f : α →* γ) (map_add : ∀ a b : α, f (a + b) = f a + f b) :
α →+* γ :=
{ to_fun := f,
.. add_monoid_hom.mk' f map_add, .. f }
end ring_hom
/-- A commutative ring is a `ring` with commutative multiplication. -/
@[protect_proj, ancestor ring comm_semigroup]
class comm_ring (α : Type u) extends ring α, comm_semigroup α
@[priority 100] -- see Note [lower instance priority]
instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α :=
{ mul_zero := mul_zero, zero_mul := zero_mul, ..s }
section comm_ring
variables [comm_ring α] {a b c : α}
/-- Pullback a `comm_ring` instance along an injective function. -/
protected def function.injective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β]
[has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) :
comm_ring β :=
{ .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul }
/-- Pullback a `comm_ring` instance along an injective function,
with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/
protected def function.injective.comm_ring_sub
[has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β]
(f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) :
comm_ring β :=
{ .. hf.ring_sub f zero one add mul neg sub, .. hf.comm_semigroup f mul }
/-- Pullback a `comm_ring` instance along an injective function. -/
protected def function.surjective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β]
[has_neg β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) :
comm_ring β :=
{ .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul }
/-- Pullback a `comm_ring` instance along an injective function,
with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/
protected def function.surjective.comm_ring_sub
[has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β]
(f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) :
comm_ring β :=
{ .. hf.ring_sub f zero one add mul neg sub, .. hf.comm_semigroup f mul }
local attribute [simp] add_assoc add_comm add_left_comm mul_comm
theorem dvd_neg_of_dvd (h : a ∣ b) : (a ∣ -b) :=
dvd.elim h
(assume c, assume : b = a * c,
dvd.intro (-c) (by simp [this]))
theorem dvd_of_dvd_neg (h : a ∣ -b) : (a ∣ b) :=
let t := dvd_neg_of_dvd h in by rwa neg_neg at t
theorem dvd_neg_iff_dvd (a b : α) : (a ∣ -b) ↔ (a ∣ b) :=
⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩
theorem neg_dvd_of_dvd (h : a ∣ b) : -a ∣ b :=
dvd.elim h
(assume c, assume : b = a * c,
dvd.intro (-c) (by simp [this]))
theorem dvd_of_neg_dvd (h : -a ∣ b) : a ∣ b :=
let t := neg_dvd_of_dvd h in by rwa neg_neg at t
theorem neg_dvd_iff_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) :=
⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩
theorem dvd_sub (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b - c :=
by { rw sub_eq_add_neg, exact dvd_add h₁ (dvd_neg_of_dvd h₂) }
theorem dvd_add_iff_left (h : a ∣ c) : a ∣ b ↔ a ∣ b + c :=
⟨λh₂, dvd_add h₂ h, λH, by have t := dvd_sub H h; rwa add_sub_cancel at t⟩
theorem dvd_add_iff_right (h : a ∣ b) : a ∣ c ↔ a ∣ b + c :=
by rw add_comm; exact dvd_add_iff_left h
theorem two_dvd_bit1 : 2 ∣ bit1 a ↔ (2 : α) ∣ 1 := (dvd_add_iff_right (@two_dvd_bit0 _ _ a)).symm
/-- Representation of a difference of two squares in a commutative ring as a product. -/
theorem mul_self_sub_mul_self (a b : α) : a * a - b * b = (a + b) * (a - b) :=
by rw [add_mul, mul_sub, mul_sub, mul_comm a b, sub_add_sub_cancel]
lemma mul_self_sub_one (a : α) : a * a - 1 = (a + 1) * (a - 1) :=
by rw [← mul_self_sub_mul_self, mul_one]
/-- An element a of a commutative ring divides the additive inverse of an element b iff a
divides b. -/
@[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) :=
⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩
/-- The additive inverse of an element a of a commutative ring divides another element b iff a
divides b. -/
@[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) :=
⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩
/-- If an element a divides another element c in a commutative ring, a divides the sum of another
element b with c iff a divides b. -/
theorem dvd_add_left (h : a ∣ c) : a ∣ b + c ↔ a ∣ b :=
(dvd_add_iff_left h).symm
/-- If an element a divides another element b in a commutative ring, a divides the sum of b and
another element c iff a divides c. -/
theorem dvd_add_right (h : a ∣ b) : a ∣ b + c ↔ a ∣ c :=
(dvd_add_iff_right h).symm
/-- An element a divides the sum a + b if and only if a divides b.-/
@[simp] lemma dvd_add_self_left {a b : α} : a ∣ a + b ↔ a ∣ b :=
dvd_add_right (dvd_refl a)
/-- An element a divides the sum b + a if and only if a divides b.-/
@[simp] lemma dvd_add_self_right {a b : α} : a ∣ b + a ↔ a ∣ b :=
dvd_add_left (dvd_refl a)
/-- Vieta's formula for a quadratic equation, relating the coefficients of the polynomial with
its roots. This particular version states that if we have a root `x` of a monic quadratic
polynomial, then there is another root `y` such that `x + y` is negative the `a_1` coefficient
and `x * y` is the `a_0` coefficient. -/
lemma Vieta_formula_quadratic {b c x : α} (h : x * x - b * x + c = 0) :
∃ y : α, y * y - b * y + c = 0 ∧ x + y = b ∧ x * y = c :=
begin
have : c = -(x * x - b * x) := (neg_eq_of_add_eq_zero h).symm,
have : c = x * (b - x), by subst this; simp [mul_sub, mul_comm],
refine ⟨b - x, _, by simp, by rw this⟩,
rw [this, sub_add, ← sub_mul, sub_self]
end
lemma dvd_mul_sub_mul {k a b x y : α} (hab : k ∣ a - b) (hxy : k ∣ x - y) :
k ∣ a * x - b * y :=
begin
convert dvd_add (dvd_mul_of_dvd_right hxy a) (dvd_mul_of_dvd_left hab y),
rw [mul_sub_left_distrib, mul_sub_right_distrib],
simp only [sub_eq_add_neg, add_assoc, neg_add_cancel_left],
end
lemma dvd_iff_dvd_of_dvd_sub {a b c : α} (h : a ∣ (b - c)) : (a ∣ b ↔ a ∣ c) :=
begin
split,
{ intro h',
convert dvd_sub h' h,
exact eq.symm (sub_sub_self b c) },
{ intro h',
convert dvd_add h h',
exact eq_add_of_sub_eq rfl }
end
end comm_ring
lemma succ_ne_self [ring α] [nontrivial α] (a : α) : a + 1 ≠ a :=
λ h, one_ne_zero ((add_right_inj a).mp (by simp [h]))
lemma pred_ne_self [ring α] [nontrivial α] (a : α) : a - 1 ≠ a :=
λ h, one_ne_zero (neg_injective ((add_right_inj a).mp (by simpa [sub_eq_add_neg] using h)))
/-- A domain is a ring with no zero divisors, i.e. satisfying
the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain
is an integral domain without assuming commutativity of multiplication. -/
@[protect_proj] class domain (α : Type u) extends ring α, nontrivial α :=
(eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0)
section domain
variable [domain α]
@[priority 100] -- see Note [lower instance priority]
instance domain.to_no_zero_divisors : no_zero_divisors α :=
⟨domain.eq_zero_or_eq_zero_of_mul_eq_zero⟩
@[priority 100] -- see Note [lower instance priority]
instance domain.to_cancel_monoid_with_zero : cancel_monoid_with_zero α :=
{ mul_left_cancel_of_ne_zero := λ a b c ha,
by { rw [← sub_eq_zero, ← mul_sub], simp [ha, sub_eq_zero] },
mul_right_cancel_of_ne_zero := λ a b c hb,
by { rw [← sub_eq_zero, ← sub_mul], simp [hb, sub_eq_zero] },
.. (infer_instance : semiring α) }
/-- Pullback a `domain` instance along an injective function. -/
protected def function.injective.domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β]
(f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) :
domain β :=
{ .. hf.ring f zero one add mul neg, .. pullback_nonzero f zero one,
.. hf.no_zero_divisors f zero mul }
end domain
/-!
### Integral domains
-/
/-- An integral domain is a commutative ring with no zero divisors, i.e. satisfying the condition
`a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, an integral domain is a domain with commutative
multiplication. -/
@[protect_proj, ancestor comm_ring domain]
class integral_domain (α : Type u) extends comm_ring α, domain α
section integral_domain
variables [integral_domain α] {a b c d e : α}
@[priority 100] -- see Note [lower instance priority]
instance integral_domain.to_comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero α :=
{ ..comm_semiring.to_comm_monoid_with_zero, ..domain.to_cancel_monoid_with_zero }
/-- Pullback an `integral_domain` instance along an injective function. -/
protected def function.injective.integral_domain [has_zero β] [has_one β] [has_add β]
[has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1)
(add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y)
(neg : ∀ x, f (-x) = -f x) :
integral_domain β :=
{ .. hf.comm_ring f zero one add mul neg, .. hf.domain f zero one add mul neg }
lemma mul_self_eq_mul_self_iff {a b : α} : a * a = b * b ↔ a = b ∨ a = -b :=
by rw [← sub_eq_zero, mul_self_sub_mul_self, mul_eq_zero, or_comm, sub_eq_zero,
add_eq_zero_iff_eq_neg]
lemma mul_self_eq_one_iff {a : α} : a * a = 1 ↔ a = 1 ∨ a = -1 :=
by rw [← mul_self_eq_mul_self_iff, one_mul]
/-- In the unit group of an integral domain, a unit is its own inverse iff the unit is one or
one's additive inverse. -/
lemma units.inv_eq_self_iff (u : units α) : u⁻¹ = u ↔ u = 1 ∨ u = -1 :=
by { rw inv_eq_iff_mul_eq_one, simp only [units.ext_iff], push_cast, exact mul_self_eq_one_iff }
/--
Makes a ring homomorphism from an additive group homomorphism from a commutative ring to an integral
domain that commutes with self multiplication, assumes that two is nonzero and one is sent to one.
-/
def add_monoid_hom.mk_ring_hom_of_mul_self_of_two_ne_zero [comm_ring β] (f : β →+ α)
(h : ∀ x, f (x * x) = f x * f x) (h_two : (2 : α) ≠ 0) (h_one : f 1 = 1) : β →+* α :=
{ map_one' := h_one,
map_mul' := begin
intros x y,
have hxy := h (x + y),
rw [mul_add, add_mul, add_mul, f.map_add, f.map_add, f.map_add, f.map_add, h x, h y, add_mul,
mul_add, mul_add, ← sub_eq_zero_iff_eq, add_comm, ← sub_sub, ← sub_sub, ← sub_sub,
mul_comm y x, mul_comm (f y) (f x)] at hxy,
simp only [add_assoc, add_sub_assoc, add_sub_cancel'_right] at hxy,
rw [sub_sub, ← two_mul, ← add_sub_assoc, ← two_mul, ← mul_sub, mul_eq_zero, sub_eq_zero_iff_eq,
or_iff_not_imp_left] at hxy,
exact hxy h_two,
end,
..f }
@[simp]
lemma add_monoid_hom.coe_fn_mk_ring_hom_of_mul_self_of_two_ne_zero [comm_ring β] (f : β →+ α)
(h h_two h_one) :
(f.mk_ring_hom_of_mul_self_of_two_ne_zero h h_two h_one : β → α) = f := rfl
@[simp]
lemma add_monoid_hom.coe_add_monoid_hom_mk_ring_hom_of_mul_self_of_two_ne_zero [comm_ring β]
(f : β →+ α) (h h_two h_one) :
(f.mk_ring_hom_of_mul_self_of_two_ne_zero h h_two h_one : β →+ α) = f := by {ext, simp}
end integral_domain
namespace ring
variables [ring R]
open_locale classical
/-- Introduce a function `inverse` on a ring `R`, which sends `x` to `x⁻¹` if `x` is invertible and
to `0` otherwise. This definition is somewhat ad hoc, but one needs a fully (rather than partially)
defined inverse function for some purposes, including for calculus. -/
noncomputable def inverse : R → R :=
λ x, if h : is_unit x then (((classical.some h)⁻¹ : units R) : R) else 0
/-- By definition, if `x` is invertible then `inverse x = x⁻¹`. -/
@[simp] lemma inverse_unit (a : units R) : inverse (a : R) = (a⁻¹ : units R) :=
begin
simp [is_unit_unit, inverse],
exact units.inv_unique (classical.some_spec (is_unit_unit a)),
end
/-- By definition, if `x` is not invertible then `inverse x = 0`. -/
@[simp] lemma inverse_non_unit (x : R) (h : ¬(is_unit x)) : inverse x = 0 := dif_neg h
end ring
/-- A predicate to express that a ring is an integral domain.
This is mainly useful because such a predicate does not contain data,
and can therefore be easily transported along ring isomorphisms. -/
structure is_integral_domain (R : Type u) [ring R] extends nontrivial R : Prop :=
(mul_comm : ∀ (x y : R), x * y = y * x)
(eq_zero_or_eq_zero_of_mul_eq_zero : ∀ x y : R, x * y = 0 → x = 0 ∨ y = 0)
-- The linter does not recognize that is_integral_domain.to_nontrivial is a structure
-- projection, disable it
attribute [nolint def_lemma doc_blame] is_integral_domain.to_nontrivial
/-- Every integral domain satisfies the predicate for integral domains. -/
lemma integral_domain.to_is_integral_domain (R : Type u) [integral_domain R] :
is_integral_domain R :=
{ .. (‹_› : integral_domain R) }
/-- If a ring satisfies the predicate for integral domains,
then it can be endowed with an `integral_domain` instance
whose data is definitionally equal to the existing data. -/
def is_integral_domain.to_integral_domain (R : Type u) [ring R] (h : is_integral_domain R) :
integral_domain R :=
{ .. (‹_› : ring R), .. (‹_› : is_integral_domain R) }
namespace semiconj_by
@[simp] lemma add_right [distrib R] {a x y x' y' : R}
(h : semiconj_by a x y) (h' : semiconj_by a x' y') :
semiconj_by a (x + x') (y + y') :=
by simp only [semiconj_by, left_distrib, right_distrib, h.eq, h'.eq]
@[simp] lemma add_left [distrib R] {a b x y : R}
(ha : semiconj_by a x y) (hb : semiconj_by b x y) :
semiconj_by (a + b) x y :=
by simp only [semiconj_by, left_distrib, right_distrib, ha.eq, hb.eq]
variables [ring R] {a b x y x' y' : R}
lemma neg_right (h : semiconj_by a x y) : semiconj_by a (-x) (-y) :=
by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm]
@[simp] lemma neg_right_iff : semiconj_by a (-x) (-y) ↔ semiconj_by a x y :=
⟨λ h, neg_neg x ▸ neg_neg y ▸ h.neg_right, semiconj_by.neg_right⟩
lemma neg_left (h : semiconj_by a x y) : semiconj_by (-a) x y :=
by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm]
@[simp] lemma neg_left_iff : semiconj_by (-a) x y ↔ semiconj_by a x y :=
⟨λ h, neg_neg a ▸ h.neg_left, semiconj_by.neg_left⟩
@[simp] lemma neg_one_right (a : R) : semiconj_by a (-1) (-1) :=
(one_right a).neg_right
@[simp] lemma neg_one_left (x : R) : semiconj_by (-1) x x :=
(semiconj_by.one_left x).neg_left
@[simp] lemma sub_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') :
semiconj_by a (x - x') (y - y') :=
by simpa only [sub_eq_add_neg] using h.add_right h'.neg_right
@[simp] lemma sub_left (ha : semiconj_by a x y) (hb : semiconj_by b x y) :
semiconj_by (a - b) x y :=
by simpa only [sub_eq_add_neg] using ha.add_left hb.neg_left
end semiconj_by
namespace commute
@[simp] theorem add_right [distrib R] {a b c : R} :
commute a b → commute a c → commute a (b + c) :=
semiconj_by.add_right
@[simp] theorem add_left [distrib R] {a b c : R} :
commute a c → commute b c → commute (a + b) c :=
semiconj_by.add_left
variables [ring R] {a b c : R}
theorem neg_right : commute a b → commute a (- b) := semiconj_by.neg_right
@[simp] theorem neg_right_iff : commute a (-b) ↔ commute a b := semiconj_by.neg_right_iff
theorem neg_left : commute a b → commute (- a) b := semiconj_by.neg_left
@[simp] theorem neg_left_iff : commute (-a) b ↔ commute a b := semiconj_by.neg_left_iff
@[simp] theorem neg_one_right (a : R) : commute a (-1) := semiconj_by.neg_one_right a
@[simp] theorem neg_one_left (a : R): commute (-1) a := semiconj_by.neg_one_left a
@[simp] theorem sub_right : commute a b → commute a c → commute a (b - c) := semiconj_by.sub_right
@[simp] theorem sub_left : commute a c → commute b c → commute (a - b) c := semiconj_by.sub_left
end commute
|
1c445f3b8b023d9e12b1571911be19daffede1e1 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Coe.lean | a97ca477ec571c291d7245414dcef1500bf20215 | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 4,352 | 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
-/
prelude
import Init.HasCoe -- import legacy HasCoe
import Init.Core
universes u v w w'
class Coe (α : Sort u) (β : Sort v) :=
(coe : α → β)
/-- Auxiliary class that contains the transitive closure of `Coe`. -/
class CoeTC (α : Sort u) (β : Sort v) :=
(coe : α → β)
/- Expensive coercion that can only appear at the beggining of a sequence of coercions. -/
class CoeHead (α : Sort u) (β : Sort v) :=
(coe : α → β)
/- Expensive coercion that can only appear at the end of a sequence of coercions. -/
class CoeTail (α : Sort u) (β : Sort v) :=
(coe : α → β)
class CoeDep (α : Sort u) (a : α) (β : Sort v) :=
(coe : β)
/- Combines CoeHead, CoeTC, CoeTail, CoeDep -/
class CoeT (α : Sort u) (a : α) (β : Sort v) :=
(coe : β)
class CoeFun (α : Sort u) (γ : outParam (α → outParam (Sort v))) :=
(coe : forall (a : α), γ a)
class CoeSort (α : Sort u) (β : outParam (Sort v)) :=
(coe : α → β)
abbrev coeB {α : Sort u} {β : Sort v} [Coe α β] (a : α) : β :=
@Coe.coe α β _ a
abbrev coeHead {α : Sort u} {β : Sort v} [CoeHead α β] (a : α) : β :=
@CoeHead.coe α β _ a
abbrev coeTail {α : Sort u} {β : Sort v} [CoeTail α β] (a : α) : β :=
@CoeTail.coe α β _ a
abbrev coeD {α : Sort u} {β : Sort v} (a : α) [CoeDep α a β] : β :=
@CoeDep.coe α a β _
abbrev coeTC {α : Sort u} {β : Sort v} [CoeTC α β] (a : α) : β :=
@CoeTC.coe α β _ a
/-- Apply coercion manually. -/
abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β :=
@CoeT.coe α a β _
abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a :=
@CoeFun.coe α γ _ a
abbrev coeSort {α : Sort u} {β : Sort v} (a : α) [CoeSort α β] : β :=
@CoeSort.coe α β _ a
instance coeTrans {α : Sort u} {β : Sort v} {δ : Sort w} [CoeTC α β] [Coe β δ] : CoeTC α δ :=
{ coe := fun a => coeB (coeTC a : β) }
instance coeBase {α : Sort u} {β : Sort v} [Coe α β] : CoeTC α β :=
{ coe := fun a => coeB a }
instance coeOfHeafOfTCOfTail {α : Sort u} {β : Sort v} {δ : Sort w} {γ : Sort w'} (a : α) [CoeTC β δ] [CoeTail δ γ] [CoeHead α β] : CoeT α a γ :=
{ coe := coeTail (coeTC (coeHead a : β) : δ) }
instance coeOfHeadOfTC {α : Sort u} {β : Sort v} {δ : Sort w} (a : α) [CoeTC β δ] [CoeHead α β] : CoeT α a δ :=
{ coe := coeTC (coeHead a : β) }
instance coeOfTCOfTail {α : Sort u} {β : Sort v} {δ : Sort w} (a : α) [CoeTC α β] [CoeTail β δ] : CoeT α a δ :=
{ coe := coeTail (coeTC a : β) }
instance coeOfHead {α : Sort u} {β : Sort v} (a : α) [CoeHead α β] : CoeT α a β :=
{ coe := coeHead a }
instance coeOfTail {α : Sort u} {β : Sort v} (a : α) [CoeTail α β] : CoeT α a β :=
{ coe := coeTail a }
instance coeOfTC {α : Sort u} {β : Sort v} (a : α) [CoeTC α β] : CoeT α a β :=
{ coe := coeTC a }
instance coeOfDep {α : Sort u} {β : Sort v} (a : α) [CoeDep α a β] : CoeT α a β :=
{ coe := coeD a }
instance coeFunTrans {α : Sort u} {β : Sort v} {γ : β → Sort w} [CoeFun β γ] [Coe α β] : CoeFun α (fun a => γ (coe a)) :=
{ coe := fun a => coeFun (coeB a : β) }
instance coeSortTrans {α : Sort u} {β : Sort v} {δ : Sort w} [CoeSort β δ] [Coe α β] : CoeSort α δ :=
{ coe := fun a => coeSort (coeB a : β) }
/- Basic instances -/
instance boolToProp : Coe Bool Prop :=
{ coe := fun b => b = true }
instance coeDecidableEq (x : Bool) : Decidable (coe x) :=
inferInstanceAs (Decidable (x = true))
instance decPropToBool (p : Prop) [Decidable p] : CoeDep Prop p Bool :=
{ coe := decide p }
instance optionCoe {α : Type u} : CoeTail α (Option α) :=
{ coe := some }
instance subtypeCoe {α : Sort u} {p : α → Prop} : CoeHead { x // p x } α :=
{ coe := fun v => v.val }
/- Coe & HasOfNat bridge -/
/-
Remark: one may question why we use `HasOfNat α` instead of `Coe Nat α`.
Reason: `HasOfNat` is for implementing polymorphic numeric literals, and we may
want to have numberic literals for a type α and **no** coercion from `Nat` to `α`. -/
instance hasOfNatOfCoe {α : Type u} {β : Type v} [HasOfNat α] [Coe α β] : HasOfNat β :=
{ ofNat := fun (n : Nat) => coe (HasOfNat.ofNat α n) }
|
42b1a13023a81edb3aed47e77b0443d7c8eaf142 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /src/Lean/Elab/Binders.lean | fb73ffbfc8b6ea2f57c54c4bd5eaeee6bd0cf4e8 | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 23,110 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Term
import Lean.Elab.Quotation
namespace Lean.Elab.Term
open Meta
/--
Given syntax of the forms
a) (`:` term)?
b) `:` term
return `term` if it is present, or a hole if not. -/
private def expandBinderType (ref : Syntax) (stx : Syntax) : Syntax :=
if stx.getNumArgs == 0 then
mkHole ref
else
stx[1]
/-- Given syntax of the form `ident <|> hole`, return `ident`. If `hole`, then we create a new anonymous name. -/
private def expandBinderIdent (stx : Syntax) : TermElabM Syntax :=
match_syntax stx with
| `(_) => mkFreshIdent stx
| _ => pure stx
/-- Given syntax of the form `(ident >> " : ")?`, return `ident`, or a new instance name. -/
private def expandOptIdent (stx : Syntax) : TermElabM Syntax := do
if stx.getNumArgs == 0 then
pure $ mkIdentFrom stx (← mkFreshInstanceName)
else
pure stx[0]
structure BinderView :=
(id : Syntax)
(type : Syntax)
(bi : BinderInfo)
partial def quoteAutoTactic : Syntax → TermElabM Syntax
| stx@(Syntax.ident _ _ _ _) => throwErrorAt stx "invalic auto tactic, identifier is not allowed"
| stx@(Syntax.node k args) => do
if stx.isAntiquot then
throwErrorAt stx "invalic auto tactic, antiquotation is not allowed"
else
let mut quotedArgs ← `(Array.empty)
for arg in args do
if k == nullKind && Quotation.isAntiquotSplice arg then
throwErrorAt arg "invalic auto tactic, antiquotation is not allowed"
else
let quotedArg ← quoteAutoTactic arg
quotedArgs ← `(Array.push $quotedArgs $quotedArg)
`(Syntax.node $(quote k) $quotedArgs)
| Syntax.atom info val => `(Syntax.atom {} $(quote val))
| Syntax.missing => unreachable!
def declareTacticSyntax (tactic : Syntax) : TermElabM Name :=
withFreshMacroScope do
let name ← MonadQuotation.addMacroScope `_auto
let type := Lean.mkConst `Lean.Syntax
let tactic ← quoteAutoTactic tactic
let val ← elabTerm tactic type
let val ← instantiateMVars val
trace[Elab.autoParam]! val
let decl := Declaration.defnDecl { name := name, lparams := [], type := type, value := val, hints := ReducibilityHints.opaque, isUnsafe := false }
addDecl decl
compileDecl decl
pure name
/-
Expand `optional (binderTactic <|> binderDefault)`
def binderTactic := parser! " := " >> " by " >> tacticParser
def binderDefault := parser! " := " >> termParser
-/
private def expandBinderModifier (type : Syntax) (optBinderModifier : Syntax) : TermElabM Syntax := do
if optBinderModifier.isNone then
pure type
else
let modifier := optBinderModifier[0]
let kind := modifier.getKind
if kind == `Lean.Parser.Term.binderDefault then
let defaultVal := modifier[1]
`(optParam $type $defaultVal)
else if kind == `Lean.Parser.Term.binderTactic then
let tac := modifier[2]
let name ← declareTacticSyntax tac
`(autoParam $type $(mkIdentFrom tac name))
else
throwUnsupportedSyntax
private def getBinderIds (ids : Syntax) : TermElabM (Array Syntax) :=
ids.getArgs.mapM fun id =>
let k := id.getKind
if k == identKind || k == `Lean.Parser.Term.hole then
pure id
else
throwErrorAt id "identifier or `_` expected"
/-
Recall that
```
def typeSpec := parser! " : " >> termParser
def optType : Parser := optional typeSpec
``` -/
def expandOptType (ref : Syntax) (optType : Syntax) : Syntax :=
if optType.isNone then
mkHole ref
else
optType[0][1]
private def matchBinder (stx : Syntax) : TermElabM (Array BinderView) :=
match stx with
| Syntax.node k args => do
if k == `Lean.Parser.Term.simpleBinder then
-- binderIdent+ >> optType
let ids ← getBinderIds args[0]
let type := expandOptType stx args[1]
ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.default }
else if k == `Lean.Parser.Term.explicitBinder then
-- `(` binderIdent+ binderType (binderDefault <|> binderTactic)? `)`
let ids ← getBinderIds args[1]
let type := expandBinderType stx args[2]
let optModifier := args[3]
let type ← expandBinderModifier type optModifier
ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.default }
else if k == `Lean.Parser.Term.implicitBinder then
-- `{` binderIdent+ binderType `}`
let ids ← getBinderIds args[1]
let type := expandBinderType stx args[2]
ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.implicit }
else if k == `Lean.Parser.Term.instBinder then
-- `[` optIdent type `]`
let id ← expandOptIdent args[1]
let type := args[2]
pure #[ { id := id, type := type, bi := BinderInfo.instImplicit } ]
else
throwUnsupportedSyntax
| _ => throwUnsupportedSyntax
private def registerFailedToInferBinderTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit :=
registerCustomErrorIfMVar type ref "failed to infer binder type"
private partial def elabBinderViews (binderViews : Array BinderView)
(i : Nat) (fvars : Array Expr) (lctx : LocalContext) (localInsts : LocalInstances) : TermElabM (Array Expr × LocalContext × LocalInstances) :=
if h : i < binderViews.size then
let binderView := binderViews.get ⟨i, h⟩
withRef binderView.type $ withLCtx lctx localInsts do
let type ← elabType binderView.type
registerFailedToInferBinderTypeInfo type binderView.type
let fvarId ← mkFreshFVarId
let fvar := mkFVar fvarId
let fvars := fvars.push fvar
let lctx := lctx.mkLocalDecl fvarId binderView.id.getId type binderView.bi
match (← isClass? type) with
| none => elabBinderViews binderViews (i+1) fvars lctx localInsts
| some className =>
resettingSynthInstanceCache do
let localInsts := localInsts.push { className := className, fvar := mkFVar fvarId }
elabBinderViews binderViews (i+1) fvars lctx localInsts
else
pure (fvars, lctx, localInsts)
private partial def elabBindersAux (binders : Array Syntax)
(i : Nat) (fvars : Array Expr) (lctx : LocalContext) (localInsts : LocalInstances) : TermElabM (Array Expr × LocalContext × LocalInstances) := do
if h : i < binders.size then
let binderViews ← matchBinder (binders.get ⟨i, h⟩)
let (fvars, lctx, localInsts) ← elabBinderViews binderViews 0 fvars lctx localInsts
elabBindersAux binders (i+1) fvars lctx localInsts
else
pure (fvars, lctx, localInsts)
/--
Elaborate the given binders (i.e., `Syntax` objects for `simpleBinder <|> bracketedBinder`),
update the local context, set of local instances, reset instance chache (if needed), and then
execute `x` with the updated context. -/
def elabBinders {α} (binders : Array Syntax) (x : Array Expr → TermElabM α) : TermElabM α :=
withoutPostponingUniverseConstraints do
if binders.isEmpty then
x #[]
else
let lctx ← getLCtx
let localInsts ← getLocalInstances
let (fvars, lctx, newLocalInsts) ← elabBindersAux binders 0 #[] lctx localInsts
resettingSynthInstanceCacheWhen (newLocalInsts.size > localInsts.size) $ withLCtx lctx newLocalInsts $
x fvars
@[inline] def elabBinder {α} (binder : Syntax) (x : Expr → TermElabM α) : TermElabM α :=
elabBinders #[binder] (fun fvars => x (fvars.get! 0))
@[builtinTermElab «forall»] def elabForall : TermElab := fun stx _ =>
match_syntax stx with
| `(forall $binders*, $term) =>
elabBinders binders fun xs => do
let e ← elabType term
mkForallFVars xs e
| _ => throwUnsupportedSyntax
@[builtinTermElab arrow] def elabArrow : TermElab :=
adaptExpander fun stx => match_syntax stx with
| `($dom:term -> $rng) => `(forall (a : $dom), $rng)
| _ => throwUnsupportedSyntax
@[builtinTermElab depArrow] def elabDepArrow : TermElab := fun stx _ =>
-- bracketedBinder `->` term
let binder := stx[0]
let term := stx[2]
elabBinders #[binder] fun xs => do
mkForallFVars xs (← elabType term)
/--
Auxiliary functions for converting `Term.app ... (Term.app id_1 id_2) ... id_n` into `#[id_1, ..., id_m]`
It is used at `expandFunBinders`. -/
private partial def getFunBinderIds? (stx : Syntax) : TermElabM (Option (Array Syntax)) :=
let rec loop (idOnly : Bool) (stx : Syntax) (acc : Array Syntax) :=
match_syntax stx with
| `($f $a) => do
if idOnly then
pure none
else
let (some acc) ← loop false f acc | pure none
loop true a acc
| `(_) => do let ident ← mkFreshIdent stx; pure (some (acc.push ident))
| `($id:ident) => pure (some (acc.push id))
| _ => pure none
loop false stx #[]
/--
Auxiliary function for expanding `fun` notation binders. Recall that `fun` parser is defined as
```
def funBinder : Parser := implicitBinder <|> instBinder <|> termParser maxPrec
parser! unicodeSymbol "λ" "fun" >> many1 funBinder >> "=>" >> termParser
```
to allow notation such as `fun (a, b) => a + b`, where `(a, b)` should be treated as a pattern.
The result is a pair `(explicitBinders, newBody)`, where `explicitBinders` is syntax of the form
```
`(` ident `:` term `)`
```
which can be elaborated using `elabBinders`, and `newBody` is the updated `body` syntax.
We update the `body` syntax when expanding the pattern notation.
Example: `fun (a, b) => a + b` expands into `fun _a_1 => match _a_1 with | (a, b) => a + b`.
See local function `processAsPattern` at `expandFunBindersAux`.
The resulting `Bool` is true if a pattern was found. We use it "mark" a macro expansion. -/
partial def expandFunBinders (binders : Array Syntax) (body : Syntax) : TermElabM (Array Syntax × Syntax × Bool) :=
let rec loop (body : Syntax) (i : Nat) (newBinders : Array Syntax) := do
if h : i < binders.size then
let binder := binders.get ⟨i, h⟩
let processAsPattern : Unit → TermElabM (Array Syntax × Syntax × Bool) := fun _ => do
let pattern := binder
let major ← mkFreshIdent binder
let (binders, newBody, _) ← loop body (i+1) (newBinders.push $ mkExplicitBinder major (mkHole binder))
let newBody ← `(match $major:ident with | $pattern => $newBody)
pure (binders, newBody, true)
match binder with
| Syntax.node `Lean.Parser.Term.implicitBinder _ => loop body (i+1) (newBinders.push binder)
| Syntax.node `Lean.Parser.Term.instBinder _ => loop body (i+1) (newBinders.push binder)
| Syntax.node `Lean.Parser.Term.explicitBinder _ => loop body (i+1) (newBinders.push binder)
| Syntax.node `Lean.Parser.Term.simpleBinder _ => loop body (i+1) (newBinders.push binder)
| Syntax.node `Lean.Parser.Term.hole _ =>
let ident ← mkFreshIdent binder
let type := binder
loop body (i+1) (newBinders.push $ mkExplicitBinder ident type)
| Syntax.node `Lean.Parser.Term.paren args =>
-- `(` (termParser >> parenSpecial)? `)`
-- parenSpecial := (tupleTail <|> typeAscription)?
let binderBody := binder[1]
if binderBody.isNone then processAsPattern ()
else
let idents := binderBody[0]
let special := binderBody[1]
if special.isNone then processAsPattern ()
else if special[0].getKind != `Lean.Parser.Term.typeAscription then
processAsPattern ()
else
-- typeAscription := `:` term
let type := special[0][1]
match (← getFunBinderIds? idents) with
| some idents => loop body (i+1) (newBinders ++ idents.map (fun ident => mkExplicitBinder ident type))
| none => processAsPattern ()
| Syntax.ident _ _ _ _ =>
let type := mkHole binder
loop body (i+1) (newBinders.push $ mkExplicitBinder binder type)
| _ => processAsPattern ()
else
pure (newBinders, body, false)
loop body 0 #[]
namespace FunBinders
structure State :=
(fvars : Array Expr := #[])
(lctx : LocalContext)
(localInsts : LocalInstances)
(expectedType? : Option Expr := none)
private def propagateExpectedType (fvar : Expr) (fvarType : Expr) (s : State) : TermElabM State := do
match s.expectedType? with
| none => pure s
| some expectedType =>
let expectedType ← whnfForall expectedType
match expectedType with
| Expr.forallE _ d b _ =>
isDefEq fvarType d
let b := b.instantiate1 fvar
pure { s with expectedType? := some b }
| _ => pure { s with expectedType? := none }
private partial def elabFunBinderViews (binderViews : Array BinderView) (i : Nat) (s : State) : TermElabM State :=
if h : i < binderViews.size then
let binderView := binderViews.get ⟨i, h⟩
withRef binderView.type $ withLCtx s.lctx s.localInsts do
let type ← elabType binderView.type
registerFailedToInferBinderTypeInfo type binderView.type
let fvarId ← mkFreshFVarId
let fvar := mkFVar fvarId
let s := { s with fvars := s.fvars.push fvar }
-- dbgTrace (toString binderView.id.getId ++ " : " ++ toString type)
/-
We do **not** want to support default and auto arguments in lambda abstractions.
Example: `fun (x : Nat := 10) => x+1`.
We do not believe this is an useful feature, and it would complicate the logic here.
-/
let lctx := s.lctx.mkLocalDecl fvarId binderView.id.getId type binderView.bi
let s ← withRef binderView.id $ propagateExpectedType fvar type s
let s := { s with lctx := lctx }
match (← isClass? type) with
| none => elabFunBinderViews binderViews (i+1) s
| some className =>
resettingSynthInstanceCache do
let localInsts := s.localInsts.push { className := className, fvar := mkFVar fvarId }
elabFunBinderViews binderViews (i+1) { s with localInsts := localInsts }
else
pure s
partial def elabFunBindersAux (binders : Array Syntax) (i : Nat) (s : State) : TermElabM State := do
if h : i < binders.size then
let binderViews ← matchBinder (binders.get ⟨i, h⟩)
let s ← elabFunBinderViews binderViews 0 s
elabFunBindersAux binders (i+1) s
else
pure s
end FunBinders
def elabFunBinders {α} (binders : Array Syntax) (expectedType? : Option Expr) (x : Array Expr → Option Expr → TermElabM α) : TermElabM α :=
if binders.isEmpty then
x #[] expectedType?
else do
let lctx ← getLCtx
let localInsts ← getLocalInstances
let s ← FunBinders.elabFunBindersAux binders 0 { lctx := lctx, localInsts := localInsts, expectedType? := expectedType? }
resettingSynthInstanceCacheWhen (s.localInsts.size > localInsts.size) $ withLCtx s.lctx s.localInsts $
x s.fvars s.expectedType?
/- Helper function for `expandEqnsIntoMatch` -/
private def getMatchAltNumPatterns (matchAlts : Syntax) : Nat :=
let alt0 := matchAlts[1][0]
let pats := alt0[0].getSepArgs
pats.size
/- Helper function for `expandMatchAltsIntoMatch` -/
private def expandMatchAltsIntoMatchAux (ref : Syntax) (matchAlts : Syntax) (matchTactic : Bool) : Nat → Array Syntax → MacroM Syntax
| 0, discrs =>
pure $ Syntax.node (if matchTactic then `Lean.Parser.Tactic.match else `Lean.Parser.Term.match)
#[mkAtomFrom ref "match ", mkNullNode discrs, mkNullNode, mkAtomFrom ref " with ", matchAlts]
| n+1, discrs => withFreshMacroScope do
let x ← `(x)
let discrs := if discrs.isEmpty then discrs else discrs.push $ mkAtomFrom ref ", "
let discrs := discrs.push $ Syntax.node `Lean.Parser.Term.matchDiscr #[mkNullNode, x]
let body ← expandMatchAltsIntoMatchAux ref matchAlts matchTactic n discrs
if matchTactic then
`(tactic| intro $x:term; $body:tactic)
else
`(@fun $x => $body)
/--
Expand `matchAlts` syntax into a full `match`-expression.
Example
```
| 0, true => alt_1
| i, _ => alt_2
```
expands intro (for tactic == false)
```
fun x_1 x_2 =>
match x_1, x_2 with
| 0, true => alt_1
| i, _ => alt_2
```
and (for tactic == true)
```
intro x_1; intro x_2;
match x_1, x_2 with
| 0, true => alt_1
| i, _ => alt_2
```
-/
def expandMatchAltsIntoMatch (ref : Syntax) (matchAlts : Syntax) (tactic := false) : MacroM Syntax :=
expandMatchAltsIntoMatchAux ref matchAlts tactic (getMatchAltNumPatterns matchAlts) #[]
def expandMatchAltsIntoMatchTactic (ref : Syntax) (matchAlts : Syntax) : MacroM Syntax :=
expandMatchAltsIntoMatchAux ref matchAlts true (getMatchAltNumPatterns matchAlts) #[]
@[builtinTermElab «fun»] def elabFun : TermElab := fun stx expectedType? => match_syntax stx with
| `(fun $binders* => $body) => do
let (binders, body, expandedPattern) ← expandFunBinders binders body
if expandedPattern then
let newStx ← `(fun $binders* => $body)
withMacroExpansion stx newStx $ elabTerm newStx expectedType?
else
elabFunBinders binders expectedType? fun xs expectedType? => do
/- We ensure the expectedType here since it will force coercions to be applied if needed.
If we just use `elabTerm`, then we will need to a coercion `Coe (α → β) (α → δ)` whenever there is a coercion `Coe β δ`,
and another instance for the dependent version. -/
let e ← elabTermEnsuringType body expectedType?
mkLambdaFVars xs e
| `(fun $m:matchAlts) => do
let stxNew ← liftMacroM $ expandMatchAltsIntoMatch stx m
withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?
| _ => throwUnsupportedSyntax
/- If `useLetExpr` is true, then a kernel let-expression `let x : type := val; body` is created.
Otherwise, we create a term of the form `(fun (x : type) => body) val`
The default elaboration order is `binders`, `typeStx`, `valStx`, and `body`.
If `elabBodyFirst == true`, then we use the order `binders`, `typeStx`, `body`, and `valStx`. -/
def elabLetDeclAux (n : Name) (binders : Array Syntax) (typeStx : Syntax) (valStx : Syntax) (body : Syntax)
(expectedType? : Option Expr) (useLetExpr : Bool) (elabBodyFirst : Bool) : TermElabM Expr := do
let (type, val, arity) ← elabBinders binders fun xs => do
let type ← elabType typeStx
registerCustomErrorIfMVar type typeStx "failed to infer 'let' declaration type"
if elabBodyFirst then
let type ← mkForallFVars xs type
let val ← mkFreshExprMVar type
pure (type, val, xs.size)
else
let val ← elabTermEnsuringType valStx type
let type ← mkForallFVars xs type
let val ← mkLambdaFVars xs val
pure (type, val, xs.size)
trace[Elab.let.decl]! "{n} : {type} := {val}"
let result ←
if useLetExpr then
withLetDecl n type val fun x => do
let body ← elabTerm body expectedType?
let body ← instantiateMVars body
mkLetFVars #[x] body
else
let f ← withLocalDecl n BinderInfo.default type fun x => do
let body ← elabTerm body expectedType?
let body ← instantiateMVars body
mkLambdaFVars #[x] body
pure $ mkApp f val
if elabBodyFirst then
forallBoundedTelescope type arity fun xs type => do
let valResult ← elabTermEnsuringType valStx type
let valResult ← mkLambdaFVars xs valResult
unless (← isDefEq val valResult) do
throwError "unexpected error when elaborating 'let'"
pure result
structure LetIdDeclView :=
(id : Name)
(binders : Array Syntax)
(type : Syntax)
(value : Syntax)
def mkLetIdDeclView (letIdDecl : Syntax) : LetIdDeclView :=
-- `letIdDecl` is of the form `ident >> many bracketedBinder >> optType >> " := " >> termParser
let id := letIdDecl[0].getId
let binders := letIdDecl[1].getArgs
let optType := letIdDecl[2]
let type := expandOptType letIdDecl optType
let value := letIdDecl[4]
{ id := id, binders := binders, type := type, value := value }
private def expandLetEqnsDeclVal (ref : Syntax) (alts : Syntax) : Nat → Array Syntax → MacroM Syntax
| 0, discrs =>
pure $ Syntax.node `Lean.Parser.Term.match
#[mkAtomFrom ref "match ", mkNullNode discrs, mkNullNode, mkAtomFrom ref " with ", alts]
| n+1, discrs => withFreshMacroScope do
let x ← `(x)
let discrs := if discrs.isEmpty then discrs else discrs.push $ mkAtomFrom ref ", "
let discrs := discrs.push $ Syntax.node `Lean.Parser.Term.matchDiscr #[mkNullNode, x]
let body ← expandLetEqnsDeclVal ref alts n discrs
`(fun $x => $body)
def expandLetEqnsDecl (letDecl : Syntax) : MacroM Syntax := do
let ref := letDecl
let matchAlts := letDecl[3]
let val ← expandMatchAltsIntoMatch ref matchAlts
pure $ Syntax.node `Lean.Parser.Term.letIdDecl #[letDecl[0], letDecl[1], letDecl[2], mkAtomFrom ref " := ", val]
def elabLetDeclCore (stx : Syntax) (expectedType? : Option Expr) (useLetExpr : Bool) (elabBodyFirst : Bool) : TermElabM Expr := do
let ref := stx
let letDecl := stx[1][0]
let body := stx[3]
if letDecl.getKind == `Lean.Parser.Term.letIdDecl then
let { id := id, binders := binders, type := type, value := val } := mkLetIdDeclView letDecl
elabLetDeclAux id binders type val body expectedType? useLetExpr elabBodyFirst
else if letDecl.getKind == `Lean.Parser.Term.letPatDecl then
-- node `Lean.Parser.Term.letPatDecl $ try (termParser >> pushNone >> optType >> " := ") >> termParser
let pat := letDecl[0]
let optType := letDecl[2]
let type := expandOptType stx optType
let val := letDecl[4]
let stxNew ← `(let x : $type := $val; match x with | $pat => $body)
let stxNew := match useLetExpr, elabBodyFirst with
| true, false => stxNew
| true, true => stxNew.setKind `Lean.Parser.Term.«let*»
| false, true => stxNew.setKind `Lean.Parser.Term.«let!»
| false, false => unreachable!
withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?
else if letDecl.getKind == `Lean.Parser.Term.letEqnsDecl then
let letDeclIdNew ← liftMacroM $ expandLetEqnsDecl letDecl
let declNew := stx[1].setArg 0 letDeclIdNew
let stxNew := stx.setArg 1 declNew
withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?
else
throwUnsupportedSyntax
@[builtinTermElab «let»] def elabLetDecl : TermElab :=
fun stx expectedType? => elabLetDeclCore stx expectedType? true false
@[builtinTermElab «let!»] def elabLetBangDecl : TermElab :=
fun stx expectedType? => elabLetDeclCore stx expectedType? false false
@[builtinTermElab «let*»] def elabLetStarDecl : TermElab :=
fun stx expectedType? => elabLetDeclCore stx expectedType? true true
builtin_initialize registerTraceClass `Elab.let
end Lean.Elab.Term
|
81634149fdac8e6f03937dc8ee6f5d1e8f43d23b | 11e28114d9553ecd984ac4819661ffce3068bafe | /src/examples/datatypes.lean | e32cc6c12d28c0cdfdf4cfb089203afdcf46be79 | [
"MIT"
] | permissive | EdAyers/lean-subtask | 9a26eb81f0c8576effed4ca94342ae1281445c59 | 04ac5a6c3bc3bfd190af4d6dcce444ddc8914e4b | refs/heads/master | 1,586,516,665,621 | 1,558,701,948,000 | 1,558,701,948,000 | 160,983,035 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 2,299 | lean | /- Author: E.W.Ayers © 2019 -/
import ..equate
open robot
section
universe u
open list
variables {α : Type u} {a h : α} {l t s : list α}
@[equate] def nil_append : [] ++ l = l := rfl
@[equate] def append_cons : (h::t) ++ l = h:: (t ++ l) := rfl
@[equate] def reverse_def : reverse l = reverse_core l [] := rfl
@[equate] def rev_nil : reverse ([] : list α) = [] := rfl
@[equate] def reverse_core_def : reverse_core (h :: t) l = reverse_core t (h :: l) := rfl
@[equate] def append_nil : l ++ [] = l := begin induction l, refl, simp end
@[equate] theorem rev_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] :=
begin
have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]),
intro l₁, induction l₁, intros, refl,
intro,
equate,
equate
end
open list
@[equate] lemma assoc : (l ++ s) ++ t = l ++ (s ++ t) :=
begin
induction l with lh lt,
equate,
equate
end -- `induction l; simp *`
lemma rev_app_rev : reverse (l ++ s) = reverse s ++ reverse l :=
begin
induction l with h l H,
equate,
equate
end
end
namespace my_nat
inductive my_nat : Type
|zero : my_nat
|succ : my_nat → my_nat
open my_nat
instance : has_zero my_nat := ⟨my_nat.zero⟩
variables {x y z : my_nat}
def add : my_nat → my_nat → my_nat
|(my_nat.zero) x := x
|(my_nat.succ x) y := my_nat.succ (add x y)
instance : has_add my_nat := ⟨add⟩
local notation `s(` x `)` := my_nat.succ x
@[equate] lemma add_zero : 0 + x = x := rfl
@[equate] lemma add_succ : (s(x)) + y = s(x + y) := rfl
@[equate] lemma nat_assoc {x y z : my_nat} : x + ( y + z ) = (x + y) + z :=
begin
induction x with x,
equate,
equate
end
@[equate] lemma succ_add : y + (s(x)) = s(y + x) := begin
induction y with y, equate, equate
end
@[equate] lemma zero_add : x + my_nat.zero = x := begin
induction x, equate, symmetry, equate -- [FIXME] remove symmetry
end
@[equate] lemma add_comm : x + y = y + x := begin
induction x with x,
rw zero_add, refl,
equate
end
end my_nat |
2e3b4c947b607100bac0a261a65cc7d34eeadb4d | 4950bf76e5ae40ba9f8491647d0b6f228ddce173 | /src/data/equiv/mul_add.lean | 9700fc1d5f6b1747c9caf9021bcc0086f5a98ae0 | [
"Apache-2.0"
] | permissive | ntzwq/mathlib | ca50b21079b0a7c6781c34b62199a396dd00cee2 | 36eec1a98f22df82eaccd354a758ef8576af2a7f | refs/heads/master | 1,675,193,391,478 | 1,607,822,996,000 | 1,607,822,996,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,428 | 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, Callum Sutton, Yury Kudryashov
-/
import algebra.group.hom
import algebra.group.type_tags
import algebra.group.units_hom
/-!
# Multiplicative and additive equivs
In this file we define two extensions of `equiv` called `add_equiv` and `mul_equiv`, which are
datatypes representing isomorphisms of `add_monoid`s/`add_group`s and `monoid`s/`group`s.
## Notations
The extended equivs all have coercions to functions, and the coercions are the canonical
notation when treating the isomorphisms as maps.
## Implementation notes
The fields for `mul_equiv`, `add_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as
these are deprecated.
## Tags
equiv, mul_equiv, add_equiv
-/
variables {A : Type*} {B : Type*} {M : Type*} {N : Type*} {P : Type*} {G : Type*} {H : Type*}
set_option old_structure_cmd true
/-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/
structure add_equiv (A B : Type*) [has_add A] [has_add B] extends A ≃ B, add_hom A B
/-- The `equiv` underlying an `add_equiv`. -/
add_decl_doc add_equiv.to_equiv
/-- The `add_hom` underlying a `add_equiv`. -/
add_decl_doc add_equiv.to_add_hom
/-- `mul_equiv α β` is the type of an equiv `α ≃ β` which preserves multiplication. -/
@[to_additive]
structure mul_equiv (M N : Type*) [has_mul M] [has_mul N] extends M ≃ N, mul_hom M N
/-- The `equiv` underlying a `mul_equiv`. -/
add_decl_doc mul_equiv.to_equiv
/-- The `mul_hom` underlying a `mul_equiv`. -/
add_decl_doc mul_equiv.to_mul_hom
infix ` ≃* `:25 := mul_equiv
infix ` ≃+ `:25 := add_equiv
namespace mul_equiv
@[to_additive]
instance [has_mul M] [has_mul N] : has_coe_to_fun (M ≃* N) := ⟨_, mul_equiv.to_fun⟩
variables [has_mul M] [has_mul N] [has_mul P]
@[simp, to_additive]
lemma to_fun_apply {f : M ≃* N} {m : M} : f.to_fun m = f m := rfl
@[simp, to_additive]
lemma to_equiv_apply {f : M ≃* N} {m : M} : f.to_equiv m = f m := rfl
/-- A multiplicative isomorphism preserves multiplication (canonical form). -/
@[simp, to_additive]
lemma map_mul (f : M ≃* N) : ∀ x y, f (x * y) = f x * f y := f.map_mul'
/-- Makes a multiplicative isomorphism from a bijection which preserves multiplication. -/
@[to_additive "Makes an additive isomorphism from a bijection which preserves addition."]
def mk' (f : M ≃ N) (h : ∀ x y, f (x * y) = f x * f y) : M ≃* N :=
⟨f.1, f.2, f.3, f.4, h⟩
@[to_additive]
protected lemma bijective (e : M ≃* N) : function.bijective e := e.to_equiv.bijective
@[to_additive]
protected lemma injective (e : M ≃* N) : function.injective e := e.to_equiv.injective
@[to_additive]
protected lemma surjective (e : M ≃* N) : function.surjective e := e.to_equiv.surjective
/-- The identity map is a multiplicative isomorphism. -/
@[refl, to_additive "The identity map is an additive isomorphism."]
def refl (M : Type*) [has_mul M] : M ≃* M :=
{ map_mul' := λ _ _, rfl,
..equiv.refl _}
instance : inhabited (M ≃* M) := ⟨refl M⟩
/-- The inverse of an isomorphism is an isomorphism. -/
@[symm, to_additive "The inverse of an isomorphism is an isomorphism."]
def symm (h : M ≃* N) : N ≃* M :=
{ map_mul' := λ n₁ n₂, h.injective $
begin
have : ∀ x, h (h.to_equiv.symm.to_fun x) = x := h.to_equiv.apply_symm_apply,
simp only [this, h.map_mul]
end,
.. h.to_equiv.symm}
/-- See Note [custom simps projection] -/
@[to_additive add_equiv.simps.inv_fun "See Note [custom simps projection]"]
def simps.inv_fun (e : M ≃* N) : N → M := e.symm
initialize_simps_projections add_equiv (to_fun → apply, inv_fun → symm_apply)
initialize_simps_projections mul_equiv (to_fun → apply, inv_fun → symm_apply)
@[simp, to_additive]
theorem to_equiv_symm (f : M ≃* N) : f.symm.to_equiv = f.to_equiv.symm := rfl
@[simp, to_additive]
theorem coe_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃) = f := rfl
@[simp, to_additive]
theorem coe_symm_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃).symm = g := rfl
/-- Transitivity of multiplication-preserving isomorphisms -/
@[trans, to_additive "Transitivity of addition-preserving isomorphisms"]
def trans (h1 : M ≃* N) (h2 : N ≃* P) : (M ≃* P) :=
{ map_mul' := λ x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y),
by rw [h1.map_mul, h2.map_mul],
..h1.to_equiv.trans h2.to_equiv }
/-- e.right_inv in canonical form -/
@[simp, to_additive]
lemma apply_symm_apply (e : M ≃* N) : ∀ y, e (e.symm y) = y :=
e.to_equiv.apply_symm_apply
/-- e.left_inv in canonical form -/
@[simp, to_additive]
lemma symm_apply_apply (e : M ≃* N) : ∀ x, e.symm (e x) = x :=
e.to_equiv.symm_apply_apply
@[simp, to_additive]
theorem refl_apply (m : M) : refl M m = m := rfl
@[simp, to_additive]
theorem trans_apply (e₁ : M ≃* N) (e₂ : N ≃* P) (m : M) : e₁.trans e₂ m = e₂ (e₁ m) := rfl
@[simp, to_additive] theorem apply_eq_iff_eq (e : M ≃* N) {x y : M} : e x = e y ↔ x = y :=
e.injective.eq_iff
@[to_additive]
lemma apply_eq_iff_symm_apply (e : M ≃* N) {x : M} {y : N} : e x = y ↔ x = e.symm y :=
e.to_equiv.apply_eq_iff_eq_symm_apply
@[to_additive]
lemma symm_apply_eq (e : M ≃* N) {x y} : e.symm x = y ↔ x = e y :=
e.to_equiv.symm_apply_eq
@[to_additive]
lemma eq_symm_apply (e : M ≃* N) {x y} : y = e.symm x ↔ e y = x :=
e.to_equiv.eq_symm_apply
/-- a multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism) -/
@[simp, to_additive]
lemma map_one {M N} [monoid M] [monoid N] (h : M ≃* N) : h 1 = 1 :=
by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul]
@[simp, to_additive]
lemma map_eq_one_iff {M N} [monoid M] [monoid N] (h : M ≃* N) {x : M} :
h x = 1 ↔ x = 1 :=
h.map_one ▸ h.to_equiv.apply_eq_iff_eq
@[to_additive]
lemma map_ne_one_iff {M N} [monoid M] [monoid N] (h : M ≃* N) {x : M} :
h x ≠ 1 ↔ x ≠ 1 :=
⟨mt h.map_eq_one_iff.2, mt h.map_eq_one_iff.1⟩
/-- A bijective `monoid` homomorphism is an isomorphism -/
@[to_additive "A bijective `add_monoid` homomorphism is an isomorphism"]
noncomputable def of_bijective {M N} [monoid M] [monoid N] (f : M →* N)
(hf : function.bijective f) : M ≃* N :=
{ map_mul' := f.map_mul',
..equiv.of_bijective f hf }
/--
Extract the forward direction of a multiplicative equivalence
as a multiplication-preserving function.
-/
@[to_additive "Extract the forward direction of an additive equivalence
as an addition-preserving function."]
def to_monoid_hom {M N} [monoid M] [monoid N] (h : M ≃* N) : (M →* N) :=
{ map_one' := h.map_one, .. h }
@[simp, to_additive]
lemma coe_to_monoid_hom {M N} [monoid M] [monoid N] (e : M ≃* N) :
⇑e.to_monoid_hom = e :=
rfl
@[to_additive]
lemma to_monoid_hom_apply {M N} [monoid M] [monoid N] (e : M ≃* N) (x : M) :
e.to_monoid_hom x = e x :=
rfl
/-- A multiplicative equivalence of groups preserves inversion. -/
@[simp, to_additive]
lemma map_inv [group G] [group H] (h : G ≃* H) (x : G) : h x⁻¹ = (h x)⁻¹ :=
h.to_monoid_hom.map_inv x
/-- Two multiplicative isomorphisms agree if they are defined by the
same underlying function. -/
@[ext, to_additive
"Two additive isomorphisms agree if they are defined by the same underlying function."]
lemma ext {f g : mul_equiv M N} (h : ∀ x, f x = g x) : f = g :=
begin
have h₁ : f.to_equiv = g.to_equiv := equiv.ext h,
cases f, cases g, congr,
{ exact (funext h) },
{ exact congr_arg equiv.inv_fun h₁ }
end
@[to_additive] lemma to_monoid_hom_injective
{M N} [monoid M] [monoid N] : function.injective (to_monoid_hom : (M ≃* N) → M →* N) :=
λ f g h, mul_equiv.ext (monoid_hom.ext_iff.1 h)
attribute [ext] add_equiv.ext
end mul_equiv
-- We don't use `to_additive` to generate definition because it fails to tell Lean about
-- equational lemmas
/-- Given a pair of additive monoid homomorphisms `f`, `g` such that `g.comp f = id` and
`f.comp g = id`, returns an additive equivalence with `to_fun = f` and `inv_fun = g`. This
constructor is useful if the underlying type(s) have specialized `ext` lemmas for additive
monoid homomorphisms. -/
def add_monoid_hom.to_add_equiv [add_monoid M] [add_monoid N] (f : M →+ N) (g : N →+ M)
(h₁ : g.comp f = add_monoid_hom.id _) (h₂ : f.comp g = add_monoid_hom.id _) :
M ≃+ N :=
{ to_fun := f,
inv_fun := g,
left_inv := add_monoid_hom.congr_fun h₁,
right_inv := add_monoid_hom.congr_fun h₂,
map_add' := f.map_add }
/-- Given a pair of monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`,
returns an multiplicative equivalence with `to_fun = f` and `inv_fun = g`. This constructor is
useful if the underlying type(s) have specialized `ext` lemmas for monoid homomorphisms. -/
@[to_additive]
def monoid_hom.to_mul_equiv [monoid M] [monoid N] (f : M →* N) (g : N →* M)
(h₁ : g.comp f = monoid_hom.id _) (h₂ : f.comp g = monoid_hom.id _) :
M ≃* N :=
{ to_fun := f,
inv_fun := g,
left_inv := monoid_hom.congr_fun h₁,
right_inv := monoid_hom.congr_fun h₂,
map_mul' := f.map_mul }
@[simp, to_additive]
lemma monoid_hom.coe_to_mul_equiv [monoid M] [monoid N] (f : M →* N) (g : N →* M) (h₁ h₂) :
⇑(f.to_mul_equiv g h₁ h₂) = f := rfl
/-- An additive equivalence of additive groups preserves subtraction. -/
lemma add_equiv.map_sub [add_group A] [add_group B] (h : A ≃+ B) (x y : A) :
h (x - y) = h x - h y :=
h.to_add_monoid_hom.map_sub x y
instance add_equiv.inhabited {M : Type*} [has_add M] : inhabited (M ≃+ M) := ⟨add_equiv.refl M⟩
/-- A group is isomorphic to its group of units. -/
@[to_additive to_add_units "An additive group is isomorphic to its group of additive units"]
def to_units {G} [group G] : G ≃* units G :=
{ to_fun := λ x, ⟨x, x⁻¹, mul_inv_self _, inv_mul_self _⟩,
inv_fun := coe,
left_inv := λ x, rfl,
right_inv := λ u, units.ext rfl,
map_mul' := λ x y, units.ext rfl }
namespace units
variables [monoid M] [monoid N] [monoid P]
/-- A multiplicative equivalence of monoids defines a multiplicative equivalence
of their groups of units. -/
def map_equiv (h : M ≃* N) : units M ≃* units N :=
{ inv_fun := map h.symm.to_monoid_hom,
left_inv := λ u, ext $ h.left_inv u,
right_inv := λ u, ext $ h.right_inv u,
.. map h.to_monoid_hom }
/-- Left multiplication by a unit of a monoid is a permutation of the underlying type. -/
@[to_additive "Left addition of an additive unit is a permutation of the underlying type."]
def mul_left (u : units M) : equiv.perm M :=
{ to_fun := λx, u * x,
inv_fun := λx, ↑u⁻¹ * x,
left_inv := u.inv_mul_cancel_left,
right_inv := u.mul_inv_cancel_left }
@[simp, to_additive]
lemma coe_mul_left (u : units M) : ⇑u.mul_left = (*) u := rfl
@[simp, to_additive]
lemma mul_left_symm (u : units M) : u.mul_left.symm = u⁻¹.mul_left :=
equiv.ext $ λ x, rfl
/-- Right multiplication by a unit of a monoid is a permutation of the underlying type. -/
@[to_additive "Right addition of an additive unit is a permutation of the underlying type."]
def mul_right (u : units M) : equiv.perm M :=
{ to_fun := λx, x * u,
inv_fun := λx, x * ↑u⁻¹,
left_inv := λ x, mul_inv_cancel_right x u,
right_inv := λ x, inv_mul_cancel_right x u }
@[simp, to_additive]
lemma coe_mul_right (u : units M) : ⇑u.mul_right = λ x : M, x * u := rfl
@[simp, to_additive]
lemma mul_right_symm (u : units M) : u.mul_right.symm = u⁻¹.mul_right :=
equiv.ext $ λ x, rfl
end units
namespace equiv
section group
variables [group G]
/-- Left multiplication in a `group` is a permutation of the underlying type. -/
@[to_additive "Left addition in an `add_group` is a permutation of the underlying type."]
protected def mul_left (a : G) : perm G := (to_units a).mul_left
@[simp, to_additive]
lemma coe_mul_left (a : G) : ⇑(equiv.mul_left a) = (*) a := rfl
@[simp, to_additive]
lemma mul_left_symm (a : G) : (equiv.mul_left a).symm = equiv.mul_left a⁻¹ :=
ext $ λ x, rfl
/-- Right multiplication in a `group` is a permutation of the underlying type. -/
@[to_additive "Right addition in an `add_group` is a permutation of the underlying type."]
protected def mul_right (a : G) : perm G := (to_units a).mul_right
@[simp, to_additive]
lemma coe_mul_right (a : G) : ⇑(equiv.mul_right a) = λ x, x * a := rfl
@[simp, to_additive]
lemma mul_right_symm (a : G) : (equiv.mul_right a).symm = equiv.mul_right a⁻¹ :=
ext $ λ x, rfl
variable (G)
/-- Inversion on a `group` is a permutation of the underlying type. -/
@[to_additive "Negation on an `add_group` is a permutation of the underlying type."]
protected def inv : perm G :=
{ to_fun := λa, a⁻¹,
inv_fun := λa, a⁻¹,
left_inv := assume a, inv_inv a,
right_inv := assume a, inv_inv a }
variable {G}
@[simp, to_additive]
lemma coe_inv : ⇑(equiv.inv G) = has_inv.inv := rfl
@[simp, to_additive]
lemma inv_symm : (equiv.inv G).symm = equiv.inv G := rfl
end group
end equiv
section type_tags
/-- Reinterpret `G ≃+ H` as `multiplicative G ≃* multiplicative H`. -/
def add_equiv.to_multiplicative [add_monoid G] [add_monoid H] :
(G ≃+ H) ≃ (multiplicative G ≃* multiplicative H) :=
{ to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative, f.symm.to_add_monoid_hom.to_multiplicative, f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `G ≃* H` as `additive G ≃+ additive H`. -/
def mul_equiv.to_additive [monoid G] [monoid H] :
(G ≃* H) ≃ (additive G ≃+ additive H) :=
{ to_fun := λ f, ⟨f.to_monoid_hom.to_additive, f.symm.to_monoid_hom.to_additive, f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_add_monoid_hom, f.symm.to_add_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `additive G ≃+ H` as `G ≃* multiplicative H`. -/
def add_equiv.to_multiplicative' [monoid G] [add_monoid H] :
(additive G ≃+ H) ≃ (G ≃* multiplicative H) :=
{ to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative', f.symm.to_add_monoid_hom.to_multiplicative'', f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `G ≃* multiplicative H` as `additive G ≃+ H` as. -/
def mul_equiv.to_additive' [monoid G] [add_monoid H] :
(G ≃* multiplicative H) ≃ (additive G ≃+ H) :=
add_equiv.to_multiplicative'.symm
/-- Reinterpret `G ≃+ additive H` as `multiplicative G ≃* H`. -/
def add_equiv.to_multiplicative'' [add_monoid G] [monoid H] :
(G ≃+ additive H) ≃ (multiplicative G ≃* H) :=
{ to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative'', f.symm.to_add_monoid_hom.to_multiplicative', f.3, f.4, f.5⟩,
inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, by { ext, refl, }, }
/-- Reinterpret `multiplicative G ≃* H` as `G ≃+ additive H` as. -/
def mul_equiv.to_additive'' [add_monoid G] [monoid H] :
(multiplicative G ≃* H) ≃ (G ≃+ additive H) :=
add_equiv.to_multiplicative''.symm
end type_tags
|
cf9320eee5ee7115ecfb2f4c3c9763fb9eb15d4f | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/geometry/euclidean/basic.lean | 2fd08526903dd49df9e56f9730813e82820b88ff | [
"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 | 57,380 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Manuel Candales
-/
import analysis.inner_product_space.projection
import analysis.special_functions.trigonometric.inverse
import algebra.quadratic_discriminant
import linear_algebra.affine_space.finite_dimensional
import analysis.calculus.conformal.normed_space
/-!
# Euclidean spaces
This file makes some definitions and proves very basic geometrical
results about real inner product spaces and Euclidean affine spaces.
Results about real inner product spaces that involve the norm and
inner product but not angles generally go in
`analysis.normed_space.inner_product`. Results with longer
proofs or more geometrical content generally go in separate files.
## Main definitions
* `inner_product_geometry.angle` is the undirected angle between two
vectors.
* `euclidean_geometry.angle`, with notation `∠`, is the undirected
angle determined by three points.
* `euclidean_geometry.orthogonal_projection` is the orthogonal
projection of a point onto an affine subspace.
* `euclidean_geometry.reflection` is the reflection of a point in an
affine subspace.
## Implementation notes
To declare `P` as the type of points in a Euclidean affine space with
`V` as the type of vectors, use `[inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]`. This works better with `out_param` to make
`V` implicit in most cases than having a separate type alias for
Euclidean affine spaces.
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
-/
noncomputable theory
open_locale big_operators
open_locale classical
open_locale real
open_locale real_inner_product_space
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. See `orientation.oangle` for the corresponding oriented angle
definition. -/
def angle (x y : V) : ℝ := real.arccos (inner x y / (∥x∥ * ∥y∥))
lemma continuous_at_angle {x : V × V} (hx1 : x.1 ≠ 0) (hx2 : x.2 ≠ 0) :
continuous_at (λ y : V × V, angle y.1 y.2) x :=
real.continuous_arccos.continuous_at.comp $ continuous_inner.continuous_at.div
((continuous_norm.comp continuous_fst).mul (continuous_norm.comp continuous_snd)).continuous_at
(by simp [hx1, hx2])
lemma angle_smul_smul {c : ℝ} (hc : c ≠ 0) (x y : V) :
angle (c • x) (c • y) = angle x y :=
have c * c ≠ 0, from mul_ne_zero hc hc,
by rw [angle, angle, real_inner_smul_left, inner_smul_right, norm_smul, norm_smul, real.norm_eq_abs,
mul_mul_mul_comm _ (∥x∥), abs_mul_abs_self, ← mul_assoc c c, mul_div_mul_left _ _ this]
@[simp] lemma _root_.linear_isometry.angle_map {E F : Type*}
[inner_product_space ℝ E] [inner_product_space ℝ F] (f : E →ₗᵢ[ℝ] F) (u v : E) :
angle (f u) (f v) = angle u v :=
by rw [angle, angle, f.inner_map_map, f.norm_map, f.norm_map]
lemma is_conformal_map.preserves_angle {E F : Type*}
[inner_product_space ℝ E] [inner_product_space ℝ F]
{f' : E →L[ℝ] F} (h : is_conformal_map f') (u v : E) :
angle (f' u) (f' v) = angle u v :=
begin
obtain ⟨c, hc, li, rfl⟩ := h,
exact (angle_smul_smul hc _ _).trans (li.angle_map _ _)
end
/-- If a real differentiable map `f` is conformal at a point `x`,
then it preserves the angles at that point. -/
lemma conformal_at.preserves_angle {E F : Type*}
[inner_product_space ℝ E] [inner_product_space ℝ F]
{f : E → F} {x : E} {f' : E →L[ℝ] F}
(h : has_fderiv_at f f' x) (H : conformal_at f x) (u v : E) :
angle (f' u) (f' v) = angle u v :=
let ⟨f₁, h₁, c⟩ := H in h₁.unique h ▸ is_conformal_map.preserves_angle c u v
/-- 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_real_inner_div_norm_mul_norm_le_one x y)).1
(abs_le.mp (abs_real_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 [real_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 [←real_inner_self_eq_norm_mul_norm, 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, div_mul_cancel_of_imp],
simp [or_imp_distrib] { contextual := tt },
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_real_inner_div_norm_mul_norm_le_one x y)).1
(abs_le.mp (abs_real_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 _), sq,
real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)),
real_inner_self_eq_norm_mul_norm,
real_inner_self_eq_norm_mul_norm],
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_nf }
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
rw [angle, ← real_inner_div_norm_mul_norm_eq_one_iff, real.arccos_eq_zero, has_le.le.le_iff_eq,
eq_comm],
exact (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2
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
rw [angle, ← real_inner_div_norm_mul_norm_eq_neg_one_iff, real.arccos_eq_pi, has_le.le.le_iff_eq],
exact (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1
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
rcases angle_eq_pi_iff.1 h with ⟨hx, ⟨r, ⟨hr, rfl⟩⟩⟩,
rw [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) : ⟪x, y⟫ = 0 ↔ angle x y = π / 2 :=
iff.symm $ by simp [angle, or_imp_distrib] { contextual := tt }
/-- If the angle between two vectors is π, the inner product equals the negative product
of the norms. -/
lemma inner_eq_neg_mul_norm_of_angle_eq_pi {x y : V} (h : angle x y = π) : ⟪x, y⟫ = - (∥x∥ * ∥y∥) :=
by simp [← cos_angle_mul_norm_mul_norm, h]
/-- If the angle between two vectors is 0, the inner product equals the product of the norms. -/
lemma inner_eq_mul_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) : ⟪x, y⟫ = ∥x∥ * ∥y∥ :=
by simp [← cos_angle_mul_norm_mul_norm, h]
/-- The inner product of two non-zero vectors equals the negative product of their norms
if and only if the angle between the two vectors is π. -/
lemma inner_eq_neg_mul_norm_iff_angle_eq_pi {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
⟪x, y⟫ = - (∥x∥ * ∥y∥) ↔ angle x y = π :=
begin
refine ⟨λ h, _, inner_eq_neg_mul_norm_of_angle_eq_pi⟩,
have h₁ : (∥x∥ * ∥y∥) ≠ 0 := (mul_pos (norm_pos_iff.mpr hx) (norm_pos_iff.mpr hy)).ne',
rw [angle, h, neg_div, div_self h₁, real.arccos_neg_one],
end
/-- The inner product of two non-zero vectors equals the product of their norms
if and only if the angle between the two vectors is 0. -/
lemma inner_eq_mul_norm_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ angle x y = 0 :=
begin
refine ⟨λ h, _, inner_eq_mul_norm_of_angle_eq_zero⟩,
have h₁ : (∥x∥ * ∥y∥) ≠ 0 := (mul_pos (norm_pos_iff.mpr hx) (norm_pos_iff.mpr hy)).ne',
rw [angle, h, div_self h₁, real.arccos_one],
end
/-- If the angle between two vectors is π, the norm of their difference equals
the sum of their norms. -/
lemma norm_sub_eq_add_norm_of_angle_eq_pi {x y : V} (h : angle x y = π) : ∥x - y∥ = ∥x∥ + ∥y∥ :=
begin
rw ← sq_eq_sq (norm_nonneg (x - y)) (add_nonneg (norm_nonneg x) (norm_nonneg y)),
rw [norm_sub_pow_two_real, inner_eq_neg_mul_norm_of_angle_eq_pi h],
ring,
end
/-- If the angle between two vectors is 0, the norm of their sum equals
the sum of their norms. -/
lemma norm_add_eq_add_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) : ∥x + y∥ = ∥x∥ + ∥y∥ :=
begin
rw ← sq_eq_sq (norm_nonneg (x + y)) (add_nonneg (norm_nonneg x) (norm_nonneg y)),
rw [norm_add_pow_two_real, inner_eq_mul_norm_of_angle_eq_zero h],
ring,
end
/-- If the angle between two vectors is 0, the norm of their difference equals
the absolute value of the difference of their norms. -/
lemma norm_sub_eq_abs_sub_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) :
∥x - y∥ = |∥x∥ - ∥y∥| :=
begin
rw [← sq_eq_sq (norm_nonneg (x - y)) (abs_nonneg (∥x∥ - ∥y∥)),
norm_sub_pow_two_real, inner_eq_mul_norm_of_angle_eq_zero h, sq_abs (∥x∥ - ∥y∥)],
ring,
end
/-- The norm of the difference of two non-zero vectors equals the sum of their norms
if and only the angle between the two vectors is π. -/
lemma norm_sub_eq_add_norm_iff_angle_eq_pi {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
∥x - y∥ = ∥x∥ + ∥y∥ ↔ angle x y = π :=
begin
refine ⟨λ h, _, norm_sub_eq_add_norm_of_angle_eq_pi⟩,
rw ← inner_eq_neg_mul_norm_iff_angle_eq_pi hx hy,
obtain ⟨hxy₁, hxy₂⟩ := ⟨norm_nonneg (x - y), add_nonneg (norm_nonneg x) (norm_nonneg y)⟩,
rw [← sq_eq_sq hxy₁ hxy₂, norm_sub_pow_two_real] at h,
calc inner x y = (∥x∥ ^ 2 + ∥y∥ ^ 2 - (∥x∥ + ∥y∥) ^ 2) / 2 : by linarith
... = -(∥x∥ * ∥y∥) : by ring,
end
/-- The norm of the sum of two non-zero vectors equals the sum of their norms
if and only the angle between the two vectors is 0. -/
lemma norm_add_eq_add_norm_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
∥x + y∥ = ∥x∥ + ∥y∥ ↔ angle x y = 0 :=
begin
refine ⟨λ h, _, norm_add_eq_add_norm_of_angle_eq_zero⟩,
rw ← inner_eq_mul_norm_iff_angle_eq_zero hx hy,
obtain ⟨hxy₁, hxy₂⟩ := ⟨norm_nonneg (x + y), add_nonneg (norm_nonneg x) (norm_nonneg y)⟩,
rw [← sq_eq_sq hxy₁ hxy₂, norm_add_pow_two_real] at h,
calc inner x y = ((∥x∥ + ∥y∥) ^ 2 - ∥x∥ ^ 2 - ∥y∥ ^ 2)/ 2 : by linarith
... = ∥x∥ * ∥y∥ : by ring,
end
/-- The norm of the difference of two non-zero vectors equals the absolute value
of the difference of their norms if and only the angle between the two vectors is 0. -/
lemma norm_sub_eq_abs_sub_norm_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
∥x - y∥ = |∥x∥ - ∥y∥| ↔ angle x y = 0 :=
begin
refine ⟨λ h, _, norm_sub_eq_abs_sub_norm_of_angle_eq_zero⟩,
rw ← inner_eq_mul_norm_iff_angle_eq_zero hx hy,
have h1 : ∥x - y∥ ^ 2 = (∥x∥ - ∥y∥) ^ 2, { rw h, exact sq_abs (∥x∥ - ∥y∥) },
rw norm_sub_pow_two_real at h1,
calc inner x y = ((∥x∥ + ∥y∥) ^ 2 - ∥x∥ ^ 2 - ∥y∥ ^ 2)/ 2 : by linarith
... = ∥x∥ * ∥y∥ : by ring,
end
/-- The norm of the sum of two vectors equals the norm of their difference if and only if
the angle between them is π/2. -/
lemma norm_add_eq_norm_sub_iff_angle_eq_pi_div_two (x y : V) :
∥x + y∥ = ∥x - y∥ ↔ angle x y = π / 2 :=
begin
rw [← sq_eq_sq (norm_nonneg (x + y)) (norm_nonneg (x - y)),
← inner_eq_zero_iff_angle_eq_pi_div_two x y, norm_add_pow_two_real, norm_sub_pow_two_real],
split; intro h; linarith,
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 inner_product_geometry
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
local notation `⟪`x`, `y`⟫` := @inner ℝ V _ x y
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 `∠ p1 p2 p3`
notation. -/
def angle (p1 p2 p3 : P) : ℝ := angle (p1 -ᵥ p2 : V) (p3 -ᵥ p2)
localized "notation (name := angle) `∠` := euclidean_geometry.angle" in euclidean_geometry
lemma continuous_at_angle {x : P × P × P} (hx12 : x.1 ≠ x.2.1) (hx32 : x.2.2 ≠ x.2.1) :
continuous_at (λ y : P × P × P, ∠ y.1 y.2.1 y.2.2) x :=
begin
let f : P × P × P → V × V := λ y, (y.1 -ᵥ y.2.1, y.2.2 -ᵥ y.2.1),
have hf1 : (f x).1 ≠ 0, by simp [hx12],
have hf2 : (f x).2 ≠ 0, by simp [hx32],
exact (inner_product_geometry.continuous_at_angle hf1 hf2).comp
((continuous_fst.vsub continuous_snd.fst).prod_mk
(continuous_snd.snd.vsub continuous_snd.fst)).continuous_at
end
@[simp] lemma _root_.affine_isometry.angle_map {V₂ P₂ : Type*} [inner_product_space ℝ V₂]
[metric_space P₂] [normed_add_torsor V₂ P₂] (f : P →ᵃⁱ[ℝ] P₂) (p₁ p₂ p₃ : P) :
∠ (f p₁) (f p₂) (f p₃) = ∠ p₁ p₂ p₃ :=
by simp_rw [angle, ←affine_isometry.map_vsub, linear_isometry.angle_map]
/-- The angle at a point does not depend on the order of the other two
points. -/
lemma angle_comm (p1 p2 p3 : P) : ∠ p1 p2 p3 = ∠ p3 p2 p1 :=
angle_comm _ _
/-- The angle at a point is nonnegative. -/
lemma angle_nonneg (p1 p2 p3 : P) : 0 ≤ ∠ p1 p2 p3 :=
angle_nonneg _ _
/-- The angle at a point is at most π. -/
lemma angle_le_pi (p1 p2 p3 : P) : ∠ p1 p2 p3 ≤ π :=
angle_le_pi _ _
/-- The angle ∠AAB at a point. -/
lemma angle_eq_left (p1 p2 : P) : ∠ 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) : ∠ 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) : ∠ p1 p2 p1 = 0 :=
angle_self (λ he, h (vsub_eq_zero_iff_eq.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 : ∠ p1 p2 p3 = π) :
∠ 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 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 : ∠ p1 p2 p3 = π) :
∠ p2 p3 p1 = 0 :=
begin
rw angle_comm at h,
exact angle_eq_zero_of_angle_eq_pi_left h
end
/-- If ∠BCD = π, then ∠ABC = ∠ABD. -/
lemma angle_eq_angle_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) :
∠ p1 p2 p3 = ∠ p1 p2 p4 :=
begin
unfold angle at *,
rcases angle_eq_pi_iff.1 h with ⟨hp2p3, ⟨r, ⟨hr, hpr⟩⟩⟩,
rw [eq_comm],
convert angle_smul_right_of_pos (p1 -ᵥ p2) (p3 -ᵥ p2) (add_pos (neg_pos_of_neg hr) zero_lt_one),
rw [add_smul, ← neg_vsub_eq_vsub_rev p2 p3, smul_neg, neg_smul, ← hpr],
simp
end
/-- If ∠BCD = π, then ∠ACB + ∠ACD = π. -/
lemma angle_add_angle_eq_pi_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) :
∠ p1 p3 p2 + ∠ p1 p3 p4 = π :=
begin
unfold angle at h,
rw [angle_comm p1 p3 p2, angle_comm p1 p3 p4],
unfold angle,
exact angle_add_angle_eq_pi_of_angle_eq_pi _ h
end
/-- Vertical Angles Theorem: angles opposite each other, formed by two intersecting straight
lines, are equal. -/
lemma angle_eq_angle_of_angle_eq_pi_of_angle_eq_pi {p1 p2 p3 p4 p5 : P}
(hapc : ∠ p1 p5 p3 = π) (hbpd : ∠ p2 p5 p4 = π) : ∠ p1 p5 p2 = ∠ p3 p5 p4 :=
by linarith [angle_add_angle_eq_pi_of_angle_eq_pi p1 hbpd, angle_comm p4 p5 p1,
angle_add_angle_eq_pi_of_angle_eq_pi p4 hapc, angle_comm p4 p5 p3]
/-- If ∠ABC = π then dist A B ≠ 0. -/
lemma left_dist_ne_zero_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : dist p1 p2 ≠ 0 :=
begin
by_contra heq,
rw [dist_eq_zero] at heq,
rw [heq, angle_eq_left] at h,
exact real.pi_ne_zero (by linarith),
end
/-- If ∠ABC = π then dist C B ≠ 0. -/
lemma right_dist_ne_zero_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : dist p3 p2 ≠ 0 :=
left_dist_ne_zero_of_angle_eq_pi $ (angle_comm _ _ _).trans h
/-- If ∠ABC = π, then (dist A C) = (dist A B) + (dist B C). -/
lemma dist_eq_add_dist_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) :
dist p1 p3 = dist p1 p2 + dist p3 p2 :=
begin
rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right],
exact norm_sub_eq_add_norm_of_angle_eq_pi h,
end
/-- If A ≠ B and C ≠ B then ∠ABC = π if and only if (dist A C) = (dist A B) + (dist B C). -/
lemma dist_eq_add_dist_iff_angle_eq_pi {p1 p2 p3 : P} (hp1p2 : p1 ≠ p2) (hp3p2 : p3 ≠ p2) :
dist p1 p3 = dist p1 p2 + dist p3 p2 ↔ ∠ p1 p2 p3 = π :=
begin
rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right],
exact norm_sub_eq_add_norm_iff_angle_eq_pi
((λ he, hp1p2 (vsub_eq_zero_iff_eq.1 he))) (λ he, hp3p2 (vsub_eq_zero_iff_eq.1 he)),
end
/-- If ∠ABC = 0, then (dist A C) = abs ((dist A B) - (dist B C)). -/
lemma dist_eq_abs_sub_dist_of_angle_eq_zero {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = 0) :
(dist p1 p3) = |(dist p1 p2) - (dist p3 p2)| :=
begin
rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right],
exact norm_sub_eq_abs_sub_norm_of_angle_eq_zero h,
end
/-- If A ≠ B and C ≠ B then ∠ABC = 0 if and only if (dist A C) = abs ((dist A B) - (dist B C)). -/
lemma dist_eq_abs_sub_dist_iff_angle_eq_zero {p1 p2 p3 : P} (hp1p2 : p1 ≠ p2) (hp3p2 : p3 ≠ p2) :
(dist p1 p3) = |(dist p1 p2) - (dist p3 p2)| ↔ ∠ p1 p2 p3 = 0 :=
begin
rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right],
exact norm_sub_eq_abs_sub_norm_iff_angle_eq_zero
((λ he, hp1p2 (vsub_eq_zero_iff_eq.1 he))) (λ he, hp3p2 (vsub_eq_zero_iff_eq.1 he)),
end
/-- The midpoint of the segment AB is the same distance from A as it is from B. -/
lemma dist_left_midpoint_eq_dist_right_midpoint (p1 p2 : P) :
dist p1 (midpoint ℝ p1 p2) = dist p2 (midpoint ℝ p1 p2) :=
by rw [dist_left_midpoint p1 p2, dist_right_midpoint p1 p2]
/-- If M is the midpoint of the segment AB, then ∠AMB = π. -/
lemma angle_midpoint_eq_pi (p1 p2 : P) (hp1p2 : p1 ≠ p2) : ∠ p1 (midpoint ℝ p1 p2) p2 = π :=
have p2 -ᵥ midpoint ℝ p1 p2 = -(p1 -ᵥ midpoint ℝ p1 p2), by { rw neg_vsub_eq_vsub_rev, simp },
by simp [angle, this, hp1p2, -zero_lt_one]
/-- If M is the midpoint of the segment AB and C is the same distance from A as it is from B
then ∠CMA = π / 2. -/
lemma angle_left_midpoint_eq_pi_div_two_of_dist_eq {p1 p2 p3 : P} (h : dist p3 p1 = dist p3 p2) :
∠ p3 (midpoint ℝ p1 p2) p1 = π / 2 :=
begin
let m : P := midpoint ℝ p1 p2,
have h1 : p3 -ᵥ p1 = (p3 -ᵥ m) - (p1 -ᵥ m) := (vsub_sub_vsub_cancel_right p3 p1 m).symm,
have h2 : p3 -ᵥ p2 = (p3 -ᵥ m) + (p1 -ᵥ m),
{ rw [left_vsub_midpoint, ← midpoint_vsub_right, vsub_add_vsub_cancel] },
rw [dist_eq_norm_vsub V p3 p1, dist_eq_norm_vsub V p3 p2, h1, h2] at h,
exact (norm_add_eq_norm_sub_iff_angle_eq_pi_div_two (p3 -ᵥ m) (p1 -ᵥ m)).mp h.symm,
end
/-- If M is the midpoint of the segment AB and C is the same distance from A as it is from B
then ∠CMB = π / 2. -/
lemma angle_right_midpoint_eq_pi_div_two_of_dist_eq {p1 p2 p3 : P} (h : dist p3 p1 = dist p3 p2) :
∠ p3 (midpoint ℝ p1 p2) p2 = π / 2 :=
by rw [midpoint_comm p1 p2, angle_left_midpoint_eq_pi_div_two_of_dist_eq h.symm]
/-- 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 p₁ w₁) (s₂.weighted_vsub 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],
rcongr i₁ i₂; rw dist_eq_norm_vsub 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) :
by have a₁ := s.affine_combination p w₁; have a₂ := s.affine_combination p w₂; exact
dist a₁ a₂ * dist a₁ a₂ = (-∑ 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_vsub V (s.affine_combination p w₁) (s.affine_combination p w₂),
←inner_self_eq_norm_mul_norm, 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 p h p h
end
/-- Suppose that `c₁` is equidistant from `p₁` and `p₂`, and the same
applies to `c₂`. Then the vector between `c₁` and `c₂` is orthogonal
to that between `p₁` and `p₂`. (In two dimensions, this says that the
diagonals of a kite are orthogonal.) -/
lemma inner_vsub_vsub_of_dist_eq_of_dist_eq {c₁ c₂ p₁ p₂ : P} (hc₁ : dist p₁ c₁ = dist p₂ c₁)
(hc₂ : dist p₁ c₂ = dist p₂ c₂) : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 :=
begin
have h : ⟪(c₂ -ᵥ c₁) + (c₂ -ᵥ c₁), p₂ -ᵥ p₁⟫ = 0,
{ conv_lhs { congr, congr, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₁,
skip, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₂ },
rw [sub_add_sub_comm, inner_sub_left],
conv_lhs { congr, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₂,
skip, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₁ },
rw [dist_comm p₁, dist_comm p₂, dist_eq_norm_vsub V _ p₁,
dist_eq_norm_vsub V _ p₂, ←real_inner_add_sub_eq_zero_iff] at hc₁ hc₂,
simp_rw [←neg_vsub_eq_vsub_rev c₁, ←neg_vsub_eq_vsub_rev c₂, sub_neg_eq_add,
neg_add_eq_sub, hc₁, hc₂, sub_zero] },
simpa [inner_add_left, ←mul_two, (by norm_num : (2 : ℝ) ≠ 0)] using h
end
/-- The squared distance between points on a line (expressed as a
multiple of a fixed vector added to a point) and another point,
expressed as a quadratic. -/
lemma dist_smul_vadd_sq (r : ℝ) (v : V) (p₁ p₂ : P) :
dist (r • v +ᵥ p₁) p₂ * dist (r • v +ᵥ p₁) p₂ =
⟪v, v⟫ * r * r + 2 * ⟪v, p₁ -ᵥ p₂⟫ * r + ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ :=
begin
rw [dist_eq_norm_vsub V _ p₂, ←real_inner_self_eq_norm_mul_norm, vadd_vsub_assoc,
real_inner_add_add_self, real_inner_smul_left, real_inner_smul_left, real_inner_smul_right],
ring
end
/-- The condition for two points on a line to be equidistant from
another point. -/
lemma dist_smul_vadd_eq_dist {v : V} (p₁ p₂ : P) (hv : v ≠ 0) (r : ℝ) :
dist (r • v +ᵥ p₁) p₂ = dist p₁ p₂ ↔ (r = 0 ∨ r = -2 * ⟪v, p₁ -ᵥ p₂⟫ / ⟪v, v⟫) :=
begin
conv_lhs { rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_smul_vadd_sq,
←sub_eq_zero, add_sub_assoc, dist_eq_norm_vsub V p₁ p₂,
←real_inner_self_eq_norm_mul_norm, sub_self] },
have hvi : ⟪v, v⟫ ≠ 0, by simpa using hv,
have hd : discrim ⟪v, v⟫ (2 * ⟪v, p₁ -ᵥ p₂⟫) 0 =
(2 * inner v (p₁ -ᵥ p₂)) * (2 * inner v (p₁ -ᵥ p₂)),
{ rw discrim, ring },
rw [quadratic_eq_zero_iff hvi hd, add_left_neg, zero_div, neg_mul_eq_neg_mul,
←mul_sub_right_distrib, sub_eq_add_neg, ←mul_two, mul_assoc, mul_div_assoc,
mul_div_mul_left, mul_div_assoc],
norm_num
end
open affine_subspace finite_dimensional
/-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at
most two points `p₁` `p₂` in a two-dimensional subspace containing those points
(two circles intersect in at most two points). -/
lemma eq_of_dist_eq_of_dist_eq_of_mem_of_finrank_eq_two {s : affine_subspace ℝ P}
[finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = 2) {c₁ c₂ p₁ p₂ p : P}
(hc₁s : c₁ ∈ s) (hc₂s : c₂ ∈ s) (hp₁s : p₁ ∈ s) (hp₂s : p₂ ∈ s) (hps : p ∈ s) {r₁ r₂ : ℝ}
(hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁)
(hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂)
(hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ :=
begin
have ho : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 :=
inner_vsub_vsub_of_dist_eq_of_dist_eq (hp₁c₁.trans hp₂c₁.symm) (hp₁c₂.trans hp₂c₂.symm),
have hop : ⟪c₂ -ᵥ c₁, p -ᵥ p₁⟫ = 0 :=
inner_vsub_vsub_of_dist_eq_of_dist_eq (hp₁c₁.trans hpc₁.symm) (hp₁c₂.trans hpc₂.symm),
let b : fin 2 → V := ![c₂ -ᵥ c₁, p₂ -ᵥ p₁],
have hb : linear_independent ℝ b,
{ refine linear_independent_of_ne_zero_of_inner_eq_zero _ _,
{ intro i,
fin_cases i; simp [b, hc.symm, hp.symm], },
{ intros i j hij,
fin_cases i; fin_cases j; try { exact false.elim (hij rfl) },
{ exact ho },
{ rw real_inner_comm, exact ho } } },
have hbs : submodule.span ℝ (set.range b) = s.direction,
{ refine eq_of_le_of_finrank_eq _ _,
{ rw [submodule.span_le, set.range_subset_iff],
intro i,
fin_cases i,
{ exact vsub_mem_direction hc₂s hc₁s },
{ exact vsub_mem_direction hp₂s hp₁s } },
{ rw [finrank_span_eq_card hb, fintype.card_fin, hd] } },
have hv : ∀ v ∈ s.direction, ∃ t₁ t₂ : ℝ, v = t₁ • (c₂ -ᵥ c₁) + t₂ • (p₂ -ᵥ p₁),
{ intros v hv,
have hr : set.range b = {c₂ -ᵥ c₁, p₂ -ᵥ p₁},
{ have hu : (finset.univ : finset (fin 2)) = {0, 1}, by dec_trivial,
rw [←fintype.coe_image_univ, hu],
simp,
refl },
rw [←hbs, hr, submodule.mem_span_insert] at hv,
rcases hv with ⟨t₁, v', hv', hv⟩,
rw submodule.mem_span_singleton at hv',
rcases hv' with ⟨t₂, rfl⟩,
exact ⟨t₁, t₂, hv⟩ },
rcases hv (p -ᵥ p₁) (vsub_mem_direction hps hp₁s) with ⟨t₁, t₂, hpt⟩,
simp only [hpt, inner_add_right, inner_smul_right, ho, mul_zero, add_zero, mul_eq_zero,
inner_self_eq_zero, vsub_eq_zero_iff_eq, hc.symm, or_false] at hop,
rw [hop, zero_smul, zero_add, ←eq_vadd_iff_vsub_eq] at hpt,
subst hpt,
have hp' : (p₂ -ᵥ p₁ : V) ≠ 0, { simp [hp.symm] },
have hp₂ : dist ((1 : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁) c₁ = r₁, { simp [hp₂c₁] },
rw [←hp₁c₁, dist_smul_vadd_eq_dist _ _ hp'] at hpc₁ hp₂,
simp only [one_ne_zero, false_or] at hp₂,
rw hp₂.symm at hpc₁,
cases hpc₁; simp [hpc₁]
end
/-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at
most two points `p₁` `p₂` in two-dimensional space (two circles intersect in at
most two points). -/
lemma eq_of_dist_eq_of_dist_eq_of_finrank_eq_two [finite_dimensional ℝ V] (hd : finrank ℝ V = 2)
{c₁ c₂ p₁ p₂ p : P} {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁)
(hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂)
(hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ :=
begin
have hd' : finrank ℝ (⊤ : affine_subspace ℝ P).direction = 2,
{ rw [direction_top, finrank_top],
exact hd },
exact eq_of_dist_eq_of_dist_eq_of_mem_of_finrank_eq_two hd'
(mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _)
hc hp hp₁c₁ hp₂c₁ hpc₁ hp₁c₂ hp₂c₂ hpc₂
end
variables {V}
/-- The orthogonal projection of a point onto a nonempty affine
subspace, whose direction is complete, as an unbundled function. This
definition is only intended for use in setting up the bundled version
`orthogonal_projection` and should not be used once that is
defined. -/
def orthogonal_projection_fn (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction]
(p : P) : P :=
classical.some $ inter_eq_singleton_of_nonempty_of_is_compl
(nonempty_subtype.mp ‹_›)
(mk'_nonempty p s.directionᗮ)
begin
rw direction_mk' p s.directionᗮ,
exact submodule.is_compl_orthogonal_of_complete_space,
end
/-- The intersection of the subspace and the orthogonal subspace
through the given point is the `orthogonal_projection_fn` of that
point onto the subspace. This lemma is only intended for use in
setting up the bundled version and should not be used once that is
defined. -/
lemma inter_eq_singleton_orthogonal_projection_fn {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] (p : P) :
(s : set P) ∩ (mk' p s.directionᗮ) = {orthogonal_projection_fn s p} :=
classical.some_spec $ inter_eq_singleton_of_nonempty_of_is_compl
(nonempty_subtype.mp ‹_›)
(mk'_nonempty p s.directionᗮ)
begin
rw direction_mk' p s.directionᗮ,
exact submodule.is_compl_orthogonal_of_complete_space
end
/-- The `orthogonal_projection_fn` lies in the given subspace. This
lemma is only intended for use in setting up the bundled version and
should not be used once that is defined. -/
lemma orthogonal_projection_fn_mem {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] (p : P) : orthogonal_projection_fn s p ∈ s :=
begin
rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn],
exact set.inter_subset_left _ _
end
/-- The `orthogonal_projection_fn` lies in the orthogonal
subspace. This lemma is only intended for use in setting up the
bundled version and should not be used once that is defined. -/
lemma orthogonal_projection_fn_mem_orthogonal {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] (p : P) :
orthogonal_projection_fn s p ∈ mk' p s.directionᗮ :=
begin
rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn],
exact set.inter_subset_right _ _
end
/-- Subtracting `p` from its `orthogonal_projection_fn` produces a
result in the orthogonal direction. This lemma is only intended for
use in setting up the bundled version and should not be used once that
is defined. -/
lemma orthogonal_projection_fn_vsub_mem_direction_orthogonal {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] (p : P) :
orthogonal_projection_fn s p -ᵥ p ∈ s.directionᗮ :=
direction_mk' p s.directionᗮ ▸
vsub_mem_direction (orthogonal_projection_fn_mem_orthogonal p) (self_mem_mk' _ _)
local attribute [instance] affine_subspace.to_add_torsor
/-- The orthogonal projection of a point onto a nonempty affine
subspace, whose direction is complete. The corresponding linear map
(mapping a vector to the difference between the projections of two
points whose difference is that vector) is the `orthogonal_projection`
for real inner product spaces, onto the direction of the affine
subspace being projected onto. -/
def orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] :
P →ᵃ[ℝ] s :=
{ to_fun := λ p, ⟨orthogonal_projection_fn s p, orthogonal_projection_fn_mem p⟩,
linear := orthogonal_projection s.direction,
map_vadd' := λ p v, begin
have hs : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ s :=
vadd_mem_of_mem_direction (orthogonal_projection s.direction v).2
(orthogonal_projection_fn_mem p),
have ho : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈
mk' (v +ᵥ p) s.directionᗮ,
{ rw [←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _) _, direction_mk',
vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc],
refine submodule.add_mem _ (orthogonal_projection_fn_vsub_mem_direction_orthogonal p) _,
rw submodule.mem_orthogonal',
intros w hw,
rw [←neg_sub, inner_neg_left, orthogonal_projection_inner_eq_zero _ w hw, neg_zero], },
have hm : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈
({orthogonal_projection_fn s (v +ᵥ p)} : set P),
{ rw ←inter_eq_singleton_orthogonal_projection_fn (v +ᵥ p),
exact set.mem_inter hs ho },
rw set.mem_singleton_iff at hm,
ext,
exact hm.symm
end }
@[simp] lemma orthogonal_projection_fn_eq {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] (p : P) :
orthogonal_projection_fn s p = orthogonal_projection s p :=
rfl
/-- The linear map corresponding to `orthogonal_projection`. -/
@[simp] lemma orthogonal_projection_linear {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] :
(orthogonal_projection s).linear = _root_.orthogonal_projection s.direction :=
rfl
/-- The intersection of the subspace and the orthogonal subspace
through the given point is the `orthogonal_projection` of that point
onto the subspace. -/
lemma inter_eq_singleton_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] (p : P) :
(s : set P) ∩ (mk' p s.directionᗮ) = {orthogonal_projection s p} :=
begin
rw ←orthogonal_projection_fn_eq,
exact inter_eq_singleton_orthogonal_projection_fn p
end
/-- The `orthogonal_projection` lies in the given subspace. -/
lemma orthogonal_projection_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction]
(p : P) : ↑(orthogonal_projection s p) ∈ s :=
(orthogonal_projection s p).2
/-- The `orthogonal_projection` lies in the orthogonal subspace. -/
lemma orthogonal_projection_mem_orthogonal (s : affine_subspace ℝ P) [nonempty s]
[complete_space s.direction] (p : P) :
↑(orthogonal_projection s p) ∈ mk' p s.directionᗮ :=
orthogonal_projection_fn_mem_orthogonal p
/-- Subtracting a point in the given subspace from the
`orthogonal_projection` produces a result in the direction of the
given subspace. -/
lemma orthogonal_projection_vsub_mem_direction {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) :
↑(orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction) ∈ s.direction :=
(orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction).2
/-- Subtracting the `orthogonal_projection` from a point in the given
subspace produces a result in the direction of the given subspace. -/
lemma vsub_orthogonal_projection_mem_direction {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) :
↑((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction) ∈ s.direction :=
((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction).2
/-- A point equals its orthogonal projection if and only if it lies in
the subspace. -/
lemma orthogonal_projection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p : P} :
↑(orthogonal_projection s p) = p ↔ p ∈ s :=
begin
split,
{ exact λ h, h ▸ orthogonal_projection_mem p },
{ intro h,
have hp : p ∈ ((s : set P) ∩ mk' p s.directionᗮ) := ⟨h, self_mem_mk' p _⟩,
rw [inter_eq_singleton_orthogonal_projection p] at hp,
symmetry,
exact hp }
end
@[simp] lemma orthogonal_projection_mem_subspace_eq_self {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] (p : s) :
orthogonal_projection s p = p :=
begin
ext,
rw orthogonal_projection_eq_self_iff,
exact p.2
end
/-- Orthogonal projection is idempotent. -/
@[simp] lemma orthogonal_projection_orthogonal_projection (s : affine_subspace ℝ P) [nonempty s]
[complete_space s.direction] (p : P) :
orthogonal_projection s (orthogonal_projection s p) = orthogonal_projection s p :=
begin
ext,
rw orthogonal_projection_eq_self_iff,
exact orthogonal_projection_mem p,
end
lemma eq_orthogonal_projection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s]
[nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) :
(orthogonal_projection s p : P) = (orthogonal_projection s' p : P) :=
begin
change orthogonal_projection_fn s p = orthogonal_projection_fn s' p,
congr,
exact h
end
/-- The distance to a point's orthogonal projection is 0 iff it lies in the subspace. -/
lemma dist_orthogonal_projection_eq_zero_iff {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p : P} :
dist p (orthogonal_projection s p) = 0 ↔ p ∈ s :=
by rw [dist_comm, dist_eq_zero, orthogonal_projection_eq_self_iff]
/-- The distance between a point and its orthogonal projection is
nonzero if it does not lie in the subspace. -/
lemma dist_orthogonal_projection_ne_zero_of_not_mem {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p : P} (hp : p ∉ s) :
dist p (orthogonal_projection s p) ≠ 0 :=
mt dist_orthogonal_projection_eq_zero_iff.mp hp
/-- Subtracting `p` from its `orthogonal_projection` produces a result
in the orthogonal direction. -/
lemma orthogonal_projection_vsub_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s]
[complete_space s.direction] (p : P) :
(orthogonal_projection s p : P) -ᵥ p ∈ s.directionᗮ :=
orthogonal_projection_fn_vsub_mem_direction_orthogonal p
/-- Subtracting the `orthogonal_projection` from `p` produces a result
in the orthogonal direction. -/
lemma vsub_orthogonal_projection_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s]
[complete_space s.direction] (p : P) :
p -ᵥ orthogonal_projection s p ∈ s.directionᗮ :=
direction_mk' p s.directionᗮ ▸
vsub_mem_direction (self_mem_mk' _ _) (orthogonal_projection_mem_orthogonal s p)
/-- Subtracting the `orthogonal_projection` from `p` produces a result in the kernel of the linear
part of the orthogonal projection. -/
lemma orthogonal_projection_vsub_orthogonal_projection (s : affine_subspace ℝ P) [nonempty s]
[complete_space s.direction] (p : P) :
_root_.orthogonal_projection s.direction (p -ᵥ orthogonal_projection s p) = 0 :=
begin
apply orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero,
intros c hc,
rw [← neg_vsub_eq_vsub_rev, inner_neg_right,
(orthogonal_projection_vsub_mem_direction_orthogonal s p c hc), neg_zero]
end
/-- Adding a vector to a point in the given subspace, then taking the
orthogonal projection, produces the original point if the vector was
in the orthogonal direction. -/
lemma orthogonal_projection_vadd_eq_self {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p : P} (hp : p ∈ s) {v : V}
(hv : v ∈ s.directionᗮ) :
orthogonal_projection s (v +ᵥ p) = ⟨p, hp⟩ :=
begin
have h := vsub_orthogonal_projection_mem_direction_orthogonal s (v +ᵥ p),
rw [vadd_vsub_assoc, submodule.add_mem_iff_right _ hv] at h,
refine (eq_of_vsub_eq_zero _).symm,
ext,
refine submodule.disjoint_def.1 s.direction.orthogonal_disjoint _ _ h,
exact (_ : s.direction).2
end
/-- Adding a vector to a point in the given subspace, then taking the
orthogonal projection, produces the original point if the vector is a
multiple of the result of subtracting a point's orthogonal projection
from that point. -/
lemma orthogonal_projection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P}
[nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (r : ℝ) (hp : p1 ∈ s) :
orthogonal_projection s (r • (p2 -ᵥ orthogonal_projection s p2 : V) +ᵥ p1) = ⟨p1, hp⟩ :=
orthogonal_projection_vadd_eq_self hp
(submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _))
/-- The square of the distance from a point in `s` to `p2` equals the
sum of the squares of the distances of the two points to the
`orthogonal_projection`. -/
lemma dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq
{s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P}
(p2 : P) (hp1 : p1 ∈ s) :
dist p1 p2 * dist p1 p2 =
dist p1 (orthogonal_projection s p2) * dist p1 (orthogonal_projection s p2) +
dist p2 (orthogonal_projection s p2) * dist p2 (orthogonal_projection s p2) :=
begin
rw [dist_comm p2 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V p1 _,
dist_eq_norm_vsub V _ p2, ← vsub_add_vsub_cancel p1 (orthogonal_projection s p2) p2,
norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero],
exact submodule.inner_right_of_mem_orthogonal
(vsub_orthogonal_projection_mem_direction p2 hp1)
(orthogonal_projection_vsub_mem_direction_orthogonal s p2),
end
/-- The square of the distance between two points constructed by
adding multiples of the same orthogonal vector to points in the same
subspace. -/
lemma dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd {s : affine_subspace ℝ P}
{p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) (r1 r2 : ℝ) {v : V}
(hv : v ∈ s.directionᗮ) :
dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) =
dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥) :=
calc dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2)
= ∥(p1 -ᵥ p2) + (r1 - r2) • v∥ * ∥(p1 -ᵥ p2) + (r1 - r2) • v∥
: by rw [dist_eq_norm_vsub V (r1 • v +ᵥ p1), vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, sub_smul,
add_comm, add_sub_assoc]
... = ∥p1 -ᵥ p2∥ * ∥p1 -ᵥ p2∥ + ∥(r1 - r2) • v∥ * ∥(r1 - r2) • v∥
: norm_add_sq_eq_norm_sq_add_norm_sq_real
(submodule.inner_right_of_mem_orthogonal (vsub_mem_direction hp1 hp2)
(submodule.smul_mem _ _ hv))
... = ∥(p1 -ᵥ p2 : V)∥ * ∥(p1 -ᵥ p2 : V)∥ + |r1 - r2| * |r1 - r2| * ∥v∥ * ∥v∥
: by { rw [norm_smul, real.norm_eq_abs], ring }
... = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥)
: by { rw [dist_eq_norm_vsub V p1, abs_mul_abs_self, mul_assoc] }
/-- Reflection in an affine subspace, which is expected to be nonempty
and complete. The word "reflection" is sometimes understood to mean
specifically reflection in a codimension-one subspace, and sometimes
more generally to cover operations such as reflection in a point. The
definition here, of reflection in an affine subspace, is a more
general sense of the word that includes both those common cases. -/
def reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] :
P ≃ᵃⁱ[ℝ] P :=
affine_isometry_equiv.mk'
(λ p, (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p)
(_root_.reflection s.direction)
↑(classical.arbitrary s)
begin
intros p,
let v := p -ᵥ ↑(classical.arbitrary s),
let a : V := _root_.orthogonal_projection s.direction v,
let b : P := ↑(classical.arbitrary s),
have key : a +ᵥ b -ᵥ (v +ᵥ b) +ᵥ (a +ᵥ b) = a + a - v +ᵥ (b -ᵥ b +ᵥ b),
{ rw [← add_vadd, vsub_vadd_eq_vsub_sub, vsub_vadd, vadd_vsub],
congr' 1,
abel },
have : p = v +ᵥ ↑(classical.arbitrary s) := (vsub_vadd p ↑(classical.arbitrary s)).symm,
simpa only [coe_vadd, reflection_apply, affine_map.map_vadd, orthogonal_projection_linear,
orthogonal_projection_mem_subspace_eq_self, vadd_vsub, continuous_linear_map.coe_coe,
continuous_linear_equiv.coe_coe, this] using key,
end
/-- The result of reflecting. -/
lemma reflection_apply (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) :
reflection s p = (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p :=
rfl
lemma eq_reflection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s]
[nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) :
(reflection s p : P) = (reflection s' p : P) :=
by unfreezingI { subst h }
/-- Reflecting twice in the same subspace. -/
@[simp] lemma reflection_reflection (s : affine_subspace ℝ P) [nonempty s]
[complete_space s.direction] (p : P) :
reflection s (reflection s p) = p :=
begin
have : ∀ a : s, ∀ b : V, (_root_.orthogonal_projection s.direction) b = 0
→ reflection s (reflection s (b +ᵥ a)) = b +ᵥ a,
{ intros a b h,
have : (a:P) -ᵥ (b +ᵥ a) = - b,
{ rw [vsub_vadd_eq_vsub_sub, vsub_self, zero_sub] },
simp [reflection, h, this] },
rw ← vsub_vadd p (orthogonal_projection s p),
exact this (orthogonal_projection s p) _ (orthogonal_projection_vsub_orthogonal_projection s p),
end
/-- Reflection is its own inverse. -/
@[simp] lemma reflection_symm (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] :
(reflection s).symm = reflection s :=
by { ext, rw ← (reflection s).injective.eq_iff, simp }
/-- Reflection is involutive. -/
lemma reflection_involutive (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] :
function.involutive (reflection s) :=
reflection_reflection s
/-- A point is its own reflection if and only if it is in the
subspace. -/
lemma reflection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction]
(p : P) : reflection s p = p ↔ p ∈ s :=
begin
rw [←orthogonal_projection_eq_self_iff, reflection_apply],
split,
{ intro h,
rw [←@vsub_eq_zero_iff_eq V, vadd_vsub_assoc,
←two_smul ℝ (↑(orthogonal_projection s p) -ᵥ p), smul_eq_zero] at h,
norm_num at h,
exact h },
{ intro h,
simp [h] }
end
/-- Reflecting a point in two subspaces produces the same result if
and only if the point has the same orthogonal projection in each of
those subspaces. -/
lemma reflection_eq_iff_orthogonal_projection_eq (s₁ s₂ : affine_subspace ℝ P)
[nonempty s₁] [nonempty s₂] [complete_space s₁.direction] [complete_space s₂.direction] (p : P) :
reflection s₁ p = reflection s₂ p ↔
(orthogonal_projection s₁ p : P) = orthogonal_projection s₂ p :=
begin
rw [reflection_apply, reflection_apply],
split,
{ intro h,
rw [←@vsub_eq_zero_iff_eq V, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm,
add_sub_assoc, vsub_sub_vsub_cancel_right,
←two_smul ℝ ((orthogonal_projection s₁ p : P) -ᵥ orthogonal_projection s₂ p),
smul_eq_zero] at h,
norm_num at h,
exact h },
{ intro h,
rw h }
end
/-- The distance between `p₁` and the reflection of `p₂` equals that
between the reflection of `p₁` and `p₂`. -/
lemma dist_reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction]
(p₁ p₂ : P) :
dist p₁ (reflection s p₂) = dist (reflection s p₁) p₂ :=
begin
conv_lhs { rw ←reflection_reflection s p₁ },
exact (reflection s).dist_map _ _
end
/-- A point in the subspace is equidistant from another point and its
reflection. -/
lemma dist_reflection_eq_of_mem (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction]
{p₁ : P} (hp₁ : p₁ ∈ s) (p₂ : P) :
dist p₁ (reflection s p₂) = dist p₁ p₂ :=
begin
rw ←reflection_eq_self_iff p₁ at hp₁,
convert (reflection s).dist_map p₁ p₂,
rw hp₁
end
/-- The reflection of a point in a subspace is contained in any larger
subspace containing both the point and the subspace reflected in. -/
lemma reflection_mem_of_le_of_mem {s₁ s₂ : affine_subspace ℝ P} [nonempty s₁]
[complete_space s₁.direction] (hle : s₁ ≤ s₂) {p : P}
(hp : p ∈ s₂) : reflection s₁ p ∈ s₂ :=
begin
rw [reflection_apply],
have ho : ↑(orthogonal_projection s₁ p) ∈ s₂ := hle (orthogonal_projection_mem p),
exact vadd_mem_of_mem_direction (vsub_mem_direction ho hp) ho
end
/-- Reflecting an orthogonal vector plus a point in the subspace
produces the negation of that vector plus the point. -/
lemma reflection_orthogonal_vadd {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p : P} (hp : p ∈ s) {v : V}
(hv : v ∈ s.directionᗮ) : reflection s (v +ᵥ p) = -v +ᵥ p :=
begin
rw [reflection_apply, orthogonal_projection_vadd_eq_self hp hv, vsub_vadd_eq_vsub_sub],
simp
end
/-- Reflecting a vector plus a point in the subspace produces the
negation of that vector plus the point if the vector is a multiple of
the result of subtracting a point's orthogonal projection from that
point. -/
lemma reflection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s]
[complete_space s.direction] {p₁ : P} (p₂ : P) (r : ℝ) (hp₁ : p₁ ∈ s) :
reflection s (r • (p₂ -ᵥ orthogonal_projection s p₂) +ᵥ p₁) =
-(r • (p₂ -ᵥ orthogonal_projection s p₂)) +ᵥ p₁ :=
reflection_orthogonal_vadd hp₁
(submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _))
omit V
/-- A set of points is cospherical if they are equidistant from some
point. In two dimensions, this is the same thing as being
concyclic. -/
def cospherical (ps : set P) : Prop :=
∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius
/-- The definition of `cospherical`. -/
lemma cospherical_def (ps : set P) :
cospherical ps ↔ ∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius :=
iff.rfl
/-- A subset of a cospherical set is cospherical. -/
lemma cospherical_subset {ps₁ ps₂ : set P} (hs : ps₁ ⊆ ps₂) (hc : cospherical ps₂) :
cospherical ps₁ :=
begin
rcases hc with ⟨c, r, hcr⟩,
exact ⟨c, r, λ p hp, hcr p (hs hp)⟩
end
include V
/-- The empty set is cospherical. -/
lemma cospherical_empty : cospherical (∅ : set P) :=
begin
use add_torsor.nonempty.some,
simp,
end
omit V
/-- A single point is cospherical. -/
lemma cospherical_singleton (p : P) : cospherical ({p} : set P) :=
begin
use p,
simp
end
include V
/-- Two points are cospherical. -/
lemma cospherical_pair (p₁ p₂ : P) : cospherical ({p₁, p₂} : set P) :=
begin
use [(2⁻¹ : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁, (2⁻¹ : ℝ) * (dist p₂ p₁)],
intro p,
rw [set.mem_insert_iff, set.mem_singleton_iff],
rintro ⟨_|_⟩,
{ rw [dist_eq_norm_vsub V p₁, vsub_vadd_eq_vsub_sub, vsub_self, zero_sub, norm_neg, norm_smul,
dist_eq_norm_vsub V p₂],
simp },
{ rw [H, dist_eq_norm_vsub V p₂, vsub_vadd_eq_vsub_sub, dist_eq_norm_vsub V p₂],
conv_lhs { congr, congr, rw ←one_smul ℝ (p₂ -ᵥ p₁ : V) },
rw [←sub_smul, norm_smul],
norm_num }
end
/-- Any three points in a cospherical set are affinely independent. -/
lemma cospherical.affine_independent {s : set P} (hs : cospherical s) {p : fin 3 → P}
(hps : set.range p ⊆ s) (hpi : function.injective p) :
affine_independent ℝ p :=
begin
rw affine_independent_iff_not_collinear,
intro hc,
rw collinear_iff_of_mem ℝ (set.mem_range_self (0 : fin 3)) at hc,
rcases hc with ⟨v, hv⟩,
rw set.forall_range_iff at hv,
have hv0 : v ≠ 0,
{ intro h,
have he : p 1 = p 0, by simpa [h] using hv 1,
exact (dec_trivial : (1 : fin 3) ≠ 0) (hpi he) },
rcases hs with ⟨c, r, hs⟩,
have hs' := λ i, hs (p i) (set.mem_of_mem_of_subset (set.mem_range_self _) hps),
choose f hf using hv,
have hsd : ∀ i, dist ((f i • v) +ᵥ p 0) c = r,
{ intro i,
rw ←hf,
exact hs' i },
have hf0 : f 0 = 0,
{ have hf0' := hf 0,
rw [eq_comm, ←@vsub_eq_zero_iff_eq V, vadd_vsub, smul_eq_zero] at hf0',
simpa [hv0] using hf0' },
have hfi : function.injective f,
{ intros i j h,
have hi := hf i,
rw [h, ←hf j] at hi,
exact hpi hi },
simp_rw [←hsd 0, hf0, zero_smul, zero_vadd, dist_smul_vadd_eq_dist (p 0) c hv0] at hsd,
have hfn0 : ∀ i, i ≠ 0 → f i ≠ 0 := λ i, (hfi.ne_iff' hf0).2,
have hfn0' : ∀ i, i ≠ 0 → f i = (-2) * ⟪v, (p 0 -ᵥ c)⟫ / ⟪v, v⟫,
{ intros i hi,
have hsdi := hsd i,
simpa [hfn0, hi] using hsdi },
have hf12 : f 1 = f 2, { rw [hfn0' 1 dec_trivial, hfn0' 2 dec_trivial] },
exact (dec_trivial : (1 : fin 3) ≠ 2) (hfi hf12)
end
end euclidean_geometry
|
4389c5d9eeaad5bc7a9dc01cfce7352d9e0d07b0 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/topology/maps.lean | b4eabe0a902c4fce373c558824017c27f1a9a115 | [
"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,956 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot
-/
import topology.order
/-!
# Specific classes of maps between topological spaces
This file introduces the following properties of a map `f : X → Y` between topological spaces:
* `is_open_map f` means the image of an open set under `f` is open.
* `is_closed_map f` means the image of a closed set under `f` is closed.
(Open and closed maps need not be continuous.)
* `inducing f` means the topology on `X` is the one induced via `f` from the topology on `Y`.
These behave like embeddings except they need not be injective. Instead, points of `X` which
are identified by `f` are also indistinguishable in the topology on `X`.
* `embedding f` means `f` is inducing and also injective. Equivalently, `f` identifies `X` with
a subspace of `Y`.
* `open_embedding f` means `f` is an embedding with open image, so it identifies `X` with an
open subspace of `Y`. Equivalently, `f` is an embedding and an open map.
* `closed_embedding f` similarly means `f` is an embedding with closed image, so it identifies
`X` with a closed subspace of `Y`. Equivalently, `f` is an embedding and a closed map.
* `quotient_map f` is the dual condition to `embedding f`: `f` is surjective and the topology
on `Y` is the one coinduced via `f` from the topology on `X`. Equivalently, `f` identifies
`Y` with a quotient of `X`. Quotient maps are also sometimes known as identification maps.
## References
* <https://en.wikipedia.org/wiki/Open_and_closed_maps>
* <https://en.wikipedia.org/wiki/Embedding#General_topology>
* <https://en.wikipedia.org/wiki/Quotient_space_(topology)#Quotient_map>
## Tags
open map, closed map, embedding, quotient map, identification map
-/
open set filter
open_locale topological_space filter
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
section inducing
structure inducing [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop :=
(induced : tα = tβ.induced f)
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
lemma inducing_id : inducing (@id α) :=
⟨induced_id.symm⟩
protected lemma inducing.comp {g : β → γ} {f : α → β} (hg : inducing g) (hf : inducing f) :
inducing (g ∘ f) :=
⟨by rw [hf.induced, hg.induced, induced_compose]⟩
lemma inducing_of_inducing_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g)
(hgf : inducing (g ∘ f)) : inducing f :=
⟨le_antisymm
(by rwa ← continuous_iff_le_induced)
(by { rw [hgf.induced, ← continuous_iff_le_induced], apply hg.comp continuous_induced_dom })⟩
lemma inducing_open {f : α → β} {s : set α}
(hf : inducing f) (h : is_open (range f)) (hs : is_open s) : is_open (f '' s) :=
let ⟨t, ht, h_eq⟩ := by rw [hf.induced] at hs; exact hs in
have is_open (t ∩ range f), from is_open_inter ht h,
h_eq ▸ by rwa [image_preimage_eq_inter_range]
lemma inducing_is_closed {f : α → β} {s : set α}
(hf : inducing f) (h : is_closed (range f)) (hs : is_closed s) : is_closed (f '' s) :=
let ⟨t, ht, h_eq⟩ := by rw [hf.induced, is_closed_induced_iff] at hs; exact hs in
have is_closed (t ∩ range f), from is_closed_inter ht h,
h_eq.symm ▸ by rwa [image_preimage_eq_inter_range]
lemma inducing.nhds_eq_comap {f : α → β} (hf : inducing f) :
∀ (a : α), 𝓝 a = comap f (𝓝 $ f a) :=
(induced_iff_nhds_eq f).1 hf.induced
lemma inducing.map_nhds_eq {f : α → β} (hf : inducing f) (a : α) (h : range f ∈ 𝓝 (f a)) :
(𝓝 a).map f = 𝓝 (f a) :=
hf.induced.symm ▸ map_nhds_induced_eq h
lemma inducing.tendsto_nhds_iff {ι : Type*}
{f : ι → β} {g : β → γ} {a : filter ι} {b : β} (hg : inducing g) :
tendsto f a (𝓝 b) ↔ tendsto (g ∘ f) a (𝓝 (g b)) :=
by rw [tendsto, tendsto, hg.induced, nhds_induced, ← map_le_iff_le_comap, filter.map_map]
lemma inducing.continuous_iff {f : α → β} {g : β → γ} (hg : inducing g) :
continuous f ↔ continuous (g ∘ f) :=
by simp [continuous_iff_continuous_at, continuous_at, inducing.tendsto_nhds_iff hg]
lemma inducing.continuous {f : α → β} (hf : inducing f) : continuous f :=
hf.continuous_iff.mp continuous_id
end inducing
section embedding
/-- A function between topological spaces is an embedding if it is injective,
and for all `s : set α`, `s` is open iff it is the preimage of an open set. -/
structure embedding [tα : topological_space α] [tβ : topological_space β] (f : α → β)
extends inducing f : Prop :=
(inj : function.injective f)
variables [topological_space α] [topological_space β] [topological_space γ]
lemma embedding.mk' (f : α → β) (inj : function.injective f)
(induced : ∀a, comap f (𝓝 (f a)) = 𝓝 a) : embedding f :=
⟨⟨(induced_iff_nhds_eq f).2 (λ a, (induced a).symm)⟩, inj⟩
lemma embedding_id : embedding (@id α) :=
⟨inducing_id, assume a₁ a₂ h, h⟩
lemma embedding.comp {g : β → γ} {f : α → β} (hg : embedding g) (hf : embedding f) :
embedding (g ∘ f) :=
{ inj:= assume a₁ a₂ h, hf.inj $ hg.inj h,
..hg.to_inducing.comp hf.to_inducing }
lemma embedding_of_embedding_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g)
(hgf : embedding (g ∘ f)) : embedding f :=
{ induced := (inducing_of_inducing_compose hf hg hgf.to_inducing).induced,
inj := assume a₁ a₂ h, hgf.inj $ by simp [h, (∘)] }
lemma embedding_open {f : α → β} {s : set α}
(hf : embedding f) (h : is_open (range f)) (hs : is_open s) : is_open (f '' s) :=
inducing_open hf.1 h hs
lemma embedding_is_closed {f : α → β} {s : set α}
(hf : embedding f) (h : is_closed (range f)) (hs : is_closed s) : is_closed (f '' s) :=
inducing_is_closed hf.1 h hs
lemma embedding.map_nhds_eq {f : α → β}
(hf : embedding f) (a : α) (h : range f ∈ 𝓝 (f a)) : (𝓝 a).map f = 𝓝 (f a) :=
inducing.map_nhds_eq hf.1 a h
lemma embedding.tendsto_nhds_iff {ι : Type*}
{f : ι → β} {g : β → γ} {a : filter ι} {b : β} (hg : embedding g) :
tendsto f a (𝓝 b) ↔ tendsto (g ∘ f) a (𝓝 (g b)) :=
by rw [tendsto, tendsto, hg.induced, nhds_induced, ← map_le_iff_le_comap, filter.map_map]
lemma embedding.continuous_iff {f : α → β} {g : β → γ} (hg : embedding g) :
continuous f ↔ continuous (g ∘ f) :=
inducing.continuous_iff hg.1
lemma embedding.continuous {f : α → β} (hf : embedding f) : continuous f :=
inducing.continuous hf.1
lemma embedding.closure_eq_preimage_closure_image {e : α → β} (he : embedding e) (s : set α) :
closure s = e ⁻¹' closure (e '' s) :=
by { ext x, rw [set.mem_preimage, ← closure_induced he.inj, he.induced] }
end embedding
/-- A function between topological spaces is a quotient map if it is surjective,
and for all `s : set β`, `s` is open iff its preimage is an open set. -/
def quotient_map {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β]
(f : α → β) : Prop :=
function.surjective f ∧ tβ = tα.coinduced f
namespace quotient_map
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
protected lemma id : quotient_map (@id α) :=
⟨assume a, ⟨a, rfl⟩, coinduced_id.symm⟩
protected lemma comp {g : β → γ} {f : α → β} (hg : quotient_map g) (hf : quotient_map f) :
quotient_map (g ∘ f) :=
⟨hg.left.comp hf.left, by rw [hg.right, hf.right, coinduced_compose]⟩
protected lemma of_quotient_map_compose {f : α → β} {g : β → γ}
(hf : continuous f) (hg : continuous g)
(hgf : quotient_map (g ∘ f)) : quotient_map g :=
⟨assume b, let ⟨a, h⟩ := hgf.left b in ⟨f a, h⟩,
le_antisymm
(by rw [hgf.right, ← continuous_iff_coinduced_le];
apply continuous_coinduced_rng.comp hf)
(by rwa ← continuous_iff_coinduced_le)⟩
protected lemma continuous_iff {f : α → β} {g : β → γ} (hf : quotient_map f) :
continuous g ↔ continuous (g ∘ f) :=
by rw [continuous_iff_coinduced_le, continuous_iff_coinduced_le, hf.right, coinduced_compose]
protected lemma continuous {f : α → β} (hf : quotient_map f) : continuous f :=
hf.continuous_iff.mp continuous_id
end quotient_map
/-- A map `f : α → β` is said to be an *open map*, if the image of any open `U : set α`
is open in `β`. -/
def is_open_map [topological_space α] [topological_space β] (f : α → β) :=
∀ U : set α, is_open U → is_open (f '' U)
namespace is_open_map
variables [topological_space α] [topological_space β] [topological_space γ]
open function
protected lemma id : is_open_map (@id α) := assume s hs, by rwa [image_id]
protected lemma comp
{g : β → γ} {f : α → β} (hg : is_open_map g) (hf : is_open_map f) : is_open_map (g ∘ f) :=
by intros s hs; rw [image_comp]; exact hg _ (hf _ hs)
lemma is_open_range {f : α → β} (hf : is_open_map f) : is_open (range f) :=
by { rw ← image_univ, exact hf _ is_open_univ }
lemma image_mem_nhds {f : α → β} (hf : is_open_map f) {x : α} {s : set α} (hx : s ∈ 𝓝 x) :
f '' s ∈ 𝓝 (f x) :=
let ⟨t, hts, ht, hxt⟩ := mem_nhds_sets_iff.1 hx in
mem_sets_of_superset (mem_nhds_sets (hf t ht) (mem_image_of_mem _ hxt)) (image_subset _ hts)
lemma nhds_le {f : α → β} (hf : is_open_map f) (a : α) : 𝓝 (f a) ≤ (𝓝 a).map f :=
le_map $ λ s, hf.image_mem_nhds
lemma of_inverse {f : α → β} {f' : β → α}
(h : continuous f') (l_inv : left_inverse f f') (r_inv : right_inverse f f') :
is_open_map f :=
assume s hs,
have f' ⁻¹' s = f '' s, by ext x; simp [mem_image_iff_of_inverse r_inv l_inv],
this ▸ h s hs
lemma to_quotient_map {f : α → β}
(open_map : is_open_map f) (cont : continuous f) (surj : function.surjective f) :
quotient_map f :=
⟨ surj,
begin
ext s,
show is_open s ↔ is_open (f ⁻¹' s),
split,
{ exact cont s },
{ assume h,
rw ← @image_preimage_eq _ _ _ s surj,
exact open_map _ h }
end⟩
end is_open_map
lemma is_open_map_iff_nhds_le [topological_space α] [topological_space β] {f : α → β} :
is_open_map f ↔ ∀(a:α), 𝓝 (f a) ≤ (𝓝 a).map f :=
begin
refine ⟨λ hf, hf.nhds_le, λ h s hs, is_open_iff_mem_nhds.2 _⟩,
rintros b ⟨a, ha, rfl⟩,
exact h _ (filter.image_mem_map $ mem_nhds_sets hs ha)
end
section is_closed_map
variables [topological_space α] [topological_space β]
def is_closed_map (f : α → β) := ∀ U : set α, is_closed U → is_closed (f '' U)
end is_closed_map
namespace is_closed_map
variables [topological_space α] [topological_space β] [topological_space γ]
open function
protected lemma id : is_closed_map (@id α) := assume s hs, by rwa image_id
protected lemma comp {g : β → γ} {f : α → β} (hg : is_closed_map g) (hf : is_closed_map f) :
is_closed_map (g ∘ f) :=
by { intros s hs, rw image_comp, exact hg _ (hf _ hs) }
lemma of_inverse {f : α → β} {f' : β → α}
(h : continuous f') (l_inv : left_inverse f f') (r_inv : right_inverse f f') :
is_closed_map f :=
assume s hs,
have f' ⁻¹' s = f '' s, by ext x; simp [mem_image_iff_of_inverse r_inv l_inv],
this ▸ continuous_iff_is_closed.mp h s hs
lemma of_nonempty {f : α → β} (h : ∀ s, is_closed s → s.nonempty → is_closed (f '' s)) :
is_closed_map f :=
begin
intros s hs, cases eq_empty_or_nonempty s with h2s h2s,
{ simp_rw [h2s, image_empty, is_closed_empty] },
{ exact h s hs h2s }
end
end is_closed_map
section open_embedding
variables [topological_space α] [topological_space β] [topological_space γ]
/-- An open embedding is an embedding with open image. -/
structure open_embedding (f : α → β) extends embedding f : Prop :=
(open_range : is_open $ range f)
lemma open_embedding.open_iff_image_open {f : α → β} (hf : open_embedding f)
{s : set α} : is_open s ↔ is_open (f '' s) :=
⟨embedding_open hf.to_embedding hf.open_range,
λ h, begin
convert ←hf.to_embedding.continuous _ h,
apply preimage_image_eq _ hf.inj
end⟩
lemma open_embedding.is_open_map {f : α → β} (hf : open_embedding f) : is_open_map f :=
λ s, hf.open_iff_image_open.mp
lemma open_embedding.continuous {f : α → β} (hf : open_embedding f) : continuous f :=
hf.to_embedding.continuous
lemma open_embedding.open_iff_preimage_open {f : α → β} (hf : open_embedding f)
{s : set β} (hs : s ⊆ range f) : is_open s ↔ is_open (f ⁻¹' s) :=
begin
convert ←hf.open_iff_image_open.symm,
rwa [image_preimage_eq_inter_range, inter_eq_self_of_subset_left]
end
lemma open_embedding_of_embedding_open {f : α → β} (h₁ : embedding f)
(h₂ : is_open_map f) : open_embedding f :=
⟨h₁, by convert h₂ univ is_open_univ; simp⟩
lemma open_embedding_of_continuous_injective_open {f : α → β} (h₁ : continuous f)
(h₂ : function.injective f) (h₃ : is_open_map f) : open_embedding f :=
begin
refine open_embedding_of_embedding_open ⟨⟨_⟩, h₂⟩ h₃,
apply le_antisymm (continuous_iff_le_induced.mp h₁) _,
intro s,
change is_open _ ≤ is_open _,
rw is_open_induced_iff,
refine λ hs, ⟨f '' s, h₃ s hs, _⟩,
rw preimage_image_eq _ h₂
end
lemma open_embedding_id : open_embedding (@id α) :=
⟨embedding_id, by convert is_open_univ; apply range_id⟩
lemma open_embedding.comp {g : β → γ} {f : α → β}
(hg : open_embedding g) (hf : open_embedding f) : open_embedding (g ∘ f) :=
⟨hg.1.comp hf.1, show is_open (range (g ∘ f)),
by rw [range_comp, ←hg.open_iff_image_open]; exact hf.2⟩
end open_embedding
section closed_embedding
variables [topological_space α] [topological_space β] [topological_space γ]
/-- A closed embedding is an embedding with closed image. -/
structure closed_embedding (f : α → β) extends embedding f : Prop :=
(closed_range : is_closed $ range f)
variables {f : α → β}
lemma closed_embedding.continuous (hf : closed_embedding f) : continuous f :=
hf.to_embedding.continuous
lemma closed_embedding.closed_iff_image_closed (hf : closed_embedding f)
{s : set α} : is_closed s ↔ is_closed (f '' s) :=
⟨embedding_is_closed hf.to_embedding hf.closed_range,
λ h, begin
convert ←continuous_iff_is_closed.mp hf.continuous _ h,
apply preimage_image_eq _ hf.inj
end⟩
lemma closed_embedding.is_closed_map (hf : closed_embedding f) : is_closed_map f :=
λ s, hf.closed_iff_image_closed.mp
lemma closed_embedding.closed_iff_preimage_closed (hf : closed_embedding f)
{s : set β} (hs : s ⊆ range f) : is_closed s ↔ is_closed (f ⁻¹' s) :=
begin
convert ←hf.closed_iff_image_closed.symm,
rwa [image_preimage_eq_inter_range, inter_eq_self_of_subset_left]
end
lemma closed_embedding_of_embedding_closed (h₁ : embedding f)
(h₂ : is_closed_map f) : closed_embedding f :=
⟨h₁, by convert h₂ univ is_closed_univ; simp⟩
lemma closed_embedding_of_continuous_injective_closed (h₁ : continuous f)
(h₂ : function.injective f) (h₃ : is_closed_map f) : closed_embedding f :=
begin
refine closed_embedding_of_embedding_closed ⟨⟨_⟩, h₂⟩ h₃,
apply le_antisymm (continuous_iff_le_induced.mp h₁) _,
intro s',
change is_open _ ≤ is_open _,
rw [←is_closed_compl_iff, ←is_closed_compl_iff],
generalize : s'ᶜ = s,
rw is_closed_induced_iff,
refine λ hs, ⟨f '' s, h₃ s hs, _⟩,
rw preimage_image_eq _ h₂
end
lemma closed_embedding_id : closed_embedding (@id α) :=
⟨embedding_id, by convert is_closed_univ; apply range_id⟩
lemma closed_embedding.comp {g : β → γ} {f : α → β}
(hg : closed_embedding g) (hf : closed_embedding f) : closed_embedding (g ∘ f) :=
⟨hg.to_embedding.comp hf.to_embedding, show is_closed (range (g ∘ f)),
by rw [range_comp, ←hg.closed_iff_image_closed]; exact hf.closed_range⟩
end closed_embedding
|
a2a85c3dd7815887ee7e6ecbd7adce3c548da963 | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/linear_algebra/basis.lean | 681be77181c799bb9b9fc165bf886ed703313b09 | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 52,472 | 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 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
variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*}
{M : Type*} {M' : Type*} {V : Type*} {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, s.sum (λ i, g i • v i) = 0 → ∀ i ∈ s, g i = 0 :=
linear_independent_iff.trans
⟨λ hf s g hg i his, have h : _ := hf (s.sum $ λ i, 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]
... = s.sum (λ j, (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)
... = s.sum (λ j, 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⟩
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 ∘ subtype.val : 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 subtype.val (subtype.val ⁻¹' ↑l.support : set s) ↑l.support,
{ apply bij_on.mk,
{ unfold maps_to },
{ apply subtype.val_injective.inj_on },
intros i hi,
rw [image_preimage_eq_inter_range, subtype.range_val],
exact ⟨hi, (finsupp.mem_supported _ _).1 hl₁ hi⟩ },
show l = 0,
{ apply finsupp.eq_zero_of_comap_domain_eq_zero (subtype.val : s → ι) _ h_bij,
apply h,
convert hl₂,
rw [finsupp.lmap_domain_apply, finsupp.map_domain_comap_domain],
exact subtype.val_injective,
rw subtype.range_val,
exact (finsupp.mem_supported _ _).1 hl₁ } },
{ intros h l hl,
have hl' : finsupp.total ι M R v (finsupp.emb_domain ⟨subtype.val, subtype.val_injective⟩ l) = 0,
{ rw finsupp.emb_domain_eq_map_domain ⟨subtype.val, subtype.val_injective⟩ l,
apply hl },
apply finsupp.emb_domain_inj.1,
rw [h (finsupp.emb_domain ⟨subtype.val, subtype.val_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 ∘ subtype.val : 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,
{ unfold maps_to },
{ 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.injective_map_domain 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 ∘ subtype.val : s → M)) :
linear_independent R (s.restrict v) :=
begin
have h_restrict : restrict v s = v ∘ (λ x, x.val) := rfl,
rw [linear_independent_iff, h_restrict, finsupp.total_comp],
intros l hl,
have h_map_domain_subtype_eq_0 : l.map_domain subtype.val = 0,
{ rw linear_independent_comp_subtype at hs,
apply hs (finsupp.lmap_domain R R (λ x : subtype s, x.val) 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.val_image_subset _ _ this },
apply @finsupp.injective_map_domain _ (subtype s) ι,
{ apply subtype.val_injective },
{ simpa },
end
lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) :=
by simp [linear_independent_subtype_disjoint]
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 finite_preimage (assume i j _ _, plift.up.inj) s.finite_to_set } }
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.coe_ext.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.coe_ext.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.inj).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.inj).total_repr,
{ refl },
{ exact f.inj } },
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.val_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 injective_comp prod.injective_inl inj_v },
{ exact injective_comp prod.injective_inr 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.
s.sum (λ i, ((g i * i x - g i * a x) • i : G → L)) y
= s.sum (λ i, (g i * i x - g i * a x) * i y) : pi.finset_sum_apply _ _ _
... = s.sum (λ i, g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl
(λ _ _, sub_mul _ _ _)
... = s.sum (λ i, g i * i x * i y) - s.sum (λ i, g i * a x * i y) : finset.sum_sub_distrib
... = (g a * a x * a y + s.sum (λ i, g i * i x * i y))
- (g a * a x * a y + s.sum (λ i, g i * a x * i y)) : by rw add_sub_add_left_eq_sub
... = (insert a s).sum (λ i, g i * i x * i y) - (insert a s).sum (λ i, g i * a x * i y) :
by rw [finset.sum_insert has, finset.sum_insert has]
... = (insert a s).sum (λ i, g i * i (x * y)) - (insert a s).sum (λ i, 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])
... = (insert a s).sum (λ i, (g i • i : G → L)) (x * y)
- a x * (insert a s).sum (λ i, (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
... = (insert a s).sum (λ i, (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 (subtype.val : 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 (subtype.val : 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
/-- 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 $ injective_of_left_inverse 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
/-- 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.coe_ext, ← 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.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,
add := λ x y, by ext; exact finsupp.add_apply,
smul := λ x y, by ext; exact finsupp.smul_apply,
..finsupp.equiv_fun_on_fintype }
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 = finset.sum finset.univ (λi, x i • v i) :=
begin
change finsupp.sum
((finsupp.equiv_fun_on_fintype.symm : (ι → R) ≃ (ι →₀ R)) x) (λ (i : ι) (a : R), a • v i)
= finset.sum finset.univ (λ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₂⟩
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 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 K _) 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,
{ apply finset.ext.mpr,
intro 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 finite_subset u.finite_to_set 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 B.range_coe_subtype 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 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) :=
begin
rcases p.mkq.exists_right_inverse_of_surjective p.range_mkq with ⟨f, hf⟩,
have mkf : ∀ x, submodule.quotient.mk (f x) = x := linear_map.ext_iff.1 hf,
have fp : ∀ x, x - f (p.mkq x) ∈ p :=
λ x, (submodule.quotient.eq p).1 (mkf (p.mkq x)).symm,
refine ⟨linear_equiv.of_linear (f.coprod p.subtype)
(p.mkq.prod (cod_restrict p (linear_map.id - f.comp p.mkq) fp))
(by ext; simp) _⟩,
ext ⟨⟨x⟩, y, hy⟩; simp,
{ apply (submodule.quotient.eq p).2,
simpa [sub_eq_add_neg, add_left_comm] using sub_mem p hy (fp x) },
{ refine subtype.coe_ext.2 _,
simp [mkf, (submodule.quotient.mk_eq_zero p).2 hy] }
end
open fintype
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
|
813988c20419873b29aac150bbbb58e0946cc92d | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/data/rat.lean | 96ecc5cac417d38b08a7e5d9ce6d1a8b9f62a3fc | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 44,835 | 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
Introduces the rational numbers as discrete, linear ordered field.
-/
import
data.nat.gcd data.pnat data.int.sqrt data.equiv.encodable
algebra.group algebra.ordered_group algebra.group_power
algebra.ordered_field
/- rational numbers -/
/-- `rat`, or `ℚ`, is the type of rational numbers. It is defined
as the set of pairs ⟨n, d⟩ of integers such that `d` is positive and `n` and
`d` are coprime. This representation is preferred to the quotient
because without periodic reduction, the numerator and denominator can grow
exponentially (for example, adding 1/2 to itself repeatedly). -/
structure rat := mk' ::
(num : ℤ)
(denom : ℕ)
(pos : denom > 0)
(cop : num.nat_abs.coprime denom)
notation `ℚ` := rat
namespace rat
protected def repr : ℚ → string
| ⟨n, d, _, _⟩ := if d = 1 then _root_.repr n else
_root_.repr n ++ "/" ++ _root_.repr d
instance : has_repr ℚ := ⟨rat.repr⟩
instance : has_to_string ℚ := ⟨rat.repr⟩
meta instance : has_to_format ℚ := ⟨coe ∘ rat.repr⟩
instance : encodable ℚ := encodable.of_equiv (Σ n : ℤ, {d : ℕ // d > 0 ∧ n.nat_abs.coprime d})
⟨λ ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ⟨a, b, c, d⟩, ⟨a, b, c, d⟩,
λ ⟨a, b, c, d⟩, rfl, λ⟨a, b, c, d⟩, rfl⟩
/-- Embed an integer as a rational number -/
def of_int (n : ℤ) : ℚ :=
⟨n, 1, nat.one_pos, nat.coprime_one_right _⟩
instance : has_zero ℚ := ⟨of_int 0⟩
instance : has_one ℚ := ⟨of_int 1⟩
instance : inhabited ℚ := ⟨0⟩
/-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ+` (not necessarily coprime) -/
def mk_pnat (n : ℤ) : ℕ+ → ℚ | ⟨d, dpos⟩ :=
let n' := n.nat_abs, g := n'.gcd d in
⟨n / g, d / g, begin
apply (nat.le_div_iff_mul_le _ _ (nat.gcd_pos_of_pos_right _ dpos)).2,
simp, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _)
end, begin
have : int.nat_abs (n / ↑g) = n' / g,
{ cases int.nat_abs_eq n with e e; rw e, { refl },
rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl },
exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) },
rw this,
exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos)
end⟩
/-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ`. In the case `d = 0`, we
define `n / 0 = 0` by convention. -/
def mk_nat (n : ℤ) (d : ℕ) : ℚ :=
if d0 : d = 0 then 0 else mk_pnat n ⟨d, nat.pos_of_ne_zero d0⟩
/-- Form the quotient `n / d` where `n d : ℤ`. -/
def mk : ℤ → ℤ → ℚ
| n (int.of_nat d) := mk_nat n d
| n -[1+ d] := mk_pnat (-n) d.succ_pnat
local infix ` /. `:70 := mk
theorem mk_pnat_eq (n d h) : mk_pnat n ⟨d, h⟩ = n /. d :=
by change n /. d with dite _ _ _; simp [ne_of_gt h]
theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl
@[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl
@[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 :=
by cases n; simp [mk_pnat]; change int.nat_abs 0 with 0; simp *; refl
@[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 :=
by by_cases n = 0; simp [*, mk_nat]
@[simp] theorem zero_mk (n) : 0 /. n = 0 :=
by cases n; simp [mk]
private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : ℤ) ∣ a :=
int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left (int.nat_abs a) b
@[simp] theorem mk_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 :=
begin
constructor; intro h; [skip, {subst a, simp}],
have : ∀ {a b}, mk_pnat a b = 0 → a = 0,
{ intros a b e, cases b with b h,
injection e with e,
apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e },
cases b with b; simp [mk, mk_nat] at h,
{ simp [mt (congr_arg int.of_nat) b0] at h,
exact this h },
{ apply neg_inj, simp [this h] }
end
theorem mk_eq : ∀ {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0),
a /. b = c /. d ↔ a * d = c * b :=
suffices ∀ a b c d hb hd, mk_pnat a ⟨b, hb⟩ = mk_pnat c ⟨d, hd⟩ ↔ a * d = c * b,
begin
intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hb],
all_goals {
cases d with d d; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hd],
all_goals { rw this, try {refl} } },
{ change a * ↑(d.succ) = -c * ↑b ↔ a * -(d.succ) = c * b,
constructor; intro h; apply neg_inj; simpa [left_distrib, neg_add_eq_iff_eq_add,
eq_neg_iff_add_eq_zero, neg_eq_iff_add_eq_zero] using h },
{ change -a * ↑d = c * b.succ ↔ a * d = c * -b.succ,
constructor; intro h; apply neg_inj; simpa [left_distrib, eq_comm] using h },
{ change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ,
simp [left_distrib] }
end,
begin
intros, simp [mk_pnat], constructor; intro h,
{ cases h with ha hb,
have ha, {
have dv := @gcd_abs_dvd_left,
have := int.eq_mul_of_div_eq_right dv ha,
rw ← int.mul_div_assoc _ dv at this,
exact int.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm },
have hb, {
have dv := λ {a b}, nat.gcd_dvd_right (int.nat_abs a) b,
have := nat.eq_mul_of_div_eq_right dv hb,
rw ← nat.mul_div_assoc _ dv at this,
exact nat.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm },
have m0 : (a.nat_abs.gcd b * c.nat_abs.gcd d : ℤ) ≠ 0, {
refine int.coe_nat_ne_zero.2 (ne_of_gt _),
apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption },
apply eq_of_mul_eq_mul_right m0,
simpa [mul_comm, mul_left_comm] using
congr (congr_arg (*) ha.symm) (congr_arg coe hb) },
{ suffices : ∀ a c, a * d = c * b →
a / a.gcd b = c / c.gcd d ∧ b / a.gcd b = d / c.gcd d,
{ cases this a.nat_abs c.nat_abs
(by simpa [int.nat_abs_mul] using congr_arg int.nat_abs h) with h₁ h₂,
have hs := congr_arg int.sign h,
simp [int.sign_eq_one_of_pos (int.coe_nat_lt.2 hb),
int.sign_eq_one_of_pos (int.coe_nat_lt.2 hd)] at hs,
conv in a { rw ← int.sign_mul_nat_abs a },
conv in c { rw ← int.sign_mul_nat_abs c },
rw [int.mul_div_assoc, int.mul_div_assoc],
exact ⟨congr (congr_arg (*) hs) (congr_arg coe h₁), h₂⟩,
all_goals { exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) } },
intros a c h,
suffices bd : b / a.gcd b = d / c.gcd d,
{ refine ⟨_, bd⟩,
apply nat.eq_of_mul_eq_mul_left hb,
rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd,
← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] },
suffices : ∀ {a c : ℕ} (b>0) (d>0),
a * d = c * b → b / a.gcd b ≤ d / c.gcd d,
{ exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) },
intros a c b hb d hd h,
have gb0 := nat.gcd_pos_of_pos_right a hb,
have gd0 := nat.gcd_pos_of_pos_right c hd,
apply nat.le_of_dvd,
apply (nat.le_div_iff_mul_le _ _ gd0).2,
simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _),
apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left,
refine ⟨c / c.gcd d, _⟩,
rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)],
apply congr_arg (/ c.gcd d),
rw [mul_comm, ← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] }
end
@[simp] theorem div_mk_div_cancel_left {a b c : ℤ} (c0 : c ≠ 0) :
(a * c) /. (b * c) = a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp },
apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp [mul_comm, mul_assoc]
end
theorem num_denom : ∀ a : ℚ, a = a.num /. a.denom
| ⟨n, d, h, (c:_=1)⟩ := show _ = mk_nat n d,
by simp [mk_nat, ne_of_gt h, mk_pnat, c]
theorem num_denom' (n d h c) : (⟨n, d, h, c⟩ : ℚ) = n /. d := num_denom _
@[elab_as_eliminator] theorem {u} num_denom_cases_on {C : ℚ → Sort u}
: ∀ (a : ℚ) (H : ∀ n d, d > 0 → (int.nat_abs n).coprime d → C (n /. d)), C a
| ⟨n, d, h, c⟩ H := by rw num_denom'; exact H n d h c
@[elab_as_eliminator] theorem {u} num_denom_cases_on' {C : ℚ → Sort u}
(a : ℚ) (H : ∀ (n:ℤ) (d:ℕ), d ≠ 0 → C (n /. d)) : C a :=
num_denom_cases_on a $ λ n d h c,
H n d $ ne_of_gt h
theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a :=
begin
cases e : a /. b with n d h c,
rw [rat.num_denom', rat.mk_eq b0
(ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $
c.dvd_of_dvd_mul_right _),
have := congr_arg int.nat_abs e,
simp [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this]
end
theorem denom_dvd (a b : ℤ) : ((a /. b).denom : ℤ) ∣ b :=
begin
by_cases b0 : b = 0, {simp [b0]},
cases e : a /. b with n d h c,
rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _),
rw [← int.nat_abs_mul, ← int.coe_nat_dvd, int.dvd_nat_abs, ← e], simp
end
protected def add : ℚ → ℚ → ℚ
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * d₂ + n₂ * d₁) ⟨d₁ * d₂, mul_pos h₁ h₂⟩
instance : has_add ℚ := ⟨rat.add⟩
theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ)
(fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂},
f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂)
(f0 : ∀ {n₁ d₁ n₂ d₂} (d₁0 : d₁ ≠ 0) (d₂0 : d₂ ≠ 0), f₂ n₁ d₁ n₂ d₂ ≠ 0)
(a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0)
(H : ∀ {n₁ d₁ n₂ d₂} (h₁ : a * d₁ = n₁ * b) (h₂ : c * d₂ = n₂ * d),
f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) :
f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d :=
begin
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
generalize hc : c /. d = x, cases x with n₂ d₂ h₂ c₂, rw num_denom' at hc,
rw fv,
have d₁0 := ne_of_gt (int.coe_nat_lt.2 h₁),
have d₂0 := ne_of_gt (int.coe_nat_lt.2 h₂),
exact (mk_eq (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((mk_eq b0 d₁0).1 ha) ((mk_eq d0 d₂0).1 hc))
end
@[simp] theorem add_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
a /. b + c /. d = (a * d + c * b) /. (b * d) :=
begin
apply lift_binop_eq rat.add; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero d₁0 d₂0 },
calc (n₁ * d₂ + n₂ * d₁) * (b * d) =
(n₁ * b) * d₂ * d + (n₂ * d) * (d₁ * b) : by simp [mul_add, mul_comm, mul_left_comm]
... = (a * d₁) * d₂ * d + (c * d₂) * (d₁ * b) : by rw [h₁, h₂]
... = (a * d + c * b) * (d₁ * d₂) : by simp [mul_add, mul_comm, mul_left_comm]
end
protected def neg : ℚ → ℚ
| ⟨n, d, h, c⟩ := ⟨-n, d, h, by simp [c]⟩
instance : has_neg ℚ := ⟨rat.neg⟩
@[simp] theorem neg_def {a b : ℤ} : -(a /. b) = -a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
show rat.mk' _ _ _ _ = _, rw num_denom',
have d0 := ne_of_gt (int.coe_nat_lt.2 h₁),
apply (mk_eq d0 b0).2, have h₁ := (mk_eq b0 d0).1 ha,
simp only [neg_mul_eq_neg_mul_symm, congr_arg has_neg.neg h₁]
end
protected def mul : ℚ → ℚ → ℚ
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * n₂) ⟨d₁ * d₂, mul_pos h₁ h₂⟩
instance : has_mul ℚ := ⟨rat.mul⟩
@[simp] theorem mul_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
(a /. b) * (c /. d) = (a * c) /. (b * d) :=
begin
apply lift_binop_eq rat.mul; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero d₁0 d₂0 },
cc
end
protected def inv : ℚ → ℚ
| ⟨(n+1:ℕ), d, h, c⟩ := ⟨d, n+1, n.succ_pos, c.symm⟩
| ⟨0, d, h, c⟩ := 0
| ⟨-[1+ n], d, h, c⟩ := ⟨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact c⟩
instance : has_inv ℚ := ⟨rat.inv⟩
@[simp] theorem inv_def {a b : ℤ} : (a /. b)⁻¹ = b /. a :=
begin
by_cases a0 : a = 0, { subst a0, simp, refl },
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha,
refine eq.trans (_ : rat.inv ⟨n, d, h, c⟩ = d /. n) _,
{ cases n with n; [cases n with n, skip],
{ refl },
{ change int.of_nat n.succ with (n+1:ℕ),
unfold rat.inv, rw num_denom' },
{ unfold rat.inv, rw num_denom', refl } },
have n0 : n ≠ 0,
{ refine mt (λ (n0 : n = 0), _) a0,
subst n0, simp at ha,
exact (mk_eq_zero b0).1 ha },
have d0 := ne_of_gt (int.coe_nat_lt.2 h),
have ha := (mk_eq b0 d0).1 ha,
apply (mk_eq n0 a0).2,
cc
end
variables (a b c : ℚ)
protected theorem add_zero : a + 0 = a :=
num_denom_cases_on' a $ λ n d h,
by rw [← zero_mk d]; simp [h, -zero_mk]
protected theorem zero_add : 0 + a = a :=
num_denom_cases_on' a $ λ n d h,
by rw [← zero_mk d]; simp [h, -zero_mk]
protected theorem add_comm : a + b = b + a :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
by simp [h₁, h₂, mul_comm]
protected theorem add_assoc : a + b + c = a + (b + c) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero, mul_add, mul_comm, mul_left_comm, add_left_comm]
protected theorem add_left_neg : -a + a = 0 :=
num_denom_cases_on' a $ λ n d h,
by simp [h]
protected theorem mul_one : a * 1 = a :=
num_denom_cases_on' a $ λ n d h,
by change (1:ℚ) with 1 /. 1; simp [h]
protected theorem one_mul : 1 * a = a :=
num_denom_cases_on' a $ λ n d h,
by change (1:ℚ) with 1 /. 1; simp [h]
protected theorem mul_comm : a * b = b * a :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
by simp [h₁, h₂, mul_comm]
protected theorem mul_assoc : a * b * c = a * (b * c) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero, mul_comm, mul_left_comm]
protected theorem add_mul : (a + b) * c = a * c + b * c :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero];
refine (div_mk_div_cancel_left (int.coe_nat_ne_zero.2 h₃)).symm.trans _;
simp [mul_add, mul_comm, mul_assoc, mul_left_comm]
protected theorem mul_add : a * (b + c) = a * b + a * c :=
by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a]
protected theorem zero_ne_one : 0 ≠ (1:ℚ) :=
mt (λ (h : 0 = 1 /. 1), (mk_eq_zero one_ne_zero).1 h.symm) one_ne_zero
protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 :=
num_denom_cases_on' a $ λ n d h a0,
have n0 : n ≠ 0, from mt (by intro e; subst e; simp) a0,
by simp [h, n0, mul_comm]; exact
eq.trans (by simp) (@div_mk_div_cancel_left 1 1 _ n0)
protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 :=
eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h)
instance : decidable_eq ℚ := by tactic.mk_dec_eq_instance
instance : discrete_field ℚ :=
{ zero := 0,
add := rat.add,
neg := rat.neg,
one := 1,
mul := rat.mul,
inv := rat.inv,
zero_add := rat.zero_add,
add_zero := rat.add_zero,
add_comm := rat.add_comm,
add_assoc := rat.add_assoc,
add_left_neg := rat.add_left_neg,
mul_one := rat.mul_one,
one_mul := rat.one_mul,
mul_comm := rat.mul_comm,
mul_assoc := rat.mul_assoc,
left_distrib := rat.mul_add,
right_distrib := rat.add_mul,
zero_ne_one := rat.zero_ne_one,
mul_inv_cancel := rat.mul_inv_cancel,
inv_mul_cancel := rat.inv_mul_cancel,
has_decidable_eq := rat.decidable_eq,
inv_zero := rfl }
/- Extra instances to short-circuit type class resolution -/
instance : field ℚ := by apply_instance
instance : division_ring ℚ := by apply_instance
instance : integral_domain ℚ := by apply_instance
-- TODO(Mario): this instance slows down data.real.basic
--instance : domain ℚ := by apply_instance
instance : nonzero_comm_ring ℚ := by apply_instance
instance : comm_ring ℚ := by apply_instance
--instance : ring ℚ := by apply_instance
instance : comm_semiring ℚ := by apply_instance
instance : semiring ℚ := by apply_instance
instance : add_comm_group ℚ := by apply_instance
instance : add_group ℚ := by apply_instance
instance : add_comm_monoid ℚ := by apply_instance
instance : add_monoid ℚ := by apply_instance
instance : add_left_cancel_semigroup ℚ := by apply_instance
instance : add_right_cancel_semigroup ℚ := by apply_instance
instance : add_comm_semigroup ℚ := by apply_instance
instance : add_semigroup ℚ := by apply_instance
instance : comm_monoid ℚ := by apply_instance
instance : monoid ℚ := by apply_instance
instance : comm_semigroup ℚ := by apply_instance
instance : semigroup ℚ := by apply_instance
theorem sub_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
a /. b - c /. d = (a * d - c * b) /. (b * d) :=
by simp [b0, d0]
protected def nonneg : ℚ → Prop
| ⟨n, d, h, c⟩ := n ≥ 0
@[simp] theorem mk_nonneg (a : ℤ) {b : ℤ} (h : b > 0) : (a /. b).nonneg ↔ a ≥ 0 :=
begin
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
simp [rat.nonneg],
have d0 := int.coe_nat_lt.2 h₁,
have := (mk_eq (ne_of_gt h) (ne_of_gt d0)).1 ha,
constructor; intro h₂,
{ apply nonneg_of_mul_nonneg_right _ d0,
rw this, exact mul_nonneg h₂ (le_of_lt h) },
{ apply nonneg_of_mul_nonneg_right _ h,
rw ← this, exact mul_nonneg h₂ (int.coe_zero_le _) },
end
protected def nonneg_add {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a + b) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
begin
have d₁0 : (d₁:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁),
have d₂0 : (d₂:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂),
simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0],
intros n₁0 n₂0,
apply add_nonneg; apply mul_nonneg; {assumption <|> apply int.coe_zero_le}
end
protected def nonneg_mul {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a * b) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
begin
have d₁0 : (d₁:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁),
have d₂0 : (d₂:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂),
simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0],
exact mul_nonneg
end
protected def nonneg_antisymm {a} : rat.nonneg a → rat.nonneg (-a) → a = 0 :=
num_denom_cases_on' a $ λ n d h,
begin
have d0 : (d:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h),
simp [d0, h],
exact λ h₁ h₂, le_antisymm (nonpos_of_neg_nonneg h₂) h₁
end
protected def nonneg_total : rat.nonneg a ∨ rat.nonneg (-a) :=
by cases a with n; exact
or.imp_right neg_nonneg_of_nonpos (le_total 0 n)
instance decidable_nonneg : decidable (rat.nonneg a) :=
by cases a; unfold rat.nonneg; apply_instance
protected def le (a b : ℚ) := rat.nonneg (b - a)
instance : has_le ℚ := ⟨rat.le⟩
instance decidable_le : decidable_rel ((≤) : ℚ → ℚ → Prop)
| a b := show decidable (rat.nonneg (b - a)), by apply_instance
protected theorem le_def {a b c d : ℤ} (b0 : b > 0) (d0 : d > 0) :
a /. b ≤ c /. d ↔ a * d ≤ c * b :=
show rat.nonneg _ ↔ _,
by simpa [ne_of_gt b0, ne_of_gt d0, mul_pos b0 d0, mul_comm]
using @sub_nonneg _ _ (b * c) (a * d)
protected theorem le_refl : a ≤ a :=
show rat.nonneg (a - a), by rw sub_self; exact le_refl (0 : ℤ)
protected theorem le_total : a ≤ b ∨ b ≤ a :=
by have := rat.nonneg_total (b - a); rwa neg_sub at this
protected theorem le_antisymm {a b : ℚ} (hab : a ≤ b) (hba : b ≤ a) : a = b :=
by have := eq_neg_of_add_eq_zero (rat.nonneg_antisymm hba $ by simpa);
rwa neg_neg at this
protected theorem le_trans {a b c : ℚ} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c :=
have rat.nonneg (b - a + (c - b)), from rat.nonneg_add hab hbc,
by simpa
instance : decidable_linear_order ℚ :=
{ le := rat.le,
le_refl := rat.le_refl,
le_trans := @rat.le_trans,
le_antisymm := @rat.le_antisymm,
le_total := rat.le_total,
decidable_eq := by apply_instance,
decidable_le := assume a b, rat.decidable_nonneg (b - a) }
/- Extra instances to short-circuit type class resolution -/
instance : has_lt ℚ := by apply_instance
instance : lattice.distrib_lattice ℚ := by apply_instance
instance : lattice.lattice ℚ := by apply_instance
instance : lattice.semilattice_inf ℚ := by apply_instance
instance : lattice.semilattice_sup ℚ := by apply_instance
instance : lattice.has_inf ℚ := by apply_instance
instance : lattice.has_sup ℚ := by apply_instance
instance : linear_order ℚ := by apply_instance
instance : partial_order ℚ := by apply_instance
instance : preorder ℚ := by apply_instance
theorem nonneg_iff_zero_le {a} : rat.nonneg a ↔ 0 ≤ a :=
show rat.nonneg a ↔ rat.nonneg (a - 0), by simp
theorem num_nonneg_iff_zero_le : ∀ {a : ℚ}, 0 ≤ a.num ↔ 0 ≤ a
| ⟨n, d, h, c⟩ := @nonneg_iff_zero_le ⟨n, d, h, c⟩
theorem mk_le {a b c d : ℤ} (h₁ : b > 0) (h₂ : d > 0) :
a /. b ≤ c /. d ↔ a * d ≤ c * b :=
by conv in (_ ≤ _) {
simp only [(≤), rat.le],
rw [sub_def (ne_of_gt h₂) (ne_of_gt h₁),
mk_nonneg _ (mul_pos h₂ h₁), ge, sub_nonneg] }
protected theorem add_le_add_left {a b c : ℚ} : c + a ≤ c + b ↔ a ≤ b :=
by unfold has_le.le rat.le; rw add_sub_add_left_eq_sub
protected theorem mul_nonneg {a b : ℚ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b :=
by rw ← nonneg_iff_zero_le at ha hb ⊢; exact rat.nonneg_mul ha hb
instance : discrete_linear_ordered_field ℚ :=
{ zero_lt_one := dec_trivial,
add_le_add_left := assume a b ab c, rat.add_le_add_left.2 ab,
add_lt_add_left := assume a b ab c, lt_of_not_ge $ λ ba,
not_le_of_lt ab $ rat.add_le_add_left.1 ba,
mul_nonneg := @rat.mul_nonneg,
mul_pos := assume a b ha hb, lt_of_le_of_ne
(rat.mul_nonneg (le_of_lt ha) (le_of_lt hb))
(mul_ne_zero (ne_of_lt ha).symm (ne_of_lt hb).symm).symm,
..rat.discrete_field, ..rat.decidable_linear_order }
/- Extra instances to short-circuit type class resolution -/
instance : linear_ordered_field ℚ := by apply_instance
instance : decidable_linear_ordered_comm_ring ℚ := by apply_instance
instance : linear_ordered_comm_ring ℚ := by apply_instance
instance : linear_ordered_ring ℚ := by apply_instance
instance : ordered_ring ℚ := by apply_instance
instance : decidable_linear_ordered_semiring ℚ := by apply_instance
instance : linear_ordered_semiring ℚ := by apply_instance
instance : ordered_semiring ℚ := by apply_instance
instance : decidable_linear_ordered_comm_group ℚ := by apply_instance
instance : ordered_comm_group ℚ := by apply_instance
instance : ordered_cancel_comm_monoid ℚ := by apply_instance
instance : ordered_comm_monoid ℚ := by apply_instance
attribute [irreducible] rat.le
theorem num_pos_iff_pos {a : ℚ} : 0 < a.num ↔ 0 < a :=
lt_iff_lt_of_le_iff_le $
by simpa [(by cases a; refl : (-a).num = -a.num)]
using @num_nonneg_iff_zero_le (-a)
theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom' _ _ _ _
theorem coe_int_eq_mk : ∀ z : ℤ, ↑z = z /. 1
| (n : ℕ) := show (n:ℚ) = n /. 1,
by induction n with n IH n; simp [*, show (1:ℚ) = 1 /. 1, from rfl]
| -[1+ n] := show (-(n + 1) : ℚ) = -[1+ n] /. 1, begin
induction n with n IH, {refl},
show -(n + 1 + 1 : ℚ) = -[1+ n.succ] /. 1,
rw [neg_add, IH],
simpa [show -1 = (-1) /. 1, from rfl]
end
theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z :=
(coe_int_eq_mk z).trans (of_int_eq_mk z).symm
theorem mk_eq_div (n d : ℤ) : n /. d = (n / d : ℚ) :=
begin
by_cases d0 : d = 0, {simp [d0, div_zero]},
rw [division_def, coe_int_eq_mk, coe_int_eq_mk, inv_def,
mul_def one_ne_zero d0, one_mul, mul_one]
end
/-- `floor q` is the largest integer `z` such that `z ≤ q` -/
def floor : ℚ → ℤ
| ⟨n, d, h, c⟩ := n / d
theorem le_floor {z : ℤ} : ∀ {r : ℚ}, z ≤ floor r ↔ (z : ℚ) ≤ r
| ⟨n, d, h, c⟩ := begin
simp [floor],
rw [num_denom'],
have h' := int.coe_nat_lt.2 h,
conv { to_rhs,
rw [coe_int_eq_mk, mk_le zero_lt_one h', mul_one] },
exact int.le_div_iff_mul_le h'
end
theorem floor_lt {r : ℚ} {z : ℤ} : floor r < z ↔ r < z :=
lt_iff_lt_of_le_iff_le le_floor
theorem floor_le (r : ℚ) : (floor r : ℚ) ≤ r :=
le_floor.1 (le_refl _)
theorem lt_succ_floor (r : ℚ) : r < (floor r).succ :=
floor_lt.1 $ int.lt_succ_self _
@[simp] theorem floor_coe (z : ℤ) : floor z = z :=
eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le]
theorem floor_mono {a b : ℚ} (h : a ≤ b) : floor a ≤ floor b :=
le_floor.2 (le_trans (floor_le _) h)
@[simp] theorem floor_add_int (r : ℚ) (z : ℤ) : floor (r + z) = floor r + z :=
eq_of_forall_le_iff $ λ a, by rw [le_floor,
← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub]
theorem floor_sub_int (r : ℚ) (z : ℤ) : floor (r - z) = floor r - z :=
eq.trans (by rw [int.cast_neg]; refl) (floor_add_int _ _)
/-- `ceil q` is the smallest integer `z` such that `q ≤ z` -/
def ceil (r : ℚ) : ℤ :=
-(floor (-r))
theorem ceil_le {z : ℤ} {r : ℚ} : ceil r ≤ z ↔ r ≤ z :=
by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff]
theorem le_ceil (r : ℚ) : r ≤ ceil r :=
ceil_le.1 (le_refl _)
@[simp] theorem ceil_coe (z : ℤ) : ceil z = z :=
by rw [ceil, ← int.cast_neg, floor_coe, neg_neg]
theorem ceil_mono {a b : ℚ} (h : a ≤ b) : ceil a ≤ ceil b :=
ceil_le.2 (le_trans h (le_ceil _))
@[simp] theorem ceil_add_int (r : ℚ) (z : ℤ) : ceil (r + z) = ceil r + z :=
by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl
theorem ceil_sub_int (r : ℚ) (z : ℤ) : ceil (r - z) = ceil r - z :=
eq.trans (by rw [int.cast_neg]; refl) (ceil_add_int _ _)
/- cast (injection into fields) -/
section cast
variables {α : Type*}
section
variables [division_ring α]
/-- Construct the canonical injection from `ℚ` into an arbitrary
division ring. If the field has positive characteristic `p`,
we define `1 / p = 1 / 0 = 0` for consistency with our
division by zero convention. -/
protected def cast : ℚ → α
| ⟨n, d, h, c⟩ := n / d
@[priority 0] instance cast_coe : has_coe ℚ α := ⟨rat.cast⟩
@[simp] theorem cast_of_int (n : ℤ) : (of_int n : α) = n :=
show (n / (1:ℕ) : α) = n, by rw [nat.cast_one, div_one]
@[simp] theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n :=
by rw [coe_int_eq_of_int, cast_of_int]
@[simp] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n :=
by rw coe_int_eq_of_int; refl
@[simp] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 :=
by rw coe_int_eq_of_int; refl
@[simp] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n :=
by rw [← int.cast_coe_nat, coe_int_num]
@[simp] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 :=
by rw [← int.cast_coe_nat, coe_int_denom]
@[simp] theorem cast_coe_nat (n : ℕ) : ((n : ℚ) : α) = n := cast_coe_int n
@[simp] theorem cast_zero : ((0 : ℚ) : α) = 0 :=
(cast_of_int _).trans int.cast_zero
@[simp] theorem cast_one : ((1 : ℚ) : α) = 1 :=
(cast_of_int _).trans int.cast_one
theorem mul_cast_comm (a : α) :
∀ (n : ℚ), (n.denom : α) ≠ 0 → a * n = n * a
| ⟨n, d, h, c⟩ h₂ := show a * (n * d⁻¹) = n * d⁻¹ * a,
by rw [← mul_assoc, int.mul_cast_comm, mul_assoc, mul_assoc,
← show (d:α)⁻¹ * a = a * d⁻¹, from
division_ring.inv_comm_of_comm h₂ (int.mul_cast_comm a d).symm]
theorem cast_mk_of_ne_zero (a b : ℤ)
(b0 : (b:α) ≠ 0) : (a /. b : α) = a / b :=
begin
have b0' : b ≠ 0, { refine mt _ b0, simp {contextual := tt} },
cases e : a /. b with n d h c,
have d0 : (d:α) ≠ 0,
{ intro d0,
have dd := denom_dvd a b,
cases (show (d:ℤ) ∣ b, by rwa e at dd) with k ke,
have : (b:α) = (d:α) * (k:α), {rw [ke, int.cast_mul], refl},
rw [d0, zero_mul] at this, contradiction },
rw [num_denom'] at e,
have := congr_arg (coe : ℤ → α) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e),
rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this,
symmetry, change (a * b⁻¹ : α) = n / d,
rw [eq_div_iff_mul_eq _ _ d0, mul_assoc, nat.mul_cast_comm,
← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one]
end
theorem cast_add_of_ne_zero : ∀ {m n : ℚ},
(m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m + n : ℚ) : α) = m + n
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin
have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl),
have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl),
rw [num_denom', num_denom', add_def d₁0' d₂0'],
suffices : (n₁ * (d₂ * (d₂⁻¹ * d₁⁻¹)) +
n₂ * (d₁ * d₂⁻¹) * d₁⁻¹ : α) = n₁ * d₁⁻¹ + n₂ * d₂⁻¹,
{ rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero],
{ simpa [division_def, left_distrib, right_distrib, mul_inv_eq,
d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] },
all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} },
rw [← mul_assoc (d₂:α), mul_inv_cancel d₂0, one_mul,
← nat.mul_cast_comm], simp [d₁0, mul_assoc]
end
@[simp] theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n
| ⟨n, d, h, c⟩ := show (↑-n * d⁻¹ : α) = -(n * d⁻¹),
by rw [int.cast_neg, neg_mul_eq_neg_mul]
theorem cast_sub_of_ne_zero {m n : ℚ}
(m0 : (m.denom : α) ≠ 0) (n0 : (n.denom : α) ≠ 0) : ((m - n : ℚ) : α) = m - n :=
have ((-n).denom : α) ≠ 0, by cases n; exact n0,
by simp [m0, this, cast_add_of_ne_zero]
theorem cast_mul_of_ne_zero : ∀ {m n : ℚ},
(m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m * n : ℚ) : α) = m * n
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin
have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl),
have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl),
rw [num_denom', num_denom', mul_def d₁0' d₂0'],
suffices : (n₁ * ((n₂ * d₂⁻¹) * d₁⁻¹) : α) = n₁ * (d₁⁻¹ * (n₂ * d₂⁻¹)),
{ rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero],
{ simpa [division_def, mul_inv_eq, d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] },
all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} },
rw [division_ring.inv_comm_of_comm d₁0 (nat.mul_cast_comm _ _).symm]
end
theorem cast_inv_of_ne_zero : ∀ {n : ℚ},
(n.num : α) ≠ 0 → (n.denom : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = n⁻¹
| ⟨n, d, h, c⟩ := λ (n0 : (n:α) ≠ 0) (d0 : (d:α) ≠ 0), begin
have n0' : (n:ℤ) ≠ 0 := λ e, by rw e at n0; exact n0 rfl,
have d0' : (d:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d0; exact d0 rfl),
rw [num_denom', inv_def],
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div];
simp [n0, d0]
end
theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.denom : α) ≠ 0)
(nn : (n.num : α) ≠ 0) (nd : (n.denom : α) ≠ 0) : ((m / n : ℚ) : α) = m / n :=
have (n⁻¹.denom : ℤ) ∣ n.num,
by conv in n⁻¹.denom { rw [num_denom n, inv_def] };
apply denom_dvd,
have (n⁻¹.denom : α) = 0 → (n.num : α) = 0, from
λ h, let ⟨k, e⟩ := this in
by have := congr_arg (coe : ℤ → α) e;
rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this,
by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def]
@[simp] theorem cast_inj [char_zero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := begin
refine ⟨λ h, _, congr_arg _⟩,
have d₁0 : d₁ ≠ 0 := ne_of_gt h₁,
have d₂0 : d₂ ≠ 0 := ne_of_gt h₂,
have d₁a : (d₁:α) ≠ 0 := nat.cast_ne_zero.2 d₁0,
have d₂a : (d₂:α) ≠ 0 := nat.cast_ne_zero.2 d₂0,
rw [num_denom', num_denom'] at h ⊢,
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [d₁0, d₂0] at h ⊢,
rwa [eq_div_iff_mul_eq _ _ d₂a, division_def, mul_assoc,
division_ring.inv_comm_of_comm d₁a (nat.mul_cast_comm _ _),
← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq _ _ d₁a, eq_comm,
← int.cast_coe_nat, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul,
int.cast_inj, ← mk_eq (int.coe_nat_ne_zero.2 d₁0) (int.coe_nat_ne_zero.2 d₂0)] at h
end
theorem cast_injective [char_zero α] : function.injective (coe : ℚ → α)
| m n := cast_inj.1
@[simp] theorem cast_eq_zero [char_zero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 :=
by rw [← cast_zero, cast_inj]
@[simp] theorem cast_ne_zero [char_zero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 :=
not_congr cast_eq_zero
theorem eq_cast_of_ne_zero (f : ℚ → α) (H1 : f 1 = 1)
(Hadd : ∀ x y, f (x + y) = f x + f y)
(Hmul : ∀ x y, f (x * y) = f x * f y) :
∀ n : ℚ, (n.denom : α) ≠ 0 → f n = n
| ⟨n, d, h, c⟩ := λ (h₂ : ((d:ℤ):α) ≠ 0), show _ = (n / (d:ℤ) : α), begin
rw [num_denom', mk_eq_div, eq_div_iff_mul_eq _ _ h₂],
have : ∀ n : ℤ, f n = n, { apply int.eq_cast; simp [H1, Hadd] },
rw [← this, ← this, ← Hmul, div_mul_cancel],
exact int.cast_ne_zero.2 (int.coe_nat_ne_zero.2 $ ne_of_gt h),
end
theorem eq_cast [char_zero α] (f : ℚ → α) (H1 : f 1 = 1)
(Hadd : ∀ x y, f (x + y) = f x + f y)
(Hmul : ∀ x y, f (x * y) = f x * f y) (n : ℚ) : f n = n :=
eq_cast_of_ne_zero _ H1 Hadd Hmul _ $
nat.cast_ne_zero.2 $ ne_of_gt n.pos
end
theorem cast_mk [discrete_field α] [char_zero α] (a b : ℤ) : ((a /. b) : α) = a / b :=
if b0 : b = 0 then by simp [b0, div_zero]
else cast_mk_of_ne_zero a b (int.cast_ne_zero.2 b0)
@[simp] theorem cast_add [division_ring α] [char_zero α] (m n) : ((m + n : ℚ) : α) = m + n :=
cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_sub [division_ring α] [char_zero α] (m n) : ((m - n : ℚ) : α) = m - n :=
cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_mul [division_ring α] [char_zero α] (m n) : ((m * n : ℚ) : α) = m * n :=
cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_inv [discrete_field α] [char_zero α] (n) : ((n⁻¹ : ℚ) : α) = n⁻¹ :=
if n0 : n.num = 0 then
by simp [show n = 0, by rw [num_denom n, n0]; simp, inv_zero] else
cast_inv_of_ne_zero (int.cast_ne_zero.2 n0) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_div [discrete_field α] [char_zero α] (m n) : ((m / n : ℚ) : α) = m / n :=
by rw [division_def, cast_mul, cast_inv, division_def]
@[simp] theorem cast_pow [discrete_field α] [char_zero α] (q) (k : ℕ) : ((q ^ k : ℚ) : α) = q ^ k :=
by induction k; simp only [*, cast_one, cast_mul, pow_zero, pow_succ]
@[simp] theorem cast_bit0 [division_ring α] [char_zero α] (n : ℚ) : ((bit0 n : ℚ) : α) = bit0 n := cast_add _ _
@[simp] theorem cast_bit1 [division_ring α] [char_zero α] (n : ℚ) : ((bit1 n : ℚ) : α) = bit1 n :=
by rw [bit1, cast_add, cast_one, cast_bit0]; refl
@[simp] theorem cast_nonneg [linear_ordered_field α] : ∀ {n : ℚ}, 0 ≤ (n : α) ↔ 0 ≤ n
| ⟨n, d, h, c⟩ := show 0 ≤ (n * d⁻¹ : α) ↔ 0 ≤ (⟨n, d, h, c⟩ : ℚ),
by rw [num_denom', ← nonneg_iff_zero_le, mk_nonneg _ (int.coe_nat_pos.2 h),
mul_nonneg_iff_right_nonneg_of_pos (@inv_pos α _ _ (nat.cast_pos.2 h)),
int.cast_nonneg]
@[simp] theorem cast_le [linear_ordered_field α] {m n : ℚ} : (m : α) ≤ n ↔ m ≤ n :=
by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg]
@[simp] theorem cast_lt [linear_ordered_field α] {m n : ℚ} : (m : α) < n ↔ m < n :=
by simpa [-cast_le] using not_congr (@cast_le α _ n m)
@[simp] theorem cast_nonpos [linear_ordered_field α] {n : ℚ} : (n : α) ≤ 0 ↔ n ≤ 0 :=
by rw [← cast_zero, cast_le]
@[simp] theorem cast_pos [linear_ordered_field α] {n : ℚ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_lt_zero [linear_ordered_field α] {n : ℚ} : (n : α) < 0 ↔ n < 0 :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_id : ∀ n : ℚ, ↑n = n
| ⟨n, d, h, c⟩ := show (n / (d : ℤ) : ℚ) = _, by rw [num_denom', mk_eq_div]
@[simp] theorem cast_min [discrete_linear_ordered_field α] {a b : ℚ} : (↑(min a b) : α) = min a b :=
by by_cases a ≤ b; simp [h, min]
@[simp] theorem cast_max [discrete_linear_ordered_field α] {a b : ℚ} : (↑(max a b) : α) = max a b :=
by by_cases a ≤ b; simp [h, max]
@[simp] theorem cast_abs [discrete_linear_ordered_field α] {q : ℚ} : ((abs q : ℚ) : α) = abs q :=
by simp [abs]
end cast
/- nat ceiling -/
/-- `nat_ceil q` is the smallest nonnegative integer `n` with `q ≤ n`.
It is the same as `ceil q` when `q ≥ 0`, otherwise it is `0`. -/
def nat_ceil (q : ℚ) : ℕ := int.to_nat (ceil q)
theorem nat_ceil_le {q : ℚ} {n : ℕ} : nat_ceil q ≤ n ↔ q ≤ n :=
by rw [nat_ceil, int.to_nat_le, ceil_le]; refl
theorem lt_nat_ceil {q : ℚ} {n : ℕ} : n < nat_ceil q ↔ (n : ℚ) < q :=
not_iff_not.1 $ by rw [not_lt, not_lt, nat_ceil_le]
theorem le_nat_ceil (q : ℚ) : q ≤ nat_ceil q :=
nat_ceil_le.1 (le_refl _)
theorem nat_ceil_mono {q₁ q₂ : ℚ} (h : q₁ ≤ q₂) : nat_ceil q₁ ≤ nat_ceil q₂ :=
nat_ceil_le.2 (le_trans h (le_nat_ceil _))
@[simp] theorem nat_ceil_coe (n : ℕ) : nat_ceil n = n :=
show (ceil (n:ℤ)).to_nat = n, by rw [ceil_coe]; refl
@[simp] theorem nat_ceil_zero : nat_ceil 0 = 0 := nat_ceil_coe 0
theorem nat_ceil_add_nat {q : ℚ} (hq : 0 ≤ q) (n : ℕ) : nat_ceil (q + n) = nat_ceil q + n :=
show int.to_nat (ceil (q + (n:ℤ))) = int.to_nat (ceil q) + n,
by rw [ceil_add_int]; exact
match ceil q, int.eq_coe_of_zero_le (ceil_mono hq) with
| _, ⟨m, rfl⟩ := rfl
end
theorem nat_ceil_lt_add_one {q : ℚ} (hq : q ≥ 0) : ↑(nat_ceil q) < q + 1 :=
lt_nat_ceil.1 $ by rw [
show nat_ceil (q+1) = nat_ceil q+1, from nat_ceil_add_nat hq 1]; apply nat.lt_succ_self
@[simp] lemma denom_neg_eq_denom : ∀ q : ℚ, (-q).denom = q.denom
| ⟨_, d, _, _⟩ := rfl
@[simp] lemma num_neg_eq_neg_num : ∀ q : ℚ, (-q).num = -(q.num)
| ⟨n, _, _, _⟩ := rfl
@[simp] lemma num_zero : rat.num 0 = 0 := rfl
lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 :=
have q = q.num /. q.denom, from num_denom _,
by simpa [hq]
lemma zero_iff_num_zero {q : ℚ} : q = 0 ↔ q.num = 0 :=
⟨λ _, by simp *, zero_of_num_zero⟩
lemma num_ne_zero_of_ne_zero {q : ℚ} (h : q ≠ 0) : q.num ≠ 0 :=
assume : q.num = 0,
h $ zero_of_num_zero this
@[simp] lemma num_one : (1 : ℚ).num = 1 := rfl
@[simp] lemma denom_one : (1 : ℚ).denom = 1 := rfl
lemma denom_ne_zero (q : ℚ) : q.denom ≠ 0 :=
ne_of_gt q.pos
lemma mk_num_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : n ≠ 0 :=
assume : n = 0,
hq $ by simpa [this] using hqnd
lemma mk_denom_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : d ≠ 0 :=
assume : d = 0,
hq $ by simpa [this] using hqnd
lemma mk_ne_zero_of_ne_zero {n d : ℤ} (h : n ≠ 0) (hd : d ≠ 0) : n /. d ≠ 0 :=
assume : n /. d = 0,
h $ (mk_eq_zero hd).1 this
lemma mul_num_denom (q r : ℚ) : q * r = (q.num * r.num) /. ↑(q.denom * r.denom) :=
have hq' : (↑q.denom : ℤ) ≠ 0, by have := denom_ne_zero q; simpa,
have hr' : (↑r.denom : ℤ) ≠ 0, by have := denom_ne_zero r; simpa,
suffices (q.num /. ↑q.denom) * (r.num /. ↑r.denom) = (q.num * r.num) /. ↑(q.denom * r.denom),
by rwa [←num_denom q, ←num_denom r] at this,
by simp [mul_def hq' hr']
lemma div_num_denom (q r : ℚ) : q / r = (q.num * r.denom) /. (q.denom * r.num) :=
if hr : r.num = 0 then
have hr' : r = 0, from zero_of_num_zero hr,
by simp *
else calc q / r = q * r⁻¹ : div_eq_mul_inv
... = (q.num /. q.denom) * (r.num /. r.denom)⁻¹ : by rw [←num_denom q, ←num_denom r]
... = (q.num /. q.denom) * (r.denom /. r.num) : by rw inv_def
... = (q.num * r.denom) /. (q.denom * r.num) : mul_def (by simpa using denom_ne_zero q) hr
lemma num_denom_mk {q : ℚ} {n d : ℤ} (hn : n ≠ 0) (hd : d ≠ 0) (qdf : q = n /. d) :
∃ c : ℤ, n = c * q.num ∧ d = c * q.denom :=
have hq : q ≠ 0, from
assume : q = 0,
hn $ (rat.mk_eq_zero hd).1 (by cc),
have q.num /. q.denom = n /. d, by rwa [←rat.num_denom q],
have q.num * d = n * ↑(q.denom), from (rat.mk_eq (by simp [rat.denom_ne_zero]) hd).1 this,
begin
existsi n / q.num,
have hqdn : q.num ∣ n, begin rw qdf, apply rat.num_dvd, assumption end,
split,
{ rw int.div_mul_cancel hqdn },
{ apply int.eq_mul_div_of_mul_eq_mul_of_dvd_left,
{apply rat.num_ne_zero_of_ne_zero hq},
{simp [rat.denom_ne_zero]},
repeat {assumption} }
end
theorem mk_pnat_num (n : ℤ) (d : ℕ+) :
(mk_pnat n d).num = n / nat.gcd n.nat_abs d :=
by cases d; refl
theorem mk_pnat_denom (n : ℤ) (d : ℕ+) :
(mk_pnat n d).denom = d / nat.gcd n.nat_abs d :=
by cases d; refl
theorem mul_num (q₁ q₂ : ℚ) : (q₁ * q₂).num =
(q₁.num * q₂.num) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) :=
by cases q₁; cases q₂; refl
theorem mul_denom (q₁ q₂ : ℚ) : (q₁ * q₂).denom =
(q₁.denom * q₂.denom) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) :=
by cases q₁; cases q₂; refl
theorem mul_self_num (q : ℚ) : (q * q).num = q.num * q.num :=
by rw [mul_num, int.nat_abs_mul, nat.coprime.gcd_eq_one, int.coe_nat_one, int.div_one];
exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop)
theorem mul_self_denom (q : ℚ) : (q * q).denom = q.denom * q.denom :=
by rw [rat.mul_denom, int.nat_abs_mul, nat.coprime.gcd_eq_one, nat.div_one];
exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop)
theorem abs_def (q : ℚ) : abs q = q.num.nat_abs /. q.denom :=
begin
have hz : (0:ℚ) = 0 /. 1 := rfl,
cases le_total q 0 with hq hq,
{ rw [abs_of_nonpos hq],
rw [num_denom q, hz, rat.le_def (int.coe_nat_pos.2 q.pos) zero_lt_one,
mul_one, zero_mul] at hq,
rw [int.of_nat_nat_abs_of_nonpos hq, ← neg_def, ← num_denom q] },
{ rw [abs_of_nonneg hq],
rw [num_denom q, hz, rat.le_def zero_lt_one (int.coe_nat_pos.2 q.pos),
mul_one, zero_mul] at hq,
rw [int.nat_abs_of_nonneg hq, ← num_denom q] }
end
lemma add_num_denom (q r : ℚ) : q + r =
((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ) :=
have hqd : (q.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 q.3,
have hrd : (r.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 r.3,
by conv { to_lhs, rw [rat.num_denom q, rat.num_denom r, rat.add_def hqd hrd] };
simp [mul_comm]
def sqrt (q : ℚ) : ℚ :=
rat.mk (int.sqrt q.num) (nat.sqrt q.denom)
theorem sqrt_eq (q : ℚ) : rat.sqrt (q*q) = abs q :=
by rw [sqrt, mul_self_num, mul_self_denom,
int.sqrt_eq, nat.sqrt_eq, abs_def]
theorem exists_mul_self (x : ℚ) :
(∃ q, q * q = x) ↔ rat.sqrt x * rat.sqrt x = x :=
⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq, abs_mul_abs_self],
λ h, ⟨rat.sqrt x, h⟩⟩
theorem sqrt_nonneg (q : ℚ) : 0 ≤ rat.sqrt q :=
nonneg_iff_zero_le.1 $ (mk_nonneg _ $ int.coe_nat_pos.2 $
nat.pos_of_ne_zero $ λ H, nat.pos_iff_ne_zero.1 q.pos $ nat.sqrt_eq_zero.1 H).2 trivial
end rat
|
7c66e15a31e7db2832a4eec87ab699d9658d0550 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/linear_algebra/clifford_algebra.lean | 080934db03e9b76d0b849d2ff99f6b14d265c4e7 | [
"Apache-2.0"
] | permissive | anthony2698/mathlib | 03cd69fe5c280b0916f6df2d07c614c8e1efe890 | 407615e05814e98b24b2ff322b14e8e3eb5e5d67 | refs/heads/master | 1,678,792,774,873 | 1,614,371,563,000 | 1,614,371,563,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,218 | lean | /-
Copyright (c) 2020 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser, Utensil Song.
-/
import algebra.ring_quot
import linear_algebra.tensor_algebra
import linear_algebra.exterior_algebra
import linear_algebra.quadratic_form
/-!
# Clifford Algebras
We construct the Clifford algebra of a module `M` over a commutative ring `R`, equipped with
a quadratic_form `Q`.
## Notation
The Clifford algebra of the `R`-module `M` equipped with a quadratic_form `Q` is denoted as
`clifford_algebra Q`.
Given a linear morphism `f : M → A` from a semimodule `M` to another `R`-algebra `A`, such that
`cond : ∀ m, f m * f m = algebra_map _ _ (Q m)`, there is a (unique) lift of `f` to an `R`-algebra
morphism, which is denoted `clifford_algebra.lift Q f cond`.
The canonical linear map `M → clifford_algebra Q` is denoted `clifford_algebra.ι Q`.
## Theorems
The main theorems proved ensure that `clifford_algebra Q` satisfies the universal property
of the Clifford algebra.
1. `ι_comp_lift` is the fact that the composition of `ι Q` with `lift Q f cond` agrees with `f`.
2. `lift_unique` ensures the uniqueness of `lift Q f cond` with respect to 1.
Additionally, when `Q = 0` an `alg_equiv` to the `exterior_algebra` is provided as `as_exterior`.
## Implementation details
The Clifford algebra of `M` is constructed as a quotient of the tensor algebra, as follows.
1. We define a relation `clifford_algebra.rel Q` on `tensor_algebra R M`.
This is the smallest relation which identifies squares of elements of `M` with `Q m`.
2. The Clifford algebra is the quotient of the tensor algebra by this relation.
This file is almost identical to `linear_algebra/exterior_algebra.lean`.
-/
variables {R : Type*} [comm_ring R]
variables {M : Type*} [add_comm_group M] [module R M]
variables (Q : quadratic_form R M)
variable {n : ℕ}
namespace clifford_algebra
open tensor_algebra
/-- `rel` relates each `ι m * ι m`, for `m : M`, with `Q m`.
The Clifford algebra of `M` is defined as the quotient modulo this relation.
-/
inductive rel : tensor_algebra R M → tensor_algebra R M → Prop
| of (m : M) : rel (ι R m * ι R m) (algebra_map R _ (Q m))
end clifford_algebra
/--
The Clifford algebra of an `R`-module `M` equipped with a quadratic_form `Q`.
-/
@[derive [inhabited, ring, algebra R]]
def clifford_algebra := ring_quot (clifford_algebra.rel Q)
namespace clifford_algebra
/--
The canonical linear map `M →ₗ[R] clifford_algebra Q`.
-/
def ι : M →ₗ[R] clifford_algebra Q :=
(ring_quot.mk_alg_hom R _).to_linear_map.comp (tensor_algebra.ι R)
/-- As well as being linear, `ι Q` squares to the quadratic form -/
@[simp]
theorem ι_square_scalar (m : M) : ι Q m * ι Q m = algebra_map R _ (Q m) :=
begin
erw [←alg_hom.map_mul, ring_quot.mk_alg_hom_rel R (rel.of m), alg_hom.commutes],
refl,
end
variables {Q} {A : Type*} [semiring A] [algebra R A]
@[simp]
theorem comp_ι_square_scalar (g : clifford_algebra Q →ₐ[R] A) (m : M) :
g (ι Q m) * g (ι Q m) = algebra_map _ _ (Q m) :=
by rw [←alg_hom.map_mul, ι_square_scalar, alg_hom.commutes]
variables (Q)
/--
Given a linear map `f : M →ₗ[R] A` into an `R`-algebra `A`, which satisfies the condition:
`cond : ∀ m : M, f m * f m = Q(m)`, this is the canonical lift of `f` to a morphism of `R`-algebras
from `clifford_algebra Q` to `A`.
-/
@[simps symm_apply]
def lift :
{f : M →ₗ[R] A // ∀ m, f m * f m = algebra_map _ _ (Q m)} ≃ (clifford_algebra Q →ₐ[R] A) :=
{ to_fun := λ f,
ring_quot.lift_alg_hom R ⟨tensor_algebra.lift R (f : M →ₗ[R] A),
(λ x y (h : rel Q x y), by {
induction h,
rw [alg_hom.commutes, alg_hom.map_mul, tensor_algebra.lift_ι_apply, f.prop], })⟩,
inv_fun := λ F, ⟨F.to_linear_map.comp (ι Q), λ m, by rw [
linear_map.comp_apply, alg_hom.to_linear_map_apply, comp_ι_square_scalar]⟩,
left_inv := λ f, by { ext, simp [ι] },
right_inv := λ F, by { ext, simp [ι] } }
variables {Q}
@[simp]
theorem ι_comp_lift (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = algebra_map _ _ (Q m)) :
(lift Q ⟨f, cond⟩).to_linear_map.comp (ι Q) = f :=
(subtype.mk_eq_mk.mp $ (lift Q).symm_apply_apply ⟨f, cond⟩)
@[simp]
theorem lift_ι_apply (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = algebra_map _ _ (Q m)) (x) :
lift Q ⟨f, cond⟩ (ι Q x) = f x :=
(linear_map.ext_iff.mp $ ι_comp_lift f cond) x
@[simp]
theorem lift_unique (f : M →ₗ[R] A) (cond : ∀ m : M, f m * f m = algebra_map _ _ (Q m))
(g : clifford_algebra Q →ₐ[R] A) :
g.to_linear_map.comp (ι Q) = f ↔ g = lift Q ⟨f, cond⟩ :=
begin
convert (lift Q).symm_apply_eq,
rw lift_symm_apply,
simp only,
end
attribute [irreducible] clifford_algebra ι lift
@[simp]
theorem lift_comp_ι (g : clifford_algebra Q →ₐ[R] A) :
lift Q ⟨g.to_linear_map.comp (ι Q), comp_ι_square_scalar _⟩ = g :=
begin
convert (lift Q).apply_symm_apply g,
rw lift_symm_apply,
refl,
end
/-- See note [partially-applied ext lemmas]. -/
@[ext]
theorem hom_ext {A : Type*} [semiring A] [algebra R A] {f g : clifford_algebra Q →ₐ[R] A} :
f.to_linear_map.comp (ι Q) = g.to_linear_map.comp (ι Q) → f = g :=
begin
intro h,
apply (lift Q).symm.injective,
rw [lift_symm_apply, lift_symm_apply],
simp only [h],
end
/-- A Clifford algebra with a zero quadratic form is isomorphic to an `exterior_algebra` -/
def as_exterior : clifford_algebra (0 : quadratic_form R M) ≃ₐ[R] exterior_algebra R M :=
alg_equiv.of_alg_hom
(clifford_algebra.lift 0 ⟨(exterior_algebra.ι R), by simp⟩)
(exterior_algebra.lift R ⟨(ι (0 : quadratic_form R M)), by simp⟩)
(by { ext, simp, })
(by { ext, simp, })
end clifford_algebra
namespace tensor_algebra
variables {Q}
/-- The canonical image of the `tensor_algebra` in the `clifford_algebra`, which maps
`tensor_algebra.ι R x` to `clifford_algebra.ι Q x`. -/
def to_clifford : tensor_algebra R M →ₐ[R] clifford_algebra Q :=
tensor_algebra.lift R (clifford_algebra.ι Q)
@[simp] lemma to_clifford_ι (m : M) : (tensor_algebra.ι R m).to_clifford = clifford_algebra.ι Q m :=
by simp [to_clifford]
end tensor_algebra
|
369a6f09102f5720816bf304f0598af154f1a172 | 3c9dc4ea6cc92e02634ef557110bde9eae393338 | /tests/lean/run/typeclass_coerce.lean | b8f411312f20430c3951bf1ce270a368b722d5e3 | [
"Apache-2.0"
] | permissive | shingtaklam1324/lean4 | 3d7efe0c8743a4e33d3c6f4adbe1300df2e71492 | 351285a2e8ad0cef37af05851cfabf31edfb5970 | refs/heads/master | 1,676,827,679,740 | 1,610,462,623,000 | 1,610,552,340,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,808 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Daniel Selsam, Leonardo de Moura
Declare new, simpler coercion class without the special support for transitivity.
Test that new tabled typeclass resolution deals with loops and diamonds correctly.
-/
class HasCoerce (a b : Type) :=
(coerce : a → b)
def coerce {a b : Type} [HasCoerce a b] : a → b :=
@HasCoerce.coerce a b _
instance coerceTrans {a b c : Type} [HasCoerce b c] [HasCoerce a b] : HasCoerce a c :=
⟨fun x => coerce (coerce x : b)⟩
instance coerceBoolToProp : HasCoerce Bool Prop :=
⟨fun y => y = true⟩
instance coerceDecidableEq (x : Bool) : Decidable (coerce x) :=
inferInstanceAs (Decidable (x = true))
instance coerceSubtype {a : Type} {p : a → Prop} : HasCoerce {x // p x} a :=
⟨Subtype.val⟩
instance liftCoerceFn {a₁ a₂ b₁ b₂ : Type} [HasCoerce a₂ a₁] [HasCoerce b₁ b₂] : HasCoerce (a₁ → b₁) (a₂ → b₂) :=
⟨fun f x => coerce (f (coerce x))⟩
instance liftCoerceFnRange {a b₁ b₂ : Type} [HasCoerce b₁ b₂] : HasCoerce (a → b₁) (a → b₂) :=
⟨fun f x => coerce (f x)⟩
instance liftCoerceFnDom {a₁ a₂ b : Type} [HasCoerce a₂ a₁] : HasCoerce (a₁ → b) (a₂ → b) :=
⟨fun f x => f (coerce x)⟩
instance liftCoercePair {a₁ a₂ b₁ b₂ : Type} [HasCoerce a₁ a₂] [HasCoerce b₁ b₂] : HasCoerce (a₁ × b₁) (a₂ × b₂) :=
⟨fun p => match p with
| (x, y) => (coerce x, coerce y)⟩
instance liftCoercePair₁ {a₁ a₂ b : Type} [HasCoerce a₁ a₂] : HasCoerce (a₁ × b) (a₂ × b) :=
⟨fun p => match p with
| (x, y) => (coerce x, y)⟩
instance liftCoercePair₂ {a b₁ b₂ : Type} [HasCoerce b₁ b₂] : HasCoerce (a × b₁) (a × b₂) :=
⟨fun p => match p with
| (x, y) => (x, coerce y)⟩
instance liftCoerceList {a b : Type} [HasCoerce a b] : HasCoerce (List a) (List b) :=
⟨fun l => List.map (@coerce a b _) l⟩
-- Tests
axiom Bot (α : Type) (n : Nat) : Type
axiom Left (α : Type) (n : Nat) : Type
axiom Right (α : Type) (n : Nat) : Type
axiom Top (α : Type) (n : Nat) : Type
@[instance] axiom BotToTopSucc (α : Type) (n : Nat) : HasCoerce (Bot α n) (Top α n.succ)
@[instance] axiom TopSuccToBot (α : Type) (n : Nat) : HasCoerce (Top α n.succ) (Bot α n)
@[instance] axiom TopToRight (α : Type) (n : Nat) : HasCoerce (Top α n) (Right α n)
@[instance] axiom TopToLeft (α : Type) (n : Nat) : HasCoerce (Top α n) (Left α n)
@[instance] axiom LeftToTop (α : Type) (n : Nat) : HasCoerce (Left α n) (Top α n)
@[instance] axiom RightToTop (α : Type) (n : Nat) : HasCoerce (Right α n) (Top α n)
@[instance] axiom LeftToBot (α : Type) (n : Nat) : HasCoerce (Left α n) (Bot α n)
@[instance] axiom RightToBot (α : Type) (n : Nat) : HasCoerce (Right α n) (Bot α n)
@[instance] axiom BotToLeft (α : Type) (n : Nat) : HasCoerce (Bot α n) (Left α n)
@[instance] axiom BotToRight (α : Type) (n : Nat) : HasCoerce (Bot α n) (Right α n)
#print "-----"
set_option maxInstSize 256
#synth HasCoerce (Top Unit Nat.zero)
(Top Unit Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ)
#synth HasCoerce (Top Unit Nat.zero × Top Unit Nat.zero × Top Unit Nat.zero)
(Top Unit Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ
× Top Unit Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ
× Top Unit Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ)
#synth HasCoerce (Top Unit Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ → Top Unit Nat.zero)
(Top Unit Nat.zero → Top Unit Nat.zero.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ.succ)
|
70f87d8d315868cbd7a2a9ac5937cc3f7f1e6754 | e0b0b1648286e442507eb62344760d5cd8d13f2d | /stage0/src/Lean/Elab/Do.lean | 54349a16f1319988f10998a97499749777008c8a | [
"Apache-2.0"
] | permissive | MULXCODE/lean4 | 743ed389e05e26e09c6a11d24607ad5a697db39b | 4675817a9e89824eca37192364cd47a4027c6437 | refs/heads/master | 1,682,231,879,857 | 1,620,423,501,000 | 1,620,423,501,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 68,913 | 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.Binders
import Lean.Elab.Match
import Lean.Elab.Quotation.Util
import Lean.Parser.Do
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
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 }
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 }
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` -/
@[inline] partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool :=
let rec @[specialize] 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 ← `(ensureExpectedType% "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 ref 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 ← `(ensureTypeOf% $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
``(ite $cond $thenBranch $elseBranch)
else
let h := optIdent[0]
``(dite $cond (fun $h => $thenBranch) (fun $h => $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 `(typeOf% $(← 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
@[inline] 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
@[inline] 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) MacroM 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
Macro.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) : MacroM (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
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]
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 ← `(forIn% $(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 (ensureExpectedType% "type mismatch, 'for'" PUnit.unit)
| some a => return ensureExpectedType% "type mismatch, 'for'" a)
doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems)
else
let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody
let forInTerm ← `(forIn% $(xs) $uvarsTuple fun $x r => $forInBody)
if doElems.isEmpty then
let auxDo ← `(do let r ← $forInTerm:term;
$uvarsTuple:term := r;
Pure.pure (ensureExpectedType% "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
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]
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) ← liftM (liftMacroM <| expandLiftMethod doElem : TermElabM _)
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
mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems)
else if k == `Lean.Parser.Term.doHave then
let var := getDoHaveVar doElem
mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems)
else if k == `Lean.Parser.Term.doLetRec then
let vars ← getDoLetRecVars doElem
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\n{doElem}"
end
def run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock :=
(doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m := 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
@[builtinTermElab «do»]
def elabDo : TermElab := fun stx expectedType? => do
tryPostponeIfNoneOrMVar expectedType?
let bindInfo ← extractBind expectedType?
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
|
02bda7f9015380bc25c49e7352c904a77181aa46 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/autoBoundErrorMsg.lean | 91db72d8dc50cf17f2805f1774bed388d09ca5f6 | [
"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 | 48 | lean | example (h : {a b : α} → a = b) : a = b := _
|
b32cc03aaa0740f4954a30eed2a72ff731ccdb3d | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /archive/imo/imo1960_q1.lean | 63c74ee06bee4a85d7f48175c8b09a83d6901fff | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 3,336 | lean | /-
Copyright (c) 2020 Kevin Lacker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Lacker
-/
import data.nat.digits
/-!
# IMO 1960 Q1
Determine all three-digit numbers $N$ having the property that $N$ is divisible by 11, and
$\dfrac{N}{11}$ is equal to the sum of the squares of the digits of $N$.
Since Lean doesn't have a way to directly express problem statements of the form
"Determine all X satisfying Y", we express two predicates where proving that one implies the
other is equivalent to solving the problem. A human solver also has to discover the
second predicate.
The strategy here is roughly brute force, checking the possible multiples of 11.
-/
open nat
def sum_of_squares (L : list ℕ) : ℕ := (L.map (λ x, x * x)).sum
def problem_predicate (n : ℕ) : Prop :=
(nat.digits 10 n).length = 3 ∧ 11 ∣ n ∧ n / 11 = sum_of_squares (nat.digits 10 n)
def solution_predicate (n : ℕ) : Prop := n = 550 ∨ n = 803
/-
Proving that three digit numbers are the ones in [100, 1000).
-/
lemma not_zero {n : ℕ} (h1 : problem_predicate n) : n ≠ 0 :=
have h2 : nat.digits 10 n ≠ list.nil, from list.ne_nil_of_length_eq_succ h1.left,
digits_ne_nil_iff_ne_zero.mp h2
lemma ge_100 {n : ℕ} (h1 : problem_predicate n) : 100 ≤ n :=
have h2 : 10^3 ≤ 10 * n, begin
rw ← h1.left,
refine nat.base_pow_length_digits_le 10 n _ (not_zero h1),
simp,
end,
by linarith
lemma lt_1000 {n : ℕ} (h1 : problem_predicate n) : n < 1000 :=
have h2 : n < 10^3, begin
rw ← h1.left,
refine nat.lt_base_pow_length_digits _,
simp,
end,
by linarith
/-
We do an exhaustive search to show that all results are covered by `solution_predicate`.
-/
def search_up_to (c n : ℕ) : Prop :=
n = c * 11 ∧ ∀ m : ℕ, m < n → problem_predicate m → solution_predicate m
lemma search_up_to_start : search_up_to 9 99 := ⟨rfl, λ n h p, by linarith [ge_100 p]⟩
lemma search_up_to_step {c n} (H : search_up_to c n)
{c' n'} (ec : c + 1 = c') (en : n + 11 = n')
{l} (el : nat.digits 10 n = l)
(H' : c = sum_of_squares l → c = 50 ∨ c = 73) :
search_up_to c' n' :=
begin
subst ec, subst en, subst el,
obtain ⟨rfl, H⟩ := H,
refine ⟨by ring, λ m l p, _⟩,
obtain ⟨h₁, ⟨m, rfl⟩, h₂⟩ := id p,
by_cases h : 11 * m < c * 11, { exact H _ h p },
have : m = c, {linarith}, subst m,
rw [nat.mul_div_cancel_left _ (by norm_num : 11 > 0), mul_comm] at h₂,
refine (H' h₂).imp _ _; {rintro rfl, norm_num}
end
lemma search_up_to_end {c} (H : search_up_to c 1001)
{n : ℕ} (ppn : problem_predicate n) : solution_predicate n :=
H.2 _ (by linarith [lt_1000 ppn]) ppn
lemma right_direction {n : ℕ} : problem_predicate n → solution_predicate n :=
begin
have := search_up_to_start,
iterate 82 {
replace := search_up_to_step this (by norm_num1; refl) (by norm_num1; refl)
(by norm_num1; refl) dec_trivial },
exact search_up_to_end this
end
/-
Now we just need to prove the equivalence, for the precise problem statement.
-/
lemma left_direction (n : ℕ) (spn : solution_predicate n) : problem_predicate n :=
by rcases spn with (rfl | rfl); norm_num [problem_predicate, sum_of_squares]
theorem imo1960_q1 (n : ℕ) : problem_predicate n ↔ solution_predicate n :=
⟨right_direction, left_direction n⟩
|
cc3ba8f94e9f2b89e86d555937569c0a4158e24b | 969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb | /src/category_theory/limits/shapes/images.lean | da30e39b67f8e459f844ea7ced4a11d1d0586991 | [
"Apache-2.0"
] | permissive | SAAluthwela/mathlib | 62044349d72dd63983a8500214736aa7779634d3 | 83a4b8b990907291421de54a78988c024dc8a552 | refs/heads/master | 1,679,433,873,417 | 1,615,998,031,000 | 1,615,998,031,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 25,282 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Markus Himmel
-/
import category_theory.limits.shapes.equalizers
import category_theory.limits.shapes.pullbacks
import category_theory.limits.shapes.strong_epi
/-!
# Categorical images
We define the categorical image of `f` as a factorisation `f = e ≫ m` through a monomorphism `m`,
so that `m` factors through the `m'` in any other such factorisation.
## Main definitions
* A `mono_factorisation` is a factorisation `f = e ≫ m`, where `m` is a monomorphism
* `is_image F` means that a given mono factorisation `F` has the universal property of the image.
* `has_image f` means that we have chosen an image for the morphism `f : X ⟶ Y`.
* In this case, `image f` is the image object, `image.ι f : image f ⟶ Y` is the monomorphism `m`
of the factorisation and `factor_thru_image f : X ⟶ image f` is the morphism `e`.
* `has_images C` means that every morphism in `C` has an image.
* Let `f : X ⟶ Y` and `g : P ⟶ Q` be morphisms in `C`, which we will represent as objects of the
arrow category `arrow C`. Then `sq : f ⟶ g` is a commutative square in `C`. If `f` and `g` have
images, then `has_image_map sq` represents the fact that there is a morphism
`i : image f ⟶ image g` making the diagram
X ----→ image f ----→ Y
| | |
| | |
↓ ↓ ↓
P ----→ image g ----→ Q
commute, where the top row is the image factorisation of `f`, the bottom row is the image
factorisation of `g`, and the outer rectangle is the commutative square `sq`.
* If a category `has_images`, then `has_image_maps` means that every commutative square admits an
image map.
* If a category `has_images`, then `has_strong_epi_images` means that the morphism to the image is
always a strong epimorphism.
## Main statements
* When `C` has equalizers, the morphism `e` appearing in an image factorisation is an epimorphism.
* When `C` has strong epi images, then these images admit image maps.
## Future work
* TODO: coimages, and abelian categories.
* TODO: connect this with existing working in the group theory and ring theory libraries.
-/
noncomputable theory
universes v u
open category_theory
open category_theory.limits.walking_parallel_pair
namespace category_theory.limits
variables {C : Type u} [category.{v} C]
variables {X Y : C} (f : X ⟶ Y)
/-- A factorisation of a morphism `f = e ≫ m`, with `m` monic. -/
structure mono_factorisation (f : X ⟶ Y) :=
(I : C)
(m : I ⟶ Y)
[m_mono : mono m]
(e : X ⟶ I)
(fac' : e ≫ m = f . obviously)
restate_axiom mono_factorisation.fac'
attribute [simp, reassoc] mono_factorisation.fac
attribute [instance] mono_factorisation.m_mono
attribute [instance] mono_factorisation.m_mono
namespace mono_factorisation
/-- The obvious factorisation of a monomorphism through itself. -/
def self [mono f] : mono_factorisation f :=
{ I := X,
m := f,
e := 𝟙 X }
-- I'm not sure we really need this, but the linter says that an inhabited instance
-- ought to exist...
instance [mono f] : inhabited (mono_factorisation f) := ⟨self f⟩
/-- The morphism `m` in a factorisation `f = e ≫ m` through a monomorphism is uniquely
determined. -/
@[ext]
lemma ext
{F F' : mono_factorisation f} (hI : F.I = F'.I) (hm : F.m = (eq_to_hom hI) ≫ F'.m) : F = F' :=
begin
cases F, cases F',
cases hI,
simp at hm,
dsimp at F_fac' F'_fac',
congr,
{ assumption },
{ resetI, apply (cancel_mono F_m).1,
rw [F_fac', hm, F'_fac'], }
end
end mono_factorisation
variable {f}
/-- Data exhibiting that a given factorisation through a mono is initial. -/
structure is_image (F : mono_factorisation f) :=
(lift : Π (F' : mono_factorisation f), F.I ⟶ F'.I)
(lift_fac' : Π (F' : mono_factorisation f), lift F' ≫ F'.m = F.m . obviously)
restate_axiom is_image.lift_fac'
attribute [simp, reassoc] is_image.lift_fac
@[simp, reassoc] lemma is_image.fac_lift {F : mono_factorisation f} (hF : is_image F)
(F' : mono_factorisation f) : F.e ≫ hF.lift F' = F'.e :=
(cancel_mono F'.m).1 $ by simp
variable (f)
namespace is_image
/-- The trivial factorisation of a monomorphism satisfies the universal property. -/
@[simps]
def self [mono f] : is_image (mono_factorisation.self f) :=
{ lift := λ F', F'.e }
instance [mono f] : inhabited (is_image (mono_factorisation.self f)) :=
⟨self f⟩
variable {f}
/-- Two factorisations through monomorphisms satisfying the universal property
must factor through isomorphic objects. -/
-- TODO this is another good candidate for a future `unique_up_to_canonical_iso`.
@[simps]
def iso_ext {F F' : mono_factorisation f} (hF : is_image F) (hF' : is_image F') : F.I ≅ F'.I :=
{ hom := hF.lift F',
inv := hF'.lift F,
hom_inv_id' := (cancel_mono F.m).1 (by simp),
inv_hom_id' := (cancel_mono F'.m).1 (by simp) }
variables {F F' : mono_factorisation f} (hF : is_image F) (hF' : is_image F')
lemma iso_ext_hom_m : (iso_ext hF hF').hom ≫ F'.m = F.m := by simp
lemma iso_ext_inv_m : (iso_ext hF hF').inv ≫ F.m = F'.m := by simp
lemma e_iso_ext_hom : F.e ≫ (iso_ext hF hF').hom = F'.e := by simp
lemma e_iso_ext_inv : F'.e ≫ (iso_ext hF hF').inv = F.e := by simp
end is_image
/-- Data exhibiting that a morphism `f` has an image. -/
structure image_factorisation (f : X ⟶ Y) :=
(F : mono_factorisation f)
(is_image : is_image F)
instance inhabited_image_factorisation (f : X ⟶ Y) [mono f] : inhabited (image_factorisation f) :=
⟨⟨_, is_image.self f⟩⟩
/-- `has_image f` means that there exists an image factorisation of `f`. -/
class has_image (f : X ⟶ Y) : Prop :=
mk' :: (exists_image : nonempty (image_factorisation f))
lemma has_image.mk {f : X ⟶ Y} (F : image_factorisation f) : has_image f :=
⟨nonempty.intro F⟩
section
variable [has_image f]
/-- The chosen factorisation of `f` through a monomorphism. -/
def image.mono_factorisation : mono_factorisation f :=
(classical.choice (has_image.exists_image)).F
/-- The witness of the universal property for the chosen factorisation of `f` through
a monomorphism. -/
def image.is_image : is_image (image.mono_factorisation f) :=
(classical.choice (has_image.exists_image)).is_image
/-- The categorical image of a morphism. -/
def image : C := (image.mono_factorisation f).I
/-- The inclusion of the image of a morphism into the target. -/
def image.ι : image f ⟶ Y := (image.mono_factorisation f).m
@[simp] lemma image.as_ι : (image.mono_factorisation f).m = image.ι f := rfl
instance : mono (image.ι f) := (image.mono_factorisation f).m_mono
/-- The map from the source to the image of a morphism. -/
def factor_thru_image : X ⟶ image f := (image.mono_factorisation f).e
/-- Rewrite in terms of the `factor_thru_image` interface. -/
@[simp]
lemma as_factor_thru_image : (image.mono_factorisation f).e = factor_thru_image f := rfl
@[simp, reassoc]
lemma image.fac : factor_thru_image f ≫ image.ι f = f := (image.mono_factorisation f).fac'
variable {f}
/-- Any other factorisation of the morphism `f` through a monomorphism receives a map from the
image. -/
def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I := (image.is_image f).lift F'
@[simp, reassoc]
lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f :=
(image.is_image f).lift_fac' F'
@[simp, reassoc]
lemma image.fac_lift (F' : mono_factorisation f) : factor_thru_image f ≫ image.lift F' = F'.e :=
(image.is_image f).fac_lift F'
@[simp, reassoc]
lemma is_image.lift_ι {F : mono_factorisation f} (hF : is_image F) :
hF.lift (image.mono_factorisation f) ≫ image.ι f = F.m :=
hF.lift_fac _
-- TODO we could put a category structure on `mono_factorisation f`,
-- with the morphisms being `g : I ⟶ I'` commuting with the `m`s
-- (they then automatically commute with the `e`s)
-- and show that an `image_of f` gives an initial object there
-- (uniqueness of the lift comes for free).
instance lift_mono (F' : mono_factorisation f) : mono (image.lift F') :=
by { apply mono_of_mono _ F'.m, simpa using mono_factorisation.m_mono _ }
lemma has_image.uniq
(F' : mono_factorisation f) (l : image f ⟶ F'.I) (w : l ≫ F'.m = image.ι f) :
l = image.lift F' :=
(cancel_mono F'.m).1 (by simp [w])
end
section
variables (C)
/-- `has_images` represents a choice of image for every morphism -/
class has_images :=
(has_image : Π {X Y : C} (f : X ⟶ Y), has_image f)
attribute [instance, priority 100] has_images.has_image
end
section
variables (f) [has_image f]
/-- The image of a monomorphism is isomorphic to the source. -/
def image_mono_iso_source [mono f] : image f ≅ X :=
is_image.iso_ext (image.is_image f) (is_image.self f)
@[simp, reassoc]
lemma image_mono_iso_source_inv_ι [mono f] : (image_mono_iso_source f).inv ≫ image.ι f = f :=
by simp [image_mono_iso_source]
@[simp, reassoc]
lemma image_mono_iso_source_hom_self [mono f] : (image_mono_iso_source f).hom ≫ f = image.ι f :=
begin
conv { to_lhs, congr, skip, rw ←image_mono_iso_source_inv_ι f, },
rw [←category.assoc, iso.hom_inv_id, category.id_comp],
end
-- This is the proof that `factor_thru_image f` is an epimorphism
-- from https://en.wikipedia.org/wiki/Image_%28category_theory%29, which is in turn taken from:
-- Mitchell, Barry (1965), Theory of categories, MR 0202787, p.12, Proposition 10.1
@[ext]
lemma image.ext {W : C} {g h : image f ⟶ W} [has_limit (parallel_pair g h)]
(w : factor_thru_image f ≫ g = factor_thru_image f ≫ h) :
g = h :=
begin
let q := equalizer.ι g h,
let e' := equalizer.lift _ w,
let F' : mono_factorisation f :=
{ I := equalizer g h,
m := q ≫ image.ι f,
m_mono := by apply mono_comp,
e := e' },
let v := image.lift F',
have t₀ : v ≫ q ≫ image.ι f = image.ι f := image.lift_fac F',
have t : v ≫ q = 𝟙 (image f) :=
(cancel_mono_id (image.ι f)).1 (by { convert t₀ using 1, rw category.assoc }),
-- The proof from wikipedia next proves `q ≫ v = 𝟙 _`,
-- and concludes that `equalizer g h ≅ image f`,
-- but this isn't necessary.
calc g = 𝟙 (image f) ≫ g : by rw [category.id_comp]
... = v ≫ q ≫ g : by rw [←t, category.assoc]
... = v ≫ q ≫ h : by rw [equalizer.condition g h]
... = 𝟙 (image f) ≫ h : by rw [←category.assoc, t]
... = h : by rw [category.id_comp]
end
instance [Π {Z : C} (g h : image f ⟶ Z), has_limit (parallel_pair g h)] :
epi (factor_thru_image f) :=
⟨λ Z g h w, image.ext f w⟩
lemma epi_image_of_epi {X Y : C} (f : X ⟶ Y) [has_image f] [E : epi f] : epi (image.ι f) :=
begin
rw ←image.fac f at E,
resetI,
exact epi_of_epi (factor_thru_image f) (image.ι f),
end
lemma epi_of_epi_image {X Y : C} (f : X ⟶ Y) [has_image f]
[epi (image.ι f)] [epi (factor_thru_image f)] : epi f :=
by { rw [←image.fac f], apply epi_comp, }
end
section
variables {f} {f' : X ⟶ Y} [has_image f] [has_image f']
/--
An equation between morphisms gives a comparison map between the images
(which momentarily we prove is an iso).
-/
def image.eq_to_hom (h : f = f') : image f ⟶ image f' :=
image.lift
{ I := image f',
m := image.ι f',
e := factor_thru_image f', }.
instance (h : f = f') : is_iso (image.eq_to_hom h) :=
⟨image.eq_to_hom h.symm,
⟨(cancel_mono (image.ι f)).1 (by simp [image.eq_to_hom]),
(cancel_mono (image.ι f')).1 (by simp [image.eq_to_hom])⟩⟩
/-- An equation between morphisms gives an isomorphism between the images. -/
def image.eq_to_iso (h : f = f') : image f ≅ image f' := as_iso (image.eq_to_hom h)
/--
As long as the category has equalizers,
the image inclusion maps commute with `image.eq_to_iso`.
-/
lemma image.eq_fac [has_equalizers C] (h : f = f') :
image.ι f = (image.eq_to_iso h).hom ≫ image.ι f' :=
by { ext, simp [image.eq_to_iso, image.eq_to_hom], }
end
section
variables {Z : C} (g : Y ⟶ Z)
/-- The comparison map `image (f ≫ g) ⟶ image g`. -/
def image.pre_comp [has_image g] [has_image (f ≫ g)] : image (f ≫ g) ⟶ image g :=
image.lift
{ I := image g,
m := image.ι g,
e := f ≫ factor_thru_image g }
@[simp, reassoc]
lemma image.factor_thru_image_pre_comp [has_image g] [has_image (f ≫ g)] :
factor_thru_image (f ≫ g) ≫ image.pre_comp f g = f ≫ factor_thru_image g :=
by simp [image.pre_comp]
/--
The two step comparison map
`image (f ≫ (g ≫ h)) ⟶ image (g ≫ h) ⟶ image h`
agrees with the one step comparison map
`image (f ≫ (g ≫ h)) ≅ image ((f ≫ g) ≫ h) ⟶ image h`.
-/
lemma image.pre_comp_comp {W : C} (h : Z ⟶ W)
[has_image (g ≫ h)] [has_image (f ≫ g ≫ h)]
[has_image h] [has_image ((f ≫ g) ≫ h)] :
image.pre_comp f (g ≫ h) ≫ image.pre_comp g h =
image.eq_to_hom (category.assoc f g h).symm ≫ (image.pre_comp (f ≫ g) h) :=
begin
apply (cancel_mono (image.ι h)).1,
simp [image.pre_comp, image.eq_to_hom],
end
variables [has_equalizers C]
/--
`image.pre_comp f g` is an isomorphism when `f` is an isomorphism
(we need `C` to have equalizers to prove this).
-/
instance image.is_iso_precomp_iso (f : X ≅ Y) [has_image g] [has_image (f.hom ≫ g)] :
is_iso (image.pre_comp f.hom g) :=
⟨image.lift
{ I := image (f.hom ≫ g),
m := image.ι (f.hom ≫ g),
e := f.inv ≫ factor_thru_image (f.hom ≫ g) },
⟨by { ext, simp [image.pre_comp], }, by { ext, simp [image.pre_comp], }⟩⟩
-- Note that in general we don't have the other comparison map you might expect
-- `image f ⟶ image (f ≫ g)`.
/-- Postcomposing by an isomorphism induces an isomorphism on the image. -/
def image.post_comp_is_iso [is_iso g] [has_image f] [has_image (f ≫ g)] :
image f ≅ image (f ≫ g) :=
{ hom := image.lift
{ I := _,
m := image.ι (f ≫ g) ≫ inv g,
m_mono := mono_comp _ _,
e := factor_thru_image (f ≫ g) },
inv := image.lift
{ I := _,
m := image.ι f ≫ g,
m_mono := mono_comp _ _,
e := factor_thru_image f } }
@[simp, reassoc] lemma image.post_comp_is_iso_hom_comp_image_ι [is_iso g] [has_image f]
[has_image (f ≫ g)] : (image.post_comp_is_iso f g).hom ≫ image.ι (f ≫ g) = image.ι f ≫ g :=
by { ext, simp [image.post_comp_is_iso] }
@[simp, reassoc] lemma image.post_comp_is_iso_inv_comp_image_ι [is_iso g] [has_image f]
[has_image (f ≫ g)] : (image.post_comp_is_iso f g).inv ≫ image.ι f = image.ι (f ≫ g) ≫ inv g :=
by { ext, simp [image.post_comp_is_iso] }
end
end category_theory.limits
namespace category_theory.limits
variables {C : Type u} [category.{v} C]
section
instance {X Y : C} (f : X ⟶ Y) [has_image f] : has_image (arrow.mk f).hom :=
show has_image f, by apply_instance
end
section has_image_map
/-- An image map is a morphism `image f → image g` fitting into a commutative square and satisfying
the obvious commutativity conditions. -/
structure image_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) :=
(map : image f.hom ⟶ image g.hom)
(map_ι' : map ≫ image.ι g.hom = image.ι f.hom ≫ sq.right . obviously)
instance inhabited_image_map {f : arrow C} [has_image f.hom] : inhabited (image_map (𝟙 f)) :=
⟨⟨𝟙 _, by tidy⟩⟩
restate_axiom image_map.map_ι'
attribute [simp, reassoc] image_map.map_ι
@[simp, reassoc]
lemma image_map.factor_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g)
(m : image_map sq) :
factor_thru_image f.hom ≫ m.map = sq.left ≫ factor_thru_image g.hom :=
(cancel_mono (image.ι g.hom)).1 $ by simp
/-- To give an image map for a commutative square with `f` at the top and `g` at the bottom, it
suffices to give a map between any mono factorisation of `f` and any image factorisation of
`g`. -/
def image_map.transport {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g)
(F : mono_factorisation f.hom) {F' : mono_factorisation g.hom} (hF' : is_image F')
{map : F.I ⟶ F'.I} (map_ι : map ≫ F'.m = F.m ≫ sq.right) : image_map sq :=
{ map := image.lift F ≫ map ≫ hF'.lift (image.mono_factorisation g.hom),
map_ι' := by simp [map_ι] }
/-- `has_image_map sq` means that there is an `image_map` for the square `sq`. -/
class has_image_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) : Prop :=
mk' :: (has_image_map : nonempty (image_map sq))
lemma has_image_map.mk {f g : arrow C} [has_image f.hom] [has_image g.hom] {sq : f ⟶ g}
(m : image_map sq) : has_image_map sq :=
⟨nonempty.intro m⟩
lemma has_image_map.transport {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g)
(F : mono_factorisation f.hom) {F' : mono_factorisation g.hom} (hF' : is_image F')
(map : F.I ⟶ F'.I) (map_ι : map ≫ F'.m = F.m ≫ sq.right) : has_image_map sq :=
has_image_map.mk $ image_map.transport sq F hF' map_ι
/-- Obtain an `image_map` from a `has_image_map` instance. -/
def has_image_map.image_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g)
[has_image_map sq] : image_map sq :=
classical.choice $ @has_image_map.has_image_map _ _ _ _ _ _ sq _
variables {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g)
section
local attribute [ext] image_map
instance : subsingleton (image_map sq) :=
subsingleton.intro $ λ a b, image_map.ext a b $ (cancel_mono (image.ι g.hom)).1 $
by simp only [image_map.map_ι]
end
variable [has_image_map sq]
/-- The map on images induced by a commutative square. -/
abbreviation image.map : image f.hom ⟶ image g.hom :=
(has_image_map.image_map sq).map
lemma image.factor_map :
factor_thru_image f.hom ≫ image.map sq = sq.left ≫ factor_thru_image g.hom :=
by simp
lemma image.map_ι : image.map sq ≫ image.ι g.hom = image.ι f.hom ≫ sq.right :=
by simp
lemma image.map_hom_mk'_ι {X Y P Q : C} {k : X ⟶ Y} [has_image k] {l : P ⟶ Q} [has_image l]
{m : X ⟶ P} {n : Y ⟶ Q} (w : m ≫ l = k ≫ n) [has_image_map (arrow.hom_mk' w)] :
image.map (arrow.hom_mk' w) ≫ image.ι l = image.ι k ≫ n :=
image.map_ι _
section
variables {h : arrow C} [has_image h.hom] (sq' : g ⟶ h)
variables [has_image_map sq']
/-- Image maps for composable commutative squares induce an image map in the composite square. -/
def image_map_comp : image_map (sq ≫ sq') :=
{ map := image.map sq ≫ image.map sq' }
@[simp]
lemma image.map_comp [has_image_map (sq ≫ sq')] :
image.map (sq ≫ sq') = image.map sq ≫ image.map sq' :=
show (has_image_map.image_map (sq ≫ sq')).map = (image_map_comp sq sq').map, by congr
end
section
variables (f)
/-- The identity `image f ⟶ image f` fits into the commutative square represented by the identity
morphism `𝟙 f` in the arrow category. -/
def image_map_id : image_map (𝟙 f) :=
{ map := 𝟙 (image f.hom) }
@[simp]
lemma image.map_id [has_image_map (𝟙 f)] : image.map (𝟙 f) = 𝟙 (image f.hom) :=
show (has_image_map.image_map (𝟙 f)).map = (image_map_id f).map, by congr
end
end has_image_map
section
variables (C) [has_images C]
/-- If a category `has_image_maps`, then all commutative squares induce morphisms on images. -/
class has_image_maps :=
(has_image_map : Π {f g : arrow C} (st : f ⟶ g), has_image_map st)
attribute [instance, priority 100] has_image_maps.has_image_map
end
section has_image_maps
variables [has_images C] [has_image_maps C]
/-- The functor from the arrow category of `C` to `C` itself that maps a morphism to its image
and a commutative square to the induced morphism on images. -/
@[simps]
def im : arrow C ⥤ C :=
{ obj := λ f, image f.hom,
map := λ _ _ st, image.map st }
end has_image_maps
section strong_epi_mono_factorisation
/-- A strong epi-mono factorisation is a decomposition `f = e ≫ m` with `e` a strong epimorphism
and `m` a monomorphism. -/
structure strong_epi_mono_factorisation {X Y : C} (f : X ⟶ Y) extends mono_factorisation f :=
[e_strong_epi : strong_epi e]
attribute [instance] strong_epi_mono_factorisation.e_strong_epi
/-- Satisfying the inhabited linter -/
instance strong_epi_mono_factorisation_inhabited {X Y : C} (f : X ⟶ Y) [strong_epi f] :
inhabited (strong_epi_mono_factorisation f) :=
⟨⟨⟨Y, 𝟙 Y, f, by simp⟩⟩⟩
/-- A mono factorisation coming from a strong epi-mono factorisation always has the universal
property of the image. -/
def strong_epi_mono_factorisation.to_mono_is_image {X Y : C} {f : X ⟶ Y}
(F : strong_epi_mono_factorisation f) : is_image F.to_mono_factorisation :=
{ lift := λ G, arrow.lift $ arrow.hom_mk' $
show G.e ≫ G.m = F.e ≫ F.m, by rw [F.to_mono_factorisation.fac, G.fac] }
variable (C)
/-- A category has strong epi-mono factorisations if every morphism admits a strong epi-mono
factorisation. -/
class has_strong_epi_mono_factorisations : Prop :=
mk' :: (has_fac : Π {X Y : C} (f : X ⟶ Y), nonempty (strong_epi_mono_factorisation f))
variable {C}
lemma has_strong_epi_mono_factorisations.mk
(d : Π {X Y : C} (f : X ⟶ Y), strong_epi_mono_factorisation f) :
has_strong_epi_mono_factorisations C :=
⟨λ X Y f, nonempty.intro $ d f⟩
@[priority 100]
instance has_images_of_has_strong_epi_mono_factorisations
[has_strong_epi_mono_factorisations C] : has_images C :=
{ has_image := λ X Y f,
let F' := classical.choice (has_strong_epi_mono_factorisations.has_fac f) in
has_image.mk { F := F'.to_mono_factorisation,
is_image := F'.to_mono_is_image } }
end strong_epi_mono_factorisation
section has_strong_epi_images
variables (C) [has_images C]
/-- A category has strong epi images if it has all images and `factor_thru_image f` is a strong
epimorphism for all `f`. -/
class has_strong_epi_images : Prop :=
(strong_factor_thru_image : Π {X Y : C} (f : X ⟶ Y), strong_epi (factor_thru_image f))
attribute [instance] has_strong_epi_images.strong_factor_thru_image
end has_strong_epi_images
section has_strong_epi_images
/-- If there is a single strong epi-mono factorisation of `f`, then every image factorisation is a
strong epi-mono factorisation. -/
lemma strong_epi_of_strong_epi_mono_factorisation {X Y : C} {f : X ⟶ Y}
(F : strong_epi_mono_factorisation f) {F' : mono_factorisation f} (hF' : is_image F') :
strong_epi F'.e :=
by { rw ←is_image.e_iso_ext_hom F.to_mono_is_image hF', apply strong_epi_comp }
lemma strong_epi_factor_thru_image_of_strong_epi_mono_factorisation {X Y : C} {f : X ⟶ Y}
[has_image f] (F : strong_epi_mono_factorisation f) : strong_epi (factor_thru_image f) :=
strong_epi_of_strong_epi_mono_factorisation F $ image.is_image f
/-- If we constructed our images from strong epi-mono factorisations, then these images are
strong epi images. -/
@[priority 100]
instance has_strong_epi_images_of_has_strong_epi_mono_factorisations
[has_strong_epi_mono_factorisations C] : has_strong_epi_images C :=
{ strong_factor_thru_image := λ X Y f,
strong_epi_factor_thru_image_of_strong_epi_mono_factorisation $
classical.choice $ has_strong_epi_mono_factorisations.has_fac f }
end has_strong_epi_images
section has_strong_epi_images
variables [has_images C]
/-- A category with strong epi images has image maps. -/
@[priority 100]
instance has_image_maps_of_has_strong_epi_images [has_strong_epi_images C] :
has_image_maps C :=
{ has_image_map := λ f g st, has_image_map.mk
{ map := arrow.lift $ arrow.hom_mk' $ show (st.left ≫ factor_thru_image g.hom) ≫ image.ι g.hom =
factor_thru_image f.hom ≫ (image.ι f.hom ≫ st.right), by simp } }
/-- If a category has images, equalizers and pullbacks, then images are automatically strong epi
images. -/
@[priority 100]
instance has_strong_epi_images_of_has_pullbacks_of_has_equalizers [has_pullbacks C]
[has_equalizers C] : has_strong_epi_images C :=
{ strong_factor_thru_image := λ X Y f,
{ epi := by apply_instance,
has_lift := λ A B x y h h_mono w, arrow.has_lift.mk
{ lift := image.lift
{ I := pullback h y,
m := pullback.snd ≫ image.ι f,
m_mono := by exactI mono_comp _ _,
e := pullback.lift _ _ w } ≫ pullback.fst,
fac_left := by simp,
fac_right := by tidy } } }
end has_strong_epi_images
variables [has_strong_epi_mono_factorisations.{v} C]
variables {X Y : C} {f : X ⟶ Y}
/--
If `C` has strong epi mono factorisations, then the image is unique up to isomorphism, in that if
`f` factors as a strong epi followed by a mono, this factorisation is essentially the image
factorisation.
-/
def image.iso_strong_epi_mono {I' : C} (e : X ⟶ I') (m : I' ⟶ Y) (comm : e ≫ m = f) [strong_epi e]
[mono m] :
I' ≅ image f :=
is_image.iso_ext {strong_epi_mono_factorisation . I := I', m := m, e := e}.to_mono_is_image $
image.is_image f
@[simp]
lemma image.iso_strong_epi_mono_hom_comp_ι {I' : C} (e : X ⟶ I') (m : I' ⟶ Y) (comm : e ≫ m = f)
[strong_epi e] [mono m] :
(image.iso_strong_epi_mono e m comm).hom ≫ image.ι f = m :=
is_image.lift_fac _ _
@[simp]
lemma image.iso_strong_epi_mono_inv_comp_mono {I' : C} (e : X ⟶ I') (m : I' ⟶ Y) (comm : e ≫ m = f)
[strong_epi e] [mono m] :
(image.iso_strong_epi_mono e m comm).inv ≫ m = image.ι f :=
image.lift_fac _
end category_theory.limits
|
6dca149fe23a555c66ca1add05f121d3f7490da5 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/ring_theory/valuation/valuation_ring.lean | ab9a3b5e97613aa7e9cdd9ee4506d6c1cc0884c2 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 17,207 | lean | /-
Copyright (c) 2022 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz
-/
import ring_theory.valuation.integers
import ring_theory.ideal.local_ring
import ring_theory.localization.fraction_ring
import ring_theory.localization.integer
import ring_theory.discrete_valuation_ring
import ring_theory.bezout
import tactic.field_simp
/-!
# Valuation Rings
A valuation ring is a domain such that for every pair of elements `a b`, either `a` divides
`b` or vice-versa.
Any valuation ring induces a natural valuation on its fraction field, as we show in this file.
Namely, given the following instances:
`[comm_ring A] [is_domain A] [valuation_ring A] [field K] [algebra A K] [is_fraction_ring A K]`,
there is a natural valuation `valuation A K` on `K` with values in `value_group A K` where
the image of `A` under `algebra_map A K` agrees with `(valuation A K).integer`.
We also provide the equivalence of the following notions for a domain `R` in `valuation_ring.tfae`.
1. `R` is a valuation ring.
2. For each `x : fraction_ring K`, either `x` or `x⁻¹` is in `R`.
3. "divides" is a total relation on the elements of `R`.
4. "contains" is a total relation on the ideals of `R`.
5. `R` is a local bezout domain.
-/
universes u v w
/-- An integral domain is called a `valuation ring` provided that for any pair
of elements `a b : A`, either `a` divides `b` or vice versa. -/
class valuation_ring (A : Type u) [comm_ring A] [is_domain A] : Prop :=
(cond [] : ∀ a b : A, ∃ c : A, a * c = b ∨ b * c = a)
namespace valuation_ring
section
variables (A : Type u) [comm_ring A]
variables (K : Type v) [field K] [algebra A K]
/-- The value group of the valuation ring `A`. -/
def value_group : Type v := quotient (mul_action.orbit_rel Aˣ K)
instance : inhabited (value_group A K) := ⟨quotient.mk' 0⟩
instance : has_le (value_group A K) := has_le.mk $ λ x y,
quotient.lift_on₂' x y (λ a b, ∃ c : A, c • b = a)
begin
rintros _ _ a b ⟨c,rfl⟩ ⟨d,rfl⟩, ext,
split,
{ rintros ⟨e,he⟩, use ((c⁻¹ : Aˣ) * e * d),
apply_fun (λ t, c⁻¹ • t) at he,
simpa [mul_smul] using he },
{ rintros ⟨e,he⟩, dsimp,
use (d⁻¹ : Aˣ) * c * e,
erw [← he, ← mul_smul, ← mul_smul],
congr' 1,
rw mul_comm,
simp only [← mul_assoc, ← units.coe_mul, mul_inv_self, one_mul] }
end
instance : has_zero (value_group A K) := ⟨quotient.mk' 0⟩
instance : has_one (value_group A K) := ⟨quotient.mk' 1⟩
instance : has_mul (value_group A K) := has_mul.mk $ λ x y,
quotient.lift_on₂' x y (λ a b, quotient.mk' $ a * b)
begin
rintros _ _ a b ⟨c,rfl⟩ ⟨d,rfl⟩,
apply quotient.sound',
dsimp,
use c * d,
simp only [mul_smul, algebra.smul_def, units.smul_def, ring_hom.map_mul,
units.coe_mul],
ring,
end
instance : has_inv (value_group A K) := has_inv.mk $ λ x,
quotient.lift_on' x (λ a, quotient.mk' a⁻¹)
begin
rintros _ a ⟨b,rfl⟩,
apply quotient.sound',
use b⁻¹,
dsimp,
rw [units.smul_def, units.smul_def, algebra.smul_def, algebra.smul_def,
mul_inv, map_units_inv],
end
variables [is_domain A] [valuation_ring A] [is_fraction_ring A K]
protected lemma le_total (a b : value_group A K) : a ≤ b ∨ b ≤ a :=
begin
rcases a with ⟨a⟩, rcases b with ⟨b⟩,
obtain ⟨xa,ya,hya,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective a,
obtain ⟨xb,yb,hyb,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective b,
have : (algebra_map A K) ya ≠ 0 :=
is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hya,
have : (algebra_map A K) yb ≠ 0 :=
is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hyb,
obtain ⟨c,(h|h)⟩ := valuation_ring.cond (xa * yb) (xb * ya),
{ right,
use c,
rw algebra.smul_def,
field_simp,
simp only [← ring_hom.map_mul, ← h], congr' 1, ring },
{ left,
use c,
rw algebra.smul_def,
field_simp,
simp only [← ring_hom.map_mul, ← h], congr' 1, ring }
end
noncomputable
instance : linear_ordered_comm_group_with_zero (value_group A K) :=
{ le_refl := by { rintro ⟨⟩, use 1, rw one_smul },
le_trans := by { rintros ⟨a⟩ ⟨b⟩ ⟨c⟩ ⟨e,rfl⟩ ⟨f,rfl⟩, use (e * f), rw mul_smul },
le_antisymm := begin
rintros ⟨a⟩ ⟨b⟩ ⟨e,rfl⟩ ⟨f,hf⟩,
by_cases hb : b = 0, { simp [hb] },
have : is_unit e,
{ apply is_unit_of_dvd_one,
use f, rw mul_comm,
rw [← mul_smul, algebra.smul_def] at hf,
nth_rewrite 1 ← one_mul b at hf,
rw ← (algebra_map A K).map_one at hf,
exact is_fraction_ring.injective _ _
(cancel_comm_monoid_with_zero.mul_right_cancel_of_ne_zero hb hf).symm },
apply quotient.sound',
use [this.unit, rfl],
end,
le_total := valuation_ring.le_total _ _,
decidable_le := by { classical, apply_instance },
mul_assoc := by { rintros ⟨a⟩ ⟨b⟩ ⟨c⟩, apply quotient.sound', rw mul_assoc, apply setoid.refl' },
one_mul := by { rintros ⟨a⟩, apply quotient.sound', rw one_mul, apply setoid.refl' },
mul_one := by { rintros ⟨a⟩, apply quotient.sound', rw mul_one, apply setoid.refl' },
mul_comm := by { rintros ⟨a⟩ ⟨b⟩, apply quotient.sound', rw mul_comm, apply setoid.refl' },
mul_le_mul_left := begin
rintros ⟨a⟩ ⟨b⟩ ⟨c,rfl⟩ ⟨d⟩,
use c, simp only [algebra.smul_def], ring,
end,
zero_mul := by { rintros ⟨a⟩, apply quotient.sound', rw zero_mul, apply setoid.refl' },
mul_zero := by { rintros ⟨a⟩, apply quotient.sound', rw mul_zero, apply setoid.refl' },
zero_le_one := ⟨0, by rw zero_smul⟩,
exists_pair_ne := begin
use [0,1],
intro c, obtain ⟨d,hd⟩ := quotient.exact' c,
apply_fun (λ t, d⁻¹ • t) at hd,
simpa using hd,
end,
inv_zero := by { apply quotient.sound', rw inv_zero, apply setoid.refl' },
mul_inv_cancel := begin
rintros ⟨a⟩ ha,
apply quotient.sound',
use 1,
simp only [one_smul],
apply (mul_inv_cancel _).symm,
contrapose ha,
simp only [not_not] at ha ⊢,
rw ha, refl,
end,
..(infer_instance : has_le (value_group A K)),
..(infer_instance : has_mul (value_group A K)),
..(infer_instance : has_inv (value_group A K)),
..(infer_instance : has_zero (value_group A K)),
..(infer_instance : has_one (value_group A K)) }
/-- Any valuation ring induces a valuation on its fraction field. -/
def valuation : valuation K (value_group A K) :=
{ to_fun := quotient.mk',
map_zero' := rfl,
map_one' := rfl,
map_mul' := λ _ _, rfl,
map_add_le_max' := begin
intros a b,
obtain ⟨xa,ya,hya,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective a,
obtain ⟨xb,yb,hyb,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective b,
have : (algebra_map A K) ya ≠ 0 :=
is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hya,
have : (algebra_map A K) yb ≠ 0 :=
is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hyb,
obtain ⟨c,(h|h)⟩ := valuation_ring.cond (xa * yb) (xb * ya),
dsimp,
{ apply le_trans _ (le_max_left _ _),
use (c + 1),
rw algebra.smul_def,
field_simp,
simp only [← ring_hom.map_mul, ← ring_hom.map_add, ← (algebra_map A K).map_one, ← h],
congr' 1, ring },
{ apply le_trans _ (le_max_right _ _),
use (c + 1),
rw algebra.smul_def,
field_simp,
simp only [← ring_hom.map_mul, ← ring_hom.map_add, ← (algebra_map A K).map_one, ← h],
congr' 1, ring }
end }
lemma mem_integer_iff (x : K) : x ∈ (valuation A K).integer ↔ ∃ a : A, algebra_map A K a = x :=
begin
split,
{ rintros ⟨c,rfl⟩,
use c,
rw [algebra.smul_def, mul_one] },
{ rintro ⟨c,rfl⟩,
use c,
rw [algebra.smul_def, mul_one] }
end
/-- The valuation ring `A` is isomorphic to the ring of integers of its associated valuation. -/
noncomputable def equiv_integer : A ≃+* (valuation A K).integer :=
ring_equiv.of_bijective (show A →ₙ+* (valuation A K).integer, from
{ to_fun := λ a, ⟨algebra_map A K a, (mem_integer_iff _ _ _).mpr ⟨a,rfl⟩⟩,
map_mul' := λ _ _, by { ext1, exact (algebra_map A K).map_mul _ _ },
map_zero' := by { ext1, exact (algebra_map A K).map_zero },
map_add' := λ _ _, by { ext1, exact (algebra_map A K).map_add _ _ } })
begin
split,
{ intros x y h,
apply_fun (coe : _ → K) at h,
dsimp at h,
exact is_fraction_ring.injective _ _ h },
{ rintros ⟨a,(ha : a ∈ (valuation A K).integer)⟩,
rw mem_integer_iff at ha,
obtain ⟨a,rfl⟩ := ha,
use [a, rfl] }
end
@[simp]
lemma coe_equiv_integer_apply (a : A) : (equiv_integer A K a : K) = algebra_map A K a := rfl
lemma range_algebra_map_eq : (valuation A K).integer = (algebra_map A K).range :=
by { ext, exact mem_integer_iff _ _ _ }
end
section
variables (A : Type u) [comm_ring A] [is_domain A] [valuation_ring A]
@[priority 100]
instance : local_ring A :=
local_ring.of_is_unit_or_is_unit_one_sub_self
begin
intros a,
obtain ⟨c,(h|h)⟩ := valuation_ring.cond a (1-a),
{ left,
apply is_unit_of_mul_eq_one _ (c+1),
simp [mul_add, h] },
{ right,
apply is_unit_of_mul_eq_one _ (c+1),
simp [mul_add, h] }
end
instance [decidable_rel ((≤) : ideal A → ideal A → Prop)] : linear_order (ideal A) :=
{ le_total := begin
intros α β,
by_cases h : α ≤ β, { exact or.inl h },
erw not_forall at h,
push_neg at h,
obtain ⟨a,h₁,h₂⟩ := h,
right,
intros b hb,
obtain ⟨c,(h|h)⟩ := valuation_ring.cond a b,
{ rw ← h,
exact ideal.mul_mem_right _ _ h₁ },
{ exfalso, apply h₂, rw ← h,
apply ideal.mul_mem_right _ _ hb },
end,
decidable_le := infer_instance,
..(infer_instance : complete_lattice (ideal A)) }
end
section
variables {R : Type*} [comm_ring R] [is_domain R] {K : Type*}
variables [field K] [algebra R K] [is_fraction_ring R K]
lemma iff_dvd_total :
valuation_ring R ↔ is_total R (∣) :=
begin
classical,
refine ⟨λ H, ⟨λ a b, _⟩, λ H, ⟨λ a b, _⟩⟩; resetI,
{ obtain ⟨c,rfl|rfl⟩ := @@valuation_ring.cond _ _ H a b; simp },
{ obtain (⟨c, rfl⟩|⟨c, rfl⟩) := @is_total.total _ _ H a b; use c; simp }
end
lemma iff_ideal_total :
valuation_ring R ↔ is_total (ideal R) (≤) :=
begin
classical,
refine ⟨λ _, by exactI ⟨le_total⟩, λ H, iff_dvd_total.mpr ⟨λ a b, _⟩⟩,
have := @is_total.total _ _ H (ideal.span {a}) (ideal.span {b}),
simp_rw ideal.span_singleton_le_span_singleton at this,
exact this.symm
end
variables {R} (K)
lemma dvd_total [h : valuation_ring R] (x y : R) : x ∣ y ∨ y ∣ x :=
@@is_total.total _ (iff_dvd_total.mp h) x y
lemma unique_irreducible [valuation_ring R] ⦃p q : R⦄
(hp : irreducible p) (hq : irreducible q) : associated p q :=
begin
have := dvd_total p q,
rw [irreducible.dvd_comm hp hq, or_self] at this,
exact associated_of_dvd_dvd (irreducible.dvd_symm hq hp this) this,
end
variable (R)
lemma iff_is_integer_or_is_integer :
valuation_ring R ↔ ∀ x : K, is_localization.is_integer R x ∨ is_localization.is_integer R x⁻¹ :=
begin
split,
{ introsI H x,
obtain ⟨x : R, y, hy, rfl⟩ := is_fraction_ring.div_surjective x,
any_goals { apply_instance },
have := (map_ne_zero_iff _ (is_fraction_ring.injective R K)).mpr (non_zero_divisors.ne_zero hy),
obtain ⟨s, rfl|rfl⟩ := valuation_ring.cond x y,
{ exact or.inr ⟨s, eq_inv_of_mul_eq_one_left $
by rwa [mul_div, div_eq_one_iff_eq, map_mul, mul_comm]⟩ },
{ exact or.inl ⟨s, by rwa [eq_div_iff, map_mul, mul_comm]⟩ } },
{ intro H,
constructor,
intros a b,
by_cases ha : a = 0, { subst ha, exact ⟨0, or.inr $ mul_zero b⟩ },
by_cases hb : b = 0, { subst hb, exact ⟨0, or.inl $ mul_zero a⟩ },
replace ha := (map_ne_zero_iff _ (is_fraction_ring.injective R K)).mpr ha,
replace hb := (map_ne_zero_iff _ (is_fraction_ring.injective R K)).mpr hb,
obtain ⟨c, e⟩|⟨c, e⟩ := H (algebra_map R K a / algebra_map R K b),
{ rw [eq_div_iff hb, ← map_mul, (is_fraction_ring.injective R K).eq_iff, mul_comm] at e,
exact ⟨c, or.inr e⟩ },
{ rw [inv_div, eq_div_iff ha, ← map_mul,
(is_fraction_ring.injective R K).eq_iff, mul_comm c] at e,
exact ⟨c, or.inl e⟩ } }
end
variable {K}
lemma is_integer_or_is_integer [h : valuation_ring R] (x : K) :
is_localization.is_integer R x ∨ is_localization.is_integer R x⁻¹ :=
(iff_is_integer_or_is_integer R K).mp h x
variable {R}
-- This implies that valuation rings are integrally closed through typeclass search.
@[priority 100]
instance [valuation_ring R] : is_bezout R :=
begin
classical,
rw is_bezout.iff_span_pair_is_principal,
intros x y,
rw ideal.span_insert,
cases le_total (ideal.span {x} : ideal R) (ideal.span {y}),
{ erw sup_eq_right.mpr h, exact ⟨⟨_, rfl⟩⟩ },
{ erw sup_eq_left.mpr h, exact ⟨⟨_, rfl⟩⟩ }
end
lemma iff_local_bezout_domain :
valuation_ring R ↔ local_ring R ∧ is_bezout R :=
begin
classical,
refine ⟨λ H, by exactI ⟨infer_instance, infer_instance⟩, _⟩,
rintro ⟨h₁, h₂⟩,
resetI,
refine iff_dvd_total.mpr ⟨λ a b, _⟩,
obtain ⟨g, e : _ = ideal.span _⟩ := is_bezout.span_pair_is_principal a b,
obtain ⟨a, rfl⟩ := ideal.mem_span_singleton'.mp
(show a ∈ ideal.span {g}, by { rw [← e], exact ideal.subset_span (by simp) }),
obtain ⟨b, rfl⟩ := ideal.mem_span_singleton'.mp
(show b ∈ ideal.span {g}, by { rw [← e], exact ideal.subset_span (by simp) }),
obtain ⟨x, y, e'⟩ := ideal.mem_span_pair.mp
(show g ∈ ideal.span {a * g, b * g}, by { rw e, exact ideal.subset_span (by simp) }),
cases eq_or_ne g 0 with h h, { simp [h] },
have : x * a + y * b = 1,
{ apply mul_left_injective₀ h, convert e'; ring_nf },
cases local_ring.is_unit_or_is_unit_of_add_one this with h' h',
left, swap, right,
all_goals
{ exact mul_dvd_mul_right (is_unit_iff_forall_dvd.mp (is_unit_of_mul_is_unit_right h') _) _ },
end
protected lemma tfae (R : Type u) [comm_ring R] [is_domain R] :
tfae [valuation_ring R,
∀ x : fraction_ring R, is_localization.is_integer R x ∨ is_localization.is_integer R x⁻¹,
is_total R (∣),
is_total (ideal R) (≤),
local_ring R ∧ is_bezout R] :=
begin
tfae_have : 1 ↔ 2, { exact iff_is_integer_or_is_integer R _ },
tfae_have : 1 ↔ 3, { exact iff_dvd_total },
tfae_have : 1 ↔ 4, { exact iff_ideal_total },
tfae_have : 1 ↔ 5, { exact iff_local_bezout_domain },
tfae_finish
end
end
lemma _root_.function.surjective.valuation_ring {R S : Type*} [comm_ring R] [is_domain R]
[valuation_ring R] [comm_ring S] [is_domain S] (f : R →+* S) (hf : function.surjective f) :
valuation_ring S :=
⟨λ a b, begin
obtain ⟨⟨a, rfl⟩, ⟨b, rfl⟩⟩ := ⟨hf a, hf b⟩,
obtain ⟨c, rfl|rfl⟩ := valuation_ring.cond a b,
exacts [⟨f c, or.inl $ (map_mul _ _ _).symm⟩, ⟨f c, or.inr $ (map_mul _ _ _).symm⟩],
end⟩
section
variables {𝒪 : Type u} {K : Type v} {Γ : Type w}
[comm_ring 𝒪] [is_domain 𝒪] [field K] [algebra 𝒪 K]
[linear_ordered_comm_group_with_zero Γ]
(v : _root_.valuation K Γ) (hh : v.integers 𝒪)
include hh
/-- If `𝒪` satisfies `v.integers 𝒪` where `v` is a valuation on a field, then `𝒪`
is a valuation ring. -/
lemma of_integers : valuation_ring 𝒪 :=
begin
constructor,
intros a b,
cases le_total (v (algebra_map 𝒪 K a)) (v (algebra_map 𝒪 K b)),
{ obtain ⟨c,hc⟩ := valuation.integers.dvd_of_le hh h,
use c, exact or.inr hc.symm },
{ obtain ⟨c,hc⟩ := valuation.integers.dvd_of_le hh h,
use c, exact or.inl hc.symm }
end
end
section
variables (K : Type u) [field K]
/-- A field is a valuation ring. -/
@[priority 100]
instance of_field : valuation_ring K :=
begin
constructor,
intros a b,
by_cases b = 0,
{ use 0, left, simp [h] },
{ use a * b⁻¹, right, field_simp, rw mul_comm }
end
end
section
variables (A : Type u) [comm_ring A] [is_domain A] [discrete_valuation_ring A]
/-- A DVR is a valuation ring. -/
@[priority 100]
instance of_discrete_valuation_ring : valuation_ring A :=
begin
constructor,
intros a b,
by_cases ha : a = 0, { use 0, right, simp [ha] },
by_cases hb : b = 0, { use 0, left, simp [hb] },
obtain ⟨ϖ,hϖ⟩ := discrete_valuation_ring.exists_irreducible A,
obtain ⟨m,u,rfl⟩ := discrete_valuation_ring.eq_unit_mul_pow_irreducible ha hϖ,
obtain ⟨n,v,rfl⟩ := discrete_valuation_ring.eq_unit_mul_pow_irreducible hb hϖ,
cases le_total m n with h h,
{ use (u⁻¹ * v : Aˣ) * ϖ^(n-m), left,
simp_rw [mul_comm (u : A), units.coe_mul, ← mul_assoc, mul_assoc _ (u : A)],
simp only [units.mul_inv, mul_one, mul_comm _ (v : A), mul_assoc, ← pow_add],
congr' 2,
linarith },
{ use (v⁻¹ * u : Aˣ) * ϖ^(m-n), right,
simp_rw [mul_comm (v : A), units.coe_mul, ← mul_assoc, mul_assoc _ (v : A)],
simp only [units.mul_inv, mul_one, mul_comm _ (u : A), mul_assoc, ← pow_add],
congr' 2,
linarith }
end
end
end valuation_ring
|
e7cc422597e412e6c24464c65526e0ea2882aa13 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/functor/fully_faithful.lean | 400658ba2ff001368faab523c3b0f0ab4def7efd | [
"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 | 12,634 | 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.natural_isomorphism
import logic.equiv.defs
/-!
# Full and faithful functors
We define typeclasses `full` and `faithful`, decorating functors.
## Main definitions and results
* Use `F.map_injective` to retrieve the fact that `F.map` is injective when `[faithful F]`.
* Similarly, `F.map_surjective` states that `F.map` is surjective when `[full F]`.
* Use `F.preimage` to obtain preimages of morphisms when `[full F]`.
* We prove some basic "cancellation" lemmas for full and/or faithful functors, as well as a
construction for "dividing" a functor by a faithful functor, see `faithful.div`.
* `full F` carries data, so definitional properties of the preimage can be used when using
`F.preimage`. To obtain an instance of `full F` non-constructively, you can use `full_of_exists`
and `full_of_surjective`.
See `category_theory.equivalence.of_fully_faithful_ess_surj` for the fact that a functor is an
equivalence if and only if it is fully faithful and essentially surjective.
-/
-- declare the `v`'s first; see `category_theory.category` for an explanation
universes v₁ v₂ v₃ u₁ u₂ u₃
namespace category_theory
variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]
/--
A functor `F : C ⥤ D` is full if for each `X Y : C`, `F.map` is surjective.
In fact, we use a constructive definition, so the `full F` typeclass contains data,
specifying a particular preimage of each `f : F.obj X ⟶ F.obj Y`.
See <https://stacks.math.columbia.edu/tag/001C>.
-/
class full (F : C ⥤ D) :=
(preimage : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), X ⟶ Y)
(witness' : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), F.map (preimage f) = f . obviously)
restate_axiom full.witness'
attribute [simp] full.witness
/--
A functor `F : C ⥤ D` is faithful if for each `X Y : C`, `F.map` is injective.
See <https://stacks.math.columbia.edu/tag/001C>.
-/
class faithful (F : C ⥤ D) : Prop :=
(map_injective' [] : ∀ {X Y : C}, function.injective (@functor.map _ _ _ _ F X Y) . obviously)
restate_axiom faithful.map_injective'
namespace functor
variables {X Y : C}
lemma map_injective (F : C ⥤ D) [faithful F] : function.injective $ @functor.map _ _ _ _ F X Y :=
faithful.map_injective F
lemma map_iso_injective (F : C ⥤ D) [faithful F] :
function.injective $ @functor.map_iso _ _ _ _ F X Y :=
λ i j h, iso.ext (map_injective F (congr_arg iso.hom h : _))
/-- The specified preimage of a morphism under a full functor. -/
def preimage (F : C ⥤ D) [full F] (f : F.obj X ⟶ F.obj Y) : X ⟶ Y :=
full.preimage.{v₁ v₂} f
@[simp] lemma image_preimage (F : C ⥤ D) [full F] {X Y : C} (f : F.obj X ⟶ F.obj Y) :
F.map (preimage F f) = f :=
by unfold preimage; obviously
lemma map_surjective (F : C ⥤ D) [full F] : function.surjective (@functor.map _ _ _ _ F X Y) :=
λ f, ⟨F.preimage f, F.image_preimage f⟩
/-- Deduce that `F` is full from the existence of preimages, using choice. -/
noncomputable def full_of_exists (F : C ⥤ D)
(h : ∀ (X Y : C) (f : F.obj X ⟶ F.obj Y), ∃ p, F.map p = f) : full F :=
by { choose p hp using h, exact ⟨p, hp⟩ }
/-- Deduce that `F` is full from surjectivity of `F.map`, using choice. -/
noncomputable def full_of_surjective (F : C ⥤ D)
(h : ∀ (X Y : C), function.surjective (@functor.map _ _ _ _ F X Y)) : full F :=
full_of_exists _ h
end functor
section
variables {F : C ⥤ D} [full F] [faithful F] {X Y Z : C}
@[simp] lemma preimage_id : F.preimage (𝟙 (F.obj X)) = 𝟙 X :=
F.map_injective (by simp)
@[simp] lemma preimage_comp (f : F.obj X ⟶ F.obj Y) (g : F.obj Y ⟶ F.obj Z) :
F.preimage (f ≫ g) = F.preimage f ≫ F.preimage g :=
F.map_injective (by simp)
@[simp] lemma preimage_map (f : X ⟶ Y) :
F.preimage (F.map f) = f :=
F.map_injective (by simp)
variables (F)
namespace functor
/-- If `F : C ⥤ D` is fully faithful, every isomorphism `F.obj X ≅ F.obj Y` has a preimage. -/
@[simps]
def preimage_iso (f : (F.obj X) ≅ (F.obj Y)) : X ≅ Y :=
{ hom := F.preimage f.hom,
inv := F.preimage f.inv,
hom_inv_id' := F.map_injective (by simp),
inv_hom_id' := F.map_injective (by simp), }
@[simp] lemma preimage_iso_map_iso (f : X ≅ Y) :
F.preimage_iso (F.map_iso f) = f :=
by { ext, simp, }
end functor
/--
If the image of a morphism under a fully faithful functor in an isomorphism,
then the original morphisms is also an isomorphism.
-/
lemma is_iso_of_fully_faithful (f : X ⟶ Y) [is_iso (F.map f)] : is_iso f :=
⟨⟨F.preimage (inv (F.map f)),
⟨F.map_injective (by simp), F.map_injective (by simp)⟩⟩⟩
/-- If `F` is fully faithful, we have an equivalence of hom-sets `X ⟶ Y` and `F X ⟶ F Y`. -/
@[simps]
def equiv_of_fully_faithful {X Y} : (X ⟶ Y) ≃ (F.obj X ⟶ F.obj Y) :=
{ to_fun := λ f, F.map f,
inv_fun := λ f, F.preimage f,
left_inv := λ f, by simp,
right_inv := λ f, by simp }
/-- If `F` is fully faithful, we have an equivalence of iso-sets `X ≅ Y` and `F X ≅ F Y`. -/
@[simps]
def iso_equiv_of_fully_faithful {X Y} : (X ≅ Y) ≃ (F.obj X ≅ F.obj Y) :=
{ to_fun := λ f, F.map_iso f,
inv_fun := λ f, F.preimage_iso f,
left_inv := λ f, by simp,
right_inv := λ f, by { ext, simp, } }
end
section
variables {E : Type*} [category E] {F G : C ⥤ D} (H : D ⥤ E) [full H] [faithful H]
/-- We can construct a natural transformation between functors by constructing a
natural transformation between those functors composed with a fully faithful functor. -/
@[simps]
def nat_trans_of_comp_fully_faithful (α : F ⋙ H ⟶ G ⋙ H) : F ⟶ G :=
{ app := λ X, (equiv_of_fully_faithful H).symm (α.app X),
naturality' := λ X Y f, by { dsimp, apply H.map_injective, simpa using α.naturality f, } }
/-- We can construct a natural isomorphism between functors by constructing a natural isomorphism
between those functors composed with a fully faithful functor. -/
@[simps]
def nat_iso_of_comp_fully_faithful (i : F ⋙ H ≅ G ⋙ H) : F ≅ G :=
nat_iso.of_components
(λ X, (iso_equiv_of_fully_faithful H).symm (i.app X))
(λ X Y f, by { dsimp, apply H.map_injective, simpa using i.hom.naturality f, })
lemma nat_iso_of_comp_fully_faithful_hom (i : F ⋙ H ≅ G ⋙ H) :
(nat_iso_of_comp_fully_faithful H i).hom = nat_trans_of_comp_fully_faithful H i.hom :=
by { ext, simp [nat_iso_of_comp_fully_faithful], }
lemma nat_iso_of_comp_fully_faithful_inv (i : F ⋙ H ≅ G ⋙ H) :
(nat_iso_of_comp_fully_faithful H i).inv = nat_trans_of_comp_fully_faithful H i.inv :=
by { ext, simp [←preimage_comp], dsimp, simp, }
/-- Horizontal composition with a fully faithful functor induces a bijection on
natural transformations. -/
@[simps]
def nat_trans.equiv_of_comp_fully_faithful : (F ⟶ G) ≃ (F ⋙ H ⟶ G ⋙ H) :=
{ to_fun := λ α, α ◫ 𝟙 H,
inv_fun := nat_trans_of_comp_fully_faithful H,
left_inv := by tidy,
right_inv := by tidy, }
/-- Horizontal composition with a fully faithful functor induces a bijection on
natural isomorphisms. -/
@[simps]
def nat_iso.equiv_of_comp_fully_faithful : (F ≅ G) ≃ (F ⋙ H ≅ G ⋙ H) :=
{ to_fun := λ e, nat_iso.hcomp e (iso.refl H),
inv_fun := nat_iso_of_comp_fully_faithful H,
left_inv := by tidy,
right_inv := by tidy, }
end
end category_theory
namespace category_theory
variables {C : Type u₁} [category.{v₁} C]
instance full.id : full (𝟭 C) :=
{ preimage := λ _ _ f, f }
instance faithful.id : faithful (𝟭 C) := by obviously
variables {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E]
variables (F F' : C ⥤ D) (G : D ⥤ E)
instance faithful.comp [faithful F] [faithful G] : faithful (F ⋙ G) :=
{ map_injective' := λ _ _ _ _ p, F.map_injective (G.map_injective p) }
lemma faithful.of_comp [faithful $ F ⋙ G] : faithful F :=
{ map_injective' := λ X Y, (F ⋙ G).map_injective.of_comp }
section
variables {F F'}
/-- If `F` is full, and naturally isomorphic to some `F'`, then `F'` is also full. -/
def full.of_iso [full F] (α : F ≅ F') : full F' :=
{ preimage := λ X Y f, F.preimage ((α.app X).hom ≫ f ≫ (α.app Y).inv),
witness' := λ X Y f, by simp [←nat_iso.naturality_1 α], }
lemma faithful.of_iso [faithful F] (α : F ≅ F') : faithful F' :=
{ map_injective' := λ X Y f f' h, F.map_injective
(by rw [←nat_iso.naturality_1 α.symm, h, nat_iso.naturality_1 α.symm]) }
end
variables {F G}
lemma faithful.of_comp_iso {H : C ⥤ E} [ℋ : faithful H] (h : F ⋙ G ≅ H) : faithful F :=
@faithful.of_comp _ _ _ _ _ _ F G (faithful.of_iso h.symm)
alias faithful.of_comp_iso ← _root_.category_theory.iso.faithful_of_comp
-- We could prove this from `faithful.of_comp_iso` using `eq_to_iso`,
-- but that would introduce a cyclic import.
lemma faithful.of_comp_eq {H : C ⥤ E} [ℋ : faithful H] (h : F ⋙ G = H) : faithful F :=
@faithful.of_comp _ _ _ _ _ _ F G (h.symm ▸ ℋ)
alias faithful.of_comp_eq ← _root_.eq.faithful_of_comp
variables (F G)
/-- “Divide” a functor by a faithful functor. -/
protected def faithful.div (F : C ⥤ E) (G : D ⥤ E) [faithful G]
(obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X)
(map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y))
(h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) :
C ⥤ D :=
{ obj := obj,
map := @map,
map_id' :=
begin
assume X,
apply G.map_injective,
apply eq_of_heq,
transitivity F.map (𝟙 X), from h_map,
rw [F.map_id, G.map_id, h_obj X]
end,
map_comp' :=
begin
assume X Y Z f g,
apply G.map_injective,
apply eq_of_heq,
transitivity F.map (f ≫ g), from h_map,
rw [F.map_comp, G.map_comp],
congr' 1;
try { exact (h_obj _).symm };
exact h_map.symm
end }
-- This follows immediately from `functor.hext` (`functor.hext h_obj @h_map`),
-- but importing `category_theory.eq_to_hom` causes an import loop:
-- category_theory.eq_to_hom → category_theory.opposites →
-- category_theory.equivalence → category_theory.fully_faithful
lemma faithful.div_comp (F : C ⥤ E) [faithful F] (G : D ⥤ E) [faithful G]
(obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X)
(map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y))
(h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) :
(faithful.div F G obj @h_obj @map @h_map) ⋙ G = F :=
begin
casesI F with F_obj _ _ _, casesI G with G_obj _ _ _,
unfold faithful.div functor.comp,
unfold_projs at h_obj,
have: F_obj = G_obj ∘ obj := (funext h_obj).symm,
substI this,
congr,
funext,
exact eq_of_heq h_map
end
lemma faithful.div_faithful (F : C ⥤ E) [faithful F] (G : D ⥤ E) [faithful G]
(obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X)
(map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y))
(h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) :
faithful (faithful.div F G obj @h_obj @map @h_map) :=
(faithful.div_comp F G _ h_obj _ @h_map).faithful_of_comp
instance full.comp [full F] [full G] : full (F ⋙ G) :=
{ preimage := λ _ _ f, F.preimage (G.preimage f) }
/-- If `F ⋙ G` is full and `G` is faithful, then `F` is full. -/
def full.of_comp_faithful [full $ F ⋙ G] [faithful G] : full F :=
{ preimage := λ X Y f, (F ⋙ G).preimage (G.map f),
witness' := λ X Y f, G.map_injective ((F ⋙ G).image_preimage _) }
/-- If `F ⋙ G` is full and `G` is faithful, then `F` is full. -/
def full.of_comp_faithful_iso {F : C ⥤ D} {G : D ⥤ E} {H : C ⥤ E} [full H] [faithful G]
(h : F ⋙ G ≅ H) : full F :=
@full.of_comp_faithful _ _ _ _ _ _ F G (full.of_iso h.symm) _
/--
Given a natural isomorphism between `F ⋙ H` and `G ⋙ H` for a fully faithful functor `H`, we
can 'cancel' it to give a natural iso between `F` and `G`.
-/
def fully_faithful_cancel_right {F G : C ⥤ D} (H : D ⥤ E)
[full H] [faithful H] (comp_iso: F ⋙ H ≅ G ⋙ H) : F ≅ G :=
nat_iso.of_components
(λ X, H.preimage_iso (comp_iso.app X))
(λ X Y f, H.map_injective (by simpa using comp_iso.hom.naturality f))
@[simp]
lemma fully_faithful_cancel_right_hom_app {F G : C ⥤ D} {H : D ⥤ E}
[full H] [faithful H] (comp_iso: F ⋙ H ≅ G ⋙ H) (X : C) :
(fully_faithful_cancel_right H comp_iso).hom.app X = H.preimage (comp_iso.hom.app X) :=
rfl
@[simp]
lemma fully_faithful_cancel_right_inv_app {F G : C ⥤ D} {H : D ⥤ E}
[full H] [faithful H] (comp_iso: F ⋙ H ≅ G ⋙ H) (X : C) :
(fully_faithful_cancel_right H comp_iso).inv.app X = H.preimage (comp_iso.inv.app X) :=
rfl
end category_theory
|
2b05cd193267dd489a463a16051763bbae11f885 | e0b0b1648286e442507eb62344760d5cd8d13f2d | /stage0/src/Lean/Parser/Command.lean | d0c3749aeebea66b08831cd6744cb23d646a49a0 | [
"Apache-2.0"
] | permissive | MULXCODE/lean4 | 743ed389e05e26e09c6a11d24607ad5a697db39b | 4675817a9e89824eca37192364cd47a4027c6437 | refs/heads/master | 1,682,231,879,857 | 1,620,423,501,000 | 1,620,423,501,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,462 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Parser.Term
import Lean.Parser.Do
namespace Lean
namespace Parser
/--
Syntax quotation for terms and (lists of) commands. We prefer terms, so ambiguous quotations like
`($x $y) will be parsed as an application, not two commands. Use `($x:command $y:command) instead.
Multiple command will be put in a `null node, but a single command will not (so that you can directly
match against a quotation in a command kind's elaborator). -/
-- TODO: use two separate quotation parsers with parser priorities instead
@[builtinTermParser] def Term.quot := leading_parser "`(" >> incQuotDepth (termParser <|> many1Unbox commandParser) >> ")"
@[builtinTermParser] def Term.precheckedQuot := leading_parser "`" >> Term.quot
namespace Command
def namedPrio := leading_parser (atomic ("(" >> nonReservedSymbol "priority") >> " := " >> priorityParser >> ")")
def optNamedPrio := optional namedPrio
def «private» := leading_parser "private "
def «protected» := leading_parser "protected "
def visibility := «private» <|> «protected»
def «noncomputable» := leading_parser "noncomputable "
def «unsafe» := leading_parser "unsafe "
def «partial» := leading_parser "partial "
def declModifiers (inline : Bool) := leading_parser optional docComment >> optional (Term.«attributes» >> if inline then skip else ppDedent ppLine) >> optional visibility >> optional «noncomputable» >> optional «unsafe» >> optional «partial»
def declId := leading_parser ident >> optional (".{" >> sepBy1 ident ", " >> "}")
def declSig := leading_parser many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.typeSpec
def optDeclSig := leading_parser many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.optType
def declValSimple := leading_parser " :=\n" >> termParser >> optional Term.whereDecls
def declValEqns := leading_parser Term.matchAltsWhereDecls
def declVal := declValSimple <|> declValEqns <|> Term.whereDecls
def «abbrev» := leading_parser "abbrev " >> declId >> optDeclSig >> declVal
def «def» := leading_parser "def " >> declId >> optDeclSig >> declVal
def «theorem» := leading_parser "theorem " >> declId >> declSig >> declVal
def «constant» := leading_parser "constant " >> declId >> declSig >> optional declValSimple
def «instance» := leading_parser Term.attrKind >> "instance " >> optNamedPrio >> optional declId >> declSig >> declVal
def «axiom» := leading_parser "axiom " >> declId >> declSig
def «example» := leading_parser "example " >> declSig >> declVal
def inferMod := leading_parser atomic (symbol "{" >> "}")
def ctor := leading_parser "\n| " >> declModifiers true >> ident >> optional inferMod >> optDeclSig
def optDeriving := leading_parser optional (atomic ("deriving " >> notSymbol "instance") >> sepBy1 ident ", ")
def «inductive» := leading_parser "inductive " >> declId >> optDeclSig >> optional (symbol ":=" <|> "where") >> many ctor >> optDeriving
def classInductive := leading_parser atomic (group (symbol "class " >> "inductive ")) >> declId >> optDeclSig >> optional (symbol ":=" <|> "where") >> many ctor >> optDeriving
def structExplicitBinder := leading_parser atomic (declModifiers true >> "(") >> many1 ident >> optional inferMod >> optDeclSig >> optional Term.binderDefault >> ")"
def structImplicitBinder := leading_parser atomic (declModifiers true >> "{") >> many1 ident >> optional inferMod >> declSig >> "}"
def structInstBinder := leading_parser atomic (declModifiers true >> "[") >> many1 ident >> optional inferMod >> declSig >> "]"
def structSimpleBinder := leading_parser atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional Term.binderDefault
def structFields := leading_parser manyIndent (ppLine >> checkColGe >>(structExplicitBinder <|> structImplicitBinder <|> structInstBinder <|> structSimpleBinder))
def structCtor := leading_parser atomic (declModifiers true >> ident >> optional inferMod >> " :: ")
def structureTk := leading_parser "structure "
def classTk := leading_parser "class "
def «extends» := leading_parser " extends " >> sepBy1 termParser ", "
def «structure» := leading_parser
(structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType
>> optional ((symbol " := " <|> " where ") >> optional structCtor >> structFields)
>> optDeriving
@[builtinCommandParser] def declaration := leading_parser
declModifiers false >> («abbrev» <|> «def» <|> «theorem» <|> «constant» <|> «instance» <|> «axiom» <|> «example» <|> «inductive» <|> classInductive <|> «structure»)
@[builtinCommandParser] def «deriving» := leading_parser "deriving " >> "instance " >> sepBy1 ident ", " >> " for " >> sepBy1 ident ", "
@[builtinCommandParser] def «section» := leading_parser "section " >> optional ident
@[builtinCommandParser] def «namespace» := leading_parser "namespace " >> ident
@[builtinCommandParser] def «end» := leading_parser "end " >> optional ident
@[builtinCommandParser] def «variable» := leading_parser "variable" >> many1 Term.bracketedBinder
@[builtinCommandParser] def «universe» := leading_parser "universe " >> ident
@[builtinCommandParser] def «universes» := leading_parser "universes " >> many1 ident
@[builtinCommandParser] def check := leading_parser "#check " >> termParser
@[builtinCommandParser] def check_failure := leading_parser "#check_failure " >> termParser -- Like `#check`, but succeeds only if term does not type check
@[builtinCommandParser] def reduce := leading_parser "#reduce " >> termParser
@[builtinCommandParser] def eval := leading_parser "#eval " >> termParser
@[builtinCommandParser] def synth := leading_parser "#synth " >> termParser
@[builtinCommandParser] def exit := leading_parser "#exit"
@[builtinCommandParser] def print := leading_parser "#print " >> (ident <|> strLit)
@[builtinCommandParser] def printAxioms := leading_parser "#print " >> nonReservedSymbol "axioms " >> ident
@[builtinCommandParser] def «resolve_name» := leading_parser "#resolve_name " >> ident
@[builtinCommandParser] def «init_quot» := leading_parser "init_quot"
def optionValue := nonReservedSymbol "true" <|> nonReservedSymbol "false" <|> strLit <|> numLit
@[builtinCommandParser] def «set_option» := leading_parser "set_option " >> ident >> ppSpace >> optionValue
def eraseAttr := leading_parser "-" >> ident
@[builtinCommandParser] def «attribute» := leading_parser "attribute " >> "[" >> sepBy1 (eraseAttr <|> Term.attrInstance) ", " >> "] " >> many1 ident
@[builtinCommandParser] def «export» := leading_parser "export " >> ident >> "(" >> many1 ident >> ")"
def openHiding := leading_parser atomic (ident >> "hiding") >> many1 ident
def openRenamingItem := leading_parser ident >> unicodeSymbol "→" "->" >> ident
def openRenaming := leading_parser atomic (ident >> "renaming") >> sepBy1 openRenamingItem ", "
def openOnly := leading_parser atomic (ident >> "(") >> many1 ident >> ")"
def openSimple := leading_parser many1 ident
def openDecl := openHiding <|> openRenaming <|> openOnly <|> openSimple
@[builtinCommandParser] def «open» := leading_parser "open " >> openDecl
@[builtinCommandParser] def «mutual» := leading_parser "mutual " >> many1 (ppLine >> notSymbol "end" >> commandParser) >> ppDedent (ppLine >> "end")
@[builtinCommandParser] def «initialize» := leading_parser "initialize " >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq
@[builtinCommandParser] def «builtin_initialize» := leading_parser "builtin_initialize " >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq
@[builtinCommandParser] def «in» := trailing_parser " in " >> commandParser
@[runBuiltinParserAttributeHooks] abbrev declModifiersF := declModifiers false
@[runBuiltinParserAttributeHooks] abbrev declModifiersT := declModifiers true
builtin_initialize
register_parser_alias "declModifiers" declModifiersF
register_parser_alias "nestedDeclModifiers" declModifiersT
register_parser_alias "declId" declId
register_parser_alias "declSig" declSig
register_parser_alias "declVal" declVal
register_parser_alias "optDeclSig" optDeclSig
register_parser_alias "openDecl" openDecl
end Command
namespace Term
@[builtinTermParser] def «open» := leading_parser:leadPrec "open " >> Command.openDecl >> " in " >> termParser
@[builtinTermParser] def «set_option» := leading_parser:leadPrec "set_option " >> ident >> ppSpace >> Command.optionValue >> " in " >> termParser
end Term
namespace Tactic
@[builtinTacticParser] def «open» := leading_parser:leadPrec "open " >> Command.openDecl >> " in " >> tacticSeq
@[builtinTacticParser] def «set_option» := leading_parser:leadPrec "set_option " >> ident >> ppSpace >> Command.optionValue >> " in " >> tacticSeq
end Tactic
end Parser
end Lean
|
2ec298d99f55244b707290295c15e28e85f53278 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/congr_lemma1.lean | 993cfdf8cbe3125c5e189d5d742f4f3ec3b0efd7 | [
"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 | 223 | lean | open tactic
set_option pp.binder_types true
example : true :=
by do
ite ← mk_const `ite,
l ← mk_congr_simp ite,
trace (congr_lemma.type l),
l ← mk_hcongr ite,
trace (congr_lemma.type l),
constructor
|
8cad85c928f02e6add2db44593d31a3e8a946a49 | f3849be5d845a1cb97680f0bbbe03b85518312f0 | /tests/lean/run/1590.lean | 6fbb0a55ae269a202a8cee92fb2d2966b69be052 | [
"Apache-2.0"
] | permissive | bjoeris/lean | 0ed95125d762b17bfcb54dad1f9721f953f92eeb | 4e496b78d5e73545fa4f9a807155113d8e6b0561 | refs/heads/master | 1,611,251,218,281 | 1,495,337,658,000 | 1,495,337,658,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 65 | lean | #check `(true.intro)
#check λ (h : true) [reflected h], `(id h)
|
0c29a946adafeb42fe414e0421446829e7a41b2b | caa1512363b76923d0e9cdb716122a5c26c3c6bc | /src/eigenvectors/linear_independent_multiset.lean | a74c5e0a5758f9541dd3bf2b32e8fd65af912e1f | [] | no_license | apurvanakade/cvx | deb20e425ce478159a98e1ffc0d37f9c88a89280 | b47784831339df5a3e45f5cddd84edc545f95808 | refs/heads/master | 1,687,403,288,536 | 1,555,930,740,000 | 1,555,930,740,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,844 | lean |
import linear_algebra.basis
import data.finset
import algebra.module
local attribute [instance] classical.prop_decidable
variables (α : Type) {ι β : Type} [inhabited ι] [division_ring α] [decidable_eq β] [add_comm_group β] [module α β]
open function set finsupp
def linear_independent_family (s : ι → β) : Prop :=
linear_independent α (range s) ∧ injective s
#check image_inv_fun
noncomputable def foo (s : ι → β) (hs : injective s) (l : β →₀ α) (hl : l.support.to_set ⊆ range s):=
finsupp.mk (l.support.image (inv_fun s)) (λ i, l (s i)) (begin
intros i,
split,
{ intros hi,
rw finset.mem_image at hi,
apply exists.elim hi,
intros x hx,
apply exists.elim hx,
intros hx hx',
rw hx'.symm,
rw @inv_fun_eq _ _ _ s x,
let H := left_inverse_inv_fun hs,
unfold left_inverse at H, }
end)
lemma linear_dependent_sum (s : ι → β) (h : ¬ linear_independent_family α s) :
∃ c : ι →₀ α, c.support.sum (λ i, c i • s i) = 0 :=
begin
by_cases h_cases : injective s,
{ have h_lin_indep : ¬ linear_independent α (range s),
{ unfold linear_independent_family at h, finish },
show ∃ c : ι →₀ α, c.support.sum (λ i, c i • s i) = 0,
{
rw [linear_independent_iff, not_forall] at h_lin_indep,
apply exists.elim h_lin_indep,
intros l hl,
let c : ι →₀ α :=
existsi c,
rw [not_imp,not_imp] at hl,
let H := @finset.sum_image _ _ _ (λ x, l x • x) _ _ c.support s _,
convert H.symm,
simp,
}
},
{ unfold injective at h_cases,
rw not_forall at h_cases,
apply exists.elim h_cases,
intros i h_not_inj,
rw not_forall at h_not_inj,
apply exists.elim h_not_inj,
intros j hij,
let c := single i (1 : α) - single j 1,
existsi c,
have h_disjoint : disjoint (single i (1 : α)).support (- single j (1 : α)).support,
{ rw [support_neg, support_single_ne_zero one_ne_zero,
support_single_ne_zero one_ne_zero],
simp [ne.symm (not_imp.1 hij).2] },
have h_disjoint' : finset.singleton i ∩ finset.singleton j = ∅,
{ convert (finset.disjoint_iff_inter_eq_empty.1 h_disjoint),
{ apply (support_single_ne_zero one_ne_zero).symm },
{ rw [support_neg, support_single_ne_zero one_ne_zero],
refl } },
have h : c.support = finset.singleton i ∪ finset.singleton j,
{ dsimp only [c],
rw [sub_eq_add_neg, support_add_eq h_disjoint,
support_neg, support_single_ne_zero one_ne_zero,
support_single_ne_zero one_ne_zero],
refl, },
show finset.sum c.support (λ i, c i • s i) = 0,
{ dsimp only [c],
rw [h, finset.sum_union h_disjoint'],
simp [finset.sum_singleton, sub_apply, single_apply, (not_imp.1 hij).2,
ne.symm (not_imp.1 hij).2, (not_imp.1 hij).1] } }
end |
70f362f21aacad711a2c15f81549a91c7439bd9c | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/lie/tensor_product.lean | 1512f182e6fbccf0351f5dc65fa1a6b0c75c1d2b | [
"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,983 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.abelian
/-!
# Tensor products of Lie modules
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Tensor products of Lie modules carry natural Lie module structures.
## Tags
lie module, tensor product, universal property
-/
universes u v w w₁ w₂ w₃
variables {R : Type u} [comm_ring R]
open lie_module
namespace tensor_product
open_locale tensor_product
namespace lie_module
variables {L : Type v} {M : Type w} {N : Type w₁} {P : Type w₂} {Q : Type w₃}
variables [lie_ring L] [lie_algebra R L]
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N]
variables [add_comm_group P] [module R P] [lie_ring_module L P] [lie_module R L P]
variables [add_comm_group Q] [module R Q] [lie_ring_module L Q] [lie_module R L Q]
local attribute [ext] tensor_product.ext
/-- It is useful to define the bracket via this auxiliary function so that we have a type-theoretic
expression of the fact that `L` acts by linear endomorphisms. It simplifies the proofs in
`lie_ring_module` below. -/
def has_bracket_aux (x : L) : module.End R (M ⊗[R] N) :=
(to_endomorphism R L M x).rtensor N + (to_endomorphism R L N x).ltensor M
/-- The tensor product of two Lie modules is a Lie ring module. -/
instance lie_ring_module : lie_ring_module L (M ⊗[R] N) :=
{ bracket := λ x, has_bracket_aux x,
add_lie := λ x y t, by
{ simp only [has_bracket_aux, linear_map.ltensor_add, linear_map.rtensor_add, lie_hom.map_add,
linear_map.add_apply], abel, },
lie_add := λ x, linear_map.map_add _,
leibniz_lie := λ x y t, by
{ suffices : (has_bracket_aux x).comp (has_bracket_aux y) =
has_bracket_aux ⁅x,y⁆ + (has_bracket_aux y).comp (has_bracket_aux x),
{ simp only [← linear_map.add_apply], rw [← linear_map.comp_apply, this], refl },
ext m n,
simp only [has_bracket_aux, lie_ring.of_associative_ring_bracket, linear_map.mul_apply,
mk_apply, linear_map.ltensor_sub, linear_map.compr₂_apply, function.comp_app,
linear_map.coe_comp, linear_map.rtensor_tmul, lie_hom.map_lie,
to_endomorphism_apply_apply, linear_map.add_apply, linear_map.map_add,
linear_map.rtensor_sub, linear_map.sub_apply, linear_map.ltensor_tmul],
abel, }, }
/-- The tensor product of two Lie modules is a Lie module. -/
instance lie_module : lie_module R L (M ⊗[R] N) :=
{ smul_lie := λ c x t, by
{ change has_bracket_aux (c • x) _ = c • has_bracket_aux _ _,
simp only [has_bracket_aux, smul_add, linear_map.rtensor_smul, linear_map.smul_apply,
linear_map.ltensor_smul, lie_hom.map_smul, linear_map.add_apply], },
lie_smul := λ c x, linear_map.map_smul _ c, }
@[simp] lemma lie_tmul_right (x : L) (m : M) (n : N) :
⁅x, m ⊗ₜ[R] n⁆ = ⁅x, m⁆ ⊗ₜ n + m ⊗ₜ ⁅x, n⁆ :=
show has_bracket_aux x (m ⊗ₜ[R] n) = _,
by simp only [has_bracket_aux, linear_map.rtensor_tmul, to_endomorphism_apply_apply,
linear_map.add_apply, linear_map.ltensor_tmul]
variables (R L M N P Q)
/-- The universal property for tensor product of modules of a Lie algebra: the `R`-linear
tensor-hom adjunction is equivariant with respect to the `L` action. -/
def lift : (M →ₗ[R] N →ₗ[R] P) ≃ₗ⁅R,L⁆ (M ⊗[R] N →ₗ[R] P) :=
{ map_lie' := λ x f, by
{ ext m n, simp only [mk_apply, linear_map.compr₂_apply, lie_tmul_right, linear_map.sub_apply,
lift.equiv_apply, linear_equiv.to_fun_eq_coe, lie_hom.lie_apply, linear_map.map_add],
abel, },
..tensor_product.lift.equiv R M N P }
@[simp] lemma lift_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) :
lift R L M N P f (m ⊗ₜ n) = f m n :=
rfl
/-- A weaker form of the universal property for tensor product of modules of a Lie algebra.
Note that maps `f` of type `M →ₗ⁅R,L⁆ N →ₗ[R] P` are exactly those `R`-bilinear maps satisfying
`⁅x, f m n⁆ = f ⁅x, m⁆ n + f m ⁅x, n⁆` for all `x, m, n` (see e.g, `lie_module_hom.map_lie₂`). -/
def lift_lie : (M →ₗ⁅R,L⁆ N →ₗ[R] P) ≃ₗ[R] (M ⊗[R] N →ₗ⁅R,L⁆ P) :=
(max_triv_linear_map_equiv_lie_module_hom.symm ≪≫ₗ
↑(max_triv_equiv (lift R L M N P))) ≪≫ₗ
max_triv_linear_map_equiv_lie_module_hom
@[simp] lemma coe_lift_lie_eq_lift_coe (f : M →ₗ⁅R,L⁆ N →ₗ[R] P) :
⇑(lift_lie R L M N P f) = lift R L M N P f :=
begin
suffices : (lift_lie R L M N P f : M ⊗[R] N →ₗ[R] P) = lift R L M N P f,
{ rw [← this, lie_module_hom.coe_to_linear_map], },
ext m n,
simp only [lift_lie, linear_equiv.trans_apply, lie_module_equiv.coe_to_linear_equiv,
coe_linear_map_max_triv_linear_map_equiv_lie_module_hom, coe_max_triv_equiv_apply,
coe_linear_map_max_triv_linear_map_equiv_lie_module_hom_symm],
end
lemma lift_lie_apply (f : M →ₗ⁅R,L⁆ N →ₗ[R] P) (m : M) (n : N) :
lift_lie R L M N P f (m ⊗ₜ n) = f m n :=
by simp only [coe_lift_lie_eq_lift_coe, lie_module_hom.coe_to_linear_map, lift_apply]
variables {R L M N P Q}
/-- A pair of Lie module morphisms `f : M → P` and `g : N → Q`, induce a Lie module morphism:
`M ⊗ N → P ⊗ Q`. -/
def map (f : M →ₗ⁅R,L⁆ P) (g : N →ₗ⁅R,L⁆ Q) : M ⊗[R] N →ₗ⁅R,L⁆ P ⊗[R] Q :=
{ map_lie' := λ x t, by
{ simp only [linear_map.to_fun_eq_coe],
apply t.induction_on,
{ simp only [linear_map.map_zero, lie_zero], },
{ intros m n, simp only [lie_module_hom.coe_to_linear_map, lie_tmul_right,
lie_module_hom.map_lie, map_tmul, linear_map.map_add], },
{ intros t₁ t₂ ht₁ ht₂, simp only [ht₁, ht₂, lie_add, linear_map.map_add], }, },
.. map (f : M →ₗ[R] P) (g : N →ₗ[R] Q), }
@[simp] lemma coe_linear_map_map (f : M →ₗ⁅R,L⁆ P) (g : N →ₗ⁅R,L⁆ Q) :
(map f g : M ⊗[R] N →ₗ[R] P ⊗[R] Q) = tensor_product.map (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :=
rfl
@[simp] lemma map_tmul (f : M →ₗ⁅R,L⁆ P) (g : N →ₗ⁅R,L⁆ Q) (m : M) (n : N) :
map f g (m ⊗ₜ n) = (f m) ⊗ₜ (g n) :=
map_tmul f g m n
/-- Given Lie submodules `M' ⊆ M` and `N' ⊆ N`, this is the natural map: `M' ⊗ N' → M ⊗ N`. -/
def map_incl (M' : lie_submodule R L M) (N' : lie_submodule R L N) :
M' ⊗[R] N' →ₗ⁅R,L⁆ M ⊗[R] N :=
map M'.incl N'.incl
@[simp] lemma map_incl_def (M' : lie_submodule R L M) (N' : lie_submodule R L N) :
map_incl M' N' = map M'.incl N'.incl :=
rfl
end lie_module
end tensor_product
namespace lie_module
open_locale tensor_product
variables (R) (L : Type v) (M : Type w)
variables [lie_ring L] [lie_algebra R L]
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
/-- The action of the Lie algebra on one of its modules, regarded as a morphism of Lie modules. -/
def to_module_hom : L ⊗[R] M →ₗ⁅R,L⁆ M :=
tensor_product.lie_module.lift_lie R L L M M
{ map_lie' := λ x m, by { ext n, simp [lie_ring.of_associative_ring_bracket], },
..(to_endomorphism R L M : L →ₗ[R] M →ₗ[R] M), }
@[simp] lemma to_module_hom_apply (x : L) (m : M) :
to_module_hom R L M (x ⊗ₜ m) = ⁅x, m⁆ :=
by simp only [to_module_hom, tensor_product.lie_module.lift_lie_apply, to_endomorphism_apply_apply,
lie_hom.coe_to_linear_map, lie_module_hom.coe_mk, linear_map.coe_mk, linear_map.to_fun_eq_coe]
end lie_module
namespace lie_submodule
open_locale tensor_product
open tensor_product.lie_module
open lie_module
variables {L : Type v} {M : Type w}
variables [lie_ring L] [lie_algebra R L]
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables (I : lie_ideal R L) (N : lie_submodule R L M)
/-- A useful alternative characterisation of Lie ideal operations on Lie submodules.
Given a Lie ideal `I ⊆ L` and a Lie submodule `N ⊆ M`, by tensoring the inclusion maps and then
applying the action of `L` on `M`, we obtain morphism of Lie modules `f : I ⊗ N → L ⊗ M → M`.
This lemma states that `⁅I, N⁆ = range f`. -/
lemma lie_ideal_oper_eq_tensor_map_range :
⁅I, N⁆ = ((to_module_hom R L M).comp (map_incl I N : ↥I ⊗ ↥N →ₗ⁅R,L⁆ L ⊗ M)).range :=
begin
rw [← coe_to_submodule_eq_iff, lie_ideal_oper_eq_linear_span, lie_module_hom.coe_submodule_range,
lie_module_hom.coe_linear_map_comp, linear_map.range_comp, map_incl_def, coe_linear_map_map,
tensor_product.map_range_eq_span_tmul, submodule.map_span],
congr, ext m, split,
{ rintros ⟨⟨x, hx⟩, ⟨n, hn⟩, rfl⟩, use x ⊗ₜ n, split,
{ use [⟨x, hx⟩, ⟨n, hn⟩], simp, },
{ simp, }, },
{ rintros ⟨t, ⟨⟨x, hx⟩, ⟨n, hn⟩, rfl⟩, h⟩, rw ← h, use [⟨x, hx⟩, ⟨n, hn⟩], simp, },
end
end lie_submodule
|
c7210b43dc397c25bb5d4e8b3c3bf2f6eec3dfc0 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/data/dfinsupp.lean | 64b3c32d502824880a3cdafe5002ad3001c46119 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 33,031 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Kenny Lau
-/
import algebra.module.pi
import algebra.big_operators.basic
import data.set.finite
/-!
# Dependent functions with finite support
For a non-dependent version see `data/finsupp.lean`.
-/
universes u u₁ u₂ v v₁ v₂ v₃ w x y l
open_locale big_operators
variables (ι : Type u) (β : ι → Type v)
namespace dfinsupp
variable [Π i, has_zero (β i)]
structure pre : Type (max u v) :=
(to_fun : Π i, β i)
(pre_support : multiset ι)
(zero : ∀ i, i ∈ pre_support ∨ to_fun i = 0)
instance inhabited_pre : inhabited (pre ι β) :=
⟨⟨λ i, 0, ∅, λ i, or.inr rfl⟩⟩
instance : setoid (pre ι β) :=
{ r := λ x y, ∀ i, x.to_fun i = y.to_fun i,
iseqv := ⟨λ f i, rfl, λ f g H i, (H i).symm,
λ f g h H1 H2 i, (H1 i).trans (H2 i)⟩ }
end dfinsupp
variable {ι}
/-- A dependent function `Π i, β i` with finite support. -/
@[reducible]
def dfinsupp [Π i, has_zero (β i)] : Type* :=
quotient (dfinsupp.setoid ι β)
variable {β}
notation `Π₀` binders `, ` r:(scoped f, dfinsupp f) := r
infix ` →ₚ `:25 := dfinsupp
namespace dfinsupp
section basic
variables [Π i, has_zero (β i)]
variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂}
variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)]
instance : has_coe_to_fun (Π₀ i, β i) :=
⟨λ _, Π i, β i, λ f, quotient.lift_on f pre.to_fun $ λ _ _, funext⟩
instance : has_zero (Π₀ i, β i) := ⟨⟦⟨λ i, 0, ∅, λ i, or.inr rfl⟩⟧⟩
instance : inhabited (Π₀ i, β i) := ⟨0⟩
@[simp] lemma zero_apply {i : ι} : (0 : Π₀ i, β i) i = 0 := rfl
@[ext]
lemma ext {f g : Π₀ i, β i} (H : ∀ i, f i = g i) : f = g :=
quotient.induction_on₂ f g (λ _ _ H, quotient.sound H) H
/-- The composition of `f : β₁ → β₂` and `g : Π₀ i, β₁ i` is
`map_range f hf g : Π₀ i, β₂ i`, well defined when `f 0 = 0`. -/
def map_range (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (g : Π₀ i, β₁ i) : Π₀ i, β₂ i :=
quotient.lift_on g (λ x, ⟦(⟨λ i, f i (x.1 i), x.2,
λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, hf]⟩ : pre ι β₂)⟧) $ λ x y H,
quotient.sound $ λ i, by simp only [H i]
@[simp] lemma map_range_apply
{f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {i : ι} :
map_range f hf g i = f i (g i) :=
quotient.induction_on g $ λ x, rfl
/-- Let `f i` be a binary operation `β₁ i → β₂ i → β i` such that `f i 0 0 = 0`.
Then `zip_with f hf` is a binary operation `Π₀ i, β₁ i → Π₀ i, β₂ i → Π₀ i, β i`. -/
def zip_with (f : Π i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0)
(g₁ : Π₀ i, β₁ i) (g₂ : Π₀ i, β₂ i) : (Π₀ i, β i) :=
begin
refine quotient.lift_on₂ g₁ g₂ (λ x y, ⟦(⟨λ i, f i (x.1 i) (y.1 i), x.2 + y.2,
λ i, _⟩ : pre ι β)⟧) _,
{ cases x.3 i with h1 h1,
{ left, rw multiset.mem_add, left, exact h1 },
cases y.3 i with h2 h2,
{ left, rw multiset.mem_add, right, exact h2 },
right, rw [h1, h2, hf] },
exact λ x₁ x₂ y₁ y₂ H1 H2, quotient.sound $ λ i, by simp only [H1 i, H2 i]
end
@[simp] lemma zip_with_apply
{f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} {i : ι} :
zip_with f hf g₁ g₂ i = f i (g₁ i) (g₂ i) :=
quotient.induction_on₂ g₁ g₂ $ λ _ _, rfl
end basic
section algebra
instance [Π i, add_monoid (β i)] : has_add (Π₀ i, β i) :=
⟨zip_with (λ _, (+)) (λ _, add_zero 0)⟩
@[simp] lemma add_apply [Π i, add_monoid (β i)] {g₁ g₂ : Π₀ i, β i} {i : ι} :
(g₁ + g₂) i = g₁ i + g₂ i :=
zip_with_apply
instance [Π i, add_monoid (β i)] : add_monoid (Π₀ i, β i) :=
{ add_monoid .
zero := 0,
add := (+),
add_assoc := λ f g h, ext $ λ i, by simp only [add_apply, add_assoc],
zero_add := λ f, ext $ λ i, by simp only [add_apply, zero_apply, zero_add],
add_zero := λ f, ext $ λ i, by simp only [add_apply, zero_apply, add_zero] }
instance [Π i, add_monoid (β i)] {i : ι} : is_add_monoid_hom (λ g : Π₀ i : ι, β i, g i) :=
{ map_add := λ _ _, add_apply, map_zero := zero_apply }
instance [Π i, add_group (β i)] : has_neg (Π₀ i, β i) :=
⟨λ f, f.map_range (λ _, has_neg.neg) (λ _, neg_zero)⟩
instance [Π i, add_comm_monoid (β i)] : add_comm_monoid (Π₀ i, β i) :=
{ add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm],
.. dfinsupp.add_monoid }
@[simp] lemma neg_apply [Π i, add_group (β i)] {g : Π₀ i, β i} {i : ι} : (- g) i = - g i :=
map_range_apply
instance [Π i, add_group (β i)] : add_group (Π₀ i, β i) :=
{ add_left_neg := λ f, ext $ λ i, by simp only [add_apply, neg_apply, zero_apply, add_left_neg],
.. dfinsupp.add_monoid,
.. (infer_instance : has_neg (Π₀ i, β i)) }
@[simp] lemma sub_apply [Π i, add_group (β i)] {g₁ g₂ : Π₀ i, β i} {i : ι} :
(g₁ - g₂) i = g₁ i - g₂ i :=
by rw [sub_eq_add_neg]; simp [sub_eq_add_neg]
instance [Π i, add_comm_group (β i)] : add_comm_group (Π₀ i, β i) :=
{ add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm],
..dfinsupp.add_group }
/-- Dependent functions with finite support inherit a semiring action from an action on each
coordinate. -/
def to_has_scalar {γ : Type w} [semiring γ] [Π i, add_comm_group (β i)] [Π i, semimodule γ (β i)] :
has_scalar γ (Π₀ i, β i) :=
⟨λc v, v.map_range (λ _, (•) c) (λ _, smul_zero _)⟩
local attribute [instance] to_has_scalar
@[simp] lemma smul_apply {γ : Type w} [semiring γ] [Π i, add_comm_group (β i)]
[Π i, semimodule γ (β i)] {i : ι} {b : γ} {v : Π₀ i, β i} :
(b • v) i = b • (v i) :=
map_range_apply
/-- Dependent functions with finite support inherit a semimodule structure from such a structure on
each coordinate. -/
def to_semimodule {γ : Type w} [semiring γ] [Π i, add_comm_group (β i)] [Π i, semimodule γ (β i)] :
semimodule γ (Π₀ i, β i) :=
semimodule.of_core {
smul_add := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, smul_add],
add_smul := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, add_smul],
one_smul := λ x, ext $ λ i, by simp only [smul_apply, one_smul],
mul_smul := λ r s x, ext $ λ i, by simp only [smul_apply, smul_smul],
.. (infer_instance : has_scalar γ (Π₀ i, β i)) }
end algebra
section filter_and_subtype_domain
/-- `filter p f` is the function which is `f i` if `p i` is true and 0 otherwise. -/
def filter [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i, β i :=
quotient.lift_on f (λ x, ⟦(⟨λ i, if p i then x.1 i else 0, x.2,
λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H,
quotient.sound $ λ i, by simp only [H i]
@[simp] lemma filter_apply [Π i, has_zero (β i)]
{p : ι → Prop} [decidable_pred p] {i : ι} {f : Π₀ i, β i} :
f.filter p i = if p i then f i else 0 :=
quotient.induction_on f $ λ x, rfl
lemma filter_apply_pos [Π i, has_zero (β i)]
{p : ι → Prop} [decidable_pred p] {f : Π₀ i, β i} {i : ι} (h : p i) :
f.filter p i = f i :=
by simp only [filter_apply, if_pos h]
lemma filter_apply_neg [Π i, has_zero (β i)]
{p : ι → Prop} [decidable_pred p] {f : Π₀ i, β i} {i : ι} (h : ¬ p i) :
f.filter p i = 0 :=
by simp only [filter_apply, if_neg h]
lemma filter_pos_add_filter_neg [Π i, add_monoid (β i)] {f : Π₀ i, β i}
{p : ι → Prop} [decidable_pred p] :
f.filter p + f.filter (λi, ¬ p i) = f :=
ext $ λ i, by simp only [add_apply, filter_apply]; split_ifs; simp only [add_zero, zero_add]
/-- `subtype_domain p f` is the restriction of the finitely supported function
`f` to the subtype `p`. -/
def subtype_domain [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p]
(f : Π₀ i, β i) : Π₀ i : subtype p, β i :=
begin
fapply quotient.lift_on f,
{ intro x,
refine ⟦⟨λ i, x.1 (i : ι),
(x.2.filter p).attach.map $ λ j, ⟨j, (multiset.mem_filter.1 j.2).2⟩, _⟩⟧,
refine λ i, or.cases_on (x.3 i) (λ H, _) or.inr,
left, rw multiset.mem_map, refine ⟨⟨i, multiset.mem_filter.2 ⟨H, i.2⟩⟩, _, subtype.eta _ _⟩,
apply multiset.mem_attach },
intros x y H,
exact quotient.sound (λ i, H i)
end
@[simp] lemma subtype_domain_zero [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] :
subtype_domain p (0 : Π₀ i, β i) = 0 :=
rfl
@[simp] lemma subtype_domain_apply [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p]
{i : subtype p} {v : Π₀ i, β i} :
(subtype_domain p v) i = v (i.val) :=
quotient.induction_on v $ λ x, rfl
@[simp] lemma subtype_domain_add [Π i, add_monoid (β i)] {p : ι → Prop} [decidable_pred p]
{v v' : Π₀ i, β i} :
(v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p :=
ext $ λ i, by simp only [add_apply, subtype_domain_apply]
instance subtype_domain.is_add_monoid_hom [Π i, add_monoid (β i)]
{p : ι → Prop} [decidable_pred p] :
is_add_monoid_hom (subtype_domain p : (Π₀ i : ι, β i) → Π₀ i : subtype p, β i) :=
{ map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero }
@[simp]
lemma subtype_domain_neg [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v : Π₀ i, β i} :
(- v).subtype_domain p = - v.subtype_domain p :=
ext $ λ i, by simp only [neg_apply, subtype_domain_apply]
@[simp] lemma subtype_domain_sub [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p]
{v v' : Π₀ i, β i} :
(v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p :=
ext $ λ i, by simp only [sub_apply, subtype_domain_apply]
end filter_and_subtype_domain
variable [dec : decidable_eq ι]
include dec
section basic
variable [Π i, has_zero (β i)]
omit dec
lemma finite_supp (f : Π₀ i, β i) : set.finite {i | f i ≠ 0} :=
begin
classical,
exact quotient.induction_on f (λ x, x.2.to_finset.finite_to_set.subset (λ i H,
multiset.mem_to_finset.2 ((x.3 i).resolve_right H)))
end
include dec
/-- Create an element of `Π₀ i, β i` from a finset `s` and a function `x`
defined on this `finset`. -/
def mk (s : finset ι) (x : Π i : (↑s : set ι), β (i : ι)) : Π₀ i, β i :=
⟦⟨λ i, if H : i ∈ s then x ⟨i, H⟩ else 0, s.1,
λ i, if H : i ∈ s then or.inl H else or.inr $ dif_neg H⟩⟧
@[simp] lemma mk_apply {s : finset ι} {x : Π i : (↑s : set ι), β i} {i : ι} :
(mk s x : Π i, β i) i = if H : i ∈ s then x ⟨i, H⟩ else 0 :=
rfl
theorem mk_injective (s : finset ι) : function.injective (@mk ι β _ _ s) :=
begin
intros x y H,
ext i,
have h1 : (mk s x : Π i, β i) i = (mk s y : Π i, β i) i, {rw H},
cases i with i hi,
change i ∈ s at hi,
dsimp only [mk_apply, subtype.coe_mk] at h1,
simpa only [dif_pos hi] using h1
end
/-- The function `single i b : Π₀ i, β i` sends `i` to `b`
and all other points to `0`. -/
def single (i : ι) (b : β i) : Π₀ i, β i :=
mk {i} $ λ j, eq.rec_on (finset.mem_singleton.1 j.prop).symm b
@[simp] lemma single_apply {i i' b} :
(single i b : Π₀ i, β i) i' = (if h : i = i' then eq.rec_on h b else 0) :=
begin
dsimp only [single],
by_cases h : i = i',
{ have h1 : i' ∈ ({i} : finset ι) := finset.mem_singleton.2 h.symm,
simp only [mk_apply, dif_pos h, dif_pos h1], refl },
{ have h1 : i' ∉ ({i} : finset ι) := finset.not_mem_singleton.2 (ne.symm h),
simp only [mk_apply, dif_neg h, dif_neg h1] }
end
@[simp] lemma single_zero {i} : (single i 0 : Π₀ i, β i) = 0 :=
quotient.sound $ λ j, if H : j ∈ ({i} : finset _)
then by dsimp only; rw [dif_pos H]; cases finset.mem_singleton.1 H; refl
else dif_neg H
@[simp] lemma single_eq_same {i b} : (single i b : Π₀ i, β i) i = b :=
by simp only [single_apply, dif_pos rfl]
lemma single_eq_of_ne {i i' b} (h : i ≠ i') : (single i b : Π₀ i, β i) i' = 0 :=
by simp only [single_apply, dif_neg h]
/-- Redefine `f i` to be `0`. -/
def erase (i : ι) (f : Π₀ i, β i) : Π₀ i, β i :=
quotient.lift_on f (λ x, ⟦(⟨λ j, if j = i then 0 else x.1 j, x.2,
λ j, or.cases_on (x.3 j) or.inl $ λ H, or.inr $ by simp only [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H,
quotient.sound $ λ j, if h : j = i then by simp only [if_pos h]
else by simp only [if_neg h, H j]
@[simp] lemma erase_apply {i j : ι} {f : Π₀ i, β i} :
(f.erase i) j = if j = i then 0 else f j :=
quotient.induction_on f $ λ x, rfl
@[simp] lemma erase_same {i : ι} {f : Π₀ i, β i} : (f.erase i) i = 0 :=
by simp
lemma erase_ne {i i' : ι} {f : Π₀ i, β i} (h : i' ≠ i) : (f.erase i) i' = f i' :=
by simp [h]
end basic
section add_monoid
variable [Π i, add_monoid (β i)]
@[simp] lemma single_add {i : ι} {b₁ b₂ : β i} : single i (b₁ + b₂) = single i b₁ + single i b₂ :=
ext $ assume i',
begin
by_cases h : i = i',
{ subst h, simp only [add_apply, single_eq_same] },
{ simp only [add_apply, single_eq_of_ne h, zero_add] }
end
lemma single_add_erase {i : ι} {f : Π₀ i, β i} : single i (f i) + f.erase i = f :=
ext $ λ i',
if h : i = i'
then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, add_zero]
else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), zero_add]
lemma erase_add_single {i : ι} {f : Π₀ i, β i} : f.erase i + single i (f i) = f :=
ext $ λ i',
if h : i = i'
then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, zero_add]
else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), add_zero]
protected theorem induction {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i)
(h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (single i b + f)) :
p f :=
begin
refine quotient.induction_on f (λ x, _),
cases x with f s H, revert f H,
apply multiset.induction_on s,
{ intros f H, convert h0, ext i, exact (H i).resolve_left id },
intros i s ih f H,
by_cases H1 : i ∈ s,
{ have H2 : ∀ j, j ∈ s ∨ f j = 0,
{ intro j, cases H j with H2 H2,
{ cases multiset.mem_cons.1 H2 with H3 H3,
{ left, rw H3, exact H1 },
{ left, exact H3 } },
right, exact H2 },
have H3 : (⟦{to_fun := f, pre_support := i :: s, zero := H}⟧ : Π₀ i, β i)
= ⟦{to_fun := f, pre_support := s, zero := H2}⟧,
{ exact quotient.sound (λ i, rfl) },
rw H3, apply ih },
have H2 : p (erase i ⟦{to_fun := f, pre_support := i :: s, zero := H}⟧),
{ dsimp only [erase, quotient.lift_on_beta],
have H2 : ∀ j, j ∈ s ∨ ite (j = i) 0 (f j) = 0,
{ intro j, cases H j with H2 H2,
{ cases multiset.mem_cons.1 H2 with H3 H3,
{ right, exact if_pos H3 },
{ left, exact H3 } },
right, split_ifs; [refl, exact H2] },
have H3 : (⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j),
pre_support := i :: s, zero := _}⟧ : Π₀ i, β i)
= ⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := s, zero := H2}⟧ :=
quotient.sound (λ i, rfl),
rw H3, apply ih },
have H3 : single i _ + _ = (⟦{to_fun := f, pre_support := i :: s, zero := H}⟧ : Π₀ i, β i) :=
single_add_erase,
rw ← H3,
change p (single i (f i) + _),
cases classical.em (f i = 0) with h h,
{ rw [h, single_zero, zero_add], exact H2 },
refine ha _ _ _ _ h H2,
rw erase_same
end
lemma induction₂ {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i)
(h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (f + single i b)) :
p f :=
dfinsupp.induction f h0 $ λ i b f h1 h2 h3,
have h4 : f + single i b = single i b + f,
{ ext j, by_cases H : i = j,
{ subst H, simp [h1] },
{ simp [H] } },
eq.rec_on h4 $ ha i b f h1 h2 h3
end add_monoid
@[simp] lemma mk_add [Π i, add_monoid (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i} :
mk s (x + y) = mk s x + mk s y :=
ext $ λ i, by simp only [add_apply, mk_apply]; split_ifs; [refl, rw zero_add]
@[simp] lemma mk_zero [Π i, has_zero (β i)] {s : finset ι} :
mk s (0 : Π i : (↑s : set ι), β i.1) = 0 :=
ext $ λ i, by simp only [mk_apply]; split_ifs; refl
@[simp] lemma mk_neg [Π i, add_group (β i)] {s : finset ι} {x : Π i : (↑s : set ι), β i.1} :
mk s (-x) = -mk s x :=
ext $ λ i, by simp only [neg_apply, mk_apply]; split_ifs; [refl, rw neg_zero]
@[simp] lemma mk_sub [Π i, add_group (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i.1} :
mk s (x - y) = mk s x - mk s y :=
ext $ λ i, by simp only [sub_apply, mk_apply]; split_ifs; [refl, rw sub_zero]
instance [Π i, add_group (β i)] {s : finset ι} : is_add_group_hom (@mk ι β _ _ s) :=
{ map_add := λ _ _, mk_add }
section
local attribute [instance] to_semimodule
variables (γ : Type w) [semiring γ] [Π i, add_comm_group (β i)] [Π i, semimodule γ (β i)]
include γ
@[simp] lemma mk_smul {s : finset ι} {c : γ} (x : Π i : (↑s : set ι), β i.1) :
mk s (c • x) = c • mk s x :=
ext $ λ i, by simp only [smul_apply, mk_apply]; split_ifs; [refl, rw smul_zero]
@[simp] lemma single_smul {i : ι} {c : γ} {x : β i} :
single i (c • x) = c • single i x :=
ext $ λ i, by simp only [smul_apply, single_apply]; split_ifs; [cases h, rw smul_zero]; refl
variable β
/-- `dfinsupp.mk` as a `linear_map`. -/
def lmk (s : finset ι) : (Π i : (↑s : set ι), β i.1) →ₗ[γ] Π₀ i, β i :=
⟨mk s, λ _ _, mk_add, λ c x, by rw [mk_smul γ x]⟩
/-- `dfinsupp.single` as a `linear_map` -/
def lsingle (i) : β i →ₗ[γ] Π₀ i, β i :=
⟨single i, λ _ _, single_add, λ _ _, single_smul _⟩
variable {β}
@[simp] lemma lmk_apply {s : finset ι} {x} : lmk β γ s x = mk s x := rfl
@[simp] lemma lsingle_apply {i : ι} {x : β i} : lsingle β γ i x = single i x := rfl
end
section support_basic
variables [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)]
/-- Set `{i | f x ≠ 0}` as a `finset`. -/
def support (f : Π₀ i, β i) : finset ι :=
quotient.lift_on f (λ x, x.2.to_finset.filter $ λ i, x.1 i ≠ 0) $
begin
intros x y Hxy,
ext i, split,
{ intro H,
rcases finset.mem_filter.1 H with ⟨h1, h2⟩,
rw Hxy i at h2,
exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (y.3 i).resolve_right h2, h2⟩ },
{ intro H,
rcases finset.mem_filter.1 H with ⟨h1, h2⟩,
rw ← Hxy i at h2,
exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (x.3 i).resolve_right h2, h2⟩ },
end
@[simp] theorem support_mk_subset {s : finset ι} {x : Π i : (↑s : set ι), β i.1} :
(mk s x).support ⊆ s :=
λ i H, multiset.mem_to_finset.1 (finset.mem_filter.1 H).1
@[simp] theorem mem_support_to_fun (f : Π₀ i, β i) (i) : i ∈ f.support ↔ f i ≠ 0 :=
begin
refine quotient.induction_on f (λ x, _),
dsimp only [support, quotient.lift_on_beta],
rw [finset.mem_filter, multiset.mem_to_finset],
exact and_iff_right_of_imp (x.3 i).resolve_right
end
theorem eq_mk_support (f : Π₀ i, β i) : f = mk f.support (λ i, f i) :=
begin
change f = mk f.support (λ i, f i.1),
ext i,
by_cases h : f i ≠ 0; [skip, rw [classical.not_not] at h];
simp [h]
end
@[simp] lemma support_zero : (0 : Π₀ i, β i).support = ∅ := rfl
lemma mem_support_iff (f : Π₀ i, β i) : ∀i:ι, i ∈ f.support ↔ f i ≠ 0 :=
f.mem_support_to_fun
@[simp] lemma support_eq_empty {f : Π₀ i, β i} : f.support = ∅ ↔ f = 0 :=
⟨λ H, ext $ by simpa [finset.ext_iff] using H, by simp {contextual:=tt}⟩
instance decidable_zero : decidable_pred (eq (0 : Π₀ i, β i)) :=
λ f, decidable_of_iff _ $ support_eq_empty.trans eq_comm
lemma support_subset_iff {s : set ι} {f : Π₀ i, β i} :
↑f.support ⊆ s ↔ (∀i∉s, f i = 0) :=
by simp [set.subset_def];
exact forall_congr (assume i, @not_imp_comm _ _ (classical.dec _) (classical.dec _))
lemma support_single_ne_zero {i : ι} {b : β i} (hb : b ≠ 0) : (single i b).support = {i} :=
begin
ext j, by_cases h : i = j,
{ subst h, simp [hb] },
simp [ne.symm h, h]
end
lemma support_single_subset {i : ι} {b : β i} : (single i b).support ⊆ {i} :=
support_mk_subset
section map_range_and_zip_with
variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂}
variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)]
lemma map_range_def [Π i (x : β₁ i), decidable (x ≠ 0)]
{f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} :
map_range f hf g = mk g.support (λ i, f i.1 (g i.1)) :=
begin
ext i,
by_cases h : g i ≠ 0; simp at h; simp [h, hf]
end
@[simp] lemma map_range_single {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {i : ι} {b : β₁ i} :
map_range f hf (single i b) = single i (f i b) :=
dfinsupp.ext $ λ i', by by_cases i = i'; [{subst i', simp}, simp [h, hf]]
variables [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i (x : β₂ i), decidable (x ≠ 0)]
lemma support_map_range {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} :
(map_range f hf g).support ⊆ g.support :=
by simp [map_range_def]
lemma zip_with_def {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0}
{g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} :
zip_with f hf g₁ g₂ = mk (g₁.support ∪ g₂.support) (λ i, f i.1 (g₁ i.1) (g₂ i.1)) :=
begin
ext i,
by_cases h1 : g₁ i ≠ 0; by_cases h2 : g₂ i ≠ 0;
simp only [classical.not_not, ne.def] at h1 h2; simp [h1, h2, hf]
end
lemma support_zip_with {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0}
{g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} :
(zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support :=
by simp [zip_with_def]
end map_range_and_zip_with
lemma erase_def (i : ι) (f : Π₀ i, β i) :
f.erase i = mk (f.support.erase i) (λ j, f j.1) :=
by { ext j, by_cases h1 : j = i; by_cases h2 : f j ≠ 0; simp at h2; simp [h1, h2] }
@[simp] lemma support_erase (i : ι) (f : Π₀ i, β i) :
(f.erase i).support = f.support.erase i :=
by { ext j, by_cases h1 : j = i; by_cases h2 : f j ≠ 0; simp at h2; simp [h1, h2] }
section filter_and_subtype_domain
variables {p : ι → Prop} [decidable_pred p]
lemma filter_def (f : Π₀ i, β i) :
f.filter p = mk (f.support.filter p) (λ i, f i.1) :=
by ext i; by_cases h1 : p i; by_cases h2 : f i ≠ 0;
simp at h2; simp [h1, h2]
@[simp] lemma support_filter (f : Π₀ i, β i) :
(f.filter p).support = f.support.filter p :=
by ext i; by_cases h : p i; simp [h]
lemma subtype_domain_def (f : Π₀ i, β i) :
f.subtype_domain p = mk (f.support.subtype p) (λ i, f i.1) :=
by ext i; cases i with i hi;
by_cases h1 : p i; by_cases h2 : f i ≠ 0;
try {simp at h2}; dsimp; simp [h1, h2]
@[simp] lemma support_subtype_domain {f : Π₀ i, β i} :
(subtype_domain p f).support = f.support.subtype p :=
by ext i; cases i with i hi;
by_cases h1 : p i; by_cases h2 : f i ≠ 0;
try {simp at h2}; dsimp; simp [h1, h2]
end filter_and_subtype_domain
end support_basic
lemma support_add [Π i, add_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] {g₁ g₂ : Π₀ i, β i} :
(g₁ + g₂).support ⊆ g₁.support ∪ g₂.support :=
support_zip_with
@[simp] lemma support_neg [Π i, add_group (β i)] [Π i (x : β i), decidable (x ≠ 0)]
{f : Π₀ i, β i} :
support (-f) = support f :=
by ext i; simp
local attribute [instance] dfinsupp.to_semimodule
lemma support_smul {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)]
[Π (i : ι) (x : β i), decidable (x ≠ 0)]
{b : γ} {v : Π₀ i, β i} : (b • v).support ⊆ v.support :=
support_map_range
instance [Π i, has_zero (β i)] [Π i, decidable_eq (β i)] : decidable_eq (Π₀ i, β i) :=
assume f g, decidable_of_iff (f.support = g.support ∧ (∀i∈f.support, f i = g i))
⟨assume ⟨h₁, h₂⟩, ext $ assume i,
if h : i ∈ f.support then h₂ i h else
have hf : f i = 0, by rwa [f.mem_support_iff, not_not] at h,
have hg : g i = 0, by rwa [h₁, g.mem_support_iff, not_not] at h,
by rw [hf, hg],
by intro h; subst h; simp⟩
section prod_and_sum
variables {γ : Type w}
-- [to_additive sum] for dfinsupp.prod doesn't work, the equation lemmas are not generated
/-- `sum f g` is the sum of `g i (f i)` over the support of `f`. -/
def sum [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [add_comm_monoid γ]
(f : Π₀ i, β i) (g : Π i, β i → γ) : γ :=
∑ i in f.support, g i (f i)
/-- `prod f g` is the product of `g i (f i)` over the support of `f`. -/
@[to_additive]
def prod [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ]
(f : Π₀ i, β i) (g : Π i, β i → γ) : γ :=
∏ i in f.support, g i (f i)
@[to_additive]
lemma prod_map_range_index {β₁ : ι → Type v₁} {β₂ : ι → Type v₂}
[Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)]
[Π i (x : β₁ i), decidable (x ≠ 0)] [Π i (x : β₂ i), decidable (x ≠ 0)] [comm_monoid γ]
{f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {h : Π i, β₂ i → γ}
(h0 : ∀i, h i 0 = 1) :
(map_range f hf g).prod h = g.prod (λi b, h i (f i b)) :=
begin
rw [map_range_def],
refine (finset.prod_subset support_mk_subset _).trans _,
{ intros i h1 h2,
dsimp, simp [h1] at h2, dsimp at h2,
simp [h1, h2, h0] },
{ refine finset.prod_congr rfl _,
intros i h1,
simp [h1] }
end
@[to_additive]
lemma prod_zero_index [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)]
[comm_monoid γ] {h : Π i, β i → γ} : (0 : Π₀ i, β i).prod h = 1 :=
rfl
@[to_additive]
lemma prod_single_index [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ]
{i : ι} {b : β i} {h : Π i, β i → γ} (h_zero : h i 0 = 1) :
(single i b).prod h = h i b :=
begin
by_cases h : b ≠ 0,
{ simp [dfinsupp.prod, support_single_ne_zero h] },
{ rw [classical.not_not] at h, simp [h, prod_zero_index, h_zero], refl }
end
@[to_additive]
lemma prod_neg_index [Π i, add_group (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ]
{g : Π₀ i, β i} {h : Π i, β i → γ} (h0 : ∀i, h i 0 = 1) :
(-g).prod h = g.prod (λi b, h i (- b)) :=
prod_map_range_index h0
omit dec
@[simp] lemma sum_apply {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁}
[Π i₁, has_zero (β₁ i₁)] [Π i (x : β₁ i), decidable (x ≠ 0)]
[Π i, add_comm_monoid (β i)]
{f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {i₂ : ι} :
(f.sum g) i₂ = f.sum (λi₁ b, g i₁ b i₂) :=
(f.support.sum_hom (λf : Π₀ i, β i, f i₂)).symm
include dec
lemma support_sum {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁}
[Π i₁, has_zero (β₁ i₁)] [Π i (x : β₁ i), decidable (x ≠ 0)]
[Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)]
{f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} :
(f.sum g).support ⊆ f.support.bind (λi, (g i (f i)).support) :=
have ∀i₁ : ι, f.sum (λ (i : ι₁) (b : β₁ i), (g i b) i₁) ≠ 0 →
(∃ (i : ι₁), f i ≠ 0 ∧ ¬ (g i (f i)) i₁ = 0),
from assume i₁ h,
let ⟨i, hi, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in
⟨i, (f.mem_support_iff i).mp hi, ne⟩,
by simpa [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply] using this
@[simp] lemma sum_zero [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)]
[add_comm_monoid γ] {f : Π₀ i, β i} :
f.sum (λi b, (0 : γ)) = 0 :=
finset.sum_const_zero
@[simp] lemma sum_add [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)]
[add_comm_monoid γ] {f : Π₀ i, β i} {h₁ h₂ : Π i, β i → γ} :
f.sum (λi b, h₁ i b + h₂ i b) = f.sum h₁ + f.sum h₂ :=
finset.sum_add_distrib
@[simp] lemma sum_neg [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)]
[add_comm_group γ] {f : Π₀ i, β i} {h : Π i, β i → γ} :
f.sum (λi b, - h i b) = - f.sum h :=
f.support.sum_hom (@has_neg.neg γ _)
@[to_additive]
lemma prod_add_index [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)]
[comm_monoid γ] {f g : Π₀ i, β i}
{h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) :
(f + g).prod h = f.prod h * g.prod h :=
have f_eq : ∏ i in f.support ∪ g.support, h i (f i) = f.prod h,
from (finset.prod_subset (finset.subset_union_left _ _) $
by simp [mem_support_iff, h_zero] {contextual := tt}).symm,
have g_eq : ∏ i in f.support ∪ g.support, h i (g i) = g.prod h,
from (finset.prod_subset (finset.subset_union_right _ _) $
by simp [mem_support_iff, h_zero] {contextual := tt}).symm,
calc ∏ i in (f + g).support, h i ((f + g) i) =
∏ i in f.support ∪ g.support, h i ((f + g) i) :
finset.prod_subset support_add $
by simp [mem_support_iff, h_zero] {contextual := tt}
... = (∏ i in f.support ∪ g.support, h i (f i)) *
(∏ i in f.support ∪ g.support, h i (g i)) :
by simp [h_add, finset.prod_mul_distrib]
... = _ : by rw [f_eq, g_eq]
lemma sum_sub_index [Π i, add_comm_group (β i)] [Π i (x : β i), decidable (x ≠ 0)]
[add_comm_group γ] {f g : Π₀ i, β i}
{h : Π i, β i → γ} (h_sub : ∀i b₁ b₂, h i (b₁ - b₂) = h i b₁ - h i b₂) :
(f - g).sum h = f.sum h - g.sum h :=
have h_zero : ∀i, h i 0 = 0,
from assume i,
have h i (0 - 0) = h i 0 - h i 0, from h_sub i 0 0,
by simpa using this,
have h_neg : ∀i b, h i (- b) = - h i b,
from assume i b,
have h i (0 - b) = h i 0 - h i b, from h_sub i 0 b,
by simpa [h_zero] using this,
have h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ + h i b₂,
from assume i b₁ b₂,
have h i (b₁ - (- b₂)) = h i b₁ - h i (- b₂), from h_sub i b₁ (-b₂),
by simpa [h_neg, sub_eq_add_neg] using this,
by simp [sub_eq_add_neg];
simp [@sum_add_index ι β _ γ _ _ _ f (-g) h h_zero h_add];
simp [@sum_neg_index ι β _ γ _ _ _ g h h_zero, h_neg];
simp [@sum_neg ι β _ γ _ _ _ g h]
@[to_additive]
lemma prod_finset_sum_index {γ : Type w} {α : Type x}
[Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)]
[comm_monoid γ]
{s : finset α} {g : α → Π₀ i, β i}
{h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) :
∏ i in s, (g i).prod h = (∑ i in s, g i).prod h :=
begin
classical,
exact finset.induction_on s
(by simp [prod_zero_index])
(by simp [prod_add_index, h_zero, h_add] {contextual := tt})
end
@[to_additive]
lemma prod_sum_index {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁}
[Π i₁, has_zero (β₁ i₁)] [Π i (x : β₁ i), decidable (x ≠ 0)]
[Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)]
[comm_monoid γ]
{f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i}
{h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) :
(f.sum g).prod h = f.prod (λi b, (g i b).prod h) :=
(prod_finset_sum_index h_zero h_add).symm
@[simp] lemma sum_single [Π i, add_comm_monoid (β i)]
[Π i (x : β i), decidable (x ≠ 0)] {f : Π₀ i, β i} :
f.sum single = f :=
begin
apply dfinsupp.induction f, {rw [sum_zero_index]},
intros i b f H hb ih,
rw [sum_add_index, ih, sum_single_index],
all_goals { intros, simp }
end
@[to_additive]
lemma prod_subtype_domain_index [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)]
[comm_monoid γ] {v : Π₀ i, β i} {p : ι → Prop} [decidable_pred p]
{h : Π i, β i → γ} (hp : ∀ x ∈ v.support, p x) :
(v.subtype_domain p).prod (λi b, h i.1 b) = v.prod h :=
finset.prod_bij (λp _, p.val)
(by { dsimp, simp })
(by simp)
(assume ⟨a₀, ha₀⟩ ⟨a₁, ha₁⟩, by simp)
(λ i hi, ⟨⟨i, hp i hi⟩, by simpa using hi, rfl⟩)
omit dec
lemma subtype_domain_sum [Π i, add_comm_monoid (β i)]
{s : finset γ} {h : γ → Π₀ i, β i} {p : ι → Prop} [decidable_pred p] :
(∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p :=
eq.symm (s.sum_hom _)
lemma subtype_domain_finsupp_sum {δ : γ → Type x} [decidable_eq γ]
[Π c, has_zero (δ c)] [Π c (x : δ c), decidable (x ≠ 0)]
[Π i, add_comm_monoid (β i)]
{p : ι → Prop} [decidable_pred p]
{s : Π₀ c, δ c} {h : Π c, δ c → Π₀ i, β i} :
(s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) :=
subtype_domain_sum
end prod_and_sum
end dfinsupp
|
9d0ac0a738254848aef9d4bb3ce9deaab8dcf272 | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /tests/lean/run/enum.lean | 06c8b44767e11f251b31af2ffa7dda579183c152 | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 390 | lean | import logic
inductive Three :=
zero : Three,
one : Three,
two : Three
namespace Three
theorem disj (a : Three) : a = zero ∨ a = one ∨ a = two :=
rec (or.inl rfl) (or.inr (or.inl rfl)) (or.inr (or.inr rfl)) a
example (a : Three) : a ≠ zero → a ≠ one → a = two :=
rec (λ h₁ h₂, absurd rfl h₁) (λ h₁ h₂, absurd rfl h₂) (λ h₁ h₂, rfl) a
end Three
|
8ec235468eea35dedeac7db594d9104e63d319ce | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Meta/RecursorInfo.lean | 824d069673a0176d11ac564cf1daa70e5a512721 | [
"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 | 13,468 | 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.AuxRecursor
import Lean.Util.FindExpr
import Lean.Meta.Basic
namespace Lean.Meta
inductive RecursorUnivLevelPos where
| motive -- marks where the universe of the motive should go
| majorType (idx : Nat) -- marks where the #idx universe of the major premise type goes
instance : ToString RecursorUnivLevelPos := ⟨fun
| RecursorUnivLevelPos.motive => "<motive-univ>"
| RecursorUnivLevelPos.majorType idx => toString idx⟩
structure RecursorInfo where
recursorName : Name
typeName : Name
univLevelPos : List RecursorUnivLevelPos
depElim : Bool
recursive : Bool
numArgs : Nat -- Total number of arguments
majorPos : Nat
paramsPos : List (Option Nat) -- Position of the recursor parameters in the major premise, instance implicit arguments are `none`
indicesPos : List Nat -- Position of the recursor indices in the major premise
produceMotive : List Bool -- If the i-th element is true then i-th minor premise produces the motive
namespace RecursorInfo
def numParams (info : RecursorInfo) : Nat := info.paramsPos.length
def numIndices (info : RecursorInfo) : Nat := info.indicesPos.length
def motivePos (info : RecursorInfo) : Nat := info.numParams
def firstIndexPos (info : RecursorInfo) : Nat := info.majorPos - info.numIndices
def isMinor (info : RecursorInfo) (pos : Nat) : Bool :=
if pos ≤ info.motivePos then false
else if info.firstIndexPos ≤ pos && pos ≤ info.majorPos then false
else true
def numMinors (info : RecursorInfo) : Nat :=
let r := info.numArgs
let r := r - info.motivePos - 1
r - (info.majorPos + 1 - info.firstIndexPos)
instance : ToString RecursorInfo := ⟨fun info =>
"{\n" ++
" name := " ++ toString info.recursorName ++ "\n" ++
" type := " ++ toString info.typeName ++ "\n" ++
" univs := " ++ toString info.univLevelPos ++ "\n" ++
" depElim := " ++ toString info.depElim ++ "\n" ++
" recursive := " ++ toString info.recursive ++ "\n" ++
" numArgs := " ++ toString info.numArgs ++ "\n" ++
" numParams := " ++ toString info.numParams ++ "\n" ++
" numIndices := " ++ toString info.numIndices ++ "\n" ++
" numMinors := " ++ toString info.numMinors ++ "\n" ++
" major := " ++ toString info.majorPos ++ "\n" ++
" motive := " ++ toString info.motivePos ++ "\n" ++
" paramsAtMajor := " ++ toString info.paramsPos ++ "\n" ++
" indicesAtMajor := " ++ toString info.indicesPos ++ "\n" ++
" produceMotive := " ++ toString info.produceMotive ++ "\n" ++
"}"⟩
end RecursorInfo
private def mkRecursorInfoForKernelRec (declName : Name) (val : RecursorVal) : MetaM RecursorInfo := do
let ival ← getConstInfoInduct val.getInduct
let numLParams := ival.levelParams.length
let univLevelPos := (List.range numLParams).map RecursorUnivLevelPos.majorType
let univLevelPos := if val.levelParams.length == numLParams then univLevelPos else RecursorUnivLevelPos.motive :: univLevelPos
let produceMotive := List.replicate val.numMinors true
let paramsPos := (List.range val.numParams).map some
let indicesPos := (List.range val.numIndices).map fun pos => val.numParams + pos
let numArgs := val.numIndices + val.numParams + val.numMinors + val.numMotives + 1
pure {
recursorName := declName,
typeName := val.getInduct,
univLevelPos := univLevelPos,
majorPos := val.getMajorIdx,
depElim := true,
recursive := ival.isRec,
produceMotive := produceMotive,
paramsPos := paramsPos,
indicesPos := indicesPos,
numArgs := numArgs
}
private def getMajorPosIfAuxRecursor? (declName : Name) (majorPos? : Option Nat) : MetaM (Option Nat) :=
if majorPos?.isSome then pure majorPos?
else do
let env ← getEnv
if !isAuxRecursor env declName then pure none
else match declName with
| .str p s =>
if s != recOnSuffix && s != casesOnSuffix && s != brecOnSuffix then
pure none
else do
let val ← getConstInfoRec (mkRecName p)
pure $ some (val.numParams + val.numIndices + (if s == casesOnSuffix then 1 else val.numMotives))
| _ => pure none
private def checkMotive (declName : Name) (motive : Expr) (motiveArgs : Array Expr) : MetaM Unit :=
unless motive.isFVar && motiveArgs.all Expr.isFVar do
throwError "invalid user defined recursor '{declName}', result type must be of the form (C t), where C is a bound variable, and t is a (possibly empty) sequence of bound variables"
/-- Compute number of parameters for (user-defined) recursor.
We assume a parameter is anything that occurs before the motive -/
private partial def getNumParams (xs : Array Expr) (motive : Expr) (i : Nat) : Nat :=
if h : i < xs.size then
let x := xs.get ⟨i, h⟩
if motive == x then i
else getNumParams xs motive (i+1)
else
i
private def getMajorPosDepElim (declName : Name) (majorPos? : Option Nat) (xs : Array Expr) (motiveArgs : Array Expr)
: MetaM (Expr × Nat × Bool) := do
match majorPos? with
| some majorPos =>
if h : majorPos < xs.size then
let major := xs.get ⟨majorPos, h⟩
let depElim := motiveArgs.contains major
pure (major, majorPos, depElim)
else throwError "invalid major premise position for user defined recursor, recursor has only {xs.size} arguments"
| none => do
if motiveArgs.isEmpty then
throwError "invalid user defined recursor, '{declName}' does not support dependent elimination, and position of the major premise was not specified (solution: set attribute '[recursor <pos>]', where <pos> is the position of the major premise)"
let major := motiveArgs.back
match xs.getIdx? major with
| some majorPos => pure (major, majorPos, true)
| none => throwError "ill-formed recursor '{declName}'"
private def getParamsPos (declName : Name) (xs : Array Expr) (numParams : Nat) (Iargs : Array Expr) : MetaM (List (Option Nat)) := do
let mut paramsPos := #[]
for i in [:numParams] do
let x := xs[i]!
match (← Iargs.findIdxM? fun Iarg => isDefEq Iarg x) with
| some j => paramsPos := paramsPos.push (some j)
| none => do
let localDecl ← x.fvarId!.getDecl
if localDecl.binderInfo.isInstImplicit then
paramsPos := paramsPos.push none
else
throwError"invalid user defined recursor '{declName}', type of the major premise does not contain the recursor parameter"
pure paramsPos.toList
private def getIndicesPos (declName : Name) (xs : Array Expr) (majorPos numIndices : Nat) (Iargs : Array Expr) : MetaM (List Nat) := do
let mut indicesPos := #[]
for i in [:numIndices] do
let i := majorPos - numIndices + i
let x := xs[i]!
match (← Iargs.findIdxM? fun Iarg => isDefEq Iarg x) with
| some j => indicesPos := indicesPos.push j
| none => throwError "invalid user defined recursor '{declName}', type of the major premise does not contain the recursor index"
pure indicesPos.toList
private def getMotiveLevel (declName : Name) (motiveResultType : Expr) : MetaM Level :=
match motiveResultType with
| Expr.sort u@(Level.zero) => pure u
| Expr.sort u@(Level.param _) => pure u
| _ =>
throwError "invalid user defined recursor '{declName}', motive result sort must be Prop or (Sort u) where u is a universe level parameter"
private def getUnivLevelPos (declName : Name) (lparams : List Name) (motiveLvl : Level) (Ilevels : List Level) : MetaM (List RecursorUnivLevelPos) := do
let Ilevels := Ilevels.toArray
let mut univLevelPos := #[]
for p in lparams do
if motiveLvl == mkLevelParam p then
univLevelPos := univLevelPos.push RecursorUnivLevelPos.motive
else
match Ilevels.findIdx? fun u => u == mkLevelParam p with
| some i => univLevelPos := univLevelPos.push (RecursorUnivLevelPos.majorType i)
| none =>
throwError "invalid user defined recursor '{declName}', major premise type does not contain universe level parameter '{p}'"
pure univLevelPos.toList
private def getProduceMotiveAndRecursive (xs : Array Expr) (numParams numIndices majorPos : Nat) (motive : Expr) : MetaM (List Bool × Bool) := do
let mut produceMotive := #[]
let mut recursor := false
for i in [:xs.size] do
if i < numParams + 1 then
continue --skip parameters and motive
if majorPos - numIndices ≤ i && i ≤ majorPos then
continue -- skip indices and major premise
-- process minor premise
let x := xs[i]!
let xType ← inferType x
(produceMotive, recursor) ← forallTelescopeReducing xType fun minorArgs minorResultType => minorResultType.withApp fun res _ => do
let produceMotive := produceMotive.push (res == motive)
let recursor ← if recursor then pure recursor else minorArgs.anyM fun minorArg => do
let minorArgType ← inferType minorArg
pure (minorArgType.find? fun e => e == motive).isSome
pure (produceMotive, recursor)
pure (produceMotive.toList, recursor)
private def checkMotiveResultType (declName : Name) (motiveArgs : Array Expr) (motiveResultType : Expr) (motiveTypeParams : Array Expr) : MetaM Unit := do
if !motiveResultType.isSort || motiveArgs.size != motiveTypeParams.size then
throwError "invalid user defined recursor '{declName}', motive must have a type of the form (C : Pi (i : B A), I A i -> Type), where A is (possibly empty) sequence of variables (aka parameters), (i : B A) is a (possibly empty) telescope (aka indices), and I is a constant"
private def mkRecursorInfoAux (cinfo : ConstantInfo) (majorPos? : Option Nat) : MetaM RecursorInfo := do
let declName := cinfo.name
let majorPos? ← getMajorPosIfAuxRecursor? declName majorPos?
forallTelescopeReducing cinfo.type fun xs type => type.withApp fun motive motiveArgs => do
checkMotive declName motive motiveArgs
let numParams := getNumParams xs motive 0
let (major, majorPos, depElim) ← getMajorPosDepElim declName majorPos? xs motiveArgs
let numIndices := if depElim then motiveArgs.size - 1 else motiveArgs.size
if majorPos < numIndices then
throwError "invalid user defined recursor '{declName}', indices must occur before major premise"
let majorType ← inferType major
majorType.withApp fun I Iargs =>
match I with
| Expr.const Iname Ilevels => do
let paramsPos ← getParamsPos declName xs numParams Iargs
let indicesPos ← getIndicesPos declName xs majorPos numIndices Iargs
let motiveType ← inferType motive
forallTelescopeReducing motiveType fun motiveTypeParams motiveResultType => do
checkMotiveResultType declName motiveArgs motiveResultType motiveTypeParams
let motiveLvl ← getMotiveLevel declName motiveResultType
let univLevelPos ← getUnivLevelPos declName cinfo.levelParams motiveLvl Ilevels
let (produceMotive, recursive) ← getProduceMotiveAndRecursive xs numParams numIndices majorPos motive
pure {
recursorName := declName,
typeName := Iname,
univLevelPos := univLevelPos,
majorPos := majorPos,
depElim := depElim,
recursive := recursive,
produceMotive := produceMotive,
paramsPos := paramsPos,
indicesPos := indicesPos,
numArgs := xs.size
}
| _ => throwError "invalid user defined recursor '{declName}', type of the major premise must be of the form (I ...), where I is a constant"
/-
@[builtin_attr_parser] def «recursor» := leading_parser "recursor " >> numLit
-/
def Attribute.Recursor.getMajorPos (stx : Syntax) : AttrM Nat := do
if stx.getKind == `Lean.Parser.Attr.recursor then
let pos := stx[1].isNatLit?.getD 0
if pos == 0 then
throwErrorAt stx "major premise position must be greater than zero"
return pos - 1
else
throwErrorAt stx "unexpected attribute argument, numeral expected"
private def mkRecursorInfoCore (declName : Name) (majorPos? : Option Nat := none) : MetaM RecursorInfo := do
let cinfo ← getConstInfo declName
match cinfo with
| ConstantInfo.recInfo val => mkRecursorInfoForKernelRec declName val
| _ => mkRecursorInfoAux cinfo majorPos?
builtin_initialize recursorAttribute : ParametricAttribute Nat ←
registerParametricAttribute {
name := `recursor,
descr := "user defined recursor, numerical parameter specifies position of the major premise",
getParam := fun _ stx => Attribute.Recursor.getMajorPos stx
afterSet := fun declName majorPos => do
discard <| mkRecursorInfoCore declName (some majorPos) |>.run'
}
def getMajorPos? (env : Environment) (declName : Name) : Option Nat :=
recursorAttribute.getParam? env declName
def mkRecursorInfo (declName : Name) (majorPos? : Option Nat := none) : MetaM RecursorInfo := do
let cinfo ← getConstInfo declName
match cinfo with
| ConstantInfo.recInfo val => mkRecursorInfoForKernelRec declName val
| _ => match majorPos? with
| none => do mkRecursorInfoAux cinfo (getMajorPos? (← getEnv) declName)
| _ => mkRecursorInfoAux cinfo majorPos?
end Lean.Meta
|
3e0da72e026eb5591e99a8df95a8f12c6caa6016 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/limits/shapes/zero_morphisms.lean | 00d1e6267f0edeff59679cf94551f4c7f0f39cb3 | [
"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 | 19,952 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.limits.shapes.products
import category_theory.limits.shapes.images
import category_theory.isomorphism_classes
import category_theory.limits.shapes.zero_objects
/-!
# Zero morphisms and zero objects
A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space,
and compositions of zero morphisms with anything give the zero morphism. (Notice this is extra
structure, not merely a property.)
A category "has a zero object" if it has an object which is both initial and terminal. Having a
zero object provides zero morphisms, as the unique morphisms factoring through the zero object.
## References
* https://en.wikipedia.org/wiki/Zero_morphism
* [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2]
-/
noncomputable theory
universes v u
universes v' u'
open category_theory
open category_theory.category
open_locale classical
namespace category_theory.limits
variables (C : Type u) [category.{v} C]
variables (D : Type u') [category.{v'} D]
/-- A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space,
and compositions of zero morphisms with anything give the zero morphism. -/
class has_zero_morphisms :=
[has_zero : Π X Y : C, has_zero (X ⟶ Y)]
(comp_zero' : ∀ {X Y : C} (f : X ⟶ Y) (Z : C), f ≫ (0 : Y ⟶ Z) = (0 : X ⟶ Z) . obviously)
(zero_comp' : ∀ (X : C) {Y Z : C} (f : Y ⟶ Z), (0 : X ⟶ Y) ≫ f = (0 : X ⟶ Z) . obviously)
attribute [instance] has_zero_morphisms.has_zero
restate_axiom has_zero_morphisms.comp_zero'
restate_axiom has_zero_morphisms.zero_comp'
variables {C}
@[simp] lemma comp_zero [has_zero_morphisms C] {X Y : C} {f : X ⟶ Y} {Z : C} :
f ≫ (0 : Y ⟶ Z) = (0 : X ⟶ Z) := has_zero_morphisms.comp_zero f Z
@[simp] lemma zero_comp [has_zero_morphisms C] {X : C} {Y Z : C} {f : Y ⟶ Z} :
(0 : X ⟶ Y) ≫ f = (0 : X ⟶ Z) := has_zero_morphisms.zero_comp X f
instance has_zero_morphisms_pempty : has_zero_morphisms (discrete pempty) :=
{ has_zero := by tidy }
instance has_zero_morphisms_punit : has_zero_morphisms (discrete punit) :=
{ has_zero := by tidy }
namespace has_zero_morphisms
variables {C}
/-- This lemma will be immediately superseded by `ext`, below. -/
private lemma ext_aux (I J : has_zero_morphisms C)
(w : ∀ X Y : C, (@has_zero_morphisms.has_zero _ _ I X Y).zero =
(@has_zero_morphisms.has_zero _ _ J X Y).zero) : I = J :=
begin
casesI I, casesI J,
congr,
{ ext X Y,
exact w X Y },
{ apply proof_irrel_heq, },
{ apply proof_irrel_heq, }
end
/--
If you're tempted to use this lemma "in the wild", you should probably
carefully consider whether you've made a mistake in allowing two
instances of `has_zero_morphisms` to exist at all.
See, particularly, the note on `zero_morphisms_of_zero_object` below.
-/
lemma ext (I J : has_zero_morphisms C) : I = J :=
begin
apply ext_aux,
intros X Y,
rw ←@has_zero_morphisms.comp_zero _ _ I X X (@has_zero_morphisms.has_zero _ _ J X X).zero,
rw @has_zero_morphisms.zero_comp _ _ J,
end
instance : subsingleton (has_zero_morphisms C) :=
⟨ext⟩
end has_zero_morphisms
open opposite has_zero_morphisms
instance has_zero_morphisms_opposite [has_zero_morphisms C] :
has_zero_morphisms Cᵒᵖ :=
{ has_zero := λ X Y, ⟨(0 : unop Y ⟶ unop X).op⟩,
comp_zero' := λ X Y f Z, congr_arg quiver.hom.op (has_zero_morphisms.zero_comp (unop Z) f.unop),
zero_comp' := λ X Y Z f, congr_arg quiver.hom.op (has_zero_morphisms.comp_zero f.unop (unop X)), }
section
variables {C} [has_zero_morphisms C]
lemma zero_of_comp_mono {X Y Z : C} {f : X ⟶ Y} (g : Y ⟶ Z) [mono g] (h : f ≫ g = 0) : f = 0 :=
by { rw [←zero_comp, cancel_mono] at h, exact h }
lemma zero_of_epi_comp {X Y Z : C} (f : X ⟶ Y) {g : Y ⟶ Z} [epi f] (h : f ≫ g = 0) : g = 0 :=
by { rw [←comp_zero, cancel_epi] at h, exact h }
lemma eq_zero_of_image_eq_zero {X Y : C} {f : X ⟶ Y} [has_image f] (w : image.ι f = 0) : f = 0 :=
by rw [←image.fac f, w, has_zero_morphisms.comp_zero]
lemma nonzero_image_of_nonzero {X Y : C} {f : X ⟶ Y} [has_image f] (w : f ≠ 0) : image.ι f ≠ 0 :=
λ h, w (eq_zero_of_image_eq_zero h)
end
section
variables [has_zero_morphisms D]
instance : has_zero_morphisms (C ⥤ D) :=
{ has_zero := λ F G, ⟨{ app := λ X, 0, }⟩ }
@[simp] lemma zero_app (F G : C ⥤ D) (j : C) : (0 : F ⟶ G).app j = 0 := rfl
end
namespace is_zero
variables [has_zero_morphisms C]
lemma eq_zero_of_src {X Y : C} (o : is_zero X) (f : X ⟶ Y) : f = 0 :=
o.eq_of_src _ _
lemma eq_zero_of_tgt {X Y : C} (o : is_zero Y) (f : X ⟶ Y) : f = 0 :=
o.eq_of_tgt _ _
lemma iff_id_eq_zero (X : C) : is_zero X ↔ (𝟙 X = 0) :=
⟨λ h, h.eq_of_src _ _,
λ h, ⟨
λ Y, ⟨⟨⟨0⟩, λ f, by { rw [←id_comp f, ←id_comp default, h, zero_comp, zero_comp], }⟩⟩,
λ Y, ⟨⟨⟨0⟩, λ f, by { rw [←comp_id f, ←comp_id default, h, comp_zero, comp_zero], }⟩⟩⟩⟩
lemma of_mono_zero (X Y : C) [mono (0 : X ⟶ Y)] : is_zero X :=
(iff_id_eq_zero X).mpr ((cancel_mono (0 : X ⟶ Y)).1 (by simp))
lemma of_epi_zero (X Y : C) [epi (0 : X ⟶ Y)] : is_zero Y :=
(iff_id_eq_zero Y).mpr ((cancel_epi (0 : X ⟶ Y)).1 (by simp))
lemma of_mono_eq_zero {X Y : C} (f : X ⟶ Y) [mono f] (h : f = 0) : is_zero X :=
by { unfreezingI { subst h, }, apply of_mono_zero X Y, }
lemma of_epi_eq_zero {X Y : C} (f : X ⟶ Y) [epi f] (h : f = 0) : is_zero Y :=
by { unfreezingI { subst h, }, apply of_epi_zero X Y, }
lemma iff_is_split_mono_eq_zero {X Y : C} (f : X ⟶ Y) [is_split_mono f] : is_zero X ↔ f = 0 :=
begin
rw iff_id_eq_zero,
split,
{ intro h, rw [←category.id_comp f, h, zero_comp], },
{ intro h, rw [←is_split_mono.id f], simp [h], },
end
lemma iff_is_split_epi_eq_zero {X Y : C} (f : X ⟶ Y) [is_split_epi f] : is_zero Y ↔ f = 0 :=
begin
rw iff_id_eq_zero,
split,
{ intro h, rw [←category.comp_id f, h, comp_zero], },
{ intro h, rw [←is_split_epi.id f], simp [h], },
end
lemma of_mono {X Y : C} (f : X ⟶ Y) [mono f] (i : is_zero Y) : is_zero X :=
begin
unfreezingI { have hf := i.eq_zero_of_tgt f, subst hf, },
exact is_zero.of_mono_zero X Y,
end
lemma of_epi {X Y : C} (f : X ⟶ Y) [epi f] (i : is_zero X) : is_zero Y :=
begin
unfreezingI { have hf := i.eq_zero_of_src f, subst hf, },
exact is_zero.of_epi_zero X Y,
end
end is_zero
/-- A category with a zero object has zero morphisms.
It is rarely a good idea to use this. Many categories that have a zero object have zero
morphisms for some other reason, for example from additivity. Library code that uses
`zero_morphisms_of_zero_object` will then be incompatible with these categories because
the `has_zero_morphisms` instances will not be definitionally equal. For this reason library
code should generally ask for an instance of `has_zero_morphisms` separately, even if it already
asks for an instance of `has_zero_objects`. -/
def is_zero.has_zero_morphisms {O : C} (hO : is_zero O) : has_zero_morphisms C :=
{ has_zero := λ X Y,
{ zero := hO.from X ≫ hO.to Y },
zero_comp' := λ X Y Z f, by { rw category.assoc, congr, apply hO.eq_of_src, },
comp_zero' := λ X Y Z f, by { rw ←category.assoc, congr, apply hO.eq_of_tgt, }}
namespace has_zero_object
variables [has_zero_object C]
open_locale zero_object
/-- A category with a zero object has zero morphisms.
It is rarely a good idea to use this. Many categories that have a zero object have zero
morphisms for some other reason, for example from additivity. Library code that uses
`zero_morphisms_of_zero_object` will then be incompatible with these categories because
the `has_zero_morphisms` instances will not be definitionally equal. For this reason library
code should generally ask for an instance of `has_zero_morphisms` separately, even if it already
asks for an instance of `has_zero_objects`. -/
def zero_morphisms_of_zero_object : has_zero_morphisms C :=
{ has_zero := λ X Y,
{ zero := (default : X ⟶ 0) ≫ default },
zero_comp' := λ X Y Z f, by { dunfold has_zero.zero, rw category.assoc, congr, },
comp_zero' := λ X Y Z f, by { dunfold has_zero.zero, rw ←category.assoc, congr, }}
section has_zero_morphisms
variables [has_zero_morphisms C]
@[simp] lemma zero_iso_is_initial_hom {X : C} (t : is_initial X) :
(zero_iso_is_initial t).hom = 0 :=
by ext
@[simp] lemma zero_iso_is_initial_inv {X : C} (t : is_initial X) :
(zero_iso_is_initial t).inv = 0 :=
by ext
@[simp] lemma zero_iso_is_terminal_hom {X : C} (t : is_terminal X) :
(zero_iso_is_terminal t).hom = 0 :=
by ext
@[simp] lemma zero_iso_is_terminal_inv {X : C} (t : is_terminal X) :
(zero_iso_is_terminal t).inv = 0 :=
by ext
@[simp] lemma zero_iso_initial_hom [has_initial C] : zero_iso_initial.hom = (0 : 0 ⟶ ⊥_ C) :=
by ext
@[simp] lemma zero_iso_initial_inv [has_initial C] : zero_iso_initial.inv = (0 : ⊥_ C ⟶ 0) :=
by ext
@[simp] lemma zero_iso_terminal_hom [has_terminal C] : zero_iso_terminal.hom = (0 : 0 ⟶ ⊤_ C) :=
by ext
@[simp] lemma zero_iso_terminal_inv [has_terminal C] : zero_iso_terminal.inv = (0 : ⊤_ C ⟶ 0) :=
by ext
end has_zero_morphisms
open_locale zero_object
instance {B : Type*} [category B] : has_zero_object (B ⥤ C) :=
(((category_theory.functor.const B).obj (0 : C)).is_zero $ λ X, is_zero_zero _).has_zero_object
end has_zero_object
open_locale zero_object
variables {D}
@[simp] lemma is_zero.map [has_zero_object D] [has_zero_morphisms D] {F : C ⥤ D} (hF : is_zero F)
{X Y : C} (f : X ⟶ Y) : F.map f = 0 :=
(hF.obj _).eq_of_src _ _
@[simp] lemma _root_.category_theory.functor.zero_obj [has_zero_object D]
(X : C) : is_zero ((0 : C ⥤ D).obj X) :=
(is_zero_zero _).obj _
@[simp] lemma _root_.category_theory.zero_map [has_zero_object D] [has_zero_morphisms D]
{X Y : C} (f : X ⟶ Y) : (0 : C ⥤ D).map f = 0 :=
(is_zero_zero _).map _
section
variables [has_zero_object C] [has_zero_morphisms C]
open_locale zero_object
@[simp]
lemma id_zero : 𝟙 (0 : C) = (0 : 0 ⟶ 0) :=
by ext
/-- An arrow ending in the zero object is zero -/
-- This can't be a `simp` lemma because the left hand side would be a metavariable.
lemma zero_of_to_zero {X : C} (f : X ⟶ 0) : f = 0 :=
by ext
lemma zero_of_target_iso_zero {X Y : C} (f : X ⟶ Y) (i : Y ≅ 0) : f = 0 :=
begin
have h : f = f ≫ i.hom ≫ 𝟙 0 ≫ i.inv := by simp only [iso.hom_inv_id, id_comp, comp_id],
simpa using h,
end
/-- An arrow starting at the zero object is zero -/
lemma zero_of_from_zero {X : C} (f : 0 ⟶ X) : f = 0 :=
by ext
lemma zero_of_source_iso_zero {X Y : C} (f : X ⟶ Y) (i : X ≅ 0) : f = 0 :=
begin
have h : f = i.hom ≫ 𝟙 0 ≫ i.inv ≫ f := by simp only [iso.hom_inv_id_assoc, id_comp, comp_id],
simpa using h,
end
lemma zero_of_source_iso_zero' {X Y : C} (f : X ⟶ Y) (i : is_isomorphic X 0) : f = 0 :=
zero_of_source_iso_zero f (nonempty.some i)
lemma zero_of_target_iso_zero' {X Y : C} (f : X ⟶ Y) (i : is_isomorphic Y 0) : f = 0 :=
zero_of_target_iso_zero f (nonempty.some i)
lemma mono_of_source_iso_zero {X Y : C} (f : X ⟶ Y) (i : X ≅ 0) : mono f :=
⟨λ Z g h w, by rw [zero_of_target_iso_zero g i, zero_of_target_iso_zero h i]⟩
lemma epi_of_target_iso_zero {X Y : C} (f : X ⟶ Y) (i : Y ≅ 0) : epi f :=
⟨λ Z g h w, by rw [zero_of_source_iso_zero g i, zero_of_source_iso_zero h i]⟩
/--
An object `X` has `𝟙 X = 0` if and only if it is isomorphic to the zero object.
Because `X ≅ 0` contains data (even if a subsingleton), we express this `↔` as an `≃`.
-/
def id_zero_equiv_iso_zero (X : C) : (𝟙 X = 0) ≃ (X ≅ 0) :=
{ to_fun := λ h, { hom := 0, inv := 0, },
inv_fun := λ i, zero_of_target_iso_zero (𝟙 X) i,
left_inv := by tidy,
right_inv := by tidy, }
@[simp]
lemma id_zero_equiv_iso_zero_apply_hom (X : C) (h : 𝟙 X = 0) :
((id_zero_equiv_iso_zero X) h).hom = 0 := rfl
@[simp]
lemma id_zero_equiv_iso_zero_apply_inv (X : C) (h : 𝟙 X = 0) :
((id_zero_equiv_iso_zero X) h).inv = 0 := rfl
/-- If `0 : X ⟶ Y` is an monomorphism, then `X ≅ 0`. -/
@[simps]
def iso_zero_of_mono_zero {X Y : C} (h : mono (0 : X ⟶ Y)) : X ≅ 0 :=
{ hom := 0,
inv := 0,
hom_inv_id' := (cancel_mono (0 : X ⟶ Y)).mp (by simp) }
/-- If `0 : X ⟶ Y` is an epimorphism, then `Y ≅ 0`. -/
@[simps]
def iso_zero_of_epi_zero {X Y : C} (h : epi (0 : X ⟶ Y)) : Y ≅ 0 :=
{ hom := 0,
inv := 0,
hom_inv_id' := (cancel_epi (0 : X ⟶ Y)).mp (by simp) }
/-- If a monomorphism out of `X` is zero, then `X ≅ 0`. -/
def iso_zero_of_mono_eq_zero {X Y : C} {f : X ⟶ Y} [mono f] (h : f = 0) : X ≅ 0 :=
by { unfreezingI { subst h, }, apply iso_zero_of_mono_zero ‹_›, }
/-- If an epimorphism in to `Y` is zero, then `Y ≅ 0`. -/
def iso_zero_of_epi_eq_zero {X Y : C} {f : X ⟶ Y} [epi f] (h : f = 0) : Y ≅ 0 :=
by { unfreezingI { subst h, }, apply iso_zero_of_epi_zero ‹_›, }
/-- If an object `X` is isomorphic to 0, there's no need to use choice to construct
an explicit isomorphism: the zero morphism suffices. -/
def iso_of_is_isomorphic_zero {X : C} (P : is_isomorphic X 0) : X ≅ 0 :=
{ hom := 0,
inv := 0,
hom_inv_id' :=
begin
casesI P,
rw ←P.hom_inv_id,
rw ←category.id_comp P.inv,
simp,
end,
inv_hom_id' := by simp, }
end
section is_iso
variables [has_zero_morphisms C]
/--
A zero morphism `0 : X ⟶ Y` is an isomorphism if and only if
the identities on both `X` and `Y` are zero.
-/
@[simps]
def is_iso_zero_equiv (X Y : C) : is_iso (0 : X ⟶ Y) ≃ (𝟙 X = 0 ∧ 𝟙 Y = 0) :=
{ to_fun := by { introsI i, rw ←is_iso.hom_inv_id (0 : X ⟶ Y),
rw ←is_iso.inv_hom_id (0 : X ⟶ Y), simp },
inv_fun := λ h, ⟨⟨(0 : Y ⟶ X), by tidy⟩⟩,
left_inv := by tidy,
right_inv := by tidy, }
/--
A zero morphism `0 : X ⟶ X` is an isomorphism if and only if
the identity on `X` is zero.
-/
def is_iso_zero_self_equiv (X : C) : is_iso (0 : X ⟶ X) ≃ (𝟙 X = 0) :=
by simpa using is_iso_zero_equiv X X
variables [has_zero_object C]
open_locale zero_object
/--
A zero morphism `0 : X ⟶ Y` is an isomorphism if and only if
`X` and `Y` are isomorphic to the zero object.
-/
def is_iso_zero_equiv_iso_zero (X Y : C) : is_iso (0 : X ⟶ Y) ≃ (X ≅ 0) × (Y ≅ 0) :=
begin
-- This is lame, because `prod` can't cope with `Prop`, so we can't use `equiv.prod_congr`.
refine (is_iso_zero_equiv X Y).trans _,
symmetry,
fsplit,
{ rintros ⟨eX, eY⟩, fsplit,
exact (id_zero_equiv_iso_zero X).symm eX,
exact (id_zero_equiv_iso_zero Y).symm eY, },
{ rintros ⟨hX, hY⟩, fsplit,
exact (id_zero_equiv_iso_zero X) hX,
exact (id_zero_equiv_iso_zero Y) hY, },
{ tidy, },
{ tidy, },
end
lemma is_iso_of_source_target_iso_zero {X Y : C} (f : X ⟶ Y) (i : X ≅ 0) (j : Y ≅ 0) : is_iso f :=
begin
rw zero_of_source_iso_zero f i,
exact (is_iso_zero_equiv_iso_zero _ _).inv_fun ⟨i, j⟩,
end
/--
A zero morphism `0 : X ⟶ X` is an isomorphism if and only if
`X` is isomorphic to the zero object.
-/
def is_iso_zero_self_equiv_iso_zero (X : C) : is_iso (0 : X ⟶ X) ≃ (X ≅ 0) :=
(is_iso_zero_equiv_iso_zero X X).trans subsingleton_prod_self_equiv
end is_iso
/-- If there are zero morphisms, any initial object is a zero object. -/
lemma has_zero_object_of_has_initial_object
[has_zero_morphisms C] [has_initial C] : has_zero_object C :=
begin
refine ⟨⟨⊥_ C, λ X, ⟨⟨⟨0⟩, by tidy⟩⟩, λ X, ⟨⟨⟨0⟩, λ f, _⟩⟩⟩⟩,
calc
f = f ≫ 𝟙 _ : (category.comp_id _).symm
... = f ≫ 0 : by congr
... = 0 : has_zero_morphisms.comp_zero _ _
end
/-- If there are zero morphisms, any terminal object is a zero object. -/
lemma has_zero_object_of_has_terminal_object
[has_zero_morphisms C] [has_terminal C] : has_zero_object C :=
begin
refine ⟨⟨⊤_ C, λ X, ⟨⟨⟨0⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨0⟩, by tidy⟩⟩⟩⟩,
calc
f = 𝟙 _ ≫ f : (category.id_comp _).symm
... = 0 ≫ f : by congr
... = 0 : zero_comp
end
section image
variable [has_zero_morphisms C]
lemma image_ι_comp_eq_zero {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} [has_image f]
[epi (factor_thru_image f)] (h : f ≫ g = 0) : image.ι f ≫ g = 0 :=
zero_of_epi_comp (factor_thru_image f) $ by simp [h]
lemma comp_factor_thru_image_eq_zero {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} [has_image g]
(h : f ≫ g = 0) : f ≫ factor_thru_image g = 0 :=
zero_of_comp_mono (image.ι g) $ by simp [h]
variables [has_zero_object C]
open_locale zero_object
/--
The zero morphism has a `mono_factorisation` through the zero object.
-/
@[simps]
def mono_factorisation_zero (X Y : C) : mono_factorisation (0 : X ⟶ Y) :=
{ I := 0, m := 0, e := 0, }
/--
The factorisation through the zero object is an image factorisation.
-/
def image_factorisation_zero (X Y : C) : image_factorisation (0 : X ⟶ Y) :=
{ F := mono_factorisation_zero X Y,
is_image := { lift := λ F', 0 } }
instance has_image_zero {X Y : C} : has_image (0 : X ⟶ Y) :=
has_image.mk $ image_factorisation_zero _ _
/-- The image of a zero morphism is the zero object. -/
def image_zero {X Y : C} : image (0 : X ⟶ Y) ≅ 0 :=
is_image.iso_ext (image.is_image (0 : X ⟶ Y)) (image_factorisation_zero X Y).is_image
/-- The image of a morphism which is equal to zero is the zero object. -/
def image_zero' {X Y : C} {f : X ⟶ Y} (h : f = 0) [has_image f] : image f ≅ 0 :=
image.eq_to_iso h ≪≫ image_zero
@[simp]
lemma image.ι_zero {X Y : C} [has_image (0 : X ⟶ Y)] : image.ι (0 : X ⟶ Y) = 0 :=
begin
rw ←image.lift_fac (mono_factorisation_zero X Y),
simp,
end
/--
If we know `f = 0`,
it requires a little work to conclude `image.ι f = 0`,
because `f = g` only implies `image f ≅ image g`.
-/
@[simp]
lemma image.ι_zero' [has_equalizers C] {X Y : C} {f : X ⟶ Y} (h : f = 0) [has_image f] :
image.ι f = 0 :=
by { rw image.eq_fac h, simp }
end image
/-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/
instance is_split_mono_sigma_ι {β : Type u'} [has_zero_morphisms C] (f : β → C)
[has_colimit (discrete.functor f)] (b : β) : is_split_mono (sigma.ι f b) := is_split_mono.mk'
{ retraction := sigma.desc $ pi.single b (𝟙 _) }
/-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/
instance is_split_epi_pi_π {β : Type u'} [has_zero_morphisms C] (f : β → C)
[has_limit (discrete.functor f)] (b : β) : is_split_epi (pi.π f b) := is_split_epi.mk'
{ section_ := pi.lift $ pi.single b (𝟙 _) }
/-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/
instance is_split_mono_coprod_inl [has_zero_morphisms C] {X Y : C} [has_colimit (pair X Y)] :
is_split_mono (coprod.inl : X ⟶ X ⨿ Y) := is_split_mono.mk'
{ retraction := coprod.desc (𝟙 X) 0, }
/-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/
instance is_split_mono_coprod_inr [has_zero_morphisms C] {X Y : C} [has_colimit (pair X Y)] :
is_split_mono (coprod.inr : Y ⟶ X ⨿ Y) := is_split_mono.mk'
{ retraction := coprod.desc 0 (𝟙 Y), }
/-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/
instance is_split_epi_prod_fst [has_zero_morphisms C] {X Y : C} [has_limit (pair X Y)] :
is_split_epi (prod.fst : X ⨯ Y ⟶ X) := is_split_epi.mk'
{ section_ := prod.lift (𝟙 X) 0, }
/-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/
instance is_split_epi_prod_snd [has_zero_morphisms C] {X Y : C} [has_limit (pair X Y)] :
is_split_epi (prod.snd : X ⨯ Y ⟶ Y) := is_split_epi.mk'
{ section_ := prod.lift 0 (𝟙 Y), }
end category_theory.limits
|
d55444e149debaa73926b20abcb2c00fdcac2c05 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/topology/metric_space/gluing.lean | c73ed5095126e378e104b271a79d61481525f372 | [
"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 | 23,741 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.metric_space.isometry
/-!
# Metric space gluing
Gluing two metric spaces along a common subset. Formally, we are given
```
Φ
Z ---> X
|
|Ψ
v
Y
```
where `hΦ : isometry Φ` and `hΨ : isometry Ψ`.
We want to complete the square by a space `glue_space hΦ hΨ` and two isometries
`to_glue_l hΦ hΨ` and `to_glue_r hΦ hΨ` that make the square commute.
We start by defining a predistance on the disjoint union `X ⊕ Y`, for which
points `Φ p` and `Ψ p` are at distance 0. The (quotient) metric space associated
to this predistance is the desired space.
This is an instance of a more general construction, where `Φ` and `Ψ` do not have to be isometries,
but the distances in the image almost coincide, up to `2ε` say. Then one can almost glue the two
spaces so that the images of a point under `Φ` and `Ψ` are `ε`-close. If `ε > 0`, this yields a
metric space structure on `X ⊕ Y`, without the need to take a quotient. In particular, when `X`
and `Y` are inhabited, this gives a natural metric space structure on `X ⊕ Y`, where the basepoints
are at distance 1, say, and the distances between other points are obtained by going through the two
basepoints.
We also define the inductive limit of metric spaces. Given
```
f 0 f 1 f 2 f 3
X 0 -----> X 1 -----> X 2 -----> X 3 -----> ...
```
where the `X n` are metric spaces and `f n` isometric embeddings, we define the inductive
limit of the `X n`, also known as the increasing union of the `X n` in this context, if we
identify `X n` and `X (n+1)` through `f n`. This is a metric space in which all `X n` embed
isometrically and in a way compatible with `f n`.
-/
noncomputable theory
universes u v w
open function set
open_locale uniformity
namespace metric
section approx_gluing
variables {X : Type u} {Y : Type v} {Z : Type w}
variables [metric_space X] [metric_space Y]
{Φ : Z → X} {Ψ : Z → Y} {ε : ℝ}
open sum (inl inr)
/-- Define a predistance on `X ⊕ Y`, for which `Φ p` and `Ψ p` are at distance `ε` -/
def glue_dist (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) : X ⊕ Y → X ⊕ Y → ℝ
| (inl x) (inl y) := dist x y
| (inr x) (inr y) := dist x y
| (inl x) (inr y) := (⨅ p, dist x (Φ p) + dist y (Ψ p)) + ε
| (inr x) (inl y) := (⨅ p, dist y (Φ p) + dist x (Ψ p)) + ε
private lemma glue_dist_self (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) : ∀ x, glue_dist Φ Ψ ε x x = 0
| (inl x) := dist_self _
| (inr x) := dist_self _
lemma glue_dist_glued_points [nonempty Z] (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) (p : Z) :
glue_dist Φ Ψ ε (inl (Φ p)) (inr (Ψ p)) = ε :=
begin
have : (⨅ q, dist (Φ p) (Φ q) + dist (Ψ p) (Ψ q)) = 0,
{ have A : ∀ q, 0 ≤ dist (Φ p) (Φ q) + dist (Ψ p) (Ψ q) :=
λq, by rw ← add_zero (0 : ℝ); exact add_le_add dist_nonneg dist_nonneg,
refine le_antisymm _ (le_cinfi A),
have : 0 = dist (Φ p) (Φ p) + dist (Ψ p) (Ψ p), by simp,
rw this,
exact cinfi_le ⟨0, forall_range_iff.2 A⟩ p },
rw [glue_dist, this, zero_add]
end
private lemma glue_dist_comm (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) :
∀ x y, glue_dist Φ Ψ ε x y = glue_dist Φ Ψ ε y x
| (inl x) (inl y) := dist_comm _ _
| (inr x) (inr y) := dist_comm _ _
| (inl x) (inr y) := rfl
| (inr x) (inl y) := rfl
variable [nonempty Z]
private lemma glue_dist_triangle (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ)
(H : ∀ p q, abs (dist (Φ p) (Φ q) - dist (Ψ p) (Ψ q)) ≤ 2 * ε) :
∀ x y z, glue_dist Φ Ψ ε x z ≤ glue_dist Φ Ψ ε x y + glue_dist Φ Ψ ε y z
| (inl x) (inl y) (inl z) := dist_triangle _ _ _
| (inr x) (inr y) (inr z) := dist_triangle _ _ _
| (inr x) (inl y) (inl z) := begin
have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) :=
λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩,
unfold glue_dist,
have : (⨅ p, dist z (Φ p) + dist x (Ψ p)) ≤ (⨅ p, dist y (Φ p) + dist x (Ψ p)) + dist y z,
{ have : (⨅ p, dist y (Φ p) + dist x (Ψ p)) + dist y z =
infi ((λt, t + dist y z) ∘ (λp, dist y (Φ p) + dist x (Ψ p))),
{ refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _
(B _ _),
intros x y hx, simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (λp, _),
calc
dist z (Φ p) + dist x (Ψ p) ≤ (dist y z + dist y (Φ p)) + dist x (Ψ p) :
add_le_add (dist_triangle_left _ _ _) (le_refl _)
... = dist y (Φ p) + dist x (Ψ p) + dist y z : by ring },
linarith
end
| (inr x) (inr y) (inl z) := begin
have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) :=
λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩,
unfold glue_dist,
have : (⨅ p, dist z (Φ p) + dist x (Ψ p)) ≤ dist x y + ⨅ p, dist z (Φ p) + dist y (Ψ p),
{ have : dist x y + (⨅ p, dist z (Φ p) + dist y (Ψ p)) =
infi ((λt, dist x y + t) ∘ (λp, dist z (Φ p) + dist y (Ψ p))),
{ refine map_cinfi_of_continuous_at_of_monotone (continuous_at_const.add continuous_at_id) _
(B _ _),
intros x y hx, simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (λp, _),
calc
dist z (Φ p) + dist x (Ψ p) ≤ dist z (Φ p) + (dist x y + dist y (Ψ p)) :
add_le_add (le_refl _) (dist_triangle _ _ _)
... = dist x y + (dist z (Φ p) + dist y (Ψ p)) : by ring },
linarith
end
| (inl x) (inl y) (inr z) := begin
have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) :=
λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩,
unfold glue_dist,
have : (⨅ p, dist x (Φ p) + dist z (Ψ p)) ≤ dist x y + ⨅ p, dist y (Φ p) + dist z (Ψ p),
{ have : dist x y + (⨅ p, dist y (Φ p) + dist z (Ψ p)) =
infi ((λt, dist x y + t) ∘ (λp, dist y (Φ p) + dist z (Ψ p))),
{ refine map_cinfi_of_continuous_at_of_monotone (continuous_at_const.add continuous_at_id) _
(B _ _),
intros x y hx, simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (λp, _),
calc
dist x (Φ p) + dist z (Ψ p) ≤ (dist x y + dist y (Φ p)) + dist z (Ψ p) :
add_le_add (dist_triangle _ _ _) (le_refl _)
... = dist x y + (dist y (Φ p) + dist z (Ψ p)) : by ring },
linarith
end
| (inl x) (inr y) (inr z) := begin
have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) :=
λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩,
unfold glue_dist,
have : (⨅ p, dist x (Φ p) + dist z (Ψ p)) ≤ (⨅ p, dist x (Φ p) + dist y (Ψ p)) + dist y z,
{ have : (⨅ p, dist x (Φ p) + dist y (Ψ p)) + dist y z =
infi ((λt, t + dist y z) ∘ (λp, dist x (Φ p) + dist y (Ψ p))),
{ refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _
(B _ _),
intros x y hx, simpa },
rw [this, comp],
refine cinfi_le_cinfi (B _ _) (λp, _),
calc
dist x (Φ p) + dist z (Ψ p) ≤ dist x (Φ p) + (dist y z + dist y (Ψ p)) :
add_le_add (le_refl _) (dist_triangle_left _ _ _)
... = dist x (Φ p) + dist y (Ψ p) + dist y z : by ring },
linarith
end
| (inl x) (inr y) (inl z) := le_of_forall_pos_le_add $ λδ δpos, begin
obtain ⟨p, hp⟩ : ∃ p, dist x (Φ p) + dist y (Ψ p) < (⨅ p, dist x (Φ p) + dist y (Ψ p)) + δ / 2,
from exists_lt_of_cinfi_lt (by linarith),
obtain ⟨q, hq⟩ : ∃ q, dist z (Φ q) + dist y (Ψ q) < (⨅ p, dist z (Φ p) + dist y (Ψ p)) + δ / 2,
from exists_lt_of_cinfi_lt (by linarith),
have : dist (Φ p) (Φ q) ≤ dist (Ψ p) (Ψ q) + 2 * ε,
{ have := le_trans (le_abs_self _) (H p q), by linarith },
calc dist x z ≤ dist x (Φ p) + dist (Φ p) (Φ q) + dist (Φ q) z : dist_triangle4 _ _ _ _
... ≤ dist x (Φ p) + dist (Ψ p) (Ψ q) + dist z (Φ q) + 2 * ε : by rw [dist_comm z]; linarith
... ≤ dist x (Φ p) + (dist y (Ψ p) + dist y (Ψ q)) + dist z (Φ q) + 2 * ε :
add_le_add (add_le_add (add_le_add (le_refl _) (dist_triangle_left _ _ _)) le_rfl) le_rfl
... ≤ ((⨅ p, dist x (Φ p) + dist y (Ψ p)) + ε) +
((⨅ p, dist z (Φ p) + dist y (Ψ p)) + ε) + δ : by linarith
end
| (inr x) (inl y) (inr z) := le_of_forall_pos_le_add $ λδ δpos, begin
obtain ⟨p, hp⟩ : ∃ p, dist y (Φ p) + dist x (Ψ p) < (⨅ p, dist y (Φ p) + dist x (Ψ p)) + δ / 2,
from exists_lt_of_cinfi_lt (by linarith),
obtain ⟨q, hq⟩ : ∃ q, dist y (Φ q) + dist z (Ψ q) < (⨅ p, dist y (Φ p) + dist z (Ψ p)) + δ / 2,
from exists_lt_of_cinfi_lt (by linarith),
have : dist (Ψ p) (Ψ q) ≤ dist (Φ p) (Φ q) + 2 * ε,
{ have := le_trans (neg_le_abs_self _) (H p q), by linarith },
calc dist x z ≤ dist x (Ψ p) + dist (Ψ p) (Ψ q) + dist (Ψ q) z : dist_triangle4 _ _ _ _
... ≤ dist x (Ψ p) + dist (Φ p) (Φ q) + dist z (Ψ q) + 2 * ε : by rw [dist_comm z]; linarith
... ≤ dist x (Ψ p) + (dist y (Φ p) + dist y (Φ q)) + dist z (Ψ q) + 2 * ε :
add_le_add (add_le_add (add_le_add le_rfl (dist_triangle_left _ _ _)) le_rfl) le_rfl
... ≤ ((⨅ p, dist y (Φ p) + dist x (Ψ p)) + ε) +
((⨅ p, dist y (Φ p) + dist z (Ψ p)) + ε) + δ : by linarith
end
private lemma glue_eq_of_dist_eq_zero (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) (ε0 : 0 < ε) :
∀ p q : X ⊕ Y, glue_dist Φ Ψ ε p q = 0 → p = q
| (inl x) (inl y) h := by rw eq_of_dist_eq_zero h
| (inl x) (inr y) h := begin
have : 0 ≤ (⨅ p, dist x (Φ p) + dist y (Ψ p)) :=
le_cinfi (λp, by simpa using add_le_add (@dist_nonneg _ _ x _) (@dist_nonneg _ _ y _)),
have : 0 + ε ≤ glue_dist Φ Ψ ε (inl x) (inr y) := add_le_add this (le_refl ε),
exfalso,
linarith
end
| (inr x) (inl y) h := begin
have : 0 ≤ ⨅ p, dist y (Φ p) + dist x (Ψ p) :=
le_cinfi (λp, by simpa [add_comm]
using add_le_add (@dist_nonneg _ _ x _) (@dist_nonneg _ _ y _)),
have : 0 + ε ≤ glue_dist Φ Ψ ε (inr x) (inl y) := add_le_add this (le_refl ε),
exfalso,
linarith
end
| (inr x) (inr y) h := by rw eq_of_dist_eq_zero h
/-- Given two maps `Φ` and `Ψ` intro metric spaces `X` and `Y` such that the distances between
`Φ p` and `Φ q`, and between `Ψ p` and `Ψ q`, coincide up to `2 ε` where `ε > 0`, one can almost
glue the two spaces `X` and `Y` along the images of `Φ` and `Ψ`, so that `Φ p` and `Ψ p` are
at distance `ε`. -/
def glue_metric_approx (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) (ε0 : 0 < ε)
(H : ∀ p q, abs (dist (Φ p) (Φ q) - dist (Ψ p) (Ψ q)) ≤ 2 * ε) : metric_space (X ⊕ Y) :=
{ dist := glue_dist Φ Ψ ε,
dist_self := glue_dist_self Φ Ψ ε,
dist_comm := glue_dist_comm Φ Ψ ε,
dist_triangle := glue_dist_triangle Φ Ψ ε H,
eq_of_dist_eq_zero := glue_eq_of_dist_eq_zero Φ Ψ ε ε0 }
end approx_gluing
section sum
/- A particular case of the previous construction is when one uses basepoints in `X` and `Y` and one
glues only along the basepoints, putting them at distance 1. We give a direct definition of
the distance, without infi, as it is easier to use in applications, and show that it is equal to
the gluing distance defined above to take advantage of the lemmas we have already proved. -/
variables {X : Type u} {Y : Type v} {Z : Type w}
variables [metric_space X] [metric_space Y] [inhabited X] [inhabited Y]
open sum (inl inr)
/-- Distance on a disjoint union. There are many (noncanonical) ways to put a distance compatible
with each factor.
If the two spaces are bounded, one can say for instance that each point in the first is at distance
`diam X + diam Y + 1` of each point in the second.
Instead, we choose a construction that works for unbounded spaces, but requires basepoints.
We embed isometrically each factor, set the basepoints at distance 1,
arbitrarily, and say that the distance from `a` to `b` is the sum of the distances of `a` and `b` to
their respective basepoints, plus the distance 1 between the basepoints.
Since there is an arbitrary choice in this construction, it is not an instance by default. -/
def sum.dist : X ⊕ Y → X ⊕ Y → ℝ
| (inl a) (inl a') := dist a a'
| (inr b) (inr b') := dist b b'
| (inl a) (inr b) := dist a (default X) + 1 + dist (default Y) b
| (inr b) (inl a) := dist b (default Y) + 1 + dist (default X) a
lemma sum.dist_eq_glue_dist {p q : X ⊕ Y} :
sum.dist p q = glue_dist (λ_ : unit, default X) (λ_ : unit, default Y) 1 p q :=
by cases p; cases q; refl <|> simp [sum.dist, glue_dist, dist_comm, add_comm, add_left_comm]
private lemma sum.dist_comm (x y : X ⊕ Y) : sum.dist x y = sum.dist y x :=
by cases x; cases y; simp only [sum.dist, dist_comm, add_comm, add_left_comm]
lemma sum.one_dist_le {x : X} {y : Y} : 1 ≤ sum.dist (inl x) (inr y) :=
le_trans (le_add_of_nonneg_right dist_nonneg) $
add_le_add_right (le_add_of_nonneg_left dist_nonneg) _
lemma sum.one_dist_le' {x : X} {y : Y} : 1 ≤ sum.dist (inr y) (inl x) :=
by rw sum.dist_comm; exact sum.one_dist_le
private lemma sum.mem_uniformity (s : set ((X ⊕ Y) × (X ⊕ Y))) :
s ∈ 𝓤 (X ⊕ Y) ↔ ∃ ε > 0, ∀ a b, sum.dist a b < ε → (a, b) ∈ s :=
begin
split,
{ rintro ⟨hsX, hsY⟩,
rcases mem_uniformity_dist.1 hsX with ⟨εX, εX0, hX⟩,
rcases mem_uniformity_dist.1 hsY with ⟨εY, εY0, hY⟩,
refine ⟨min (min εX εY) 1, lt_min (lt_min εX0 εY0) zero_lt_one, _⟩,
rintro (a|a) (b|b) h,
{ exact hX (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_left _ _))) },
{ cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le },
{ cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le' },
{ exact hY (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_right _ _))) } },
{ rintro ⟨ε, ε0, H⟩,
split; rw [filter.mem_sets, filter.mem_map, mem_uniformity_dist];
exact ⟨ε, ε0, λ x y h, H _ _ (by exact h)⟩ }
end
/-- The distance on the disjoint union indeed defines a metric space. All the distance properties
follow from our choice of the distance. The harder work is to show that the uniform structure
defined by the distance coincides with the disjoint union uniform structure. -/
def metric_space_sum : metric_space (X ⊕ Y) :=
{ dist := sum.dist,
dist_self := λx, by cases x; simp only [sum.dist, dist_self],
dist_comm := sum.dist_comm,
dist_triangle := λp q r,
by simp only [dist, sum.dist_eq_glue_dist]; exact glue_dist_triangle _ _ _ (by norm_num) _ _ _,
eq_of_dist_eq_zero := λp q,
by simp only [dist, sum.dist_eq_glue_dist]; exact glue_eq_of_dist_eq_zero _ _ _ zero_lt_one _ _,
to_uniform_space := sum.uniform_space,
uniformity_dist := uniformity_dist_of_mem_uniformity _ _ sum.mem_uniformity }
local attribute [instance] metric_space_sum
lemma sum.dist_eq {x y : X ⊕ Y} : dist x y = sum.dist x y := rfl
/-- The left injection of a space in a disjoint union in an isometry -/
lemma isometry_on_inl : isometry (sum.inl : X → (X ⊕ Y)) :=
isometry_emetric_iff_metric.2 $ λx y, rfl
/-- The right injection of a space in a disjoint union in an isometry -/
lemma isometry_on_inr : isometry (sum.inr : Y → (X ⊕ Y)) :=
isometry_emetric_iff_metric.2 $ λx y, rfl
end sum
section gluing
/- Exact gluing of two metric spaces along isometric subsets. -/
variables {X : Type u} {Y : Type v} {Z : Type w}
variables [nonempty Z] [metric_space Z] [metric_space X] [metric_space Y]
{Φ : Z → X} {Ψ : Z → Y} {ε : ℝ}
open sum (inl inr)
local attribute [instance] pseudo_metric.dist_setoid
/-- Given two isometric embeddings `Φ : Z → X` and `Ψ : Z → Y`, we define a pseudo metric space
structure on `X ⊕ Y` by declaring that `Φ x` and `Ψ x` are at distance `0`. -/
def glue_premetric (hΦ : isometry Φ) (hΨ : isometry Ψ) : pseudo_metric_space (X ⊕ Y) :=
{ dist := glue_dist Φ Ψ 0,
dist_self := glue_dist_self Φ Ψ 0,
dist_comm := glue_dist_comm Φ Ψ 0,
dist_triangle := glue_dist_triangle Φ Ψ 0 $ λp q, by rw [hΦ.dist_eq, hΨ.dist_eq]; simp }
/-- Given two isometric embeddings `Φ : Z → X` and `Ψ : Z → Y`, we define a
space `glue_space hΦ hΨ` by identifying in `X ⊕ Y` the points `Φ x` and `Ψ x`. -/
def glue_space (hΦ : isometry Φ) (hΨ : isometry Ψ) : Type* :=
@pseudo_metric_quot _ (glue_premetric hΦ hΨ)
instance metric_space_glue_space (hΦ : isometry Φ) (hΨ : isometry Ψ) :
metric_space (glue_space hΦ hΨ) :=
@metric_space_quot _ (glue_premetric hΦ hΨ)
/-- The canonical map from `X` to the space obtained by gluing isometric subsets in `X` and `Y`. -/
def to_glue_l (hΦ : isometry Φ) (hΨ : isometry Ψ) (x : X) : glue_space hΦ hΨ :=
by letI : pseudo_metric_space (X ⊕ Y) := glue_premetric hΦ hΨ; exact ⟦inl x⟧
/-- The canonical map from `Y` to the space obtained by gluing isometric subsets in `X` and `Y`. -/
def to_glue_r (hΦ : isometry Φ) (hΨ : isometry Ψ) (y : Y) : glue_space hΦ hΨ :=
by letI : pseudo_metric_space (X ⊕ Y) := glue_premetric hΦ hΨ; exact ⟦inr y⟧
instance inhabited_left (hΦ : isometry Φ) (hΨ : isometry Ψ) [inhabited X] :
inhabited (glue_space hΦ hΨ) :=
⟨to_glue_l _ _ (default _)⟩
instance inhabited_right (hΦ : isometry Φ) (hΨ : isometry Ψ) [inhabited Y] :
inhabited (glue_space hΦ hΨ) :=
⟨to_glue_r _ _ (default _)⟩
lemma to_glue_commute (hΦ : isometry Φ) (hΨ : isometry Ψ) :
(to_glue_l hΦ hΨ) ∘ Φ = (to_glue_r hΦ hΨ) ∘ Ψ :=
begin
letI : pseudo_metric_space (X ⊕ Y) := glue_premetric hΦ hΨ,
funext,
simp only [comp, to_glue_l, to_glue_r, quotient.eq],
exact glue_dist_glued_points Φ Ψ 0 x
end
lemma to_glue_l_isometry (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_l hΦ hΨ) :=
isometry_emetric_iff_metric.2 $ λ_ _, rfl
lemma to_glue_r_isometry (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_r hΦ hΨ) :=
isometry_emetric_iff_metric.2 $ λ_ _, rfl
end gluing --section
section inductive_limit
/- In this section, we define the inductive limit of
f 0 f 1 f 2 f 3
X 0 -----> X 1 -----> X 2 -----> X 3 -----> ...
where the X n are metric spaces and f n isometric embeddings. We do it by defining a premetric
space structure on Σ n, X n, where the predistance dist x y is obtained by pushing x and y in a
common X k using composition by the f n, and taking the distance there. This does not depend on
the choice of k as the f n are isometries. The metric space associated to this premetric space
is the desired inductive limit.-/
open nat
variables {X : ℕ → Type u} [∀ n, metric_space (X n)] {f : Π n, X n → X (n+1)}
/-- Predistance on the disjoint union `Σ n, X n`. -/
def inductive_limit_dist (f : Π n, X n → X (n+1)) (x y : Σ n, X n) : ℝ :=
dist (le_rec_on (le_max_left x.1 y.1) f x.2 : X (max x.1 y.1))
(le_rec_on (le_max_right x.1 y.1) f y.2 : X (max x.1 y.1))
/-- The predistance on the disjoint union `Σ n, X n` can be computed in any `X k` for large
enough `k`. -/
lemma inductive_limit_dist_eq_dist (I : ∀ n, isometry (f n))
(x y : Σ n, X n) (m : ℕ) : ∀ hx : x.1 ≤ m, ∀ hy : y.1 ≤ m,
inductive_limit_dist f x y = dist (le_rec_on hx f x.2 : X m) (le_rec_on hy f y.2 : X m) :=
begin
induction m with m hm,
{ assume hx hy,
have A : max x.1 y.1 = 0, { rw [nonpos_iff_eq_zero.1 hx, nonpos_iff_eq_zero.1 hy], simp },
unfold inductive_limit_dist,
congr; simp only [A] },
{ assume hx hy,
by_cases h : max x.1 y.1 = m.succ,
{ unfold inductive_limit_dist,
congr; simp only [h] },
{ have : max x.1 y.1 ≤ succ m := by simp [hx, hy],
have : max x.1 y.1 ≤ m := by simpa [h] using of_le_succ this,
have xm : x.1 ≤ m := le_trans (le_max_left _ _) this,
have ym : y.1 ≤ m := le_trans (le_max_right _ _) this,
rw [le_rec_on_succ xm, le_rec_on_succ ym, (I m).dist_eq],
exact hm xm ym }}
end
/-- Premetric space structure on `Σ n, X n`.-/
def inductive_premetric (I : ∀ n, isometry (f n)) :
pseudo_metric_space (Σ n, X n) :=
{ dist := inductive_limit_dist f,
dist_self := λx, by simp [dist, inductive_limit_dist],
dist_comm := λx y, begin
let m := max x.1 y.1,
have hx : x.1 ≤ m := le_max_left _ _,
have hy : y.1 ≤ m := le_max_right _ _,
unfold dist,
rw [inductive_limit_dist_eq_dist I x y m hx hy, inductive_limit_dist_eq_dist I y x m hy hx,
dist_comm]
end,
dist_triangle := λx y z, begin
let m := max (max x.1 y.1) z.1,
have hx : x.1 ≤ m := le_trans (le_max_left _ _) (le_max_left _ _),
have hy : y.1 ≤ m := le_trans (le_max_right _ _) (le_max_left _ _),
have hz : z.1 ≤ m := le_max_right _ _,
calc inductive_limit_dist f x z
= dist (le_rec_on hx f x.2 : X m) (le_rec_on hz f z.2 : X m) :
inductive_limit_dist_eq_dist I x z m hx hz
... ≤ dist (le_rec_on hx f x.2 : X m) (le_rec_on hy f y.2 : X m)
+ dist (le_rec_on hy f y.2 : X m) (le_rec_on hz f z.2 : X m) :
dist_triangle _ _ _
... = inductive_limit_dist f x y + inductive_limit_dist f y z :
by rw [inductive_limit_dist_eq_dist I x y m hx hy,
inductive_limit_dist_eq_dist I y z m hy hz]
end }
local attribute [instance] inductive_premetric pseudo_metric.dist_setoid
/-- The type giving the inductive limit in a metric space context. -/
def inductive_limit (I : ∀ n, isometry (f n)) : Type* :=
@pseudo_metric_quot _ (inductive_premetric I)
/-- Metric space structure on the inductive limit. -/
instance metric_space_inductive_limit (I : ∀ n, isometry (f n)) :
metric_space (inductive_limit I) :=
@metric_space_quot _ (inductive_premetric I)
/-- Mapping each `X n` to the inductive limit. -/
def to_inductive_limit (I : ∀ n, isometry (f n)) (n : ℕ) (x : X n) : metric.inductive_limit I :=
by letI : pseudo_metric_space (Σ n, X n) := inductive_premetric I; exact ⟦sigma.mk n x⟧
instance (I : ∀ n, isometry (f n)) [inhabited (X 0)] : inhabited (inductive_limit I) :=
⟨to_inductive_limit _ 0 (default _)⟩
/-- The map `to_inductive_limit n` mapping `X n` to the inductive limit is an isometry. -/
lemma to_inductive_limit_isometry (I : ∀ n, isometry (f n)) (n : ℕ) :
isometry (to_inductive_limit I n) := isometry_emetric_iff_metric.2 $ λx y,
begin
change inductive_limit_dist f ⟨n, x⟩ ⟨n, y⟩ = dist x y,
rw [inductive_limit_dist_eq_dist I ⟨n, x⟩ ⟨n, y⟩ n (le_refl n) (le_refl n),
le_rec_on_self, le_rec_on_self]
end
/-- The maps `to_inductive_limit n` are compatible with the maps `f n`. -/
lemma to_inductive_limit_commute (I : ∀ n, isometry (f n)) (n : ℕ) :
(to_inductive_limit I n.succ) ∘ (f n) = to_inductive_limit I n :=
begin
funext,
simp only [comp, to_inductive_limit, quotient.eq],
show inductive_limit_dist f ⟨n.succ, f n x⟩ ⟨n, x⟩ = 0,
{ rw [inductive_limit_dist_eq_dist I ⟨n.succ, f n x⟩ ⟨n, x⟩ n.succ,
le_rec_on_self, le_rec_on_succ, le_rec_on_self, dist_self],
exact le_refl _,
exact le_refl _,
exact le_succ _ }
end
end inductive_limit --section
end metric --namespace
|
1db0370e1bf212b2a6e238a1684862ee6bcb3f96 | 367134ba5a65885e863bdc4507601606690974c1 | /src/field_theory/splitting_field.lean | 96e0501f876979f4bea76b78ce651627ce0ce230 | [
"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 | 35,919 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
Definition of splitting fields, and definition of homomorphism into any field that splits
-/
import ring_theory.adjoin_root
import ring_theory.algebra_tower
import ring_theory.algebraic
import ring_theory.polynomial
import field_theory.minpoly
import linear_algebra.finite_dimensional
import tactic.field_simp
noncomputable theory
open_locale classical big_operators
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
namespace polynomial
variables [field α] [field β] [field γ]
open polynomial
section splits
variables (i : α →+* β)
/-- A polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1. -/
def splits (f : polynomial α) : Prop :=
f = 0 ∨ ∀ {g : polynomial β}, irreducible g → g ∣ f.map i → degree g = 1
@[simp] lemma splits_zero : splits i (0 : polynomial α) := or.inl rfl
@[simp] lemma splits_C (a : α) : splits i (C a) :=
if ha : a = 0 then ha.symm ▸ (@C_0 α _).symm ▸ splits_zero i
else
have hia : i a ≠ 0, from mt ((is_add_group_hom.injective_iff i).1
i.injective _) ha,
or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 (not_not.2 (is_unit_iff_degree_eq_zero.2 $
by have := congr_arg degree hp;
simp [degree_C hia, @eq_comm (with_bot ℕ) 0,
nat.with_bot.add_eq_zero_iff] at this; clear _fun_match; tauto))
lemma splits_of_degree_eq_one {f : polynomial α} (hf : degree f = 1) : splits i f :=
or.inr $ λ g hg ⟨p, hp⟩,
by have := congr_arg degree hp;
simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1,
mt is_unit_iff_degree_eq_zero.2 hg.1] at this;
clear _fun_match; tauto
lemma splits_of_degree_le_one {f : polynomial α} (hf : degree f ≤ 1) : splits i f :=
begin
cases h : degree f with n,
{ rw [degree_eq_bot.1 h]; exact splits_zero i },
{ cases n with n,
{ rw [eq_C_of_degree_le_zero (trans_rel_right (≤) h (le_refl _))];
exact splits_C _ _ },
{ have hn : n = 0,
{ rw h at hf,
cases n, { refl }, { exact absurd hf dec_trivial } },
exact splits_of_degree_eq_one _ (by rw [h, hn]; refl) } }
end
lemma splits_of_nat_degree_le_one {f : polynomial α} (hf : nat_degree f ≤ 1) : splits i f :=
splits_of_degree_le_one i (degree_le_of_nat_degree_le hf)
lemma splits_of_nat_degree_eq_one {f : polynomial α} (hf : nat_degree f = 1) : splits i f :=
splits_of_nat_degree_le_one i (le_of_eq hf)
lemma splits_mul {f g : polynomial α} (hf : splits i f) (hg : splits i g) : splits i (f * g) :=
if h : f * g = 0 then by simp [h]
else or.inr $ λ p hp hpf, ((principal_ideal_ring.irreducible_iff_prime.1 hp).2.2 _ _
(show p ∣ map i f * map i g, by convert hpf; rw polynomial.map_mul)).elim
(hf.resolve_left (λ hf, by simpa [hf] using h) hp)
(hg.resolve_left (λ hg, by simpa [hg] using h) hp)
lemma splits_of_splits_mul {f g : polynomial α} (hfg : f * g ≠ 0) (h : splits i (f * g)) :
splits i f ∧ splits i g :=
⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi
(by rw map_mul; exact dvd.trans hg (dvd_mul_right _ _)),
or.inr $ λ g hgi hg, or.resolve_left h hfg hgi
(by rw map_mul; exact dvd.trans hg (dvd_mul_left _ _))⟩
lemma splits_of_splits_of_dvd {f g : polynomial α} (hf0 : f ≠ 0) (hf : splits i f) (hgf : g ∣ f) :
splits i g :=
by { obtain ⟨f, rfl⟩ := hgf, exact (splits_of_splits_mul i hf0 hf).1 }
lemma splits_of_splits_gcd_left {f g : polynomial α} (hf0 : f ≠ 0) (hf : splits i f) :
splits i (euclidean_domain.gcd f g) :=
polynomial.splits_of_splits_of_dvd i hf0 hf (euclidean_domain.gcd_dvd_left f g)
lemma splits_of_splits_gcd_right {f g : polynomial α} (hg0 : g ≠ 0) (hg : splits i g) :
splits i (euclidean_domain.gcd f g) :=
polynomial.splits_of_splits_of_dvd i hg0 hg (euclidean_domain.gcd_dvd_right f g)
lemma splits_map_iff (j : β →+* γ) {f : polynomial α} :
splits j (f.map i) ↔ splits (j.comp i) f :=
by simp [splits, polynomial.map_map]
theorem splits_one : splits i 1 :=
splits_C i 1
theorem splits_of_is_unit {u : polynomial α} (hu : is_unit u) : u.splits i :=
splits_of_splits_of_dvd i one_ne_zero (splits_one _) $ is_unit_iff_dvd_one.1 hu
theorem splits_X_sub_C {x : α} : (X - C x).splits i :=
splits_of_degree_eq_one _ $ degree_X_sub_C x
theorem splits_X : X.splits i :=
splits_of_degree_eq_one _ $ degree_X
theorem splits_id_iff_splits {f : polynomial α} :
(f.map i).splits (ring_hom.id β) ↔ f.splits i :=
by rw [splits_map_iff, ring_hom.id_comp]
theorem splits_mul_iff {f g : polynomial α} (hf : f ≠ 0) (hg : g ≠ 0) :
(f * g).splits i ↔ f.splits i ∧ g.splits i :=
⟨splits_of_splits_mul i (mul_ne_zero hf hg), λ ⟨hfs, hgs⟩, splits_mul i hfs hgs⟩
theorem splits_prod {ι : Type w} {s : ι → polynomial α} {t : finset ι} :
(∀ j ∈ t, (s j).splits i) → (∏ x in t, s x).splits i :=
begin
refine finset.induction_on t (λ _, splits_one i) (λ a t hat ih ht, _),
rw finset.forall_mem_insert at ht, rw finset.prod_insert hat,
exact splits_mul i ht.1 (ih ht.2)
end
lemma splits_pow {f : polynomial α} (hf : f.splits i) (n : ℕ) : (f ^ n).splits i :=
begin
rw [←finset.card_range n, ←finset.prod_const],
exact splits_prod i (λ j hj, hf),
end
lemma splits_X_pow (n : ℕ) : (X ^ n).splits i := splits_pow i (splits_X i) n
theorem splits_prod_iff {ι : Type w} {s : ι → polynomial α} {t : finset ι} :
(∀ j ∈ t, s j ≠ 0) → ((∏ x in t, s x).splits i ↔ ∀ j ∈ t, (s j).splits i) :=
begin
refine finset.induction_on t (λ _, ⟨λ _ _ h, h.elim, λ _, splits_one i⟩) (λ a t hat ih ht, _),
rw finset.forall_mem_insert at ht ⊢,
rw [finset.prod_insert hat, splits_mul_iff i ht.1 (finset.prod_ne_zero_iff.2 ht.2), ih ht.2]
end
lemma degree_eq_one_of_irreducible_of_splits {p : polynomial β}
(h_nz : p ≠ 0) (hp : irreducible p) (hp_splits : splits (ring_hom.id β) p) :
p.degree = 1 :=
begin
rcases hp_splits,
{ contradiction },
{ apply hp_splits hp, simp }
end
lemma exists_root_of_splits {f : polynomial α} (hs : splits i f) (hf0 : degree f ≠ 0) :
∃ x, eval₂ i x f = 0 :=
if hf0 : f = 0 then ⟨37, by simp [hf0]⟩
else
let ⟨g, hg⟩ := wf_dvd_monoid.exists_irreducible_factor
(show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 (by rwa degree_map))
(map_ne_zero hf0) in
let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0 hg.1 hg.2) in
let ⟨i, hi⟩ := hg.2 in
⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩
lemma exists_multiset_of_splits {f : polynomial α} : splits i f →
∃ (s : multiset β), f.map i = C (i f.leading_coeff) *
(s.map (λ a : β, (X : polynomial β) - C a)).prod :=
suffices splits (ring_hom.id _) (f.map i) → ∃ s : multiset β, f.map i =
(C (f.map i).leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod,
by rwa [splits_map_iff, leading_coeff_map i] at this,
wf_dvd_monoid.induction_on_irreducible (f.map i)
(λ _, ⟨{37}, by simp [i.map_zero]⟩)
(λ u hu _, ⟨0,
by conv_lhs { rw eq_C_of_degree_eq_zero (is_unit_iff_degree_eq_zero.1 hu) };
simp [leading_coeff, nat_degree_eq_of_degree_eq_some (is_unit_iff_degree_eq_zero.1 hu)]⟩)
(λ f p hf0 hp ih hfs,
have hpf0 : p * f ≠ 0, from mul_ne_zero hp.ne_zero hf0,
let ⟨s, hs⟩ := ih (splits_of_splits_mul _ hpf0 hfs).2 in
⟨-(p * norm_unit p).coeff 0 ::ₘ s,
have hp1 : degree p = 1, from hfs.resolve_left hpf0 hp (by simp),
begin
rw [multiset.map_cons, multiset.prod_cons, leading_coeff_mul, C_mul, mul_assoc,
mul_left_comm (C f.leading_coeff), ← hs, ← mul_assoc, mul_left_inj' hf0],
conv_lhs {rw eq_X_add_C_of_degree_eq_one hp1},
simp only [mul_add, coe_norm_unit_of_ne_zero hp.ne_zero, mul_comm p, coeff_neg,
C_neg, sub_eq_add_neg, neg_neg, coeff_C_mul, (mul_assoc _ _ _).symm, C_mul.symm,
mul_inv_cancel (show p.leading_coeff ≠ 0, from mt leading_coeff_eq_zero.1
hp.ne_zero), one_mul],
end⟩)
/-- Pick a root of a polynomial that splits. -/
def root_of_splits {f : polynomial α} (hf : f.splits i) (hfd : f.degree ≠ 0) : β :=
classical.some $ exists_root_of_splits i hf hfd
theorem map_root_of_splits {f : polynomial α} (hf : f.splits i) (hfd) :
f.eval₂ i (root_of_splits i hf hfd) = 0 :=
classical.some_spec $ exists_root_of_splits i hf hfd
theorem roots_map {f : polynomial α} (hf : f.splits $ ring_hom.id α) :
(f.map i).roots = (f.roots).map i :=
if hf0 : f = 0 then by rw [hf0, map_zero, roots_zero, roots_zero, multiset.map_zero] else
have hmf0 : f.map i ≠ 0 := map_ne_zero hf0,
let ⟨m, hm⟩ := exists_multiset_of_splits _ hf in
have h1 : (0 : polynomial α) ∉ m.map (λ r, X - C r),
from zero_nmem_multiset_map_X_sub_C _ _,
have h2 : (0 : polynomial β) ∉ m.map (λ r, X - C (i r)),
from zero_nmem_multiset_map_X_sub_C _ _,
begin
rw map_id at hm, rw hm at hf0 hmf0 ⊢, rw map_mul at hmf0 ⊢,
rw [roots_mul hf0, roots_mul hmf0, map_C, roots_C, zero_add, roots_C, zero_add,
map_multiset_prod, multiset.map_map], simp_rw [(∘), map_sub, map_X, map_C],
rw [roots_multiset_prod _ h2, multiset.bind_map,
roots_multiset_prod _ h1, multiset.bind_map],
simp_rw roots_X_sub_C,
rw [multiset.bind_cons, multiset.bind_zero, add_zero,
multiset.bind_cons, multiset.bind_zero, add_zero, multiset.map_id']
end
lemma eq_prod_roots_of_splits {p : polynomial α} {i : α →+* β}
(hsplit : splits i p) :
p.map i = C (i p.leading_coeff) * ((p.map i).roots.map (λ a, X - C a)).prod :=
begin
by_cases p_eq_zero : p = 0,
{ rw [p_eq_zero, map_zero, leading_coeff_zero, i.map_zero, C.map_zero, zero_mul] },
obtain ⟨s, hs⟩ := exists_multiset_of_splits i hsplit,
have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero),
have prod_ne_zero : C (i p.leading_coeff) * (multiset.map (λ a, X - C a) s).prod ≠ 0 :=
by rwa hs at map_ne_zero,
have zero_nmem : (0 : polynomial β) ∉ s.map (λ a, X - C a),
from zero_nmem_multiset_map_X_sub_C _ _,
have map_bind_roots_eq : (s.map (λ a, X - C a)).bind (λ a, a.roots) = s,
{ refine multiset.induction_on s (by rw [multiset.map_zero, multiset.zero_bind]) _,
intros a s ih,
rw [multiset.map_cons, multiset.cons_bind, ih, roots_X_sub_C,
multiset.cons_add, zero_add] },
rw [hs, roots_mul prod_ne_zero, roots_C, zero_add,
roots_multiset_prod _ zero_nmem,
map_bind_roots_eq]
end
lemma eq_X_sub_C_of_splits_of_single_root {x : α} {h : polynomial α} (h_splits : splits i h)
(h_roots : (h.map i).roots = {i x}) : h = (C (leading_coeff h)) * (X - C x) :=
begin
apply polynomial.map_injective _ i.injective,
rw [eq_prod_roots_of_splits h_splits, h_roots],
simp,
end
lemma nat_degree_multiset_prod {R : Type*} [integral_domain R] {s : multiset (polynomial R)}
(h : (0 : polynomial R) ∉ s) :
nat_degree s.prod = (s.map nat_degree).sum :=
begin
revert h,
refine s.induction_on _ _,
{ simp },
intros p s ih h,
rw [multiset.mem_cons, not_or_distrib] at h,
have hprod : s.prod ≠ 0 := multiset.prod_ne_zero h.2,
rw [multiset.prod_cons, nat_degree_mul (ne.symm h.1) hprod, ih h.2,
multiset.map_cons, multiset.sum_cons],
end
lemma nat_degree_eq_card_roots {p : polynomial α} {i : α →+* β}
(hsplit : splits i p) : p.nat_degree = (p.map i).roots.card :=
begin
by_cases p_eq_zero : p = 0,
{ rw [p_eq_zero, nat_degree_zero, map_zero, roots_zero, multiset.card_zero] },
have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero),
rw eq_prod_roots_of_splits hsplit at map_ne_zero,
conv_lhs { rw [← nat_degree_map i, eq_prod_roots_of_splits hsplit] },
have : (0 : polynomial β) ∉ (map i p).roots.map (λ a, X - C a),
from zero_nmem_multiset_map_X_sub_C _ _,
simp [nat_degree_mul (left_ne_zero_of_mul map_ne_zero) (right_ne_zero_of_mul map_ne_zero),
nat_degree_multiset_prod this]
end
lemma degree_eq_card_roots {p : polynomial α} {i : α →+* β} (p_ne_zero : p ≠ 0)
(hsplit : splits i p) : p.degree = (p.map i).roots.card :=
by rw [degree_eq_nat_degree p_ne_zero, nat_degree_eq_card_roots hsplit]
section UFD
local attribute [instance, priority 10] principal_ideal_ring.to_unique_factorization_monoid
local infix ` ~ᵤ ` : 50 := associated
open unique_factorization_monoid associates
lemma splits_of_exists_multiset {f : polynomial α} {s : multiset β}
(hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod) :
splits i f :=
if hf0 : f = 0 then or.inl hf0
else
or.inr $ λ p hp hdp,
have ht : multiset.rel associated
(factors (f.map i)) (s.map (λ a : β, (X : polynomial β) - C a)) :=
factors_unique
(λ p hp, irreducible_of_factor _ hp)
(λ p' m, begin
obtain ⟨a,m,rfl⟩ := multiset.mem_map.1 m,
exact irreducible_of_degree_eq_one (degree_X_sub_C _),
end)
(associated.symm $ calc _ ~ᵤ f.map i :
⟨(units.map' C : units β →* units (polynomial β)) (units.mk0 (f.map i).leading_coeff
(mt leading_coeff_eq_zero.1 (map_ne_zero hf0))),
by conv_rhs {rw [hs, ← leading_coeff_map i, mul_comm]}; refl⟩
... ~ᵤ _ : associated.symm (unique_factorization_monoid.factors_prod (by simpa using hf0))),
let ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd (by simpa) hp hdp in
let ⟨q', hq', hqq'⟩ := multiset.exists_mem_of_rel_of_mem ht hq in
let ⟨a, ha⟩ := multiset.mem_map.1 hq' in
by rw [← degree_X_sub_C a, ha.2];
exact degree_eq_degree_of_associated (hpq.trans hqq')
lemma splits_of_splits_id {f : polynomial α} : splits (ring_hom.id _) f → splits i f :=
unique_factorization_monoid.induction_on_prime f (λ _, splits_zero _)
(λ _ hu _, splits_of_degree_le_one _
((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial))
(λ a p ha0 hp ih hfi, splits_mul _
(splits_of_degree_eq_one _
((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.resolve_left
hp.1 (irreducible_of_prime hp) (by rw map_id)))
(ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2))
end UFD
lemma splits_iff_exists_multiset {f : polynomial α} : splits i f ↔
∃ (s : multiset β), f.map i = C (i f.leading_coeff) *
(s.map (λ a : β, (X : polynomial β) - C a)).prod :=
⟨exists_multiset_of_splits i, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩
lemma splits_comp_of_splits (j : β →+* γ) {f : polynomial α}
(h : splits i f) : splits (j.comp i) f :=
begin
change i with ((ring_hom.id _).comp i) at h,
rw [← splits_map_iff],
rw [← splits_map_iff i] at h,
exact splits_of_splits_id _ h
end
/-- A monic polynomial `p` that has as much roots as its degree
can be written `p = ∏(X - a)`, for `a` in `p.roots`. -/
lemma prod_multiset_X_sub_C_of_monic_of_roots_card_eq {p : polynomial α}
(hmonic : p.monic) (hroots : p.roots.card = p.nat_degree) :
(multiset.map (λ (a : α), X - C a) p.roots).prod = p :=
begin
have hprodmonic : (multiset.map (λ (a : α), X - C a) p.roots).prod.monic,
{ simp only [prod_multiset_root_eq_finset_root (ne_zero_of_monic hmonic),
monic_prod_of_monic, monic_X_sub_C, monic_pow, forall_true_iff] },
have hdegree : (multiset.map (λ (a : α), X - C a) p.roots).prod.nat_degree = p.nat_degree,
{ rw [← hroots, nat_degree_multiset_prod (zero_nmem_multiset_map_X_sub_C _ (λ a : α, a))],
simp only [eq_self_iff_true, mul_one, nat.cast_id, nsmul_eq_mul, multiset.sum_repeat,
multiset.map_const,nat_degree_X_sub_C, function.comp, multiset.map_map] },
obtain ⟨q, hq⟩ := prod_multiset_X_sub_C_dvd p,
have qzero : q ≠ 0,
{ rintro rfl, apply hmonic.ne_zero, simpa only [mul_zero] using hq },
have degp :
p.nat_degree = (multiset.map (λ (a : α), X - C a) p.roots).prod.nat_degree + q.nat_degree,
{ nth_rewrite 0 [hq],
simp only [nat_degree_mul (ne_zero_of_monic hprodmonic) qzero] },
have degq : q.nat_degree = 0,
{ rw hdegree at degp,
exact (add_right_inj p.nat_degree).mp (tactic.ring_exp.add_pf_sum_z degp rfl).symm },
obtain ⟨u, hu⟩ := is_unit_iff_degree_eq_zero.2 ((degree_eq_iff_nat_degree_eq qzero).2 degq),
have hassoc : associated (multiset.map (λ (a : α), X - C a) p.roots).prod p,
{ rw associated, use u, rw [hu, ← hq] },
exact eq_of_monic_of_associated hprodmonic hmonic hassoc
end
/-- A polynomial `p` that has as much roots as its degree
can be written `p = p.leading_coeff * ∏(X - a)`, for `a` in `p.roots`. -/
lemma C_leading_coeff_mul_prod_multiset_X_sub_C {p : polynomial α}
(hroots : p.roots.card = p.nat_degree) :
(C p.leading_coeff) * (multiset.map (λ (a : α), X - C a) p.roots).prod = p :=
begin
by_cases hzero : p = 0,
{ rw [hzero, leading_coeff_zero, ring_hom.map_zero, zero_mul], },
{ have hcoeff : p.leading_coeff ≠ 0,
{ intro h, exact hzero (leading_coeff_eq_zero.1 h) },
have hrootsnorm : (normalize p).roots.card = (normalize p).nat_degree,
{ rw [roots_normalize, normalize_apply, nat_degree_mul hzero (units.ne_zero _), hroots,
coe_norm_unit, nat_degree_C, add_zero], },
have hprod := prod_multiset_X_sub_C_of_monic_of_roots_card_eq (monic_normalize hzero)
hrootsnorm,
rw [roots_normalize, normalize_apply, coe_norm_unit_of_ne_zero hzero] at hprod,
calc (C p.leading_coeff) * (multiset.map (λ (a : α), X - C a) p.roots).prod
= p * C ((p.leading_coeff)⁻¹ * p.leading_coeff) :
by rw [hprod, mul_comm, mul_assoc, ← C_mul]
... = p * C 1 : by field_simp
... = p : by simp only [mul_one, ring_hom.map_one], },
end
/-- A polynomial splits if and only if it has as much roots as its degree. -/
lemma splits_iff_card_roots {p : polynomial α} :
splits (ring_hom.id α) p ↔ p.roots.card = p.nat_degree :=
begin
split,
{ intro H, rw [nat_degree_eq_card_roots H, map_id] },
{ intro hroots,
apply (splits_iff_exists_multiset (ring_hom.id α)).2,
use p.roots,
simp only [ring_hom.id_apply, map_id],
exact (C_leading_coeff_mul_prod_multiset_X_sub_C hroots).symm },
end
end splits
end polynomial
section embeddings
variables (F : Type*) [field F]
/-- If `p` is the minimal polynomial of `a` over `F` then `F[a] ≃ₐ[F] F[x]/(p)` -/
def alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly
{R : Type*} [comm_ring R] [algebra F R] (x : R) :
algebra.adjoin F ({x} : set R) ≃ₐ[F] adjoin_root (minpoly F x) :=
alg_equiv.symm $ alg_equiv.of_bijective
(alg_hom.cod_restrict
(adjoin_root.lift_hom _ x $ minpoly.aeval F x) _
(λ p, adjoin_root.induction_on _ p $ λ p,
(algebra.adjoin_singleton_eq_range F x).symm ▸ (polynomial.aeval _).mem_range.mpr ⟨p, rfl⟩))
⟨(alg_hom.injective_cod_restrict _ _ _).2 $ (alg_hom.injective_iff _).2 $ λ p,
adjoin_root.induction_on _ p $ λ p hp, ideal.quotient.eq_zero_iff_mem.2 $
ideal.mem_span_singleton.2 $ minpoly.dvd F x hp,
λ y, let ⟨p, _, hp⟩ := (subalgebra.ext_iff.1 (algebra.adjoin_singleton_eq_range F x) y).1 y.2 in
⟨adjoin_root.mk _ p, subtype.eq hp⟩⟩
open finset
-- Speed up the following proof.
local attribute [irreducible] minpoly
-- TODO: Why is this so slow?
/-- If `K` and `L` are field extensions of `F` and we have `s : finset K` such that
the minimal polynomial of each `x ∈ s` splits in `L` then `algebra.adjoin F s` embeds in `L`. -/
theorem lift_of_splits {F K L : Type*} [field F] [field K] [field L]
[algebra F K] [algebra F L] (s : finset K) :
(∀ x ∈ s, is_integral F x ∧ polynomial.splits (algebra_map F L) (minpoly F x)) →
nonempty (algebra.adjoin F (↑s : set K) →ₐ[F] L) :=
begin
refine finset.induction_on s (λ H, _) (λ a s has ih H, _),
{ rw [coe_empty, algebra.adjoin_empty],
exact ⟨(algebra.of_id F L).comp (algebra.bot_equiv F K)⟩ },
rw forall_mem_insert at H, rcases H with ⟨⟨H1, H2⟩, H3⟩, cases ih H3 with f,
choose H3 H4 using H3,
rw [coe_insert, set.insert_eq, set.union_comm, algebra.adjoin_union],
letI := (f : algebra.adjoin F (↑s : set K) →+* L).to_algebra,
haveI : finite_dimensional F (algebra.adjoin F (↑s : set K)) :=
(submodule.fg_iff_finite_dimensional _).1 (fg_adjoin_of_finite (set.finite_mem_finset s) H3),
letI := field_of_finite_dimensional F (algebra.adjoin F (↑s : set K)),
have H5 : is_integral (algebra.adjoin F (↑s : set K)) a := is_integral_of_is_scalar_tower a H1,
have H6 : (minpoly (algebra.adjoin F (↑s : set K)) a).splits
(algebra_map (algebra.adjoin F (↑s : set K)) L),
{ refine polynomial.splits_of_splits_of_dvd _
(polynomial.map_ne_zero $ minpoly.ne_zero H1 :
polynomial.map (algebra_map _ _) _ ≠ 0)
((polynomial.splits_map_iff _ _).2 _)
(minpoly.dvd _ _ _),
{ rw ← is_scalar_tower.algebra_map_eq, exact H2 },
{ rw [← is_scalar_tower.aeval_apply, minpoly.aeval] } },
obtain ⟨y, hy⟩ := polynomial.exists_root_of_splits _ H6 (ne_of_lt (minpoly.degree_pos H5)).symm,
refine ⟨subalgebra.of_under _ _ _⟩,
refine (adjoin_root.lift_hom (minpoly (algebra.adjoin F (↑s : set K)) a) y hy).comp _,
exact alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly (algebra.adjoin F (↑s : set K)) a
end
end embeddings
namespace polynomial
variables [field α] [field β] [field γ]
open polynomial
section splitting_field
/-- Non-computably choose an irreducible factor from a polynomial. -/
def factor (f : polynomial α) : polynomial α :=
if H : ∃ g, irreducible g ∧ g ∣ f then classical.some H else X
instance irreducible_factor (f : polynomial α) : irreducible (factor f) :=
begin
rw factor, split_ifs with H, { exact (classical.some_spec H).1 }, { exact irreducible_X }
end
theorem factor_dvd_of_not_is_unit {f : polynomial α} (hf1 : ¬is_unit f) : factor f ∣ f :=
begin
by_cases hf2 : f = 0, { rw hf2, exact dvd_zero _ },
rw [factor, dif_pos (wf_dvd_monoid.exists_irreducible_factor hf1 hf2)],
exact (classical.some_spec $ wf_dvd_monoid.exists_irreducible_factor hf1 hf2).2
end
theorem factor_dvd_of_degree_ne_zero {f : polynomial α} (hf : f.degree ≠ 0) : factor f ∣ f :=
factor_dvd_of_not_is_unit (mt degree_eq_zero_of_is_unit hf)
theorem factor_dvd_of_nat_degree_ne_zero {f : polynomial α} (hf : f.nat_degree ≠ 0) :
factor f ∣ f :=
factor_dvd_of_degree_ne_zero (mt nat_degree_eq_of_degree_eq_some hf)
/-- Divide a polynomial f by X - C r where r is a root of f in a bigger field extension. -/
def remove_factor (f : polynomial α) : polynomial (adjoin_root $ factor f) :=
map (adjoin_root.of f.factor) f /ₘ (X - C (adjoin_root.root f.factor))
theorem X_sub_C_mul_remove_factor (f : polynomial α) (hf : f.nat_degree ≠ 0) :
(X - C (adjoin_root.root f.factor)) * f.remove_factor = map (adjoin_root.of f.factor) f :=
let ⟨g, hg⟩ := factor_dvd_of_nat_degree_ne_zero hf in
mul_div_by_monic_eq_iff_is_root.2 $ by rw [is_root.def, eval_map, hg, eval₂_mul, ← hg,
adjoin_root.eval₂_root, zero_mul]
theorem nat_degree_remove_factor (f : polynomial α) :
f.remove_factor.nat_degree = f.nat_degree - 1 :=
by rw [remove_factor, nat_degree_div_by_monic _ (monic_X_sub_C _), nat_degree_map,
nat_degree_X_sub_C]
theorem nat_degree_remove_factor' {f : polynomial α} {n : ℕ} (hfn : f.nat_degree = n+1) :
f.remove_factor.nat_degree = n :=
by rw [nat_degree_remove_factor, hfn, n.add_sub_cancel]
/-- Auxiliary construction to a splitting field of a polynomial. Uses induction on the degree. -/
def splitting_field_aux (n : ℕ) : Π {α : Type u} [field α], by exactI Π (f : polynomial α),
f.nat_degree = n → Type u :=
nat.rec_on n (λ α _ _ _, α) $ λ n ih α _ f hf, by exactI
ih f.remove_factor (nat_degree_remove_factor' hf)
namespace splitting_field_aux
theorem succ (n : ℕ) (f : polynomial α) (hfn : f.nat_degree = n + 1) :
splitting_field_aux (n+1) f hfn =
splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn) := rfl
instance field (n : ℕ) : Π {α : Type u} [field α], by exactI
Π {f : polynomial α} (hfn : f.nat_degree = n), field (splitting_field_aux n f hfn) :=
nat.rec_on n (λ α _ _ _, ‹field α›) $ λ n ih α _ f hf, ih _
instance inhabited {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n) :
inhabited (splitting_field_aux n f hfn) := ⟨37⟩
instance algebra (n : ℕ) : Π {α : Type u} [field α], by exactI
Π {f : polynomial α} (hfn : f.nat_degree = n), algebra α (splitting_field_aux n f hfn) :=
nat.rec_on n (λ α _ _ _, by exactI algebra.id α) $ λ n ih α _ f hfn,
by exactI @@algebra.comap.algebra _ _ _ _ _ _ _ (ih _)
instance algebra' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) :
algebra (adjoin_root f.factor) (splitting_field_aux _ _ hfn) :=
splitting_field_aux.algebra n _
instance algebra'' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) :
algebra α (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) :=
splitting_field_aux.algebra (n+1) hfn
instance algebra''' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) :
algebra (adjoin_root f.factor)
(splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) :=
splitting_field_aux.algebra n _
instance scalar_tower {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) :
is_scalar_tower α (adjoin_root f.factor) (splitting_field_aux _ _ hfn) :=
is_scalar_tower.of_algebra_map_eq $ λ x, rfl
instance scalar_tower' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) :
is_scalar_tower α (adjoin_root f.factor)
(splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) :=
is_scalar_tower.of_algebra_map_eq $ λ x, rfl
theorem algebra_map_succ (n : ℕ) (f : polynomial α) (hfn : f.nat_degree = n + 1) :
by exact algebra_map α (splitting_field_aux _ _ hfn) =
(algebra_map (adjoin_root f.factor)
(splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn))).comp
(adjoin_root.of f.factor) :=
rfl
protected theorem splits (n : ℕ) : ∀ {α : Type u} [field α], by exactI
∀ (f : polynomial α) (hfn : f.nat_degree = n),
splits (algebra_map α $ splitting_field_aux n f hfn) f :=
nat.rec_on n (λ α _ _ hf, by exactI splits_of_degree_le_one _
(le_trans degree_le_nat_degree $ hf.symm ▸ with_bot.coe_le_coe.2 zero_le_one)) $ λ n ih α _ f hf,
by { resetI, rw [← splits_id_iff_splits, algebra_map_succ, ← map_map, splits_id_iff_splits,
← X_sub_C_mul_remove_factor f (λ h, by { rw h at hf, cases hf })],
exact splits_mul _ (splits_X_sub_C _) (ih _ _) }
theorem exists_lift (n : ℕ) : ∀ {α : Type u} [field α], by exactI
∀ (f : polynomial α) (hfn : f.nat_degree = n) {β : Type*} [field β], by exactI
∀ (j : α →+* β) (hf : splits j f), ∃ k : splitting_field_aux n f hfn →+* β,
k.comp (algebra_map _ _) = j :=
nat.rec_on n (λ α _ _ _ β _ j _, by exactI ⟨j, j.comp_id⟩) $ λ n ih α _ f hf β _ j hj, by exactI
have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hf, cases hf },
have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl },
let ⟨r, hr⟩ := exists_root_of_splits _ (splits_of_splits_of_dvd j hfn0 hj
(factor_dvd_of_nat_degree_ne_zero hndf))
(mt is_unit_iff_degree_eq_zero.2 f.irreducible_factor.1) in
have hmf0 : map (adjoin_root.of f.factor) f ≠ 0, from map_ne_zero hfn0,
have hsf : splits (adjoin_root.lift j r hr) f.remove_factor,
by { rw ← X_sub_C_mul_remove_factor _ hndf at hmf0, refine (splits_of_splits_mul _ hmf0 _).2,
rwa [X_sub_C_mul_remove_factor _ hndf, ← splits_id_iff_splits, map_map, adjoin_root.lift_comp_of,
splits_id_iff_splits] },
let ⟨k, hk⟩ := ih f.remove_factor (nat_degree_remove_factor' hf) (adjoin_root.lift j r hr) hsf in
⟨k, by rw [algebra_map_succ, ← ring_hom.comp_assoc, hk, adjoin_root.lift_comp_of]⟩
theorem adjoin_roots (n : ℕ) : ∀ {α : Type u} [field α], by exactI
∀ (f : polynomial α) (hfn : f.nat_degree = n),
algebra.adjoin α (↑(f.map $ algebra_map α $ splitting_field_aux n f hfn).roots.to_finset :
set (splitting_field_aux n f hfn)) = ⊤ :=
nat.rec_on n (λ α _ f hf, by exactI algebra.eq_top_iff.2 (λ x, subalgebra.range_le _ ⟨x, rfl⟩)) $
λ n ih α _ f hfn, by exactI
have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hfn, cases hfn },
have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl },
have hmf0 : map (algebra_map α (splitting_field_aux n.succ f hfn)) f ≠ 0 := map_ne_zero hfn0,
by { rw [algebra_map_succ, ← map_map, ← X_sub_C_mul_remove_factor _ hndf, map_mul] at hmf0 ⊢,
rw [roots_mul hmf0, map_sub, map_X, map_C, roots_X_sub_C, multiset.to_finset_add, finset.coe_union,
multiset.to_finset_cons, multiset.to_finset_zero, insert_emptyc_eq, finset.coe_singleton,
algebra.adjoin_union, ← set.image_singleton, algebra.adjoin_algebra_map α (adjoin_root f.factor)
(splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)),
adjoin_root.adjoin_root_eq_top, algebra.map_top,
is_scalar_tower.range_under_adjoin α (adjoin_root f.factor)
(splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)),
ih, subalgebra.res_top] }
end splitting_field_aux
/-- A splitting field of a polynomial. -/
def splitting_field (f : polynomial α) :=
splitting_field_aux _ f rfl
namespace splitting_field
variables (f : polynomial α)
instance : field (splitting_field f) :=
splitting_field_aux.field _ _
instance inhabited : inhabited (splitting_field f) := ⟨37⟩
instance : algebra α (splitting_field f) :=
splitting_field_aux.algebra _ _
protected theorem splits : splits (algebra_map α (splitting_field f)) f :=
splitting_field_aux.splits _ _ _
variables [algebra α β] (hb : splits (algebra_map α β) f)
/-- Embeds the splitting field into any other field that splits the polynomial. -/
def lift : splitting_field f →ₐ[α] β :=
{ commutes' := λ r, by { have := classical.some_spec (splitting_field_aux.exists_lift _ _ _ _ hb),
exact ring_hom.ext_iff.1 this r },
.. classical.some (splitting_field_aux.exists_lift _ _ _ _ hb) }
theorem adjoin_roots : algebra.adjoin α
(↑(f.map (algebra_map α $ splitting_field f)).roots.to_finset : set (splitting_field f)) = ⊤ :=
splitting_field_aux.adjoin_roots _ _ _
theorem adjoin_root_set : algebra.adjoin α (f.root_set f.splitting_field) = ⊤ :=
adjoin_roots f
end splitting_field
variables (α β) [algebra α β]
/-- Typeclass characterising splitting fields. -/
class is_splitting_field (f : polynomial α) : Prop :=
(splits [] : splits (algebra_map α β) f)
(adjoin_roots [] : algebra.adjoin α (↑(f.map (algebra_map α β)).roots.to_finset : set β) = ⊤)
namespace is_splitting_field
variables {α}
instance splitting_field (f : polynomial α) : is_splitting_field α (splitting_field f) f :=
⟨splitting_field.splits f, splitting_field.adjoin_roots f⟩
section scalar_tower
variables {α β γ} [algebra β γ] [algebra α γ] [is_scalar_tower α β γ]
variables {α}
instance map (f : polynomial α) [is_splitting_field α γ f] :
is_splitting_field β γ (f.map $ algebra_map α β) :=
⟨by { rw [splits_map_iff, ← is_scalar_tower.algebra_map_eq], exact splits γ f },
subalgebra.res_inj α $ by { rw [map_map, ← is_scalar_tower.algebra_map_eq, subalgebra.res_top,
eq_top_iff, ← adjoin_roots γ f, algebra.adjoin_le_iff],
exact λ x hx, @algebra.subset_adjoin β _ _ _ _ _ _ hx }⟩
variables {α} (β)
theorem splits_iff (f : polynomial α) [is_splitting_field α β f] :
polynomial.splits (ring_hom.id α) f ↔ (⊤ : subalgebra α β) = ⊥ :=
⟨λ h, eq_bot_iff.2 $ adjoin_roots β f ▸ (roots_map (algebra_map α β) h).symm ▸
algebra.adjoin_le_iff.2 (λ y hy,
let ⟨x, hxs, hxy⟩ := finset.mem_image.1 (by rwa multiset.to_finset_map at hy) in
hxy ▸ subalgebra.algebra_map_mem _ _),
λ h, @ring_equiv.to_ring_hom_refl α _ ▸
ring_equiv.trans_symm (ring_equiv.of_bijective _ $ algebra.bijective_algebra_map_iff.2 h) ▸
by { rw ring_equiv.to_ring_hom_trans, exact splits_comp_of_splits _ _ (splits β f) }⟩
theorem mul (f g : polynomial α) (hf : f ≠ 0) (hg : g ≠ 0) [is_splitting_field α β f]
[is_splitting_field β γ (g.map $ algebra_map α β)] :
is_splitting_field α γ (f * g) :=
⟨(is_scalar_tower.algebra_map_eq α β γ).symm ▸ splits_mul _
(splits_comp_of_splits _ _ (splits β f))
((splits_map_iff _ _).1 (splits γ $ g.map $ algebra_map α β)),
by rw [map_mul, roots_mul (mul_ne_zero (map_ne_zero hf : f.map (algebra_map α γ) ≠ 0)
(map_ne_zero hg)), multiset.to_finset_add, finset.coe_union, algebra.adjoin_union,
is_scalar_tower.algebra_map_eq α β γ, ← map_map,
roots_map (algebra_map β γ) ((splits_id_iff_splits $ algebra_map α β).2 $ splits β f),
multiset.to_finset_map, finset.coe_image, algebra.adjoin_algebra_map, adjoin_roots,
algebra.map_top, is_scalar_tower.range_under_adjoin, ← map_map, adjoin_roots,
subalgebra.res_top]⟩
end scalar_tower
/-- Splitting field of `f` embeds into any field that splits `f`. -/
def lift [algebra α γ] (f : polynomial α) [is_splitting_field α β f]
(hf : polynomial.splits (algebra_map α γ) f) : β →ₐ[α] γ :=
if hf0 : f = 0 then (algebra.of_id α γ).comp $
(algebra.bot_equiv α β : (⊥ : subalgebra α β) →ₐ[α] α).comp $
by { rw ← (splits_iff β f).1 (show f.splits (ring_hom.id α), from hf0.symm ▸ splits_zero _),
exact algebra.to_top } else
alg_hom.comp (by { rw ← adjoin_roots β f, exact classical.choice (lift_of_splits _ $ λ y hy,
have aeval y f = 0, from (eval₂_eq_eval_map _).trans $
(mem_roots $ by exact map_ne_zero hf0).1 (multiset.mem_to_finset.mp hy),
⟨(is_algebraic_iff_is_integral _).1 ⟨f, hf0, this⟩,
splits_of_splits_of_dvd _ hf0 hf $ minpoly.dvd _ _ this⟩) })
algebra.to_top
theorem finite_dimensional (f : polynomial α) [is_splitting_field α β f] : finite_dimensional α β :=
finite_dimensional.iff_fg.2 $ @algebra.coe_top α β _ _ _ ▸ adjoin_roots β f ▸
fg_adjoin_of_finite (set.finite_mem_finset _) (λ y hy,
if hf : f = 0
then by { rw [hf, map_zero, roots_zero] at hy, cases hy }
else (is_algebraic_iff_is_integral _).1 ⟨f, hf, (eval₂_eq_eval_map _).trans $
(mem_roots $ by exact map_ne_zero hf).1 (multiset.mem_to_finset.mp hy)⟩)
instance (f : polynomial α) : _root_.finite_dimensional α f.splitting_field :=
finite_dimensional f.splitting_field f
/-- Any splitting field is isomorphic to `splitting_field f`. -/
def alg_equiv (f : polynomial α) [is_splitting_field α β f] : β ≃ₐ[α] splitting_field f :=
begin
refine alg_equiv.of_bijective (lift β f $ splits (splitting_field f) f)
⟨ring_hom.injective (lift β f $ splits (splitting_field f) f).to_ring_hom, _⟩,
haveI := finite_dimensional (splitting_field f) f,
haveI := finite_dimensional β f,
have : finite_dimensional.findim α β = finite_dimensional.findim α (splitting_field f) :=
le_antisymm
(linear_map.findim_le_findim_of_injective
(show function.injective (lift β f $ splits (splitting_field f) f).to_linear_map, from
ring_hom.injective (lift β f $ splits (splitting_field f) f : β →+* f.splitting_field)))
(linear_map.findim_le_findim_of_injective
(show function.injective (lift (splitting_field f) f $ splits β f).to_linear_map, from
ring_hom.injective (lift (splitting_field f) f $ splits β f : f.splitting_field →+* β))),
change function.surjective (lift β f $ splits (splitting_field f) f).to_linear_map,
refine (linear_map.injective_iff_surjective_of_findim_eq_findim this).1 _,
exact ring_hom.injective (lift β f $ splits (splitting_field f) f : β →+* f.splitting_field)
end
end is_splitting_field
end splitting_field
end polynomial
|
120fe9551871d039cb0bd3212faceeb57a347c79 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/e3.lean | e22f6d6b6026c1eb1e6fd7e03fe5b6a5fd391aea | [
"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 | 389 | lean | prelude
definition Prop := Type.{0}
definition false := ∀x : Prop, x
check false
theorem false.elim (C : Prop) (H : false) : C
:= H C
definition eq {A : Type} (a b : A)
:= ∀ {P : A → Prop}, P a → P b
check eq
infix `=`:50 := eq
theorem refl {A : Type} (a : A) : a = a
:= λ P H, H
theorem subst {A : Type} {P : A -> Prop} {a b : A} (H1 : a = b) (H2 : P a) : P b
:= @H1 P H2
|
14a990fd5b42bfa11ee7396b84a0a3ad7b24f75f | 4727251e0cd73359b15b664c3170e5d754078599 | /src/topology/algebra/constructions.lean | d41da27532151857668b0fdc431ed51d4cb18e4e | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 2,754 | lean | /-
Copyright (c) 2021 Nicolò Cavalleri. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nicolò Cavalleri
-/
import topology.homeomorph
/-!
# Topological space structure on the opposite monoid and on the units group
In this file we define `topological_space` structure on `Mᵐᵒᵖ`, `Mᵃᵒᵖ`, `Mˣ`, and `add_units M`.
This file does not import definitions of a topological monoid and/or a continuous multiplicative
action, so we postpone the proofs of `has_continuous_mul Mᵐᵒᵖ` etc till we have these definitions.
## Tags
topological space, opposite monoid, units
-/
variables {M X : Type*}
open filter
open_locale topological_space
namespace mul_opposite
/-- Put the same topological space structure on the opposite monoid as on the original space. -/
@[to_additive] instance [topological_space M] : topological_space Mᵐᵒᵖ :=
topological_space.induced (unop : Mᵐᵒᵖ → M) ‹_›
variables [topological_space M]
@[continuity, to_additive] lemma continuous_unop : continuous (unop : Mᵐᵒᵖ → M) :=
continuous_induced_dom
@[continuity, to_additive] lemma continuous_op : continuous (op : M → Mᵐᵒᵖ) :=
continuous_induced_rng continuous_id
@[to_additive] instance [t2_space M] : t2_space Mᵐᵒᵖ :=
⟨λ x y h, separated_by_continuous mul_opposite.continuous_unop $ unop_injective.ne h⟩
/-- `mul_opposite.op` as a homeomorphism. -/
@[to_additive "`add_opposite.op` as a homeomorphism."]
def op_homeomorph : M ≃ₜ Mᵐᵒᵖ :=
{ to_equiv := op_equiv,
continuous_to_fun := continuous_op,
continuous_inv_fun := continuous_unop }
@[simp, to_additive] lemma map_op_nhds (x : M) : map (op : M → Mᵐᵒᵖ) (𝓝 x) = 𝓝 (op x) :=
op_homeomorph.map_nhds_eq x
@[simp, to_additive] lemma map_unop_nhds (x : Mᵐᵒᵖ) : map (unop : Mᵐᵒᵖ → M) (𝓝 x) = 𝓝 (unop x) :=
op_homeomorph.symm.map_nhds_eq x
@[simp, to_additive] lemma comap_op_nhds (x : Mᵐᵒᵖ) : comap (op : M → Mᵐᵒᵖ) (𝓝 x) = 𝓝 (unop x) :=
op_homeomorph.comap_nhds_eq x
@[simp, to_additive] lemma comap_unop_nhds (x : M) : comap (unop : Mᵐᵒᵖ → M) (𝓝 x) = 𝓝 (op x) :=
op_homeomorph.symm.comap_nhds_eq x
end mul_opposite
namespace units
open mul_opposite
variables [topological_space M] [monoid M]
/-- The units of a monoid are equipped with a topology, via the embedding into `M × M`. -/
@[to_additive] instance : topological_space Mˣ :=
topological_space.induced (embed_product M) prod.topological_space
@[to_additive] lemma continuous_embed_product : continuous (embed_product M) :=
continuous_induced_dom
@[to_additive] lemma continuous_coe : continuous (coe : Mˣ → M) :=
(@continuous_embed_product M _ _).fst
end units
|
4e0ca48b51dbd2abb5347cfb65564b1e0a8e58c0 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/analysis/normed_space/bounded_linear_maps.lean | e3bdda58b3c51b3f026db338ffefee2656c61fce | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 22,059 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
-/
import analysis.normed_space.multilinear
/-!
# Continuous linear maps
This file defines a class stating that a map between normed vector spaces is (bi)linear and
continuous.
Instead of asking for continuity, the definition takes the equivalent condition (because the space
is normed) that `∥f x∥` is bounded by a multiple of `∥x∥`. Hence the "bounded" in the name refers to
`∥f x∥/∥x∥` rather than `∥f x∥` itself.
## Main declarations
* `is_bounded_linear_map`: Class stating that a map `f : E → F` is linear and has `∥f x∥` bounded
by a multiple of `∥x∥`.
* `is_bounded_bilinear_map`: Class stating that a map `f : E × F → G` is bilinear and continuous,
but through the simpler to provide statement that `∥f (x, y)∥` is bounded by a multiple of
`∥x∥ * ∥y∥`
* `is_bounded_bilinear_map.linear_deriv`: Derivative of a continuous bilinear map as a linear map.
* `is_bounded_bilinear_map.deriv`: Derivative of a continuous bilinear map as a continuous linear
map. The proof that it is indeed the derivative is `is_bounded_bilinear_map.has_fderiv_at` in
`analysis.calculus.fderiv`.
* `linear_map.norm_apply_of_isometry`: A linear isometry preserves the norm.
## Notes
The main use of this file is `is_bounded_bilinear_map`. The file `analysis.normed_space.multilinear`
already expounds the theory of multilinear maps, but the `2`-variables case is sufficiently simpler
to currently deserve its own treatment.
`is_bounded_linear_map` is effectively an unbundled version of `continuous_linear_map` (defined
in `topology.algebra.module`, theory over normed spaces developed in
`analysis.normed_space.operator_norm`), albeit the name disparity. A bundled
`continuous_linear_map` is to be preferred over a `is_bounded_linear_map` hypothesis. Historical
artifact, really.
-/
noncomputable theory
open_locale classical big_operators topological_space
open filter (tendsto) metric
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{F : Type*} [normed_group F] [normed_space 𝕜 F]
{G : Type*} [normed_group G] [normed_space 𝕜 G]
/-- A function `f` satisfies `is_bounded_linear_map 𝕜 f` if it is linear and satisfies the
inequality `∥f x∥ ≤ M * ∥x∥` for some positive constant `M`. -/
structure is_bounded_linear_map (𝕜 : Type*) [normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{F : Type*} [normed_group F] [normed_space 𝕜 F] (f : E → F)
extends is_linear_map 𝕜 f : Prop :=
(bound : ∃ M, 0 < M ∧ ∀ x : E, ∥f x∥ ≤ M * ∥x∥)
lemma is_linear_map.with_bound
{f : E → F} (hf : is_linear_map 𝕜 f) (M : ℝ) (h : ∀ x : E, ∥f x∥ ≤ M * ∥x∥) :
is_bounded_linear_map 𝕜 f :=
⟨ hf, classical.by_cases
(assume : M ≤ 0, ⟨1, zero_lt_one, λ x,
(h x).trans $ mul_le_mul_of_nonneg_right (this.trans zero_le_one) (norm_nonneg x)⟩)
(assume : ¬ M ≤ 0, ⟨M, lt_of_not_ge this, h⟩)⟩
/-- A continuous linear map satisfies `is_bounded_linear_map` -/
lemma continuous_linear_map.is_bounded_linear_map (f : E →L[𝕜] F) : is_bounded_linear_map 𝕜 f :=
{ bound := f.bound,
..f.to_linear_map.is_linear }
namespace is_bounded_linear_map
/-- Construct a linear map from a function `f` satisfying `is_bounded_linear_map 𝕜 f`. -/
def to_linear_map (f : E → F) (h : is_bounded_linear_map 𝕜 f) : E →ₗ[𝕜] F :=
(is_linear_map.mk' _ h.to_is_linear_map)
/-- Construct a continuous linear map from is_bounded_linear_map -/
def to_continuous_linear_map {f : E → F} (hf : is_bounded_linear_map 𝕜 f) : E →L[𝕜] F :=
{ cont := let ⟨C, Cpos, hC⟩ := hf.bound in linear_map.continuous_of_bound _ C hC,
..to_linear_map f hf}
lemma zero : is_bounded_linear_map 𝕜 (λ (x:E), (0:F)) :=
(0 : E →ₗ F).is_linear.with_bound 0 $ by simp [le_refl]
lemma id : is_bounded_linear_map 𝕜 (λ (x:E), x) :=
linear_map.id.is_linear.with_bound 1 $ by simp [le_refl]
lemma fst : is_bounded_linear_map 𝕜 (λ x : E × F, x.1) :=
begin
refine (linear_map.fst 𝕜 E F).is_linear.with_bound 1 (λ x, _),
rw one_mul,
exact le_max_left _ _
end
lemma snd : is_bounded_linear_map 𝕜 (λ x : E × F, x.2) :=
begin
refine (linear_map.snd 𝕜 E F).is_linear.with_bound 1 (λ x, _),
rw one_mul,
exact le_max_right _ _
end
variables {f g : E → F}
lemma smul (c : 𝕜) (hf : is_bounded_linear_map 𝕜 f) :
is_bounded_linear_map 𝕜 (c • f) :=
let ⟨hlf, M, hMp, hM⟩ := hf in
(c • hlf.mk' f).is_linear.with_bound (∥c∥ * M) $ λ x,
calc ∥c • f x∥ = ∥c∥ * ∥f x∥ : norm_smul c (f x)
... ≤ ∥c∥ * (M * ∥x∥) : mul_le_mul_of_nonneg_left (hM _) (norm_nonneg _)
... = (∥c∥ * M) * ∥x∥ : (mul_assoc _ _ _).symm
lemma neg (hf : is_bounded_linear_map 𝕜 f) :
is_bounded_linear_map 𝕜 (λ e, -f e) :=
begin
rw show (λ e, -f e) = (λ e, (-1 : 𝕜) • f e), { funext, simp },
exact smul (-1) hf
end
lemma add (hf : is_bounded_linear_map 𝕜 f) (hg : is_bounded_linear_map 𝕜 g) :
is_bounded_linear_map 𝕜 (λ e, f e + g e) :=
let ⟨hlf, Mf, hMfp, hMf⟩ := hf in
let ⟨hlg, Mg, hMgp, hMg⟩ := hg in
(hlf.mk' _ + hlg.mk' _).is_linear.with_bound (Mf + Mg) $ λ x,
calc ∥f x + g x∥ ≤ Mf * ∥x∥ + Mg * ∥x∥ : norm_add_le_of_le (hMf x) (hMg x)
... ≤ (Mf + Mg) * ∥x∥ : by rw add_mul
lemma sub (hf : is_bounded_linear_map 𝕜 f) (hg : is_bounded_linear_map 𝕜 g) :
is_bounded_linear_map 𝕜 (λ e, f e - g e) :=
by simpa [sub_eq_add_neg] using add hf (neg hg)
lemma comp {g : F → G}
(hg : is_bounded_linear_map 𝕜 g) (hf : is_bounded_linear_map 𝕜 f) :
is_bounded_linear_map 𝕜 (g ∘ f) :=
(hg.to_continuous_linear_map.comp hf.to_continuous_linear_map).is_bounded_linear_map
protected lemma tendsto (x : E) (hf : is_bounded_linear_map 𝕜 f) :
tendsto f (𝓝 x) (𝓝 (f x)) :=
let ⟨hf, M, hMp, hM⟩ := hf in
tendsto_iff_norm_tendsto_zero.2 $
squeeze_zero (λ e, norm_nonneg _)
(λ e,
calc ∥f e - f x∥ = ∥hf.mk' f (e - x)∥ : by rw (hf.mk' _).map_sub e x; refl
... ≤ M * ∥e - x∥ : hM (e - x))
(suffices tendsto (λ (e : E), M * ∥e - x∥) (𝓝 x) (𝓝 (M * 0)), by simpa,
tendsto_const_nhds.mul (tendsto_norm_sub_self _))
lemma continuous (hf : is_bounded_linear_map 𝕜 f) : continuous f :=
continuous_iff_continuous_at.2 $ λ _, hf.tendsto _
lemma lim_zero_bounded_linear_map (hf : is_bounded_linear_map 𝕜 f) :
tendsto f (𝓝 0) (𝓝 0) :=
(hf.1.mk' _).map_zero ▸ continuous_iff_continuous_at.1 hf.continuous 0
section
open asymptotics filter
theorem is_O_id {f : E → F} (h : is_bounded_linear_map 𝕜 f) (l : filter E) :
is_O f (λ x, x) l :=
let ⟨M, hMp, hM⟩ := h.bound in is_O.of_bound _ (mem_sets_of_superset univ_mem_sets (λ x _, hM x))
theorem is_O_comp {E : Type*} {g : F → G} (hg : is_bounded_linear_map 𝕜 g)
{f : E → F} (l : filter E) : is_O (λ x', g (f x')) f l :=
(hg.is_O_id ⊤).comp_tendsto le_top
theorem is_O_sub {f : E → F} (h : is_bounded_linear_map 𝕜 f)
(l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l :=
is_O_comp h l
end
end is_bounded_linear_map
section
variables {ι : Type*} [decidable_eq ι] [fintype ι]
/-- Taking the cartesian product of two continuous multilinear maps
is a bounded linear operation. -/
lemma is_bounded_linear_map_prod_multilinear
{E : ι → Type*} [∀ i, normed_group (E i)] [∀ i, normed_space 𝕜 (E i)] :
is_bounded_linear_map 𝕜
(λ p : (continuous_multilinear_map 𝕜 E F) × (continuous_multilinear_map 𝕜 E G), p.1.prod p.2) :=
{ map_add := λ p₁ p₂, by { ext1 m, refl },
map_smul := λ c p, by { ext1 m, refl },
bound := ⟨1, zero_lt_one, λ p, begin
rw one_mul,
apply continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λ m, _),
rw [continuous_multilinear_map.prod_apply, norm_prod_le_iff],
split,
{ exact (p.1.le_op_norm m).trans
(mul_le_mul_of_nonneg_right (norm_fst_le p) (finset.prod_nonneg (λ i hi, norm_nonneg _))) },
{ exact (p.2.le_op_norm m).trans
(mul_le_mul_of_nonneg_right (norm_snd_le p) (finset.prod_nonneg (λ i hi, norm_nonneg _))) },
end⟩ }
/-- Given a fixed continuous linear map `g`, associating to a continuous multilinear map `f` the
continuous multilinear map `f (g m₁, ..., g mₙ)` is a bounded linear operation. -/
lemma is_bounded_linear_map_continuous_multilinear_map_comp_linear (g : G →L[𝕜] E) :
is_bounded_linear_map 𝕜 (λ f : continuous_multilinear_map 𝕜 (λ (i : ι), E) F,
f.comp_continuous_linear_map (λ _, g)) :=
begin
refine is_linear_map.with_bound ⟨λ f₁ f₂, by { ext m, refl }, λ c f, by { ext m, refl }⟩
(∥g∥ ^ (fintype.card ι)) (λ f, _),
apply continuous_multilinear_map.op_norm_le_bound _ _ (λ m, _),
{ apply_rules [mul_nonneg, pow_nonneg, norm_nonneg] },
calc ∥f (g ∘ m)∥ ≤
∥f∥ * ∏ i, ∥g (m i)∥ : f.le_op_norm _
... ≤ ∥f∥ * ∏ i, (∥g∥ * ∥m i∥) : begin
apply mul_le_mul_of_nonneg_left _ (norm_nonneg _),
exact finset.prod_le_prod (λ i hi, norm_nonneg _) (λ i hi, g.le_op_norm _)
end
... = ∥g∥ ^ fintype.card ι * ∥f∥ * ∏ i, ∥m i∥ :
by { simp [finset.prod_mul_distrib, finset.card_univ], ring }
end
end
section bilinear_map
variable (𝕜)
/-- A map `f : E × F → G` satisfies `is_bounded_bilinear_map 𝕜 f` if it is bilinear and
continuous. -/
structure is_bounded_bilinear_map (f : E × F → G) : Prop :=
(add_left : ∀ (x₁ x₂ : E) (y : F), f (x₁ + x₂, y) = f (x₁, y) + f (x₂, y))
(smul_left : ∀ (c : 𝕜) (x : E) (y : F), f (c • x, y) = c • f (x, y))
(add_right : ∀ (x : E) (y₁ y₂ : F), f (x, y₁ + y₂) = f (x, y₁) + f (x, y₂))
(smul_right : ∀ (c : 𝕜) (x : E) (y : F), f (x, c • y) = c • f (x,y))
(bound : ∃ C > 0, ∀ (x : E) (y : F), ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥)
variable {𝕜}
variable {f : E × F → G}
lemma continuous_linear_map.is_bounded_bilinear_map (f : E →L[𝕜] F →L[𝕜] G) :
is_bounded_bilinear_map 𝕜 (λ x : E × F, f x.1 x.2) :=
{ add_left := λ x₁ x₂ y, by rw [f.map_add, continuous_linear_map.add_apply],
smul_left := λ c x y, by rw [f.map_smul _, continuous_linear_map.smul_apply],
add_right := λ x, (f x).map_add,
smul_right := λ c x y, (f x).map_smul c y,
bound := ⟨max ∥f∥ 1, zero_lt_one.trans_le (le_max_right _ _),
λ x y, (f.le_op_norm₂ x y).trans $
by apply_rules [mul_le_mul_of_nonneg_right, norm_nonneg, le_max_left]⟩ }
protected lemma is_bounded_bilinear_map.is_O (h : is_bounded_bilinear_map 𝕜 f) :
asymptotics.is_O f (λ p : E × F, ∥p.1∥ * ∥p.2∥) ⊤ :=
let ⟨C, Cpos, hC⟩ := h.bound in asymptotics.is_O.of_bound _ $
filter.eventually_of_forall $ λ ⟨x, y⟩, by simpa [mul_assoc] using hC x y
lemma is_bounded_bilinear_map.is_O_comp {α : Type*} (H : is_bounded_bilinear_map 𝕜 f)
{g : α → E} {h : α → F} {l : filter α} :
asymptotics.is_O (λ x, f (g x, h x)) (λ x, ∥g x∥ * ∥h x∥) l :=
H.is_O.comp_tendsto le_top
protected lemma is_bounded_bilinear_map.is_O' (h : is_bounded_bilinear_map 𝕜 f) :
asymptotics.is_O f (λ p : E × F, ∥p∥ * ∥p∥) ⊤ :=
h.is_O.trans (asymptotics.is_O_fst_prod'.norm_norm.mul asymptotics.is_O_snd_prod'.norm_norm)
lemma is_bounded_bilinear_map.map_sub_left (h : is_bounded_bilinear_map 𝕜 f) {x y : E} {z : F} :
f (x - y, z) = f (x, z) - f(y, z) :=
calc f (x - y, z) = f (x + (-1 : 𝕜) • y, z) : by simp [sub_eq_add_neg]
... = f (x, z) + (-1 : 𝕜) • f (y, z) : by simp only [h.add_left, h.smul_left]
... = f (x, z) - f (y, z) : by simp [sub_eq_add_neg]
lemma is_bounded_bilinear_map.map_sub_right (h : is_bounded_bilinear_map 𝕜 f) {x : E} {y z : F} :
f (x, y - z) = f (x, y) - f (x, z) :=
calc f (x, y - z) = f (x, y + (-1 : 𝕜) • z) : by simp [sub_eq_add_neg]
... = f (x, y) + (-1 : 𝕜) • f (x, z) : by simp only [h.add_right, h.smul_right]
... = f (x, y) - f (x, z) : by simp [sub_eq_add_neg]
lemma is_bounded_bilinear_map.is_bounded_linear_map_left (h : is_bounded_bilinear_map 𝕜 f) (y : F) :
is_bounded_linear_map 𝕜 (λ x, f (x, y)) :=
{ map_add := λ x x', h.add_left _ _ _,
map_smul := λ c x, h.smul_left _ _ _,
bound := begin
rcases h.bound with ⟨C, C_pos, hC⟩,
refine ⟨C * (∥y∥ + 1), mul_pos C_pos (lt_of_lt_of_le (zero_lt_one) (by simp)), λ x, _⟩,
have : ∥y∥ ≤ ∥y∥ + 1, by simp [zero_le_one],
calc ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥ : hC x y
... ≤ C * ∥x∥ * (∥y∥ + 1) :
by apply_rules [norm_nonneg, mul_le_mul_of_nonneg_left, le_of_lt C_pos, mul_nonneg]
... = C * (∥y∥ + 1) * ∥x∥ : by ring
end }
lemma is_bounded_bilinear_map.is_bounded_linear_map_right
(h : is_bounded_bilinear_map 𝕜 f) (x : E) :
is_bounded_linear_map 𝕜 (λ y, f (x, y)) :=
{ map_add := λ y y', h.add_right _ _ _,
map_smul := λ c y, h.smul_right _ _ _,
bound := begin
rcases h.bound with ⟨C, C_pos, hC⟩,
refine ⟨C * (∥x∥ + 1), mul_pos C_pos (lt_of_lt_of_le (zero_lt_one) (by simp)), λ y, _⟩,
have : ∥x∥ ≤ ∥x∥ + 1, by simp [zero_le_one],
calc ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥ : hC x y
... ≤ C * (∥x∥ + 1) * ∥y∥ :
by apply_rules [mul_le_mul_of_nonneg_right, norm_nonneg, mul_le_mul_of_nonneg_left,
le_of_lt C_pos]
end }
lemma is_bounded_bilinear_map_smul {𝕜' : Type*} [normed_field 𝕜']
[normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜 E] [normed_space 𝕜' E]
[is_scalar_tower 𝕜 𝕜' E] :
is_bounded_bilinear_map 𝕜 (λ (p : 𝕜' × E), p.1 • p.2) :=
{ add_left := add_smul,
smul_left := λ c x y, by simp [smul_assoc],
add_right := smul_add,
smul_right := λ c x y, by simp [smul_assoc, smul_algebra_smul_comm],
bound := ⟨1, zero_lt_one, λ x y, by simp [norm_smul] ⟩ }
lemma is_bounded_bilinear_map_mul :
is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) :=
by simp_rw ← smul_eq_mul; exact is_bounded_bilinear_map_smul
lemma is_bounded_bilinear_map_comp :
is_bounded_bilinear_map 𝕜 (λ (p : (E →L[𝕜] F) × (F →L[𝕜] G)), p.2.comp p.1) :=
{ add_left := λ x₁ x₂ y, begin
ext z,
change y (x₁ z + x₂ z) = y (x₁ z) + y (x₂ z),
rw y.map_add
end,
smul_left := λ c x y, begin
ext z,
change y (c • (x z)) = c • y (x z),
rw continuous_linear_map.map_smul
end,
add_right := λ x y₁ y₂, rfl,
smul_right := λ c x y, rfl,
bound := ⟨1, zero_lt_one, λ x y, calc
∥continuous_linear_map.comp ((x, y).snd) ((x, y).fst)∥
≤ ∥y∥ * ∥x∥ : continuous_linear_map.op_norm_comp_le _ _
... = 1 * ∥x∥ * ∥ y∥ : by ring ⟩ }
lemma continuous_linear_map.is_bounded_linear_map_comp_left (g : F →L[𝕜] G) :
is_bounded_linear_map 𝕜 (λ (f : E →L[𝕜] F), continuous_linear_map.comp g f) :=
is_bounded_bilinear_map_comp.is_bounded_linear_map_left _
lemma continuous_linear_map.is_bounded_linear_map_comp_right (f : E →L[𝕜] F) :
is_bounded_linear_map 𝕜 (λ (g : F →L[𝕜] G), continuous_linear_map.comp g f) :=
is_bounded_bilinear_map_comp.is_bounded_linear_map_right _
lemma is_bounded_bilinear_map_apply :
is_bounded_bilinear_map 𝕜 (λ p : (E →L[𝕜] F) × E, p.1 p.2) :=
{ add_left := by simp,
smul_left := by simp,
add_right := by simp,
smul_right := by simp,
bound := ⟨1, zero_lt_one, by simp [continuous_linear_map.le_op_norm]⟩ }
/-- The function `continuous_linear_map.smul_right`, associating to a continuous linear map
`f : E → 𝕜` and a scalar `c : F` the tensor product `f ⊗ c` as a continuous linear map from `E` to
`F`, is a bounded bilinear map. -/
lemma is_bounded_bilinear_map_smul_right :
is_bounded_bilinear_map 𝕜
(λ p, (continuous_linear_map.smul_right : (E →L[𝕜] 𝕜) → F → (E →L[𝕜] F)) p.1 p.2) :=
{ add_left := λ m₁ m₂ f, by { ext z, simp [add_smul] },
smul_left := λ c m f, by { ext z, simp [mul_smul] },
add_right := λ m f₁ f₂, by { ext z, simp [smul_add] },
smul_right := λ c m f, by { ext z, simp [smul_smul, mul_comm] },
bound := ⟨1, zero_lt_one, λ m f, by simp⟩ }
/-- The composition of a continuous linear map with a continuous multilinear map is a bounded
bilinear operation. -/
lemma is_bounded_bilinear_map_comp_multilinear {ι : Type*} {E : ι → Type*}
[decidable_eq ι] [fintype ι] [∀ i, normed_group (E i)] [∀ i, normed_space 𝕜 (E i)] :
is_bounded_bilinear_map 𝕜 (λ p : (F →L[𝕜] G) × (continuous_multilinear_map 𝕜 E F),
p.1.comp_continuous_multilinear_map p.2) :=
{ add_left := λ g₁ g₂ f, by { ext m, refl },
smul_left := λ c g f, by { ext m, refl },
add_right := λ g f₁ f₂, by { ext m, simp },
smul_right := λ c g f, by { ext m, simp },
bound := ⟨1, zero_lt_one, λ g f, begin
apply continuous_multilinear_map.op_norm_le_bound _ _ (λ m, _),
{ apply_rules [mul_nonneg, zero_le_one, norm_nonneg] },
calc ∥g (f m)∥ ≤ ∥g∥ * ∥f m∥ : g.le_op_norm _
... ≤ ∥g∥ * (∥f∥ * ∏ i, ∥m i∥) :
mul_le_mul_of_nonneg_left (f.le_op_norm _) (norm_nonneg _)
... = 1 * ∥g∥ * ∥f∥ * ∏ i, ∥m i∥ : by ring
end⟩ }
/-- Definition of the derivative of a bilinear map `f`, given at a point `p` by
`q ↦ f(p.1, q.2) + f(q.1, p.2)` as in the standard formula for the derivative of a product.
We define this function here as a linear map `E × F →ₗ[𝕜] G`, then `is_bounded_bilinear_map.deriv`
strengthens it to a continuous linear map `E × F →L[𝕜] G`.
``. -/
def is_bounded_bilinear_map.linear_deriv (h : is_bounded_bilinear_map 𝕜 f) (p : E × F) :
E × F →ₗ[𝕜] G :=
{ to_fun := λ q, f (p.1, q.2) + f (q.1, p.2),
map_add' := λ q₁ q₂, begin
change f (p.1, q₁.2 + q₂.2) + f (q₁.1 + q₂.1, p.2) =
f (p.1, q₁.2) + f (q₁.1, p.2) + (f (p.1, q₂.2) + f (q₂.1, p.2)),
simp [h.add_left, h.add_right], abel
end,
map_smul' := λ c q, begin
change f (p.1, c • q.2) + f (c • q.1, p.2) = c • (f (p.1, q.2) + f (q.1, p.2)),
simp [h.smul_left, h.smul_right, smul_add]
end }
/-- The derivative of a bounded bilinear map at a point `p : E × F`, as a continuous linear map
from `E × F` to `G`. The statement that this is indeed the derivative of `f` is
`is_bounded_bilinear_map.has_fderiv_at` in `analysis.calculus.fderiv`. -/
def is_bounded_bilinear_map.deriv (h : is_bounded_bilinear_map 𝕜 f) (p : E × F) : E × F →L[𝕜] G :=
(h.linear_deriv p).mk_continuous_of_exists_bound $ begin
rcases h.bound with ⟨C, Cpos, hC⟩,
refine ⟨C * ∥p.1∥ + C * ∥p.2∥, λ q, _⟩,
calc ∥f (p.1, q.2) + f (q.1, p.2)∥
≤ C * ∥p.1∥ * ∥q.2∥ + C * ∥q.1∥ * ∥p.2∥ : norm_add_le_of_le (hC _ _) (hC _ _)
... ≤ C * ∥p.1∥ * ∥q∥ + C * ∥q∥ * ∥p.2∥ : begin
apply add_le_add,
exact mul_le_mul_of_nonneg_left
(le_max_right _ _) (mul_nonneg (le_of_lt Cpos) (norm_nonneg _)),
apply mul_le_mul_of_nonneg_right _ (norm_nonneg _),
exact mul_le_mul_of_nonneg_left (le_max_left _ _) (le_of_lt Cpos),
end
... = (C * ∥p.1∥ + C * ∥p.2∥) * ∥q∥ : by ring
end
@[simp] lemma is_bounded_bilinear_map_deriv_coe (h : is_bounded_bilinear_map 𝕜 f) (p q : E × F) :
h.deriv p q = f (p.1, q.2) + f (q.1, p.2) := rfl
variables (𝕜)
/-- The function `lmul_left_right : 𝕜' × 𝕜' → (𝕜' →L[𝕜] 𝕜')` is a bounded bilinear map. -/
lemma continuous_linear_map.lmul_left_right_is_bounded_bilinear
(𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] :
is_bounded_bilinear_map 𝕜 (λ p : 𝕜' × 𝕜', continuous_linear_map.lmul_left_right 𝕜 𝕜' p.1 p.2) :=
(continuous_linear_map.lmul_left_right 𝕜 𝕜').is_bounded_bilinear_map
variables {𝕜}
/-- Given a bounded bilinear map `f`, the map associating to a point `p` the derivative of `f` at
`p` is itself a bounded linear map. -/
lemma is_bounded_bilinear_map.is_bounded_linear_map_deriv (h : is_bounded_bilinear_map 𝕜 f) :
is_bounded_linear_map 𝕜 (λ p : E × F, h.deriv p) :=
begin
rcases h.bound with ⟨C, Cpos : 0 < C, hC⟩,
refine is_linear_map.with_bound ⟨λ p₁ p₂, _, λ c p, _⟩ (C + C) (λ p, _),
{ ext; simp [h.add_left, h.add_right]; abel },
{ ext; simp [h.smul_left, h.smul_right, smul_add] },
{ refine continuous_linear_map.op_norm_le_bound _
(mul_nonneg (add_nonneg Cpos.le Cpos.le) (norm_nonneg _)) (λ q, _),
calc ∥f (p.1, q.2) + f (q.1, p.2)∥
≤ C * ∥p.1∥ * ∥q.2∥ + C * ∥q.1∥ * ∥p.2∥ : norm_add_le_of_le (hC _ _) (hC _ _)
... ≤ C * ∥p∥ * ∥q∥ + C * ∥q∥ * ∥p∥ : by apply_rules [add_le_add, mul_le_mul, norm_nonneg,
Cpos.le, le_refl, le_max_left, le_max_right, mul_nonneg]
... = (C + C) * ∥p∥ * ∥q∥ : by ring },
end
end bilinear_map
/-- A linear isometry preserves the norm. -/
lemma linear_map.norm_apply_of_isometry (f : E →ₗ[𝕜] F) {x : E} (hf : isometry f) : ∥f x∥ = ∥x∥ :=
by { simp_rw [←dist_zero_right, ←f.map_zero], exact isometry.dist_eq hf _ _ }
/-- Construct a continuous linear equiv from
a linear map that is also an isometry with full range. -/
def continuous_linear_equiv.of_isometry (f : E →ₗ[𝕜] F) (hf : isometry f) (hfr : f.range = ⊤) :
E ≃L[𝕜] F :=
continuous_linear_equiv.of_homothety
(linear_equiv.of_bijective f (linear_map.ker_eq_bot.mpr (isometry.injective hf)) hfr)
1 zero_lt_one (λ _, by simp [one_mul, f.norm_apply_of_isometry hf])
|
16711c77cfe778facdcc2faa004e1e8843967700 | d450724ba99f5b50b57d244eb41fef9f6789db81 | /src/instructor/lectures/lecture_23b.lean | b5047796dba12236b5325fedac24b504a45ef3ec | [] | no_license | jakekauff/CS2120F21 | 4f009adeb4ce4a148442b562196d66cc6c04530c | e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad | refs/heads/main | 1,693,841,880,030 | 1,637,604,848,000 | 1,637,604,848,000 | 399,946,698 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,440 | lean | /-
A challenging example that we considered recently
was the question whether a relation {(1,2),(4,5)}
is transitive. It is because it is a model of the
constraint that defines transitivity: a universal
generalization of a conditional. For every three
possible objects, a, b, and c, if the pair (a,b)
is in the relation, and (b,c) is, too, only then
must the relation also contain the pair (a,c), if
it is to be transitive. But in the case where there
are *no* instances of pairs, (a,b) and (b,c), with
a common, pair-joining element, b, then there are
no cases in which there needs to be a third pair.
In this unit we just strengthen the idea that you
already have that a univeral genealization (a ∀)
over an empty set is always true, and that makes
sense because there are no cases that individually
have to satisfy the given constraints.
-/
/-
UNIVERSAL QUANTIFICATION OVER AN EMPTY SET IS TRUE
Let's review the most puzzling of the examples from
last time: a relation r = {(0,1), (2,3)} we said is
transitive because it satisfies the constraint that
defines transitivity: for every x, y, and x, if (x,y)
is in r, and (y,z) is in r, then (x,z) is in r. This
relation is transitive because in *every* case where
we have (x, y) and (y, z) in r, (x, z) is in r. In
this example, there are *no* such cases, and so the
predicate is satisfied!
Let's think about this principle using a different
example. Question: is every ball in an empty bucket
of balls red?
-/
axioms (Ball : Type) (red : Ball → Prop)
def empty_bucket := ({} : set Ball)
lemma allBallsInEmptyBucketAreRed :
∀ (b : Ball), b ∈ empty_bucket → red b :=
begin
assume b h,
cases h, -- finish off this proof
end
/-
Whoa, ok. That's a little bit counterintuitive, but
it's correct. A universal quantification over an empty
set is always trivially true.
Here's another way to think about it. Suppose we had
a set with two balls in it: { b1, b2 }. To show that
every ball is red, we could use case analysis: break
the task into two cases: show that b1 is red, AND
show that all balls in the remaining set, { b2 }, are
red.
To prove the latter, we'd show that b2 is red, and
that all balls in the remaining set, {}, are red.
So we have that all balls are red if (red b1) ∧
(red b2) ∧ "all balls in {} are red".
If b1 and b2 really are red, then the last proposition
better be true if the whole chain of ∧ operations is to
be true. When you think about ∀ as a version of ∧ that
can take any number of arguments, not just 2, it becomes
clear that when applied to zero arguments, the answer
really has to be true, otherwise this operation would
*always* produce propositions that are ultimately false.
-/
/-
So now let's revisit once again our funny example of
transitivity: { (0,1), (2,3) }. There are no cases
here where we have both (x,y) and (y,z) as pairs in
this relation, so there are no cases to consider.
When there are no cases to consider, the conclusion
holds in all cases, of which there are 0, so it holds.
Question: Is this symmetric? {(0,1), (1,0), (2,2)}
How about this: {(0,1), (1,0), (2,3)}?
Now suppose that we have a relation, r, over a set
of values, {0, 1, 2, 3, 4, 5}. Is this relation
reflexive? {} What about this: {(0, 1), (2, 3)}
Question: If a relation is transitive and symmetric
is it necessarily reflexive? If so, give an informal
argument/proof. If not, give a counter-example.
-/
|
41c675b481168858491a0b7d16783a9492a1a0c4 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /13_More_Tactics.org.6.lean | 4e40fea0e515b8d9c816c34bf2f4e1f9ac242682 | [] | 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 | 184 | lean | import standard
import data.nat
open nat
example : ∃ x, x > 2 :=
by existsi 3; exact dec_trivial
example (B : ℕ → Type) (b : B 2) : Σ x : ℕ, B x :=
by existsi 2; assumption
|
2a8d2d762e7f67cddc4b8adab6870f777c4f386a | 947b78d97130d56365ae2ec264df196ce769371a | /src/Lean/Eval.lean | c15aa6655c79fb165f0b76b44eaaa4c98bf0a297 | [
"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 | 905 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Environment
namespace Lean
universe u
/-- `HasEval` extension that gives access to the current environment & options.
The basic `HasEval` class is in the prelude and should not depend on these
types. -/
class MetaHasEval (α : Type u) :=
(eval : Environment → Options → α → forall (hideUnit : optParam Bool true), IO Environment)
instance metaHasEvalOfHasEval {α : Type u} [HasEval α] : MetaHasEval α :=
⟨fun env opts a hideUnit => do HasEval.eval a hideUnit; pure env⟩
def runMetaEval {α : Type u} [MetaHasEval α] (env : Environment) (opts : Options) (a : α) : IO (String × Except IO.Error Environment) :=
IO.FS.withIsolatedStreams (MetaHasEval.eval env opts a false)
end Lean
|
8ca28a8ff237143a37698551b9a994889bcb32b9 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Std/Data/HashMap.lean | e9cecaeb86efd8df11f67f7a2e3776989ef06082 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 9,093 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Std.Data.AssocList
namespace Std
universe u v w
def HashMapBucket (α : Type u) (β : Type v) :=
{ b : Array (AssocList α β) // b.size > 0 }
def HashMapBucket.update {α : Type u} {β : Type v} (data : HashMapBucket α β) (i : USize) (d : AssocList α β) (h : i.toNat < data.val.size) : HashMapBucket α β :=
⟨ data.val.uset i d h,
by erw [Array.size_set]; apply data.property ⟩
structure HashMapImp (α : Type u) (β : Type v) where
size : Nat
buckets : HashMapBucket α β
private def numBucketsForCapacity (capacity : Nat) : Nat :=
-- a "load factor" of 0.75 is the usual standard for hash maps
capacity * 4 / 3
def mkHashMapImp {α : Type u} {β : Type v} (capacity := 0) : HashMapImp α β :=
let_fun nbuckets := numBucketsForCapacity capacity
let n := if nbuckets = 0 then 8 else nbuckets
{ size := 0,
buckets :=
⟨ mkArray n AssocList.nil,
by simp; cases nbuckets; decide; apply Nat.zero_lt_succ; done ⟩ }
namespace HashMapImp
variable {α : Type u} {β : Type v}
def mkIdx {n : Nat} (h : n > 0) (u : USize) : { u : USize // u.toNat < n } :=
⟨u % n, USize.modn_lt _ h⟩
@[inline] def reinsertAux (hashFn : α → UInt64) (data : HashMapBucket α β) (a : α) (b : β) : HashMapBucket α β :=
let ⟨i, h⟩ := mkIdx data.property (hashFn a |>.toUSize)
data.update i (AssocList.cons a b data.val[i]) h
@[inline] def foldBucketsM {δ : Type w} {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (d : δ) (f : δ → α → β → m δ) : m δ :=
data.val.foldlM (init := d) fun d b => b.foldlM f d
@[inline] def foldBuckets {δ : Type w} (data : HashMapBucket α β) (d : δ) (f : δ → α → β → δ) : δ :=
Id.run $ foldBucketsM data d f
@[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (d : δ) (h : HashMapImp α β) : m δ :=
foldBucketsM h.buckets d f
@[inline] def fold {δ : Type w} (f : δ → α → β → δ) (d : δ) (m : HashMapImp α β) : δ :=
foldBuckets m.buckets d f
@[inline] def forBucketsM {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (f : α → β → m PUnit) : m PUnit :=
data.val.forM fun b => b.forM f
@[inline] def forM {m : Type w → Type w} [Monad m] (f : α → β → m PUnit) (h : HashMapImp α β) : m PUnit :=
forBucketsM h.buckets f
def findEntry? [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option (α × β) :=
match m with
| ⟨_, buckets⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a |>.toUSize)
buckets.val[i].findEntry? a
def find? [beq : BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option β :=
match m with
| ⟨_, buckets⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a |>.toUSize)
buckets.val[i].find? a
def contains [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Bool :=
match m with
| ⟨_, buckets⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a |>.toUSize)
buckets.val[i].contains a
def moveEntries [Hashable α] (i : Nat) (source : Array (AssocList α β)) (target : HashMapBucket α β) : HashMapBucket α β :=
if h : i < source.size then
let idx : Fin source.size := ⟨i, h⟩
let es : AssocList α β := source.get idx
-- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl
let source := source.set idx AssocList.nil
let target := es.foldl (reinsertAux hash) target
moveEntries (i+1) source target
else target
termination_by _ i source _ => source.size - i
def expand [Hashable α] (size : Nat) (buckets : HashMapBucket α β) : HashMapImp α β :=
let nbuckets := buckets.val.size * 2
have : nbuckets > 0 := Nat.mul_pos buckets.property (by decide)
let new_buckets : HashMapBucket α β := ⟨mkArray nbuckets AssocList.nil, by simp; assumption⟩
{ size := size,
buckets := moveEntries 0 buckets.val new_buckets }
@[inline] def insert [beq : BEq α] [Hashable α] (m : HashMapImp α β) (a : α) (b : β) : HashMapImp α β × Bool :=
match m with
| ⟨size, buckets⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a |>.toUSize)
let bkt := buckets.val[i]
if bkt.contains a then
(⟨size, buckets.update i (bkt.replace a b) h⟩, true)
else
let size' := size + 1
let buckets' := buckets.update i (AssocList.cons a b bkt) h
if numBucketsForCapacity size' ≤ buckets.val.size then
({ size := size', buckets := buckets' }, false)
else
(expand size' buckets', false)
def erase [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : HashMapImp α β :=
match m with
| ⟨ size, buckets ⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a |>.toUSize)
let bkt := buckets.val[i]
if bkt.contains a then ⟨size - 1, buckets.update i (bkt.erase a) h⟩
else m
inductive WellFormed [BEq α] [Hashable α] : HashMapImp α β → Prop where
| mkWff : ∀ n, WellFormed (mkHashMapImp n)
| insertWff : ∀ m a b, WellFormed m → WellFormed (insert m a b |>.1)
| eraseWff : ∀ m a, WellFormed m → WellFormed (erase m a)
end HashMapImp
def HashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] :=
{ m : HashMapImp α β // m.WellFormed }
open Std.HashMapImp
def mkHashMap {α : Type u} {β : Type v} [BEq α] [Hashable α] (capacity := 0) : HashMap α β :=
⟨ mkHashMapImp capacity, WellFormed.mkWff capacity ⟩
namespace HashMap
instance [BEq α] [Hashable α] : Inhabited (HashMap α β) where
default := mkHashMap
instance [BEq α] [Hashable α] : EmptyCollection (HashMap α β) := ⟨mkHashMap⟩
@[inline] def empty [BEq α] [Hashable α] : HashMap α β :=
mkHashMap
variable {α : Type u} {β : Type v} {_ : BEq α} {_ : Hashable α}
def insert (m : HashMap α β) (a : α) (b : β) : HashMap α β :=
match m with
| ⟨ m, hw ⟩ =>
match h:m.insert a b with
| (m', _) => ⟨ m', by have aux := WellFormed.insertWff m a b hw; rw [h] at aux; assumption ⟩
/-- Similar to `insert`, but also returns a Boolean flad indicating whether an existing entry has been replaced with `a -> b`. -/
def insert' (m : HashMap α β) (a : α) (b : β) : HashMap α β × Bool :=
match m with
| ⟨ m, hw ⟩ =>
match h:m.insert a b with
| (m', replaced) => (⟨ m', by have aux := WellFormed.insertWff m a b hw; rw [h] at aux; assumption ⟩, replaced)
@[inline] def erase (m : HashMap α β) (a : α) : HashMap α β :=
match m with
| ⟨ m, hw ⟩ => ⟨ m.erase a, WellFormed.eraseWff m a hw ⟩
@[inline] def findEntry? (m : HashMap α β) (a : α) : Option (α × β) :=
match m with
| ⟨ m, _ ⟩ => m.findEntry? a
@[inline] def find? (m : HashMap α β) (a : α) : Option β :=
match m with
| ⟨ m, _ ⟩ => m.find? a
@[inline] def findD (m : HashMap α β) (a : α) (b₀ : β) : β :=
(m.find? a).getD b₀
@[inline] def find! [Inhabited β] (m : HashMap α β) (a : α) : β :=
match m.find? a with
| some b => b
| none => panic! "key is not in the map"
instance : GetElem (HashMap α β) α (Option β) fun _ _ => True where
getElem m k _ := m.find? k
@[inline] def contains (m : HashMap α β) (a : α) : Bool :=
match m with
| ⟨ m, _ ⟩ => m.contains a
@[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (init : δ) (h : HashMap α β) : m δ :=
match h with
| ⟨ h, _ ⟩ => h.foldM f init
@[inline] def fold {δ : Type w} (f : δ → α → β → δ) (init : δ) (m : HashMap α β) : δ :=
match m with
| ⟨ m, _ ⟩ => m.fold f init
@[inline] def forM {m : Type w → Type w} [Monad m] (f : α → β → m PUnit) (h : HashMap α β) : m PUnit :=
match h with
| ⟨ h, _ ⟩ => h.forM f
@[inline] def size (m : HashMap α β) : Nat :=
match m with
| ⟨ {size := sz, ..}, _ ⟩ => sz
@[inline] def isEmpty (m : HashMap α β) : Bool :=
m.size = 0
def toList (m : HashMap α β) : List (α × β) :=
m.fold (init := []) fun r k v => (k, v)::r
def toArray (m : HashMap α β) : Array (α × β) :=
m.fold (init := #[]) fun r k v => r.push (k, v)
def numBuckets (m : HashMap α β) : Nat :=
m.val.buckets.val.size
/-- Builds a `HashMap` from a list of key-value pairs. Values of duplicated keys are replaced by their respective last occurrences. -/
def ofList (l : List (α × β)) : HashMap α β :=
l.foldl (init := HashMap.empty) (fun m p => m.insert p.fst p.snd)
/-- Variant of `ofList` which accepts a function that combines values of duplicated keys. -/
def ofListWith (l : List (α × β)) (f : β → β → β) : HashMap α β :=
l.foldl (init := HashMap.empty)
(fun m p =>
match m.find? p.fst with
| none => m.insert p.fst p.snd
| some v => m.insert p.fst $ f v p.snd)
end HashMap
end Std
|
36c273444b23e2c2496233ad034a704c5b18603f | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /leanpkg/leanpkg/proc.lean | 8ed73265c8da40cecd53b7c864138f74c6418cc6 | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 626 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Gabriel Ebner
-/
import system.io leanpkg.toml
open io io.proc
variable [io.interface]
namespace leanpkg
def exec_cmd (args : io.process.spawn_args) : io unit := do
let cmdstr := join " " (args.cmd :: args.args),
io.put_str_ln $ "> " ++
match args.cwd with
| some cwd := cmdstr ++ " # in directory " ++ cwd
| none := cmdstr
end,
ch ← spawn args,
exitv ← wait ch,
when (exitv ≠ 0) $ io.fail $
"external command exited with status " ++ exitv.to_string
end leanpkg
|
d92a1a1307a4ef9283cf88aec5d006612ac34226 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/linear_algebra/affine_space/affine_map.lean | 49fe60c2c55c1852c25bc08d7cd96efc517bf852 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 23,585 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import algebra.add_torsor
import data.set.intervals.unordered_interval
import linear_algebra.affine_space.basic
import linear_algebra.bilinear_map
import linear_algebra.pi
import linear_algebra.prod
import tactic.abel
/-!
# Affine maps
This file defines affine maps.
## Main definitions
* `affine_map` is the type of affine maps between two affine spaces with the same ring `k`. Various
basic examples of affine maps are defined, including `const`, `id`, `line_map` and `homothety`.
## Notations
* `P1 →ᵃ[k] P2` is a notation for `affine_map k P1 P2`;
* `affine_space V P`: a localized notation for `add_torsor V P` defined in
`linear_algebra.affine_space.basic`.
## Implementation notes
`out_param` is used in the definition of `[add_torsor V P]` to make `V` an implicit argument
(deduced from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes
using it, to be added as implicit arguments to individual lemmas. As for modules, `k` is an
explicit argument rather than implied by `P` or `V`.
This file only provides purely algebraic definitions and results. Those depending on analysis or
topology are defined elsewhere; see `analysis.normed_space.add_torsor` and
`topology.algebra.affine`.
## References
* https://en.wikipedia.org/wiki/Affine_space
* https://en.wikipedia.org/wiki/Principal_homogeneous_space
-/
open_locale affine
/-- An `affine_map k P1 P2` (notation: `P1 →ᵃ[k] P2`) is a map from `P1` to `P2` that
induces a corresponding linear map from `V1` to `V2`. -/
structure affine_map (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*)
[ring k]
[add_comm_group V1] [module k V1] [affine_space V1 P1]
[add_comm_group V2] [module k V2] [affine_space V2 P2] :=
(to_fun : P1 → P2)
(linear : V1 →ₗ[k] V2)
(map_vadd' : ∀ (p : P1) (v : V1), to_fun (v +ᵥ p) = linear v +ᵥ to_fun p)
notation P1 ` →ᵃ[`:25 k:25 `] `:0 P2:0 := affine_map k P1 P2
instance (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*)
[ring k]
[add_comm_group V1] [module k V1] [affine_space V1 P1]
[add_comm_group V2] [module k V2] [affine_space V2 P2]:
has_coe_to_fun (P1 →ᵃ[k] P2) (λ _, P1 → P2) := ⟨affine_map.to_fun⟩
namespace linear_map
variables {k : Type*} {V₁ : Type*} {V₂ : Type*} [ring k] [add_comm_group V₁] [module k V₁]
[add_comm_group V₂] [module k V₂] (f : V₁ →ₗ[k] V₂)
/-- Reinterpret a linear map as an affine map. -/
def to_affine_map : V₁ →ᵃ[k] V₂ :=
{ to_fun := f,
linear := f,
map_vadd' := λ p v, f.map_add v p }
@[simp] lemma coe_to_affine_map : ⇑f.to_affine_map = f := rfl
@[simp] lemma to_affine_map_linear : f.to_affine_map.linear = f := rfl
end linear_map
namespace affine_map
variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} {P2 : Type*}
{V3 : Type*} {P3 : Type*} {V4 : Type*} {P4 : Type*} [ring k]
[add_comm_group V1] [module k V1] [affine_space V1 P1]
[add_comm_group V2] [module k V2] [affine_space V2 P2]
[add_comm_group V3] [module k V3] [affine_space V3 P3]
[add_comm_group V4] [module k V4] [affine_space V4 P4]
include V1 V2
/-- Constructing an affine map and coercing back to a function
produces the same map. -/
@[simp] lemma coe_mk (f : P1 → P2) (linear add) :
((mk f linear add : P1 →ᵃ[k] P2) : P1 → P2) = f := rfl
/-- `to_fun` is the same as the result of coercing to a function. -/
@[simp] lemma to_fun_eq_coe (f : P1 →ᵃ[k] P2) : f.to_fun = ⇑f := rfl
/-- An affine map on the result of adding a vector to a point produces
the same result as the linear map applied to that vector, added to the
affine map applied to that point. -/
@[simp] lemma map_vadd (f : P1 →ᵃ[k] P2) (p : P1) (v : V1) :
f (v +ᵥ p) = f.linear v +ᵥ f p := f.map_vadd' p v
/-- The linear map on the result of subtracting two points is the
result of subtracting the result of the affine map on those two
points. -/
@[simp] lemma linear_map_vsub (f : P1 →ᵃ[k] P2) (p1 p2 : P1) :
f.linear (p1 -ᵥ p2) = f p1 -ᵥ f p2 :=
by conv_rhs { rw [←vsub_vadd p1 p2, map_vadd, vadd_vsub] }
/-- Two affine maps are equal if they coerce to the same function. -/
@[ext] lemma ext {f g : P1 →ᵃ[k] P2} (h : ∀ p, f p = g p) : f = g :=
begin
rcases f with ⟨f, f_linear, f_add⟩,
rcases g with ⟨g, g_linear, g_add⟩,
obtain rfl : f = g := funext h,
congr' with v,
cases (add_torsor.nonempty : nonempty P1) with p,
apply vadd_right_cancel (f p),
erw [← f_add, ← g_add]
end
lemma ext_iff {f g : P1 →ᵃ[k] P2} : f = g ↔ ∀ p, f p = g p := ⟨λ h p, h ▸ rfl, ext⟩
lemma coe_fn_injective : @function.injective (P1 →ᵃ[k] P2) (P1 → P2) coe_fn :=
λ f g H, ext $ congr_fun H
protected lemma congr_arg (f : P1 →ᵃ[k] P2) {x y : P1} (h : x = y) : f x = f y :=
congr_arg _ h
protected lemma congr_fun {f g : P1 →ᵃ[k] P2} (h : f = g) (x : P1) : f x = g x :=
h ▸ rfl
variables (k P1)
/-- Constant function as an `affine_map`. -/
def const (p : P2) : P1 →ᵃ[k] P2 :=
{ to_fun := function.const P1 p,
linear := 0,
map_vadd' := λ p v, by simp }
@[simp] lemma coe_const (p : P2) : ⇑(const k P1 p) = function.const P1 p := rfl
@[simp] lemma const_linear (p : P2) : (const k P1 p).linear = 0 := rfl
variables {k P1}
lemma linear_eq_zero_iff_exists_const (f : P1 →ᵃ[k] P2) :
f.linear = 0 ↔ ∃ q, f = const k P1 q :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ use f (classical.arbitrary P1),
ext,
rw [coe_const, function.const_apply, ← @vsub_eq_zero_iff_eq V2, ← f.linear_map_vsub, h,
linear_map.zero_apply], },
{ rcases h with ⟨q, rfl⟩,
exact const_linear k P1 q, },
end
instance nonempty : nonempty (P1 →ᵃ[k] P2) :=
(add_torsor.nonempty : nonempty P2).elim $ λ p, ⟨const k P1 p⟩
/-- Construct an affine map by verifying the relation between the map and its linear part at one
base point. Namely, this function takes a map `f : P₁ → P₂`, a linear map `f' : V₁ →ₗ[k] V₂`, and
a point `p` such that for any other point `p'` we have `f p' = f' (p' -ᵥ p) +ᵥ f p`. -/
def mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p : P1) (h : ∀ p' : P1, f p' = f' (p' -ᵥ p) +ᵥ f p) :
P1 →ᵃ[k] P2 :=
{ to_fun := f,
linear := f',
map_vadd' := λ p' v, by rw [h, h p', vadd_vsub_assoc, f'.map_add, vadd_vadd] }
@[simp] lemma coe_mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : ⇑(mk' f f' p h) = f := rfl
@[simp] lemma mk'_linear (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : (mk' f f' p h).linear = f' := rfl
section has_smul
variables {R : Type*} [monoid R] [distrib_mul_action R V2] [smul_comm_class k R V2]
/-- The space of affine maps to a module inherits an `R`-action from the action on its codomain. -/
instance : mul_action R (P1 →ᵃ[k] V2) :=
{ smul := λ c f, ⟨c • f, c • f.linear, λ p v, by simp [smul_add]⟩,
one_smul := λ f, ext $ λ p, one_smul _ _,
mul_smul := λ c₁ c₂ f, ext $ λ p, mul_smul _ _ _ }
@[simp, norm_cast] lemma coe_smul (c : R) (f : P1 →ᵃ[k] V2) : ⇑(c • f) = c • f := rfl
@[simp] lemma smul_linear (t : R) (f : P1 →ᵃ[k] V2) : (t • f).linear = t • f.linear := rfl
instance [distrib_mul_action Rᵐᵒᵖ V2] [is_central_scalar R V2] :
is_central_scalar R (P1 →ᵃ[k] V2) :=
{ op_smul_eq_smul := λ r x, ext $ λ _, op_smul_eq_smul _ _ }
end has_smul
instance : has_zero (P1 →ᵃ[k] V2) := { zero := ⟨0, 0, λ p v, (zero_vadd _ _).symm⟩ }
instance : has_add (P1 →ᵃ[k] V2) :=
{ add := λ f g, ⟨f + g, f.linear + g.linear, λ p v, by simp [add_add_add_comm]⟩ }
instance : has_sub (P1 →ᵃ[k] V2) :=
{ sub := λ f g, ⟨f - g, f.linear - g.linear, λ p v, by simp [sub_add_sub_comm]⟩ }
instance : has_neg (P1 →ᵃ[k] V2) := { neg := λ f, ⟨-f, -f.linear, λ p v, by simp [add_comm]⟩ }
@[simp, norm_cast] lemma coe_zero : ⇑(0 : P1 →ᵃ[k] V2) = 0 := rfl
@[simp, norm_cast] lemma coe_add (f g : P1 →ᵃ[k] V2) : ⇑(f + g) = f + g := rfl
@[simp, norm_cast] lemma coe_neg (f : P1 →ᵃ[k] V2) : ⇑(-f) = -f := rfl
@[simp, norm_cast] lemma coe_sub (f g : P1 →ᵃ[k] V2) : ⇑(f - g) = f - g := rfl
@[simp] lemma zero_linear : (0 : P1 →ᵃ[k] V2).linear = 0 := rfl
@[simp] lemma add_linear (f g : P1 →ᵃ[k] V2) : (f + g).linear = f.linear + g.linear := rfl
@[simp] lemma sub_linear (f g : P1 →ᵃ[k] V2) : (f - g).linear = f.linear - g.linear := rfl
@[simp] lemma neg_linear (f : P1 →ᵃ[k] V2) : (-f).linear = -f.linear := rfl
/-- The set of affine maps to a vector space is an additive commutative group. -/
instance : add_comm_group (P1 →ᵃ[k] V2) :=
coe_fn_injective.add_comm_group _
coe_zero coe_add coe_neg coe_sub (λ _ _, coe_smul _ _) (λ _ _, coe_smul _ _)
/-- The space of affine maps from `P1` to `P2` is an affine space over the space of affine maps
from `P1` to the vector space `V2` corresponding to `P2`. -/
instance : affine_space (P1 →ᵃ[k] V2) (P1 →ᵃ[k] P2) :=
{ vadd := λ f g, ⟨λ p, f p +ᵥ g p, f.linear + g.linear, λ p v,
by simp [vadd_vadd, add_right_comm]⟩,
zero_vadd := λ f, ext $ λ p, zero_vadd _ (f p),
add_vadd := λ f₁ f₂ f₃, ext $ λ p, add_vadd (f₁ p) (f₂ p) (f₃ p),
vsub := λ f g, ⟨λ p, f p -ᵥ g p, f.linear - g.linear, λ p v,
by simp [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, sub_add_eq_add_sub]⟩,
vsub_vadd' := λ f g, ext $ λ p, vsub_vadd (f p) (g p),
vadd_vsub' := λ f g, ext $ λ p, vadd_vsub (f p) (g p) }
@[simp] lemma vadd_apply (f : P1 →ᵃ[k] V2) (g : P1 →ᵃ[k] P2) (p : P1) :
(f +ᵥ g) p = f p +ᵥ g p :=
rfl
@[simp] lemma vsub_apply (f g : P1 →ᵃ[k] P2) (p : P1) :
(f -ᵥ g : P1 →ᵃ[k] V2) p = f p -ᵥ g p :=
rfl
/-- `prod.fst` as an `affine_map`. -/
def fst : (P1 × P2) →ᵃ[k] P1 :=
{ to_fun := prod.fst,
linear := linear_map.fst k V1 V2,
map_vadd' := λ _ _, rfl }
@[simp] lemma coe_fst : ⇑(fst : (P1 × P2) →ᵃ[k] P1) = prod.fst := rfl
@[simp] lemma fst_linear : (fst : (P1 × P2) →ᵃ[k] P1).linear = linear_map.fst k V1 V2 := rfl
/-- `prod.snd` as an `affine_map`. -/
def snd : (P1 × P2) →ᵃ[k] P2 :=
{ to_fun := prod.snd,
linear := linear_map.snd k V1 V2,
map_vadd' := λ _ _, rfl }
@[simp] lemma coe_snd : ⇑(snd : (P1 × P2) →ᵃ[k] P2) = prod.snd := rfl
@[simp] lemma snd_linear : (snd : (P1 × P2) →ᵃ[k] P2).linear = linear_map.snd k V1 V2 := rfl
variables (k P1)
omit V2
/-- Identity map as an affine map. -/
def id : P1 →ᵃ[k] P1 :=
{ to_fun := id,
linear := linear_map.id,
map_vadd' := λ p v, rfl }
/-- The identity affine map acts as the identity. -/
@[simp] lemma coe_id : ⇑(id k P1) = _root_.id := rfl
@[simp] lemma id_linear : (id k P1).linear = linear_map.id := rfl
variable {P1}
/-- The identity affine map acts as the identity. -/
lemma id_apply (p : P1) : id k P1 p = p := rfl
variables {k P1}
instance : inhabited (P1 →ᵃ[k] P1) := ⟨id k P1⟩
include V2 V3
/-- Composition of affine maps. -/
def comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : P1 →ᵃ[k] P3 :=
{ to_fun := f ∘ g,
linear := f.linear.comp g.linear,
map_vadd' := begin
intros p v,
rw [function.comp_app, g.map_vadd, f.map_vadd],
refl
end }
/-- Composition of affine maps acts as applying the two functions. -/
@[simp] lemma coe_comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) :
⇑(f.comp g) = f ∘ g := rfl
/-- Composition of affine maps acts as applying the two functions. -/
lemma comp_apply (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) (p : P1) :
f.comp g p = f (g p) := rfl
omit V3
@[simp] lemma comp_id (f : P1 →ᵃ[k] P2) : f.comp (id k P1) = f := ext $ λ p, rfl
@[simp] lemma id_comp (f : P1 →ᵃ[k] P2) : (id k P2).comp f = f := ext $ λ p, rfl
include V3 V4
lemma comp_assoc (f₃₄ : P3 →ᵃ[k] P4) (f₂₃ : P2 →ᵃ[k] P3) (f₁₂ : P1 →ᵃ[k] P2) :
(f₃₄.comp f₂₃).comp f₁₂ = f₃₄.comp (f₂₃.comp f₁₂) :=
rfl
omit V2 V3 V4
instance : monoid (P1 →ᵃ[k] P1) :=
{ one := id k P1,
mul := comp,
one_mul := id_comp,
mul_one := comp_id,
mul_assoc := comp_assoc }
@[simp] lemma coe_mul (f g : P1 →ᵃ[k] P1) : ⇑(f * g) = f ∘ g := rfl
@[simp] lemma coe_one : ⇑(1 : P1 →ᵃ[k] P1) = _root_.id := rfl
/-- `affine_map.linear` on endomorphisms is a `monoid_hom`. -/
@[simps] def linear_hom : (P1 →ᵃ[k] P1) →* (V1 →ₗ[k] V1) :=
{ to_fun := linear,
map_one' := rfl,
map_mul' := λ _ _, rfl }
include V2
@[simp] lemma injective_iff_linear_injective (f : P1 →ᵃ[k] P2) :
function.injective f.linear ↔ function.injective f :=
begin
obtain ⟨p⟩ := (infer_instance : nonempty P1),
have h : ⇑f.linear = (equiv.vadd_const (f p)).symm ∘ f ∘ (equiv.vadd_const p),
{ ext v, simp [f.map_vadd, vadd_vsub_assoc], },
rw [h, equiv.comp_injective, equiv.injective_comp],
end
@[simp] lemma surjective_iff_linear_surjective (f : P1 →ᵃ[k] P2) :
function.surjective f.linear ↔ function.surjective f :=
begin
obtain ⟨p⟩ := (infer_instance : nonempty P1),
have h : ⇑f.linear = (equiv.vadd_const (f p)).symm ∘ f ∘ (equiv.vadd_const p),
{ ext v, simp [f.map_vadd, vadd_vsub_assoc], },
rw [h, equiv.comp_surjective, equiv.surjective_comp],
end
lemma image_vsub_image {s t : set P1} (f : P1 →ᵃ[k] P2) :
(f '' s) -ᵥ (f '' t) = f.linear '' (s -ᵥ t) :=
begin
ext v,
simp only [set.mem_vsub, set.mem_image, exists_exists_and_eq_and, exists_and_distrib_left,
← f.linear_map_vsub],
split,
{ rintros ⟨x, hx, y, hy, hv⟩,
exact ⟨x -ᵥ y, ⟨x, hx, y, hy, rfl⟩, hv⟩, },
{ rintros ⟨-, ⟨x, hx, y, hy, rfl⟩, rfl⟩,
exact ⟨x, hx, y, hy, rfl⟩, },
end
omit V2
/-! ### Definition of `affine_map.line_map` and lemmas about it -/
/-- The affine map from `k` to `P1` sending `0` to `p₀` and `1` to `p₁`. -/
def line_map (p₀ p₁ : P1) : k →ᵃ[k] P1 :=
((linear_map.id : k →ₗ[k] k).smul_right (p₁ -ᵥ p₀)).to_affine_map +ᵥ const k k p₀
lemma coe_line_map (p₀ p₁ : P1) : (line_map p₀ p₁ : k → P1) = λ c, c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl
lemma line_map_apply (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c = c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl
lemma line_map_apply_module' (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = c • (p₁ - p₀) + p₀ := rfl
lemma line_map_apply_module (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = (1 - c) • p₀ + c • p₁ :=
by simp [line_map_apply_module', smul_sub, sub_smul]; abel
omit V1
lemma line_map_apply_ring' (a b c : k) : line_map a b c = c * (b - a) + a :=
rfl
lemma line_map_apply_ring (a b c : k) : line_map a b c = (1 - c) * a + c * b :=
line_map_apply_module a b c
include V1
lemma line_map_vadd_apply (p : P1) (v : V1) (c : k) :
line_map p (v +ᵥ p) c = c • v +ᵥ p :=
by rw [line_map_apply, vadd_vsub]
@[simp] lemma line_map_linear (p₀ p₁ : P1) :
(line_map p₀ p₁ : k →ᵃ[k] P1).linear = linear_map.id.smul_right (p₁ -ᵥ p₀) :=
add_zero _
lemma line_map_same_apply (p : P1) (c : k) : line_map p p c = p := by simp [line_map_apply]
@[simp] lemma line_map_same (p : P1) : line_map p p = const k k p :=
ext $ line_map_same_apply p
@[simp] lemma line_map_apply_zero (p₀ p₁ : P1) : line_map p₀ p₁ (0:k) = p₀ :=
by simp [line_map_apply]
@[simp] lemma line_map_apply_one (p₀ p₁ : P1) : line_map p₀ p₁ (1:k) = p₁ :=
by simp [line_map_apply]
include V2
@[simp] lemma apply_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) (c : k) :
f (line_map p₀ p₁ c) = line_map (f p₀) (f p₁) c :=
by simp [line_map_apply]
@[simp] lemma comp_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) :
f.comp (line_map p₀ p₁) = line_map (f p₀) (f p₁) :=
ext $ f.apply_line_map p₀ p₁
@[simp] lemma fst_line_map (p₀ p₁ : P1 × P2) (c : k) :
(line_map p₀ p₁ c).1 = line_map p₀.1 p₁.1 c :=
fst.apply_line_map p₀ p₁ c
@[simp] lemma snd_line_map (p₀ p₁ : P1 × P2) (c : k) :
(line_map p₀ p₁ c).2 = line_map p₀.2 p₁.2 c :=
snd.apply_line_map p₀ p₁ c
omit V2
lemma line_map_symm (p₀ p₁ : P1) :
line_map p₀ p₁ = (line_map p₁ p₀).comp (line_map (1:k) (0:k)) :=
by { rw [comp_line_map], simp }
lemma line_map_apply_one_sub (p₀ p₁ : P1) (c : k) :
line_map p₀ p₁ (1 - c) = line_map p₁ p₀ c :=
by { rw [line_map_symm p₀, comp_apply], congr, simp [line_map_apply] }
@[simp] lemma line_map_vsub_left (p₀ p₁ : P1) (c : k) :
line_map p₀ p₁ c -ᵥ p₀ = c • (p₁ -ᵥ p₀) :=
vadd_vsub _ _
@[simp] lemma left_vsub_line_map (p₀ p₁ : P1) (c : k) :
p₀ -ᵥ line_map p₀ p₁ c = c • (p₀ -ᵥ p₁) :=
by rw [← neg_vsub_eq_vsub_rev, line_map_vsub_left, ← smul_neg, neg_vsub_eq_vsub_rev]
@[simp] lemma line_map_vsub_right (p₀ p₁ : P1) (c : k) :
line_map p₀ p₁ c -ᵥ p₁ = (1 - c) • (p₀ -ᵥ p₁) :=
by rw [← line_map_apply_one_sub, line_map_vsub_left]
@[simp] lemma right_vsub_line_map (p₀ p₁ : P1) (c : k) :
p₁ -ᵥ line_map p₀ p₁ c = (1 - c) • (p₁ -ᵥ p₀) :=
by rw [← line_map_apply_one_sub, left_vsub_line_map]
lemma line_map_vadd_line_map (v₁ v₂ : V1) (p₁ p₂ : P1) (c : k) :
line_map v₁ v₂ c +ᵥ line_map p₁ p₂ c = line_map (v₁ +ᵥ p₁) (v₂ +ᵥ p₂) c :=
((fst : V1 × P1 →ᵃ[k] V1) +ᵥ snd).apply_line_map (v₁, p₁) (v₂, p₂) c
lemma line_map_vsub_line_map (p₁ p₂ p₃ p₄ : P1) (c : k) :
line_map p₁ p₂ c -ᵥ line_map p₃ p₄ c = line_map (p₁ -ᵥ p₃) (p₂ -ᵥ p₄) c :=
-- Why Lean fails to find this instance without a hint?
by letI : affine_space (V1 × V1) (P1 × P1) := prod.add_torsor; exact
((fst : P1 × P1 →ᵃ[k] P1) -ᵥ (snd : P1 × P1 →ᵃ[k] P1)).apply_line_map (_, _) (_, _) c
/-- Decomposition of an affine map in the special case when the point space and vector space
are the same. -/
lemma decomp (f : V1 →ᵃ[k] V2) : (f : V1 → V2) = f.linear + (λ z, f 0) :=
begin
ext x,
calc
f x = f.linear x +ᵥ f 0 : by simp [← f.map_vadd]
... = (f.linear.to_fun + λ (z : V1), f 0) x : by simp
end
/-- Decomposition of an affine map in the special case when the point space and vector space
are the same. -/
lemma decomp' (f : V1 →ᵃ[k] V2) : (f.linear : V1 → V2) = f - (λ z, f 0) :=
by rw decomp ; simp only [linear_map.map_zero, pi.add_apply, add_sub_cancel, zero_add]
omit V1
lemma image_interval {k : Type*} [linear_ordered_field k] (f : k →ᵃ[k] k)
(a b : k) :
f '' set.interval a b = set.interval (f a) (f b) :=
begin
have : ⇑f = (λ x, x + f 0) ∘ λ x, x * (f 1 - f 0),
{ ext x,
change f x = x • (f 1 -ᵥ f 0) +ᵥ f 0,
rw [← f.linear_map_vsub, ← f.linear.map_smul, ← f.map_vadd],
simp only [vsub_eq_sub, add_zero, mul_one, vadd_eq_add, sub_zero, smul_eq_mul] },
rw [this, set.image_comp],
simp only [set.image_add_const_interval, set.image_mul_const_interval]
end
section
variables {ι : Type*} {V : Π i : ι, Type*} {P : Π i : ι, Type*} [Π i, add_comm_group (V i)]
[Π i, module k (V i)] [Π i, add_torsor (V i) (P i)]
include V
/-- Evaluation at a point as an affine map. -/
def proj (i : ι) : (Π i : ι, P i) →ᵃ[k] P i :=
{ to_fun := λ f, f i,
linear := @linear_map.proj k ι _ V _ _ i,
map_vadd' := λ p v, rfl }
@[simp] lemma proj_apply (i : ι) (f : Π i, P i) : @proj k _ ι V P _ _ _ i f = f i := rfl
@[simp] lemma proj_linear (i : ι) :
(@proj k _ ι V P _ _ _ i).linear = @linear_map.proj k ι _ V _ _ i := rfl
lemma pi_line_map_apply (f g : Π i, P i) (c : k) (i : ι) :
line_map f g c i = line_map (f i) (g i) c :=
(proj i : (Π i, P i) →ᵃ[k] P i).apply_line_map f g c
end
end affine_map
namespace affine_map
variables {R k V1 P1 V2 : Type*}
section ring
variables [ring k] [add_comm_group V1] [affine_space V1 P1] [add_comm_group V2]
variables [module k V1] [module k V2]
include V1
section distrib_mul_action
variables [monoid R] [distrib_mul_action R V2] [smul_comm_class k R V2]
/-- The space of affine maps to a module inherits an `R`-action from the action on its codomain. -/
instance : distrib_mul_action R (P1 →ᵃ[k] V2) :=
{ smul_add := λ c f g, ext $ λ p, smul_add _ _ _,
smul_zero := λ c, ext $ λ p, smul_zero _ }
end distrib_mul_action
section module
variables [semiring R] [module R V2] [smul_comm_class k R V2]
/-- The space of affine maps taking values in an `R`-module is an `R`-module. -/
instance : module R (P1 →ᵃ[k] V2) :=
{ smul := (•),
add_smul := λ c₁ c₂ f, ext $ λ p, add_smul _ _ _,
zero_smul := λ f, ext $ λ p, zero_smul _ _,
.. affine_map.distrib_mul_action }
variables (R)
/-- The space of affine maps between two modules is linearly equivalent to the product of the
domain with the space of linear maps, by taking the value of the affine map at `(0 : V1)` and the
linear part.
See note [bundled maps over different rings]-/
@[simps] def to_const_prod_linear_map : (V1 →ᵃ[k] V2) ≃ₗ[R] V2 × (V1 →ₗ[k] V2) :=
{ to_fun := λ f, ⟨f 0, f.linear⟩,
inv_fun := λ p, p.2.to_affine_map + const k V1 p.1,
left_inv := λ f, by { ext, rw f.decomp, simp, },
right_inv := by { rintros ⟨v, f⟩, ext; simp, },
map_add' := by simp,
map_smul' := by simp, }
end module
end ring
section comm_ring
variables [comm_ring k] [add_comm_group V1] [affine_space V1 P1] [add_comm_group V2]
variables [module k V1] [module k V2]
include V1
/-- `homothety c r` is the homothety (also known as dilation) about `c` with scale factor `r`. -/
def homothety (c : P1) (r : k) : P1 →ᵃ[k] P1 :=
r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c
lemma homothety_def (c : P1) (r : k) :
homothety c r = r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c :=
rfl
lemma homothety_apply (c : P1) (r : k) (p : P1) : homothety c r p = r • (p -ᵥ c : V1) +ᵥ c := rfl
lemma homothety_eq_line_map (c : P1) (r : k) (p : P1) : homothety c r p = line_map c p r := rfl
@[simp] lemma homothety_one (c : P1) : homothety c (1:k) = id k P1 :=
by { ext p, simp [homothety_apply] }
@[simp] lemma homothety_apply_same (c : P1) (r : k) : homothety c r c = c := line_map_same_apply c r
lemma homothety_mul_apply (c : P1) (r₁ r₂ : k) (p : P1) :
homothety c (r₁ * r₂) p = homothety c r₁ (homothety c r₂ p) :=
by simp [homothety_apply, mul_smul]
lemma homothety_mul (c : P1) (r₁ r₂ : k) :
homothety c (r₁ * r₂) = (homothety c r₁).comp (homothety c r₂) :=
ext $ homothety_mul_apply c r₁ r₂
@[simp] lemma homothety_zero (c : P1) : homothety c (0:k) = const k P1 c :=
by { ext p, simp [homothety_apply] }
@[simp] lemma homothety_add (c : P1) (r₁ r₂ : k) :
homothety c (r₁ + r₂) = r₁ • (id k P1 -ᵥ const k P1 c) +ᵥ homothety c r₂ :=
by simp only [homothety_def, add_smul, vadd_vadd]
/-- `homothety` as a multiplicative monoid homomorphism. -/
def homothety_hom (c : P1) : k →* P1 →ᵃ[k] P1 :=
⟨homothety c, homothety_one c, homothety_mul c⟩
@[simp] lemma coe_homothety_hom (c : P1) : ⇑(homothety_hom c : k →* _) = homothety c := rfl
/-- `homothety` as an affine map. -/
def homothety_affine (c : P1) : k →ᵃ[k] (P1 →ᵃ[k] P1) :=
⟨homothety c, (linear_map.lsmul k _).flip (id k P1 -ᵥ const k P1 c),
function.swap (homothety_add c)⟩
@[simp] lemma coe_homothety_affine (c : P1) :
⇑(homothety_affine c : k →ᵃ[k] _) = homothety c :=
rfl
end comm_ring
end affine_map
|
43db9ca6dc6706501adec7e1f44cdf324121c54e | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/linear_algebra/bilinear_map.lean | 2d9681ce2e4b984fc8280c8f0e0d60bb8afa9263 | [
"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 | 16,763 | 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
-/
import linear_algebra.basic
import linear_algebra.basis
/-!
# Basics on bilinear maps
This file provides basics on bilinear maps. The most general form considered are maps that are
semilinear in both arguments. They are of type `M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P`, where `M` and `N`
are modules over `R` and `S` respectively, `P` is a module over both `R₂` and `S₂` with
commuting actions, and `ρ₁₂ : R →+* R₂` and `σ₁₂ : S →+* S₂`.
## Main declarations
* `linear_map.mk₂`: a constructor for bilinear maps,
taking an unbundled function together with proof witnesses of bilinearity
* `linear_map.flip`: turns a bilinear map `M × N → P` into `N × M → P`
* `linear_map.lcomp` and `linear_map.llcomp`: composition of linear maps as a bilinear map
* `linear_map.compl₂`: composition of a bilinear map `M × N → P` with a linear map `Q → M`
* `linear_map.compr₂`: composition of a bilinear map `M × N → P` with a linear map `Q → N`
* `linear_map.lsmul`: scalar multiplication as a bilinear map `R × M → M`
## Tags
bilinear
-/
variables {ι₁ ι₂ : Type*}
namespace linear_map
section semiring
-- the `ₗ` subscript variables are for special cases about linear (as opposed to semilinear) maps
variables {R : Type*} [semiring R] {S : Type*} [semiring S]
variables {R₂ : Type*} [semiring R₂] {S₂ : Type*} [semiring S₂]
variables {M : Type*} {N : Type*} {P : Type*}
variables {M₂ : Type*} {N₂ : Type*} {P₂ : Type*}
variables {Nₗ : Type*} {Pₗ : Type*}
variables {M' : Type*} {N' : Type*} {P' : Type*}
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P]
variables [add_comm_monoid M₂] [add_comm_monoid N₂] [add_comm_monoid P₂]
variables [add_comm_monoid Nₗ] [add_comm_monoid Pₗ]
variables [add_comm_group M'] [add_comm_group N'] [add_comm_group P']
variables [module R M] [module S N] [module R₂ P] [module S₂ P]
variables [module R M₂] [module S N₂] [module R P₂] [module S₂ P₂]
variables [module R Pₗ] [module S Pₗ]
variables [module R M'] [module S N'] [module R₂ P'] [module S₂ P']
variables [smul_comm_class S₂ R₂ P] [smul_comm_class S R Pₗ] [smul_comm_class S₂ R₂ P']
variables [smul_comm_class S₂ R P₂]
variables {ρ₁₂ : R →+* R₂} {σ₁₂ : S →+* S₂}
variables (ρ₁₂ σ₁₂)
/-- Create a bilinear map from a function that is semilinear in each component.
See `mk₂'` and `mk₂` for the linear case. -/
def mk₂'ₛₗ (f : M → N → P)
(H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c:R) m n, f (c • m) n = (ρ₁₂ c) • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c:S) m n, f m (c • n) = (σ₁₂ c) • f m n) : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P :=
{ to_fun := λ m, { to_fun := f m, map_add' := H3 m, map_smul' := λ c, H4 c m},
map_add' := λ m₁ m₂, linear_map.ext $ H1 m₁ m₂,
map_smul' := λ c m, linear_map.ext $ H2 c m }
variables {ρ₁₂ σ₁₂}
@[simp] theorem mk₂'ₛₗ_apply
(f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) :
(mk₂'ₛₗ ρ₁₂ σ₁₂ f H1 H2 H3 H4 : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) m n = f m n := rfl
variables (R S)
/-- Create a bilinear map from a function that is linear in each component.
See `mk₂` for the special case where both arguments come from modules over the same ring. -/
def mk₂' (f : M → N → Pₗ)
(H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c:R) m n, f (c • m) n = c • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c:S) m n, f m (c • n) = c • f m n) : M →ₗ[R] N →ₗ[S] Pₗ :=
mk₂'ₛₗ (ring_hom.id R) (ring_hom.id S) f H1 H2 H3 H4
variables {R S}
@[simp] theorem mk₂'_apply
(f : M → N → Pₗ) {H1 H2 H3 H4} (m : M) (n : N) :
(mk₂' R S f H1 H2 H3 H4 : M →ₗ[R] N →ₗ[S] Pₗ) m n = f m n := rfl
theorem ext₂ {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P}
(H : ∀ m n, f m n = g m n) : f = g :=
linear_map.ext (λ m, linear_map.ext $ λ n, H m n)
lemma congr_fun₂ {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (h : f = g) (x y) : f x y = g x y :=
linear_map.congr_fun (linear_map.congr_fun h x) y
section
local attribute [instance] smul_comm_class.symm
/-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map from `M × N` to
`P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/
def flip (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) : N →ₛₗ[σ₁₂] M →ₛₗ[ρ₁₂] P :=
mk₂'ₛₗ σ₁₂ ρ₁₂ (λ n m, f m n)
(λ n₁ n₂ m, (f m).map_add _ _)
(λ c n m, (f m).map_smulₛₗ _ _)
(λ n m₁ m₂, by rw f.map_add; refl)
(λ c n m, by rw f.map_smulₛₗ; refl)
end
@[simp] theorem flip_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (m : M) (n : N) : flip f n m = f m n := rfl
@[simp] lemma flip_flip [smul_comm_class R₂ S₂ P] (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) :
f.flip.flip = f := linear_map.ext₂ (λ x y, ((f.flip).flip_apply _ _).trans (f.flip_apply _ _))
open_locale big_operators
variables {R}
theorem flip_inj {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (H : flip f = flip g) : f = g :=
ext₂ $ λ m n, show flip f n m = flip g n m, by rw H
theorem map_zero₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (y) : f 0 y = 0 :=
(flip f y).map_zero
theorem map_neg₂ (f : M' →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P') (x y) : f (-x) y = -f x y :=
(flip f y).map_neg _
theorem map_sub₂ (f : M' →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P') (x y z) : f (x - y) z = f x z - f y z :=
(flip f z).map_sub _ _
theorem map_add₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (x₁ x₂ y) : f (x₁ + x₂) y = f x₁ y + f x₂ y :=
(flip f y).map_add _ _
theorem map_smul₂ (f : M₂ →ₗ[R] N₂ →ₛₗ[σ₁₂] P₂) (r : R) (x y) : f (r • x) y = r • f x y :=
(flip f y).map_smul _ _
theorem map_smulₛₗ₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (r : R) (x y) : f (r • x) y = (ρ₁₂ r) • f x y :=
(flip f y).map_smulₛₗ _ _
theorem map_sum₂ {ι : Type*} (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (t : finset ι) (x : ι → M) (y) :
f (∑ i in t, x i) y = ∑ i in t, f (x i) y :=
(flip f y).map_sum
/-- Restricting a bilinear map in the second entry -/
def dom_restrict₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (q : submodule S N) :
M →ₛₗ[ρ₁₂] q →ₛₗ[σ₁₂] P :=
{ to_fun := λ m, (f m).dom_restrict q,
map_add' := λ m₁ m₂, linear_map.ext $ λ _, by simp only [map_add, dom_restrict_apply, add_apply],
map_smul' := λ c m, linear_map.ext $ λ _, by simp only [f.map_smulₛₗ, dom_restrict_apply,
smul_apply]}
lemma dom_restrict₂_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (q : submodule S N) (x : M) (y : q) :
f.dom_restrict₂ q x y = f x y := rfl
/-- Restricting a bilinear map in both components -/
def dom_restrict₁₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (p : submodule R M) (q : submodule S N) :
p →ₛₗ[ρ₁₂] q →ₛₗ[σ₁₂] P := (f.dom_restrict p).dom_restrict₂ q
lemma dom_restrict₁₂_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (p : submodule R M) (q : submodule S N)
(x : p) (y : q) : f.dom_restrict₁₂ p q x y = f x y := rfl
end semiring
section comm_semiring
variables {R : Type*} [comm_semiring R] {R₂ : Type*} [comm_semiring R₂]
variables {R₃ : Type*} [comm_semiring R₃] {R₄ : Type*} [comm_semiring R₄]
variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*}
variables {Mₗ : Type*} {Nₗ : Type*} {Pₗ : Type*} {Qₗ Qₗ': Type*}
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q]
variables [add_comm_monoid Mₗ] [add_comm_monoid Nₗ] [add_comm_monoid Pₗ]
variables [add_comm_monoid Qₗ] [add_comm_monoid Qₗ']
variables [module R M] [module R₂ N] [module R₃ P] [module R₄ Q]
variables [module R Mₗ] [module R Nₗ] [module R Pₗ] [module R Qₗ] [module R Qₗ']
variables {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃}
variables {σ₄₂ : R₄ →+* R₂} {σ₄₃ : R₄ →+* R₃}
variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₄₂ σ₂₃ σ₄₃]
variables (R)
/-- Create a bilinear map from a function that is linear in each component.
This is a shorthand for `mk₂'` for the common case when `R = S`. -/
def mk₂ (f : M → Nₗ → Pₗ)
(H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n)
(H2 : ∀ (c:R) m n, f (c • m) n = c • f m n)
(H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂)
(H4 : ∀ (c:R) m n, f m (c • n) = c • f m n) : M →ₗ[R] Nₗ →ₗ[R] Pₗ :=
mk₂' R R f H1 H2 H3 H4
@[simp] theorem mk₂_apply
(f : M → Nₗ → Pₗ) {H1 H2 H3 H4} (m : M) (n : Nₗ) :
(mk₂ R f H1 H2 H3 H4 : M →ₗ[R] Nₗ →ₗ[R] Pₗ) m n = f m n := rfl
variables (R M N P)
/-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map `M → N → P`,
change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/
def lflip : (M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) →ₗ[R₃] N →ₛₗ[σ₂₃] M →ₛₗ[σ₁₃] P :=
{ to_fun := flip, map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl }
variables {R M N P}
variables (f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P)
@[simp] theorem lflip_apply (m : M) (n : N) : lflip R M N P f n m = f m n := rfl
variables (R Pₗ)
/-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/
def lcomp (f : M →ₗ[R] Nₗ) : (Nₗ →ₗ[R] Pₗ) →ₗ[R] M →ₗ[R] Pₗ :=
flip $ linear_map.comp (flip id) f
variables {R Pₗ}
@[simp] theorem lcomp_apply (f : M →ₗ[R] Nₗ) (g : Nₗ →ₗ[R] Pₗ) (x : M) :
lcomp R Pₗ f g x = g (f x) := rfl
theorem lcomp_apply' (f : M →ₗ[R] Nₗ) (g : Nₗ →ₗ[R] Pₗ) :
lcomp R Pₗ f g = g ∘ₗ f := rfl
variables (P σ₂₃)
/-- Composing a semilinear map `M → N` and a semilinear map `N → P` to form a semilinear map
`M → P` is itself a linear map. -/
def lcompₛₗ (f : M →ₛₗ[σ₁₂] N) : (N →ₛₗ[σ₂₃] P) →ₗ[R₃] M →ₛₗ[σ₁₃] P :=
flip $ linear_map.comp (flip id) f
variables {P σ₂₃}
include σ₁₃
@[simp] theorem lcompₛₗ_apply (f : M →ₛₗ[σ₁₂] N) (g : N →ₛₗ[σ₂₃] P) (x : M) :
lcompₛₗ P σ₂₃ f g x = g (f x) := rfl
omit σ₁₃
variables (R M Nₗ Pₗ)
/-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/
def llcomp : (Nₗ →ₗ[R] Pₗ) →ₗ[R] (M →ₗ[R] Nₗ) →ₗ[R] M →ₗ[R] Pₗ :=
flip { to_fun := lcomp R Pₗ,
map_add' := λ f f', ext₂ $ λ g x, g.map_add _ _,
map_smul' := λ (c : R) f, ext₂ $ λ g x, g.map_smul _ _ }
variables {R M Nₗ Pₗ}
section
@[simp] theorem llcomp_apply (f : Nₗ →ₗ[R] Pₗ) (g : M →ₗ[R] Nₗ) (x : M) :
llcomp R M Nₗ Pₗ f g x = f (g x) := rfl
theorem llcomp_apply' (f : Nₗ →ₗ[R] Pₗ) (g : M →ₗ[R] Nₗ) :
llcomp R M Nₗ Pₗ f g = f ∘ₗ g := rfl
end
/-- Composing a linear map `Q → N` and a bilinear map `M → N → P` to
form a bilinear map `M → Q → P`. -/
def compl₂ (g : Q →ₛₗ[σ₄₂] N) : M →ₛₗ[σ₁₃] Q →ₛₗ[σ₄₃] P := (lcompₛₗ _ _ g).comp f
include σ₄₃
@[simp] theorem compl₂_apply (g : Q →ₛₗ[σ₄₂] N) (m : M) (q : Q) :
f.compl₂ g m q = f m (g q) := rfl
omit σ₄₃
@[simp] theorem compl₂_id : f.compl₂ linear_map.id = f :=
by { ext, rw [compl₂_apply, id_coe, id.def] }
/-- Composing linear maps `Q → M` and `Q' → N` with a bilinear map `M → N → P` to
form a bilinear map `Q → Q' → P`. -/
def compl₁₂ (f : Mₗ →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Qₗ →ₗ[R] Mₗ) (g' : Qₗ' →ₗ[R] Nₗ) :
Qₗ →ₗ[R] Qₗ' →ₗ[R] Pₗ :=
(f.comp g).compl₂ g'
@[simp] theorem compl₁₂_apply (f : Mₗ →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Qₗ →ₗ[R] Mₗ) (g' : Qₗ' →ₗ[R] Nₗ)
(x : Qₗ) (y : Qₗ') : f.compl₁₂ g g' x y = f (g x) (g' y) := rfl
@[simp] theorem compl₁₂_id_id (f : Mₗ →ₗ[R] Nₗ →ₗ[R] Pₗ) :
f.compl₁₂ (linear_map.id) (linear_map.id) = f :=
by { ext, simp_rw [compl₁₂_apply, id_coe, id.def] }
lemma compl₁₂_inj {f₁ f₂ : Mₗ →ₗ[R] Nₗ →ₗ[R] Pₗ} {g : Qₗ →ₗ[R] Mₗ} {g' : Qₗ' →ₗ[R] Nₗ}
(hₗ : function.surjective g) (hᵣ : function.surjective g') :
f₁.compl₁₂ g g' = f₂.compl₁₂ g g' ↔ f₁ = f₂ :=
begin
split; intros h,
{ -- B₁.comp l r = B₂.comp l r → B₁ = B₂
ext x y,
cases hₗ x with x' hx, subst hx,
cases hᵣ y with y' hy, subst hy,
convert linear_map.congr_fun₂ h x' y' },
{ -- B₁ = B₂ → B₁.comp l r = B₂.comp l r
subst h },
end
/-- Composing a linear map `P → Q` and a bilinear map `M → N → P` to
form a bilinear map `M → N → Q`. -/
def compr₂ (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[R] Qₗ) : M →ₗ[R] Nₗ →ₗ[R] Qₗ :=
(llcomp R Nₗ Pₗ Qₗ g) ∘ₗ f
@[simp] theorem compr₂_apply (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[R] Qₗ) (m : M) (n : Nₗ) :
f.compr₂ g m n = g (f m n) := rfl
variables (R M)
/-- Scalar multiplication as a bilinear map `R → M → M`. -/
def lsmul : R →ₗ[R] M →ₗ[R] M :=
mk₂ R (•) add_smul (λ _ _ _, mul_smul _ _ _) smul_add
(λ r s m, by simp only [smul_smul, smul_eq_mul, mul_comm])
variables {R M}
@[simp] theorem lsmul_apply (r : R) (m : M) : lsmul R M r m = r • m := rfl
end comm_semiring
section comm_ring
variables {R R₂ S S₂ M N P : Type*}
variables {Mₗ Nₗ Pₗ : Type*}
variables [comm_ring R] [comm_ring S] [comm_ring R₂] [comm_ring S₂]
section add_comm_monoid
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P]
variables [add_comm_monoid Mₗ] [add_comm_monoid Nₗ] [add_comm_monoid Pₗ]
variables [module R M] [module S N] [module R₂ P] [module S₂ P]
variables [module R Mₗ] [module R Nₗ] [module R Pₗ]
variables [smul_comm_class S₂ R₂ P]
variables {ρ₁₂ : R →+* R₂} {σ₁₂ : S →+* S₂}
variables (b₁ : basis ι₁ R M) (b₂ : basis ι₂ S N) (b₁' : basis ι₁ R Mₗ) (b₂' : basis ι₂ R Nₗ)
/-- Two bilinear maps are equal when they are equal on all basis vectors. -/
lemma ext_basis {B B' : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P}
(h : ∀ i j, B (b₁ i) (b₂ j) = B' (b₁ i) (b₂ j)) : B = B' :=
b₁.ext $ λ i, b₂.ext $ λ j, h i j
/-- Write out `B x y` as a sum over `B (b i) (b j)` if `b` is a basis.
Version for semi-bilinear maps, see `sum_repr_mul_repr_mul` for the bilinear version. -/
lemma sum_repr_mul_repr_mulₛₗ {B : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (x y) :
(b₁.repr x).sum (λ i xi, (b₂.repr y).sum (λ j yj, (ρ₁₂ xi) • (σ₁₂ yj) • B (b₁ i) (b₂ j))) =
B x y :=
begin
conv_rhs { rw [← b₁.total_repr x, ← b₂.total_repr y] },
simp_rw [finsupp.total_apply, finsupp.sum, map_sum₂, map_sum,
linear_map.map_smulₛₗ₂, linear_map.map_smulₛₗ],
end
/-- Write out `B x y` as a sum over `B (b i) (b j)` if `b` is a basis.
Version for bilinear maps, see `sum_repr_mul_repr_mulₛₗ` for the semi-bilinear version. -/
lemma sum_repr_mul_repr_mul {B : Mₗ →ₗ[R] Nₗ →ₗ[R] Pₗ} (x y) :
(b₁'.repr x).sum (λ i xi, (b₂'.repr y).sum (λ j yj, xi • yj • B (b₁' i) (b₂' j))) =
B x y :=
begin
conv_rhs { rw [← b₁'.total_repr x, ← b₂'.total_repr y] },
simp_rw [finsupp.total_apply, finsupp.sum, map_sum₂, map_sum,
linear_map.map_smul₂, linear_map.map_smul],
end
end add_comm_monoid
section add_comm_group
variables [add_comm_group M] [add_comm_group N] [add_comm_group P]
variables [module R M] [module S N] [module R₂ P] [module S₂ P]
lemma lsmul_injective [no_zero_smul_divisors R M] {x : R} (hx : x ≠ 0) :
function.injective (lsmul R M x) :=
smul_right_injective _ hx
lemma ker_lsmul [no_zero_smul_divisors R M] {a : R} (ha : a ≠ 0) :
(linear_map.lsmul R M a).ker = ⊥ :=
linear_map.ker_eq_bot_of_injective (linear_map.lsmul_injective ha)
end add_comm_group
end comm_ring
end linear_map
|
6de6d4839c73ed9b2629eb2b0c94f712d91fbc33 | 6fbf10071e62af7238f2de8f9aa83d55d8763907 | /src/2.5_logic_propositions.lean | baf568f6b164ceaffd980afa9ca9a325dab00d8a | [] | no_license | HasanMukati/uva-cs-dm-s19 | ee5aad4568a3ca330c2738ed579c30e1308b03b0 | 3e7177682acdb56a2d16914e0344c10335583dcf | refs/heads/master | 1,596,946,213,130 | 1,568,221,949,000 | 1,568,221,949,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 295 | lean | namespace Propositions.ex1
axioms (P Q : Prop)
axioms (p1 p2 : P)
axiom Cool : P → Prop
#check true
#check false
#check P
#check Q
#check p1 = p2
#check P ∧ Q
#check P → Q
#check P ↔ Q
#check P ∨ Q
#check ¬ P
#check ∀ p : P, Cool p
#check ∃ p : P, Cool p
end Propositions.ex1
|
bd033922a4dcf5b786bd3206dd5efcbae3433234 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /test/library_search/ordered_ring.lean | 244e01019986d4cb6d6f4a65915220d7d49722cd | [
"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 | 462 | 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 tactic.basic
import data.nat.basic
import algebra.ordered_ring
/- Turn off trace messages so they don't pollute the test build: -/
set_option trace.silence_library_search true
example {a b : ℕ} (h : b > 0) (w : a ≥ 1) : b ≤ a * b :=
by library_search -- exact (le_mul_iff_one_le_left h).mpr w
|
0808bda4f357e856af3e610ec66d564ed028afe5 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/tactic/ext.lean | d793bf656d7c331b126846139925fdc6cf4611da | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 6,901 | lean |
import tactic.basic data.list.defs data.prod data.sum tactic.rcases
universes u₁ u₂
open interactive interactive.types
open lean.parser nat tactic
meta def get_ext_subject : expr → tactic name
| (expr.pi n bi d b) :=
do v ← mk_local' n bi d,
b' ← whnf $ b.instantiate_var v,
get_ext_subject b'
| (expr.app _ e) :=
do t ← infer_type e >>= instantiate_mvars >>= head_beta,
if t.get_app_fn.is_constant then
pure $ t.get_app_fn.const_name
else if t.is_pi then
pure $ name.mk_numeral 0 name.anonymous
else if t.is_sort then
pure $ name.mk_numeral 1 name.anonymous
else do
t ← pp t,
fail format!"only constants and Pi types are supported: {t}"
| e := fail format!"Only expressions of the form `_ → _ → ... → R ... e are supported: {e}"
open native
@[reducible] def ext_param_type := option name ⊕ option name
meta def opt_minus : lean.parser (option name → ext_param_type) :=
sum.inl <$ tk "-" <|> pure sum.inr
meta def ext_param :=
opt_minus <*> ( name.mk_numeral 0 name.anonymous <$ brackets "(" ")" (tk "→" <|> tk "->") <|>
none <$ tk "*" <|>
some <$> ident )
meta def saturate_fun : name → tactic expr
| (name.mk_numeral 0 name.anonymous) :=
do v₀ ← mk_mvar,
v₁ ← mk_mvar,
return $ v₀.imp v₁
| (name.mk_numeral 1 name.anonymous) :=
do u ← mk_meta_univ,
pure $ expr.sort u
| n :=
do e ← resolve_constant n >>= mk_const,
a ← get_arity e,
e.mk_app <$> (list.iota a).mmap (λ _, mk_mvar)
meta def equiv_type_constr (n n' : name) : tactic unit :=
do e ← saturate_fun n,
e' ← saturate_fun n',
unify e e' <|> fail format!"{n} and {n'} are not definitionally equal types"
/--
Tag lemmas of the form:
```
@[extensionality]
lemma my_collection.ext (a b : my_collection)
(h : ∀ x, a.lookup x = b.lookup y) :
a = b := ...
```
The attribute indexes extensionality lemma using the type of the
objects (i.e. `my_collection`) which it gets from the statement of
the lemma. In some cases, the same lemma can be used to state the
extensionality of multiple types that are definitionally equivalent.
```
attribute [extensionality [(→),thunk,stream]] funext
```
Those parameters are cumulative. The following are equivalent:
```
attribute [extensionality [(→),thunk]] funext
attribute [extensionality [stream]] funext
```
and
```
attribute [extensionality [(→),thunk,stream]] funext
```
One removes type names from the list for one lemma with:
```
attribute [extensionality [-stream,-thunk]] funext
```
Finally, the following:
```
@[extensionality]
lemma my_collection.ext (a b : my_collection)
(h : ∀ x, a.lookup x = b.lookup y) :
a = b := ...
```
is equivalent to
```
@[extensionality *]
lemma my_collection.ext (a b : my_collection)
(h : ∀ x, a.lookup x = b.lookup y) :
a = b := ...
```
This allows us specify type synonyms along with the type
that referred to in the lemma statement.
```
@[extensionality [*,my_type_synonym]]
lemma my_collection.ext (a b : my_collection)
(h : ∀ x, a.lookup x = b.lookup y) :
a = b := ...
```
-/
@[user_attribute]
meta def extensional_attribute : user_attribute (name_map name) (bool × list ext_param_type × list name × list (name × name)) :=
{ name := `extensionality,
descr := "lemmas usable by `ext` tactic",
cache_cfg := { mk_cache := λ ls,
do { attrs ← ls.mmap $ λ l,
do { ⟨_,_,ls,_⟩ ← extensional_attribute.get_param l,
pure $ prod.mk <$> ls <*> pure l },
pure $ rb_map.of_list $ attrs.join },
dependencies := [] },
parser :=
do { ls ← pure <$> ext_param <|> list_of ext_param <|> pure [],
m ← extensional_attribute.get_cache,
pure $ (ff,ls,[],m.to_list) },
after_set := some $ λ n _ b,
do (ff,ls,_,ls') ← extensional_attribute.get_param n | pure (),
s ← mk_const n >>= infer_type >>= get_ext_subject,
let (rs,ls'') := if ls.empty
then ([],[s])
else ls.partition_map (sum.map (flip option.get_or_else s) (flip option.get_or_else s)),
ls''.mmap' (equiv_type_constr s),
let l := ls'' ∪ (ls'.filter $ λ l, prod.snd l = n).map prod.fst \ rs,
extensional_attribute.set n (tt,[],l,[]) b }
attribute [extensionality] array.ext propext prod.ext
attribute [extensionality [(→),thunk]] _root_.funext
namespace ulift
@[extensionality] lemma ext {α : Type u₁} (X Y : ulift.{u₂} α) (w : X.down = Y.down) : X = Y :=
begin
cases X, cases Y, dsimp at w, rw w,
end
end ulift
namespace plift
@[extensionality] lemma ext {P : Prop} (a b : plift P) : a = b :=
begin
cases a, cases b, refl
end
end plift
namespace tactic
meta def try_intros : ext_patt → tactic ext_patt
| [] := try intros $> []
| (x::xs) :=
do tgt ← target >>= whnf,
if tgt.is_pi
then rintro [x] >> try_intros xs
else pure (x :: xs)
meta def ext1 (xs : ext_patt) (cfg : apply_cfg := {}): tactic ext_patt :=
do subject ← target >>= get_ext_subject,
m ← extensional_attribute.get_cache,
do { rule ← m.find subject,
applyc rule cfg } <|>
do { ls ← attribute.get_instances `extensionality,
ls.any_of (λ n, applyc n cfg) } <|>
fail format!"no applicable extensionality rule found for {subject}",
try_intros xs
meta def ext : ext_patt → option ℕ → tactic unit
| _ (some 0) := skip
| xs n := focus1 $ do
ys ← ext1 xs, try (ext ys (nat.pred <$> n))
local postfix `?`:9001 := optional
local postfix *:9001 := many
/--
`ext1 id` selects and apply one extensionality lemma (with attribute
`extensionality`), using `id`, if provided, to name a local constant
introduced by the lemma. If `id` is omitted, the local constant is
named automatically, as per `intro`.
-/
meta def interactive.ext1 (xs : parse ext_parse) : tactic unit :=
ext1 xs $> ()
/--
- `ext` applies as many extensionality lemmas as possible;
- `ext ids`, with `ids` a list of identifiers, finds extentionality and applies them
until it runs out of identifiers in `ids` to name the local constants.
When trying to prove:
```
α β : Type,
f g : α → set β
⊢ f = g
```
applying `ext x y` yields:
```
α β : Type,
f g : α → set β,
x : α,
y : β
⊢ y ∈ f x ↔ y ∈ f x
```
by applying functional extensionality and set extensionality.
A maximum depth can be provided with `ext x y z : 3`.
-/
meta def interactive.ext : parse ext_parse → parse (tk ":" *> small_nat)? → tactic unit
| [] (some n) := iterate_range 1 n (ext1 [] $> ())
| [] none := repeat1 (ext1 [] $> ())
| xs n := tactic.ext xs n
end tactic
|
f9f7763c7e149ed78d5dac56715900aeb07ed479 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/special_functions/log/basic.lean | a4ffa13124f6f2618667c566bb136e9cc18c4e90 | [
"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 | 12,111 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne
-/
import analysis.special_functions.exp
import data.nat.factorization.basic
/-!
# Real logarithm
In this file we define `real.log` to be the logarithm of a real number. As usual, we extend it from
its domain `(0, +∞)` to a globally defined function. We choose to do it so that `log 0 = 0` and
`log (-x) = log x`.
We prove some basic properties of this function and show that it is continuous.
## Tags
logarithm, continuity
-/
open set filter function
open_locale topological_space
noncomputable theory
namespace real
variables {x y : ℝ}
/-- The real logarithm function, equal to the inverse of the exponential for `x > 0`,
to `log |x|` for `x < 0`, and to `0` for `0`. We use this unconventional extension to
`(-∞, 0]` as it gives the formula `log (x * y) = log x + log y` for all nonzero `x` and `y`, and
the derivative of `log` is `1/x` away from `0`. -/
@[pp_nodot] noncomputable def log (x : ℝ) : ℝ :=
if hx : x = 0 then 0 else exp_order_iso.symm ⟨|x|, abs_pos.2 hx⟩
lemma log_of_ne_zero (hx : x ≠ 0) : log x = exp_order_iso.symm ⟨|x|, abs_pos.2 hx⟩ := dif_neg hx
lemma log_of_pos (hx : 0 < x) : log x = exp_order_iso.symm ⟨x, hx⟩ :=
by { rw [log_of_ne_zero hx.ne'], congr, exact abs_of_pos hx }
lemma exp_log_eq_abs (hx : x ≠ 0) : exp (log x) = |x| :=
by rw [log_of_ne_zero hx, ← coe_exp_order_iso_apply, order_iso.apply_symm_apply, subtype.coe_mk]
lemma exp_log (hx : 0 < x) : exp (log x) = x :=
by { rw exp_log_eq_abs hx.ne', exact abs_of_pos hx }
lemma exp_log_of_neg (hx : x < 0) : exp (log x) = -x :=
by { rw exp_log_eq_abs (ne_of_lt hx), exact abs_of_neg hx }
lemma le_exp_log (x : ℝ) : x ≤ exp (log x) :=
begin
by_cases h_zero : x = 0,
{ rw [h_zero, log, dif_pos rfl, exp_zero], exact zero_le_one, },
{ rw exp_log_eq_abs h_zero, exact le_abs_self _, },
end
@[simp] lemma log_exp (x : ℝ) : log (exp x) = x :=
exp_injective $ exp_log (exp_pos x)
lemma surj_on_log : surj_on log (Ioi 0) univ :=
λ x _, ⟨exp x, exp_pos x, log_exp x⟩
lemma log_surjective : surjective log :=
λ x, ⟨exp x, log_exp x⟩
@[simp] lemma range_log : range log = univ :=
log_surjective.range_eq
@[simp] lemma log_zero : log 0 = 0 := dif_pos rfl
@[simp] lemma log_one : log 1 = 0 :=
exp_injective $ by rw [exp_log zero_lt_one, exp_zero]
@[simp] lemma log_abs (x : ℝ) : log (|x|) = log x :=
begin
by_cases h : x = 0,
{ simp [h] },
{ rw [← exp_eq_exp, exp_log_eq_abs h, exp_log_eq_abs (abs_pos.2 h).ne', abs_abs] }
end
@[simp] lemma log_neg_eq_log (x : ℝ) : log (-x) = log x :=
by rw [← log_abs x, ← log_abs (-x), abs_neg]
lemma sinh_log {x : ℝ} (hx : 0 < x) : sinh (log x) = (x - x⁻¹) / 2 :=
by rw [sinh_eq, exp_neg, exp_log hx]
lemma cosh_log {x : ℝ} (hx : 0 < x) : cosh (log x) = (x + x⁻¹) / 2 :=
by rw [cosh_eq, exp_neg, exp_log hx]
lemma surj_on_log' : surj_on log (Iio 0) univ :=
λ x _, ⟨-exp x, neg_lt_zero.2 $ exp_pos x, by rw [log_neg_eq_log, log_exp]⟩
lemma log_mul (hx : x ≠ 0) (hy : y ≠ 0) : log (x * y) = log x + log y :=
exp_injective $
by rw [exp_log_eq_abs (mul_ne_zero hx hy), exp_add, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_mul]
lemma log_div (hx : x ≠ 0) (hy : y ≠ 0) : log (x / y) = log x - log y :=
exp_injective $
by rw [exp_log_eq_abs (div_ne_zero hx hy), exp_sub, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_div]
@[simp] lemma log_inv (x : ℝ) : log (x⁻¹) = -log x :=
begin
by_cases hx : x = 0, { simp [hx] },
rw [← exp_eq_exp, exp_log_eq_abs (inv_ne_zero hx), exp_neg, exp_log_eq_abs hx, abs_inv]
end
lemma log_le_log (h : 0 < x) (h₁ : 0 < y) : log x ≤ log y ↔ x ≤ y :=
by rw [← exp_le_exp, exp_log h, exp_log h₁]
lemma log_lt_log (hx : 0 < x) : x < y → log x < log y :=
by { intro h, rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)] }
lemma log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y :=
by { rw [← exp_lt_exp, exp_log hx, exp_log hy] }
lemma log_le_iff_le_exp (hx : 0 < x) : log x ≤ y ↔ x ≤ exp y := by rw [←exp_le_exp, exp_log hx]
lemma log_lt_iff_lt_exp (hx : 0 < x) : log x < y ↔ x < exp y := by rw [←exp_lt_exp, exp_log hx]
lemma le_log_iff_exp_le (hy : 0 < y) : x ≤ log y ↔ exp x ≤ y := by rw [←exp_le_exp, exp_log hy]
lemma lt_log_iff_exp_lt (hy : 0 < y) : x < log y ↔ exp x < y := by rw [←exp_lt_exp, exp_log hy]
lemma log_pos_iff (hx : 0 < x) : 0 < log x ↔ 1 < x :=
by { rw ← log_one, exact log_lt_log_iff zero_lt_one hx }
lemma log_pos (hx : 1 < x) : 0 < log x :=
(log_pos_iff (lt_trans zero_lt_one hx)).2 hx
lemma log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 :=
by { rw ← log_one, exact log_lt_log_iff h zero_lt_one }
lemma log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 := (log_neg_iff h0).2 h1
lemma log_nonneg_iff (hx : 0 < x) : 0 ≤ log x ↔ 1 ≤ x :=
by rw [← not_lt, log_neg_iff hx, not_lt]
lemma log_nonneg (hx : 1 ≤ x) : 0 ≤ log x :=
(log_nonneg_iff (zero_lt_one.trans_le hx)).2 hx
lemma log_nonpos_iff (hx : 0 < x) : log x ≤ 0 ↔ x ≤ 1 :=
by rw [← not_lt, log_pos_iff hx, not_lt]
lemma log_nonpos_iff' (hx : 0 ≤ x) : log x ≤ 0 ↔ x ≤ 1 :=
begin
rcases hx.eq_or_lt with (rfl|hx),
{ simp [le_refl, zero_le_one] },
exact log_nonpos_iff hx
end
lemma log_nonpos (hx : 0 ≤ x) (h'x : x ≤ 1) : log x ≤ 0 :=
(log_nonpos_iff' hx).2 h'x
lemma strict_mono_on_log : strict_mono_on log (set.Ioi 0) :=
λ x hx y hy hxy, log_lt_log hx hxy
lemma strict_anti_on_log : strict_anti_on log (set.Iio 0) :=
begin
rintros x (hx : x < 0) y (hy : y < 0) hxy,
rw [← log_abs y, ← log_abs x],
refine log_lt_log (abs_pos.2 hy.ne) _,
rwa [abs_of_neg hy, abs_of_neg hx, neg_lt_neg_iff]
end
lemma log_inj_on_pos : set.inj_on log (set.Ioi 0) :=
strict_mono_on_log.inj_on
lemma eq_one_of_pos_of_log_eq_zero {x : ℝ} (h₁ : 0 < x) (h₂ : log x = 0) : x = 1 :=
log_inj_on_pos (set.mem_Ioi.2 h₁) (set.mem_Ioi.2 zero_lt_one) (h₂.trans real.log_one.symm)
lemma log_ne_zero_of_pos_of_ne_one {x : ℝ} (hx_pos : 0 < x) (hx : x ≠ 1) : log x ≠ 0 :=
mt (eq_one_of_pos_of_log_eq_zero hx_pos) hx
@[simp] lemma log_eq_zero {x : ℝ} : log x = 0 ↔ x = 0 ∨ x = 1 ∨ x = -1 :=
begin
split,
{ intros h,
rcases lt_trichotomy x 0 with x_lt_zero | rfl | x_gt_zero,
{ refine or.inr (or.inr (eq_neg_iff_eq_neg.mp _)),
rw [←log_neg_eq_log x] at h,
exact (eq_one_of_pos_of_log_eq_zero (neg_pos.mpr x_lt_zero) h).symm, },
{ exact or.inl rfl },
{ exact or.inr (or.inl (eq_one_of_pos_of_log_eq_zero x_gt_zero h)), }, },
{ rintro (rfl|rfl|rfl); simp only [log_one, log_zero, log_neg_eq_log], }
end
@[simp] lemma log_pow (x : ℝ) (n : ℕ) : log (x ^ n) = n * log x :=
begin
induction n with n ih,
{ simp },
rcases eq_or_ne x 0 with rfl | hx,
{ simp },
rw [pow_succ', log_mul (pow_ne_zero _ hx) hx, ih, nat.cast_succ, add_mul, one_mul],
end
@[simp] lemma log_zpow (x : ℝ) (n : ℤ) : log (x ^ n) = n * log x :=
begin
induction n,
{ rw [int.of_nat_eq_coe, zpow_coe_nat, log_pow, int.cast_coe_nat] },
rw [zpow_neg_succ_of_nat, log_inv, log_pow, int.cast_neg_succ_of_nat, nat.cast_add_one,
neg_mul_eq_neg_mul],
end
lemma log_sqrt {x : ℝ} (hx : 0 ≤ x) : log (sqrt x) = log x / 2 :=
by { rw [eq_div_iff, mul_comm, ← nat.cast_two, ← log_pow, sq_sqrt hx], exact two_ne_zero }
lemma log_le_sub_one_of_pos {x : ℝ} (hx : 0 < x) : log x ≤ x - 1 :=
begin
rw le_sub_iff_add_le,
convert add_one_le_exp (log x),
rw exp_log hx,
end
/-- Bound for `|log x * x|` in the interval `(0, 1]`. -/
lemma abs_log_mul_self_lt (x: ℝ) (h1 : 0 < x) (h2 : x ≤ 1) : |log x * x| < 1 :=
begin
have : 0 < 1/x := by simpa only [one_div, inv_pos] using h1,
replace := log_le_sub_one_of_pos this,
replace : log (1 / x) < 1/x := by linarith,
rw [log_div one_ne_zero h1.ne', log_one, zero_sub, lt_div_iff h1] at this,
have aux : 0 ≤ -log x * x,
{ refine mul_nonneg _ h1.le, rw ←log_inv, apply log_nonneg,
rw [←(le_inv h1 zero_lt_one), inv_one], exact h2, },
rw [←(abs_of_nonneg aux), neg_mul, abs_neg] at this, exact this,
end
/-- The real logarithm function tends to `+∞` at `+∞`. -/
lemma tendsto_log_at_top : tendsto log at_top at_top :=
tendsto_comp_exp_at_top.1 $ by simpa only [log_exp] using tendsto_id
lemma tendsto_log_nhds_within_zero : tendsto log (𝓝[≠] 0) at_bot :=
begin
rw [← (show _ = log, from funext log_abs)],
refine tendsto.comp _ tendsto_abs_nhds_within_zero,
simpa [← tendsto_comp_exp_at_bot] using tendsto_id
end
lemma continuous_on_log : continuous_on log {0}ᶜ :=
begin
rw [continuous_on_iff_continuous_restrict, restrict],
conv in (log _) { rw [log_of_ne_zero (show (x : ℝ) ≠ 0, from x.2)] },
exact exp_order_iso.symm.continuous.comp (continuous_subtype_coe.norm.subtype_mk _)
end
@[continuity] lemma continuous_log : continuous (λ x : {x : ℝ // x ≠ 0}, log x) :=
continuous_on_iff_continuous_restrict.1 $ continuous_on_log.mono $ λ x hx, hx
@[continuity] lemma continuous_log' : continuous (λ x : {x : ℝ // 0 < x}, log x) :=
continuous_on_iff_continuous_restrict.1 $ continuous_on_log.mono $ λ x hx, ne_of_gt hx
lemma continuous_at_log (hx : x ≠ 0) : continuous_at log x :=
(continuous_on_log x hx).continuous_at $ is_open.mem_nhds is_open_compl_singleton hx
@[simp] lemma continuous_at_log_iff : continuous_at log x ↔ x ≠ 0 :=
begin
refine ⟨_, continuous_at_log⟩,
rintros h rfl,
exact not_tendsto_nhds_of_tendsto_at_bot tendsto_log_nhds_within_zero _
(h.tendsto.mono_left inf_le_left)
end
open_locale big_operators
lemma log_prod {α : Type*} (s : finset α) (f : α → ℝ) (hf : ∀ x ∈ s, f x ≠ 0):
log (∏ i in s, f i) = ∑ i in s, log (f i) :=
begin
induction s using finset.cons_induction_on with a s ha ih,
{ simp },
{ rw [finset.forall_mem_cons] at hf,
simp [ih hf.2, log_mul hf.1 (finset.prod_ne_zero_iff.2 hf.2)] }
end
lemma log_nat_eq_sum_factorization (n : ℕ) : log n = n.factorization.sum (λ p t, t * log p) :=
begin
rcases eq_or_ne n 0 with rfl | hn,
{ simp },
nth_rewrite 0 [←nat.factorization_prod_pow_eq_self hn],
rw [finsupp.prod, nat.cast_prod, log_prod _ _ (λ p hp, _), finsupp.sum],
{ simp_rw [nat.cast_pow, log_pow] },
{ norm_cast,
exact pow_ne_zero _ (nat.prime_of_mem_factorization hp).ne_zero },
end
lemma tendsto_pow_log_div_mul_add_at_top (a b : ℝ) (n : ℕ) (ha : a ≠ 0) :
tendsto (λ x, log x ^ n / (a * x + b)) at_top (𝓝 0) :=
((tendsto_div_pow_mul_exp_add_at_top a b n ha.symm).comp tendsto_log_at_top).congr'
(by filter_upwards [eventually_gt_at_top (0 : ℝ)] with x hx using by simp [exp_log hx])
lemma is_o_pow_log_id_at_top {n : ℕ} : (λ x, log x ^ n) =o[at_top] id :=
begin
rw asymptotics.is_o_iff_tendsto',
{ simpa using tendsto_pow_log_div_mul_add_at_top 1 0 n one_ne_zero },
filter_upwards [eventually_ne_at_top (0 : ℝ)] with x h₁ h₂ using (h₁ h₂).elim,
end
lemma is_o_log_id_at_top : log =o[at_top] id := is_o_pow_log_id_at_top.congr_left (λ x, pow_one _)
end real
section continuity
open real
variables {α : Type*}
lemma filter.tendsto.log {f : α → ℝ} {l : filter α} {x : ℝ} (h : tendsto f l (𝓝 x)) (hx : x ≠ 0) :
tendsto (λ x, log (f x)) l (𝓝 (log x)) :=
(continuous_at_log hx).tendsto.comp h
variables [topological_space α] {f : α → ℝ} {s : set α} {a : α}
lemma continuous.log (hf : continuous f) (h₀ : ∀ x, f x ≠ 0) : continuous (λ x, log (f x)) :=
continuous_on_log.comp_continuous hf h₀
lemma continuous_at.log (hf : continuous_at f a) (h₀ : f a ≠ 0) :
continuous_at (λ x, log (f x)) a :=
hf.log h₀
lemma continuous_within_at.log (hf : continuous_within_at f s a) (h₀ : f a ≠ 0) :
continuous_within_at (λ x, log (f x)) s a :=
hf.log h₀
lemma continuous_on.log (hf : continuous_on f s) (h₀ : ∀ x ∈ s, f x ≠ 0) :
continuous_on (λ x, log (f x)) s :=
λ x hx, (hf x hx).log (h₀ x hx)
end continuity
|
5697f5471a08a962d60cee1c2044aad291a7e1a4 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/tietze_extension.lean | 5364e367cb487087cb314dcd64f4ab21b416e14f | [
"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 | 22,969 | lean | /-
Copyright (c) 2021 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import analysis.specific_limits.basic
import data.set.intervals.iso_Ioo
import topology.algebra.order.monotone_continuity
import topology.urysohns_bounded
/-!
# Tietze extension theorem
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we prove a few version of the Tietze extension theorem. The theorem says that a
continuous function `s → ℝ` defined on a closed set in a normal topological space `Y` can be
extended to a continuous function on the whole space. Moreover, if all values of the original
function belong to some (finite or infinite, open or closed) interval, then the extension can be
chosen so that it takes values in the same interval. In particular, if the original function is a
bounded function, then there exists a bounded extension of the same norm.
The proof mostly follows <https://ncatlab.org/nlab/show/Tietze+extension+theorem>. We patch a small
gap in the proof for unbounded functions, see
`exists_extension_forall_exists_le_ge_of_closed_embedding`.
## Implementation notes
We first prove the theorems for a closed embedding `e : X → Y` of a topological space into a normal
topological space, then specialize them to the case `X = s : set Y`, `e = coe`.
## Tags
Tietze extension theorem, Urysohn's lemma, normal topological space
-/
variables {X Y : Type*} [topological_space X] [topological_space Y] [normal_space Y]
open metric set filter
open_locale bounded_continuous_function topology
noncomputable theory
namespace bounded_continuous_function
/-- One step in the proof of the Tietze extension theorem. If `e : C(X, Y)` is a closed embedding
of a topological space into a normal topological space and `f : X →ᵇ ℝ` is a bounded continuous
function, then there exists a bounded continuous function `g : Y →ᵇ ℝ` of the norm `‖g‖ ≤ ‖f‖ / 3`
such that the distance between `g ∘ e` and `f` is at most `(2 / 3) * ‖f‖`. -/
lemma tietze_extension_step (f : X →ᵇ ℝ) (e : C(X, Y)) (he : closed_embedding e) :
∃ g : Y →ᵇ ℝ, ‖g‖ ≤ ‖f‖ / 3 ∧ dist (g.comp_continuous e) f ≤ (2 / 3) * ‖f‖ :=
begin
have h3 : (0 : ℝ) < 3 := by norm_num1,
have h23 : 0 < (2 / 3 : ℝ) := by norm_num1,
-- In the trivial case `f = 0`, we take `g = 0`
rcases eq_or_ne f 0 with (rfl|hf), { use 0, simp },
replace hf : 0 < ‖f‖ := norm_pos_iff.2 hf,
/- Otherwise, the closed sets `e '' (f ⁻¹' (Iic (-‖f‖ / 3)))` and `e '' (f ⁻¹' (Ici (‖f‖ / 3)))`
are disjoint, hence by Urysohn's lemma there exists a function `g` that is equal to `-‖f‖ / 3`
on the former set and is equal to `‖f‖ / 3` on the latter set. This function `g` satisfies the
assertions of the lemma. -/
have hf3 : -‖f‖ / 3 < ‖f‖ / 3, from (div_lt_div_right h3).2 (left.neg_lt_self hf),
have hc₁ : is_closed (e '' (f ⁻¹' (Iic (-‖f‖ / 3)))),
from he.is_closed_map _ (is_closed_Iic.preimage f.continuous),
have hc₂ : is_closed (e '' (f ⁻¹' (Ici (‖f‖ / 3)))),
from he.is_closed_map _ (is_closed_Ici.preimage f.continuous),
have hd : disjoint (e '' (f ⁻¹' (Iic (-‖f‖ / 3)))) (e '' (f ⁻¹' (Ici (‖f‖ / 3)))),
{ refine disjoint_image_of_injective he.inj (disjoint.preimage _ _),
rwa [Iic_disjoint_Ici, not_le] },
rcases exists_bounded_mem_Icc_of_closed_of_le hc₁ hc₂ hd hf3.le with ⟨g, hg₁, hg₂, hgf⟩,
refine ⟨g, _, _⟩,
{ refine (norm_le $ div_nonneg hf.le h3.le).mpr (λ y, _),
simpa [abs_le, neg_div] using hgf y },
{ refine (dist_le $ mul_nonneg h23.le hf.le).mpr (λ x, _),
have hfx : -‖f‖ ≤ f x ∧ f x ≤ ‖f‖,
by simpa only [real.norm_eq_abs, abs_le] using f.norm_coe_le_norm x,
cases le_total (f x) (-‖f‖ / 3) with hle₁ hle₁,
{ calc |g (e x) - f x| = -‖f‖ / 3 - f x:
by rw [hg₁ (mem_image_of_mem _ hle₁), abs_of_nonneg (sub_nonneg.2 hle₁)]
... ≤ (2 / 3) * ‖f‖ : by linarith },
{ cases le_total (f x) (‖f‖ / 3) with hle₂ hle₂,
{ simp only [neg_div] at *,
calc dist (g (e x)) (f x) ≤ |g (e x)| + |f x| : dist_le_norm_add_norm _ _
... ≤ ‖f‖ / 3 + ‖f‖ / 3 :
add_le_add (abs_le.2 $ hgf _) (abs_le.2 ⟨hle₁, hle₂⟩)
... = (2 / 3) * ‖f‖ : by linarith },
{ calc |g (e x) - f x| = f x - ‖f‖ / 3 :
by rw [hg₂ (mem_image_of_mem _ hle₂), abs_sub_comm, abs_of_nonneg (sub_nonneg.2 hle₂)]
... ≤ (2 / 3) * ‖f‖ : by linarith } } }
end
/-- **Tietze extension theorem** for real-valued bounded continuous maps, a version with a closed
embedding and bundled composition. If `e : C(X, Y)` is a closed embedding of a topological space
into a normal topological space and `f : X →ᵇ ℝ` is a bounded continuous function, then there exists
a bounded continuous function `g : Y →ᵇ ℝ` of the same norm such that `g ∘ e = f`. -/
lemma exists_extension_norm_eq_of_closed_embedding' (f : X →ᵇ ℝ) (e : C(X, Y))
(he : closed_embedding e) :
∃ g : Y →ᵇ ℝ, ‖g‖ = ‖f‖ ∧ g.comp_continuous e = f :=
begin
/- For the proof, we iterate `tietze_extension_step`. Each time we apply it to the difference
between the previous approximation and `f`. -/
choose F hF_norm hF_dist using λ f : X →ᵇ ℝ, tietze_extension_step f e he,
set g : ℕ → Y →ᵇ ℝ := λ n, (λ g, g + F (f - g.comp_continuous e))^[n] 0,
have g0 : g 0 = 0 := rfl,
have g_succ : ∀ n, g (n + 1) = g n + F (f - (g n).comp_continuous e),
from λ n, function.iterate_succ_apply' _ _ _,
have hgf : ∀ n, dist ((g n).comp_continuous e) f ≤ (2 / 3) ^ n * ‖f‖,
{ intro n, induction n with n ihn,
{ simp [g0] },
{ rw [g_succ n, add_comp_continuous, ← dist_sub_right, add_sub_cancel', pow_succ, mul_assoc],
refine (hF_dist _).trans (mul_le_mul_of_nonneg_left _ (by norm_num1)),
rwa ← dist_eq_norm' } },
have hg_dist : ∀ n, dist (g n) (g (n + 1)) ≤ 1 / 3 * ‖f‖ * (2 / 3) ^ n,
{ intro n,
calc dist (g n) (g (n + 1)) = ‖F (f - (g n).comp_continuous e)‖ :
by rw [g_succ, dist_eq_norm', add_sub_cancel']
... ≤ ‖f - (g n).comp_continuous e‖ / 3 : hF_norm _
... = (1 / 3) * dist ((g n).comp_continuous e) f :
by rw [dist_eq_norm', one_div, div_eq_inv_mul]
... ≤ (1 / 3) * ((2 / 3) ^ n * ‖f‖) :
mul_le_mul_of_nonneg_left (hgf n) (by norm_num1)
... = 1 / 3 * ‖f‖ * (2 / 3) ^ n : by ac_refl },
have hg_cau : cauchy_seq g, from cauchy_seq_of_le_geometric _ _ (by norm_num1) hg_dist,
have : tendsto (λ n, (g n).comp_continuous e) at_top (𝓝 $ (lim at_top g).comp_continuous e),
from ((continuous_comp_continuous e).tendsto _).comp hg_cau.tendsto_lim,
have hge : (lim at_top g).comp_continuous e = f,
{ refine tendsto_nhds_unique this (tendsto_iff_dist_tendsto_zero.2 _),
refine squeeze_zero (λ _, dist_nonneg) hgf _,
rw ← zero_mul (‖f‖),
refine (tendsto_pow_at_top_nhds_0_of_lt_1 _ _).mul tendsto_const_nhds; norm_num1 },
refine ⟨lim at_top g, le_antisymm _ _, hge⟩,
{ rw [← dist_zero_left, ← g0],
refine (dist_le_of_le_geometric_of_tendsto₀ _ _ (by norm_num1)
hg_dist hg_cau.tendsto_lim).trans_eq _,
field_simp [show (3 - 2 : ℝ) = 1, by norm_num1] },
{ rw ← hge, exact norm_comp_continuous_le _ _ }
end
/-- **Tietze extension theorem** for real-valued bounded continuous maps, a version with a closed
embedding and unbundled composition. If `e : C(X, Y)` is a closed embedding of a topological space
into a normal topological space and `f : X →ᵇ ℝ` is a bounded continuous function, then there exists
a bounded continuous function `g : Y →ᵇ ℝ` of the same norm such that `g ∘ e = f`. -/
lemma exists_extension_norm_eq_of_closed_embedding (f : X →ᵇ ℝ) {e : X → Y}
(he : closed_embedding e) :
∃ g : Y →ᵇ ℝ, ‖g‖ = ‖f‖ ∧ g ∘ e = f :=
begin
rcases exists_extension_norm_eq_of_closed_embedding' f ⟨e, he.continuous⟩ he with ⟨g, hg, rfl⟩,
exact ⟨g, hg, rfl⟩
end
/-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed
set. If `f` is a bounded continuous real-valued function defined on a closed set in a normal
topological space, then it can be extended to a bounded continuous function of the same norm defined
on the whole space. -/
lemma exists_norm_eq_restrict_eq_of_closed {s : set Y} (f : s →ᵇ ℝ) (hs : is_closed s) :
∃ g : Y →ᵇ ℝ, ‖g‖ = ‖f‖ ∧ g.restrict s = f :=
exists_extension_norm_eq_of_closed_embedding' f ((continuous_map.id _).restrict s)
(closed_embedding_subtype_coe hs)
/-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed
embedding and a bounded continuous function that takes values in a non-trivial closed interval.
See also `exists_extension_forall_mem_of_closed_embedding` for a more general statement that works
for any interval (finite or infinite, open or closed).
If `e : X → Y` is a closed embedding and `f : X →ᵇ ℝ` is a bounded continuous function such that
`f x ∈ [a, b]` for all `x`, where `a ≤ b`, then there exists a bounded continuous function
`g : Y →ᵇ ℝ` such that `g y ∈ [a, b]` for all `y` and `g ∘ e = f`. -/
lemma exists_extension_forall_mem_Icc_of_closed_embedding (f : X →ᵇ ℝ) {a b : ℝ} {e : X → Y}
(hf : ∀ x, f x ∈ Icc a b) (hle : a ≤ b) (he : closed_embedding e) :
∃ g : Y →ᵇ ℝ, (∀ y, g y ∈ Icc a b) ∧ g ∘ e = f :=
begin
rcases exists_extension_norm_eq_of_closed_embedding (f - const X ((a + b) / 2)) he
with ⟨g, hgf, hge⟩,
refine ⟨const Y ((a + b) / 2) + g, λ y, _, _⟩,
{ suffices : ‖f - const X ((a + b) / 2)‖ ≤ (b - a) / 2,
by simpa [real.Icc_eq_closed_ball, add_mem_closed_ball_iff_norm]
using (norm_coe_le_norm g y).trans (hgf.trans_le this),
refine (norm_le $ div_nonneg (sub_nonneg.2 hle) zero_le_two).2 (λ x, _),
simpa only [real.Icc_eq_closed_ball] using hf x },
{ ext x,
have : g (e x) = f x - (a + b) / 2 := congr_fun hge x,
simp [this] }
end
/-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed
embedding. Let `e` be a closed embedding of a nonempty topological space `X` into a normal
topological space `Y`. Let `f` be a bounded continuous real-valued function on `X`. Then there
exists a bounded continuous function `g : Y →ᵇ ℝ` such that `g ∘ e = f` and each value `g y` belongs
to a closed interval `[f x₁, f x₂]` for some `x₁` and `x₂`. -/
lemma exists_extension_forall_exists_le_ge_of_closed_embedding [nonempty X] (f : X →ᵇ ℝ) {e : X → Y}
(he : closed_embedding e) :
∃ g : Y →ᵇ ℝ, (∀ y, ∃ x₁ x₂, g y ∈ Icc (f x₁) (f x₂)) ∧ g ∘ e = f :=
begin
inhabit X,
-- Put `a = ⨅ x, f x` and `b = ⨆ x, f x`
obtain ⟨a, ha⟩ : ∃ a, is_glb (range f) a,
from ⟨_, is_glb_cinfi (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).1⟩,
obtain ⟨b, hb⟩ : ∃ b, is_lub (range f) b,
from ⟨_, is_lub_csupr (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).2⟩,
-- Then `f x ∈ [a, b]` for all `x`
have hmem : ∀ x, f x ∈ Icc a b, from λ x, ⟨ha.1 ⟨x, rfl⟩, hb.1 ⟨x, rfl⟩⟩,
-- Rule out the trivial case `a = b`
have hle : a ≤ b := (hmem default).1.trans (hmem default).2,
rcases hle.eq_or_lt with (rfl|hlt),
{ have : ∀ x, f x = a, by simpa using hmem,
use const Y a, simp [this, function.funext_iff] },
-- Put `c = (a + b) / 2`. Then `a < c < b` and `c - a = b - c`.
set c := (a + b) / 2,
have hac : a < c := left_lt_add_div_two.2 hlt,
have hcb : c < b := add_div_two_lt_right.2 hlt,
have hsub : c - a = b - c, by { simp only [c], field_simp, ring },
/- Due to `exists_extension_forall_mem_Icc_of_closed_embedding`, there exists an extension `g`
such that `g y ∈ [a, b]` for all `y`. However, if `a` and/or `b` do not belong to the range of
`f`, then we need to ensure that these points do not belong to the range of `g`. This is done
in two almost identical steps. First we deal with the case `∀ x, f x ≠ a`. -/
obtain ⟨g, hg_mem, hgf⟩ : ∃ g : Y →ᵇ ℝ, (∀ y, ∃ x, g y ∈ Icc (f x) b) ∧ g ∘ e = f,
{ rcases exists_extension_forall_mem_Icc_of_closed_embedding f hmem hle he
with ⟨g, hg_mem, hgf⟩,
-- If `a ∈ range f`, then we are done.
rcases em (∃ x, f x = a) with ⟨x, rfl⟩|ha',
{ exact ⟨g, λ y, ⟨x, hg_mem _⟩, hgf⟩ },
/- Otherwise, `g ⁻¹' {a}` is disjoint with `range e ∪ g ⁻¹' (Ici c)`, hence there exists a
function `dg : Y → ℝ` such that `dg ∘ e = 0`, `dg y = 0` whenever `c ≤ g y`, `dg y = c - a`
whenever `g y = a`, and `0 ≤ dg y ≤ c - a` for all `y`. -/
have hd : disjoint (range e ∪ g ⁻¹' (Ici c)) (g ⁻¹' {a}),
{ refine disjoint_union_left.2 ⟨_, disjoint.preimage _ _⟩,
{ rw set.disjoint_left,
rintro _ ⟨x, rfl⟩ (rfl : g (e x) = a),
exact ha' ⟨x, (congr_fun hgf x).symm⟩ },
{ exact set.disjoint_singleton_right.2 hac.not_le } },
rcases exists_bounded_mem_Icc_of_closed_of_le
(he.closed_range.union $ is_closed_Ici.preimage g.continuous)
(is_closed_singleton.preimage g.continuous) hd (sub_nonneg.2 hac.le)
with ⟨dg, dg0, dga, dgmem⟩,
replace hgf : ∀ x, (g + dg) (e x) = f x,
{ intro x, simp [dg0 (or.inl $ mem_range_self _), ← hgf] },
refine ⟨g + dg, λ y, _, funext hgf⟩,
{ have hay : a < (g + dg) y,
{ rcases (hg_mem y).1.eq_or_lt with rfl|hlt,
{ refine (lt_add_iff_pos_right _).2 _,
calc 0 < c - g y : sub_pos.2 hac
... = dg y : (dga rfl).symm },
{ exact hlt.trans_le ((le_add_iff_nonneg_right _).2 $ (dgmem y).1) } },
rcases ha.exists_between hay with ⟨_, ⟨x, rfl⟩, hax, hxy⟩,
refine ⟨x, hxy.le, _⟩,
cases le_total c (g y) with hc hc,
{ simp [dg0 (or.inr hc), (hg_mem y).2] },
{ calc g y + dg y ≤ c + (c - a) : add_le_add hc (dgmem _).2
... = b : by rw [hsub, add_sub_cancel'_right] } } },
/- Now we deal with the case `∀ x, f x ≠ b`. The proof is the same as in the first case, with
minor modifications that make it hard to deduplicate code. -/
choose xl hxl hgb using hg_mem,
rcases em (∃ x, f x = b) with ⟨x, rfl⟩|hb',
{ exact ⟨g, λ y, ⟨xl y, x, hxl y, hgb y⟩, hgf⟩ },
have hd : disjoint (range e ∪ g ⁻¹' (Iic c)) (g ⁻¹' {b}),
{ refine disjoint_union_left.2 ⟨_, disjoint.preimage _ _⟩,
{ rw set.disjoint_left,
rintro _ ⟨x, rfl⟩ (rfl : g (e x) = b),
exact hb' ⟨x, (congr_fun hgf x).symm⟩ },
{ exact set.disjoint_singleton_right.2 hcb.not_le } },
rcases exists_bounded_mem_Icc_of_closed_of_le
(he.closed_range.union $ is_closed_Iic.preimage g.continuous)
(is_closed_singleton.preimage g.continuous) hd (sub_nonneg.2 hcb.le)
with ⟨dg, dg0, dgb, dgmem⟩,
replace hgf : ∀ x, (g - dg) (e x) = f x,
{ intro x, simp [dg0 (or.inl $ mem_range_self _), ← hgf] },
refine ⟨g - dg, λ y, _, funext hgf⟩,
{ have hyb : (g - dg) y < b,
{ rcases (hgb y).eq_or_lt with rfl|hlt,
{ refine (sub_lt_self_iff _).2 _,
calc 0 < g y - c : sub_pos.2 hcb
... = dg y : (dgb rfl).symm },
{ exact ((sub_le_self_iff _).2 (dgmem _).1).trans_lt hlt } },
rcases hb.exists_between hyb with ⟨_, ⟨xu, rfl⟩, hyxu, hxub⟩,
cases lt_or_le c (g y) with hc hc,
{ rcases em (a ∈ range f) with ⟨x, rfl⟩|ha',
{ refine ⟨x, xu, _, hyxu.le⟩,
calc f x = c - (b - c) : by rw [← hsub, sub_sub_cancel]
... ≤ g y - dg y : sub_le_sub hc.le (dgmem _).2 },
{ have hay : a < (g - dg) y,
{ calc a = c - (b - c) : by rw [← hsub, sub_sub_cancel]
... < g y - (b - c) : sub_lt_sub_right hc _
... ≤ g y - dg y : sub_le_sub_left (dgmem _).2 _ },
rcases ha.exists_between hay with ⟨_, ⟨x, rfl⟩, ha, hxy⟩,
exact ⟨x, xu, hxy.le, hyxu.le⟩ } },
{ refine ⟨xl y, xu, _, hyxu.le⟩,
simp [dg0 (or.inr hc), hxl] } },
end
/-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed
embedding. Let `e` be a closed embedding of a nonempty topological space `X` into a normal
topological space `Y`. Let `f` be a bounded continuous real-valued function on `X`. Let `t` be
a nonempty convex set of real numbers (we use `ord_connected` instead of `convex` to automatically
deduce this argument by typeclass search) such that `f x ∈ t` for all `x`. Then there exists
a bounded continuous real-valued function `g : Y →ᵇ ℝ` such that `g y ∈ t` for all `y` and
`g ∘ e = f`. -/
lemma exists_extension_forall_mem_of_closed_embedding (f : X →ᵇ ℝ) {t : set ℝ} {e : X → Y}
[hs : ord_connected t] (hf : ∀ x, f x ∈ t) (hne : t.nonempty) (he : closed_embedding e) :
∃ g : Y →ᵇ ℝ, (∀ y, g y ∈ t) ∧ g ∘ e = f :=
begin
casesI is_empty_or_nonempty X,
{ rcases hne with ⟨c, hc⟩,
refine ⟨const Y c, λ y, hc, funext $ λ x, is_empty_elim x⟩ },
rcases exists_extension_forall_exists_le_ge_of_closed_embedding f he with ⟨g, hg, hgf⟩,
refine ⟨g, λ y, _, hgf⟩,
rcases hg y with ⟨xl, xu, h⟩,
exact hs.out (hf _) (hf _) h
end
/-- **Tietze extension theorem** for real-valued bounded continuous maps, a version for a closed
set. Let `s` be a closed set in a normal topological space `Y`. Let `f` be a bounded continuous
real-valued function on `s`. Let `t` be a nonempty convex set of real numbers (we use
`ord_connected` instead of `convex` to automatically deduce this argument by typeclass search) such
that `f x ∈ t` for all `x : s`. Then there exists a bounded continuous real-valued function
`g : Y →ᵇ ℝ` such that `g y ∈ t` for all `y` and `g.restrict s = f`. -/
lemma exists_forall_mem_restrict_eq_of_closed {s : set Y} (f : s →ᵇ ℝ) (hs : is_closed s)
{t : set ℝ} [ord_connected t] (hf : ∀ x, f x ∈ t) (hne : t.nonempty) :
∃ g : Y →ᵇ ℝ, (∀ y, g y ∈ t) ∧ g.restrict s = f :=
begin
rcases exists_extension_forall_mem_of_closed_embedding f hf hne (closed_embedding_subtype_coe hs)
with ⟨g, hg, hgf⟩,
exact ⟨g, hg, fun_like.coe_injective hgf⟩
end
end bounded_continuous_function
namespace continuous_map
/-- **Tietze extension theorem** for real-valued continuous maps, a version for a closed
embedding. Let `e` be a closed embedding of a nonempty topological space `X` into a normal
topological space `Y`. Let `f` be a continuous real-valued function on `X`. Let `t` be a nonempty
convex set of real numbers (we use `ord_connected` instead of `convex` to automatically deduce this
argument by typeclass search) such that `f x ∈ t` for all `x`. Then there exists a continuous
real-valued function `g : C(Y, ℝ)` such that `g y ∈ t` for all `y` and `g ∘ e = f`. -/
lemma exists_extension_forall_mem_of_closed_embedding (f : C(X, ℝ)) {t : set ℝ} {e : X → Y}
[hs : ord_connected t] (hf : ∀ x, f x ∈ t) (hne : t.nonempty) (he : closed_embedding e) :
∃ g : C(Y, ℝ), (∀ y, g y ∈ t) ∧ g ∘ e = f :=
begin
have h : ℝ ≃o Ioo (-1 : ℝ) 1 := order_iso_Ioo_neg_one_one ℝ,
set F : X →ᵇ ℝ :=
{ to_fun := coe ∘ (h ∘ f),
continuous_to_fun := continuous_subtype_coe.comp (h.continuous.comp f.continuous),
map_bounded' := bounded_range_iff.1 ((bounded_Ioo (-1 : ℝ) 1).mono $
forall_range_iff.2 $ λ x, (h (f x)).2) },
set t' : set ℝ := (coe ∘ h) '' t,
have ht_sub : t' ⊆ Ioo (-1 : ℝ) 1 := image_subset_iff.2 (λ x hx, (h x).2),
haveI : ord_connected t',
{ constructor, rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ z hz,
lift z to Ioo (-1 : ℝ) 1 using (Icc_subset_Ioo (h x).2.1 (h y).2.2 hz),
change z ∈ Icc (h x) (h y) at hz, rw [← h.image_Icc] at hz,
rcases hz with ⟨z, hz, rfl⟩,
exact ⟨z, hs.out hx hy hz, rfl⟩ },
have hFt : ∀ x, F x ∈ t', from λ x, mem_image_of_mem _ (hf x),
rcases F.exists_extension_forall_mem_of_closed_embedding hFt (hne.image _) he
with ⟨G, hG, hGF⟩,
set g : C(Y, ℝ) := ⟨h.symm ∘ cod_restrict G _ (λ y, ht_sub (hG y)), h.symm.continuous.comp $
G.continuous.subtype_mk _⟩,
have hgG : ∀ {y a}, g y = a ↔ G y = h a,
from λ y a, h.to_equiv.symm_apply_eq.trans subtype.ext_iff,
refine ⟨g, λ y, _, _⟩,
{ rcases hG y with ⟨a, ha, hay⟩,
convert ha,
exact hgG.2 hay.symm },
{ ext x, exact hgG.2 (congr_fun hGF _) }
end
/-- **Tietze extension theorem** for real-valued continuous maps, a version for a closed
embedding. Let `e` be a closed embedding of a nonempty topological space `X` into a normal
topological space `Y`. Let `f` be a continuous real-valued function on `X`. Then there exists a
continuous real-valued function `g : C(Y, ℝ)` such that `g ∘ e = f`. -/
lemma exists_extension_of_closed_embedding (f : C(X, ℝ)) (e : X → Y) (he : closed_embedding e) :
∃ g : C(Y, ℝ), g ∘ e = f :=
(exists_extension_forall_mem_of_closed_embedding f (λ x, mem_univ _) univ_nonempty he).imp $
λ g, and.right
/-- **Tietze extension theorem** for real-valued continuous maps, a version for a closed set. Let
`s` be a closed set in a normal topological space `Y`. Let `f` be a continuous real-valued function
on `s`. Let `t` be a nonempty convex set of real numbers (we use `ord_connected` instead of `convex`
to automatically deduce this argument by typeclass search) such that `f x ∈ t` for all `x : s`. Then
there exists a continuous real-valued function `g : C(Y, ℝ)` such that `g y ∈ t` for all `y` and
`g.restrict s = f`. -/
lemma exists_restrict_eq_forall_mem_of_closed {s : set Y} (f : C(s, ℝ)) {t : set ℝ}
[ord_connected t] (ht : ∀ x, f x ∈ t) (hne : t.nonempty) (hs : is_closed s) :
∃ g : C(Y, ℝ), (∀ y, g y ∈ t) ∧ g.restrict s = f :=
let ⟨g, hgt, hgf⟩ := exists_extension_forall_mem_of_closed_embedding f ht hne
(closed_embedding_subtype_coe hs)
in ⟨g, hgt, coe_injective hgf⟩
/-- **Tietze extension theorem** for real-valued continuous maps, a version for a closed set. Let
`s` be a closed set in a normal topological space `Y`. Let `f` be a continuous real-valued function
on `s`. Then there exists a continuous real-valued function `g : C(Y, ℝ)` such that
`g.restrict s = f`. -/
lemma exists_restrict_eq_of_closed {s : set Y} (f : C(s, ℝ)) (hs : is_closed s) :
∃ g : C(Y, ℝ), g.restrict s = f :=
let ⟨g, hg, hgf⟩ := exists_restrict_eq_forall_mem_of_closed f (λ _, mem_univ _) univ_nonempty hs
in ⟨g, hgf⟩
end continuous_map
|
2ed217b779659cbf77df0ea3a3b4b17990d53395 | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch5/ex0305.lean | fd62da6ab6130884702ae92a9515bed0a94dc401 | [] | 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 | 142 | lean | example (p q : ℕ → Prop) : (∃ x, p x) → ∃ x, p x ∨ q x :=
begin
intro h,
cases h with x hpx,
existsi x, left, exact hpx
end
|
07059608d89efd191f3becd5092ea59b7bee1f84 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/computability/turing_machine.lean | d4c5b816e3052d70effc3fbad4bc4a79c31618b7 | [
"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 | 109,947 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.fintype.basic
import data.pfun
import logic.function.iterate
import order.basic
import tactic.apply_fun
/-!
# Turing machines
This file defines a sequence of simple machine languages, starting with Turing machines and working
up to more complex languages based on Wang B-machines.
## Naming conventions
Each model of computation in this file shares a naming convention for the elements of a model of
computation. These are the parameters for the language:
* `Γ` is the alphabet on the tape.
* `Λ` is the set of labels, or internal machine states.
* `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and
later models achieve this by mixing it into `Λ`.
* `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks.
All of these variables denote "essentially finite" types, but for technical reasons it is
convenient to allow them to be infinite anyway. When using an infinite type, we will be interested
to prove that only finitely many values of the type are ever interacted with.
Given these parameters, there are a few common structures for the model that arise:
* `stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is
finite, and for later models it is an infinite inductive type representing "possible program
texts".
* `cfg` is the set of instantaneous configurations, that is, the state of the machine together with
its environment.
* `machine` is the set of all machines in the model. Usually this is approximately a function
`Λ → stmt`, although different models have different ways of halting and other actions.
* `step : cfg → option cfg` is the function that describes how the state evolves over one step.
If `step c = none`, then `c` is a terminal state, and the result of the computation is read off
from `c`. Because of the type of `step`, these models are all deterministic by construction.
* `init : input → cfg` sets up the initial state. The type `input` depends on the model;
in most cases it is `list Γ`.
* `eval : machine → input → part output`, given a machine `M` and input `i`, starts from
`init i`, runs `step` until it reaches an output, and then applies a function `cfg → output` to
the final state to obtain the result. The type `output` depends on the model.
* `supports : machine → finset Λ → Prop` asserts that a machine `M` starts in `S : finset Λ`, and
can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input
cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when
convenient, and prove that only finitely many of these states are actually accessible. This
formalizes "essentially finite" mentioned above.
-/
open relation
open nat (iterate)
open function (update iterate_succ iterate_succ_apply iterate_succ'
iterate_succ_apply' iterate_zero_apply)
namespace turing
/-- The `blank_extends` partial order holds of `l₁` and `l₂` if `l₂` is obtained by adding
blanks (`default Γ`) to the end of `l₁`. -/
def blank_extends {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop :=
∃ n, l₂ = l₁ ++ list.repeat (default Γ) n
@[refl] theorem blank_extends.refl {Γ} [inhabited Γ] (l : list Γ) : blank_extends l l :=
⟨0, by simp⟩
@[trans] theorem blank_extends.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} :
blank_extends l₁ l₂ → blank_extends l₂ l₃ → blank_extends l₁ l₃ :=
by rintro ⟨i, rfl⟩ ⟨j, rfl⟩; exact ⟨i+j, by simp [list.repeat_add]⟩
theorem blank_extends.below_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} :
blank_extends l l₁ → blank_extends l l₂ →
l₁.length ≤ l₂.length → blank_extends l₁ l₂ :=
begin
rintro ⟨i, rfl⟩ ⟨j, rfl⟩ h, use j - i,
simp only [list.length_append, add_le_add_iff_left, list.length_repeat] at h,
simp only [← list.repeat_add, add_tsub_cancel_of_le h, list.append_assoc],
end
/-- Any two extensions by blank `l₁,l₂` of `l` have a common join (which can be taken to be the
longer of `l₁` and `l₂`). -/
def blank_extends.above {Γ} [inhabited Γ] {l l₁ l₂ : list Γ}
(h₁ : blank_extends l l₁) (h₂ : blank_extends l l₂) :
{l' // blank_extends l₁ l' ∧ blank_extends l₂ l'} :=
if h : l₁.length ≤ l₂.length then
⟨l₂, h₁.below_of_le h₂ h, blank_extends.refl _⟩
else
⟨l₁, blank_extends.refl _, h₂.below_of_le h₁ (le_of_not_ge h)⟩
theorem blank_extends.above_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} :
blank_extends l₁ l → blank_extends l₂ l →
l₁.length ≤ l₂.length → blank_extends l₁ l₂ :=
begin
rintro ⟨i, rfl⟩ ⟨j, e⟩ h, use i - j,
refine list.append_right_cancel (e.symm.trans _),
rw [list.append_assoc, ← list.repeat_add, tsub_add_cancel_of_le],
apply_fun list.length at e,
simp only [list.length_append, list.length_repeat] at e,
rwa [← add_le_add_iff_left, e, add_le_add_iff_right]
end
/-- `blank_rel` is the symmetric closure of `blank_extends`, turning it into an equivalence
relation. Two lists are related by `blank_rel` if one extends the other by blanks. -/
def blank_rel {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop :=
blank_extends l₁ l₂ ∨ blank_extends l₂ l₁
@[refl] theorem blank_rel.refl {Γ} [inhabited Γ] (l : list Γ) : blank_rel l l :=
or.inl (blank_extends.refl _)
@[symm] theorem blank_rel.symm {Γ} [inhabited Γ] {l₁ l₂ : list Γ} :
blank_rel l₁ l₂ → blank_rel l₂ l₁ := or.symm
@[trans] theorem blank_rel.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} :
blank_rel l₁ l₂ → blank_rel l₂ l₃ → blank_rel l₁ l₃ :=
begin
rintro (h₁|h₁) (h₂|h₂),
{ exact or.inl (h₁.trans h₂) },
{ cases le_total l₁.length l₃.length with h h,
{ exact or.inl (h₁.above_of_le h₂ h) },
{ exact or.inr (h₂.above_of_le h₁ h) } },
{ cases le_total l₁.length l₃.length with h h,
{ exact or.inl (h₁.below_of_le h₂ h) },
{ exact or.inr (h₂.below_of_le h₁ h) } },
{ exact or.inr (h₂.trans h₁) },
end
/-- Given two `blank_rel` lists, there exists (constructively) a common join. -/
def blank_rel.above {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) :
{l // blank_extends l₁ l ∧ blank_extends l₂ l} :=
begin
refine if hl : l₁.length ≤ l₂.length
then ⟨l₂, or.elim h id (λ h', _), blank_extends.refl _⟩
else ⟨l₁, blank_extends.refl _, or.elim h (λ h', _) id⟩,
exact (blank_extends.refl _).above_of_le h' hl,
exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl)
end
/-- Given two `blank_rel` lists, there exists (constructively) a common meet. -/
def blank_rel.below {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) :
{l // blank_extends l l₁ ∧ blank_extends l l₂} :=
begin
refine if hl : l₁.length ≤ l₂.length
then ⟨l₁, blank_extends.refl _, or.elim h id (λ h', _)⟩
else ⟨l₂, or.elim h (λ h', _) id, blank_extends.refl _⟩,
exact (blank_extends.refl _).above_of_le h' hl,
exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl)
end
theorem blank_rel.equivalence (Γ) [inhabited Γ] : equivalence (@blank_rel Γ _) :=
⟨blank_rel.refl, @blank_rel.symm _ _, @blank_rel.trans _ _⟩
/-- Construct a setoid instance for `blank_rel`. -/
def blank_rel.setoid (Γ) [inhabited Γ] : setoid (list Γ) := ⟨_, blank_rel.equivalence _⟩
/-- A `list_blank Γ` is a quotient of `list Γ` by extension by blanks at the end. This is used to
represent half-tapes of a Turing machine, so that we can pretend that the list continues
infinitely with blanks. -/
def list_blank (Γ) [inhabited Γ] := quotient (blank_rel.setoid Γ)
instance list_blank.inhabited {Γ} [inhabited Γ] : inhabited (list_blank Γ) := ⟨quotient.mk' []⟩
instance list_blank.has_emptyc {Γ} [inhabited Γ] : has_emptyc (list_blank Γ) := ⟨quotient.mk' []⟩
/-- A modified version of `quotient.lift_on'` specialized for `list_blank`, with the stronger
precondition `blank_extends` instead of `blank_rel`. -/
@[elab_as_eliminator, reducible]
protected def list_blank.lift_on {Γ} [inhabited Γ] {α} (l : list_blank Γ) (f : list Γ → α)
(H : ∀ a b, blank_extends a b → f a = f b) : α :=
l.lift_on' f $ by rintro a b (h|h); [exact H _ _ h, exact (H _ _ h).symm]
/-- The quotient map turning a `list` into a `list_blank`. -/
def list_blank.mk {Γ} [inhabited Γ] : list Γ → list_blank Γ := quotient.mk'
@[elab_as_eliminator]
protected lemma list_blank.induction_on {Γ} [inhabited Γ]
{p : list_blank Γ → Prop} (q : list_blank Γ)
(h : ∀ a, p (list_blank.mk a)) : p q := quotient.induction_on' q h
/-- The head of a `list_blank` is well defined. -/
def list_blank.head {Γ} [inhabited Γ] (l : list_blank Γ) : Γ :=
l.lift_on list.head begin
rintro _ _ ⟨i, rfl⟩,
cases a, {cases i; refl}, refl
end
@[simp] theorem list_blank.head_mk {Γ} [inhabited Γ] (l : list Γ) :
list_blank.head (list_blank.mk l) = l.head := rfl
/-- The tail of a `list_blank` is well defined (up to the tail of blanks). -/
def list_blank.tail {Γ} [inhabited Γ] (l : list_blank Γ) : list_blank Γ :=
l.lift_on (λ l, list_blank.mk l.tail) begin
rintro _ _ ⟨i, rfl⟩,
refine quotient.sound' (or.inl _),
cases a; [{cases i; [exact ⟨0, rfl⟩, exact ⟨i, rfl⟩]}, exact ⟨i, rfl⟩]
end
@[simp] theorem list_blank.tail_mk {Γ} [inhabited Γ] (l : list Γ) :
list_blank.tail (list_blank.mk l) = list_blank.mk l.tail := rfl
/-- We can cons an element onto a `list_blank`. -/
def list_blank.cons {Γ} [inhabited Γ] (a : Γ) (l : list_blank Γ) : list_blank Γ :=
l.lift_on (λ l, list_blank.mk (list.cons a l)) begin
rintro _ _ ⟨i, rfl⟩,
exact quotient.sound' (or.inl ⟨i, rfl⟩),
end
@[simp] theorem list_blank.cons_mk {Γ} [inhabited Γ] (a : Γ) (l : list Γ) :
list_blank.cons a (list_blank.mk l) = list_blank.mk (a :: l) := rfl
@[simp] theorem list_blank.head_cons {Γ} [inhabited Γ] (a : Γ) :
∀ (l : list_blank Γ), (l.cons a).head = a :=
quotient.ind' $ by exact λ l, rfl
@[simp] theorem list_blank.tail_cons {Γ} [inhabited Γ] (a : Γ) :
∀ (l : list_blank Γ), (l.cons a).tail = l :=
quotient.ind' $ by exact λ l, rfl
/-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where
this only holds for nonempty lists. -/
@[simp] theorem list_blank.cons_head_tail {Γ} [inhabited Γ] :
∀ (l : list_blank Γ), l.tail.cons l.head = l :=
quotient.ind' begin
refine (λ l, quotient.sound' (or.inr _)),
cases l, {exact ⟨1, rfl⟩}, {refl},
end
/-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where
this only holds for nonempty lists. -/
theorem list_blank.exists_cons {Γ} [inhabited Γ] (l : list_blank Γ) :
∃ a l', l = list_blank.cons a l' :=
⟨_, _, (list_blank.cons_head_tail _).symm⟩
/-- The n-th element of a `list_blank` is well defined for all `n : ℕ`, unlike in a `list`. -/
def list_blank.nth {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : Γ :=
l.lift_on (λ l, list.inth l n) begin
rintro l _ ⟨i, rfl⟩,
simp only [list.inth],
cases lt_or_le _ _ with h h, {rw list.nth_append h},
rw list.nth_len_le h,
cases le_or_lt _ _ with h₂ h₂, {rw list.nth_len_le h₂},
rw [list.nth_le_nth h₂, list.nth_le_append_right h, list.nth_le_repeat]
end
@[simp] theorem list_blank.nth_mk {Γ} [inhabited Γ] (l : list Γ) (n : ℕ) :
(list_blank.mk l).nth n = l.inth n := rfl
@[simp] theorem list_blank.nth_zero {Γ} [inhabited Γ] (l : list_blank Γ) : l.nth 0 = l.head :=
begin
conv {to_lhs, rw [← list_blank.cons_head_tail l]},
exact quotient.induction_on' l.tail (λ l, rfl)
end
@[simp] theorem list_blank.nth_succ {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) :
l.nth (n + 1) = l.tail.nth n :=
begin
conv {to_lhs, rw [← list_blank.cons_head_tail l]},
exact quotient.induction_on' l.tail (λ l, rfl)
end
@[ext] theorem list_blank.ext {Γ} [inhabited Γ] {L₁ L₂ : list_blank Γ} :
(∀ i, L₁.nth i = L₂.nth i) → L₁ = L₂ :=
list_blank.induction_on L₁ $ λ l₁, list_blank.induction_on L₂ $ λ l₂ H,
begin
wlog h : l₁.length ≤ l₂.length using l₁ l₂,
swap, { exact (this $ λ i, (H i).symm).symm },
refine quotient.sound' (or.inl ⟨l₂.length - l₁.length, _⟩),
refine list.ext_le _ (λ i h h₂, eq.symm _),
{ simp only [add_tsub_cancel_of_le h, list.length_append, list.length_repeat] },
simp at H,
cases lt_or_le i l₁.length with h' h',
{ simpa only [list.nth_le_append _ h',
list.nth_le_nth h, list.nth_le_nth h', option.iget] using H i },
{ simpa only [list.nth_le_append_right h', list.nth_le_repeat,
list.nth_le_nth h, list.nth_len_le h', option.iget] using H i },
end
/-- Apply a function to a value stored at the nth position of the list. -/
@[simp] def list_blank.modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) : ℕ → list_blank Γ → list_blank Γ
| 0 L := L.tail.cons (f L.head)
| (n+1) L := (L.tail.modify_nth n).cons L.head
theorem list_blank.nth_modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) (n i) (L : list_blank Γ) :
(L.modify_nth f n).nth i = if i = n then f (L.nth i) else L.nth i :=
begin
induction n with n IH generalizing i L,
{ cases i; simp only [list_blank.nth_zero, if_true,
list_blank.head_cons, list_blank.modify_nth, eq_self_iff_true,
list_blank.nth_succ, if_false, list_blank.tail_cons] },
{ cases i,
{ rw if_neg (nat.succ_ne_zero _).symm,
simp only [list_blank.nth_zero, list_blank.head_cons, list_blank.modify_nth] },
{ simp only [IH, list_blank.modify_nth, list_blank.nth_succ, list_blank.tail_cons],
congr } }
end
/-- A pointed map of `inhabited` types is a map that sends one default value to the other. -/
structure {u v} pointed_map (Γ : Type u) (Γ' : Type v)
[inhabited Γ] [inhabited Γ'] : Type (max u v) :=
(f : Γ → Γ') (map_pt' : f (default _) = default _)
instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : inhabited (pointed_map Γ Γ') :=
⟨⟨λ _, default _, rfl⟩⟩
instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : has_coe_to_fun (pointed_map Γ Γ') (λ _, Γ → Γ') :=
⟨pointed_map.f⟩
@[simp] theorem pointed_map.mk_val {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : Γ → Γ') (pt) : (pointed_map.mk f pt : Γ → Γ') = f := rfl
@[simp] theorem pointed_map.map_pt {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') : f (default _) = default _ := pointed_map.map_pt' _
@[simp] theorem pointed_map.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list Γ) : (l.map f).head = f l.head :=
by cases l; [exact (pointed_map.map_pt f).symm, refl]
/-- The `map` function on lists is well defined on `list_blank`s provided that the map is
pointed. -/
def list_blank.map {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) : list_blank Γ' :=
l.lift_on (λ l, list_blank.mk (list.map f l)) begin
rintro l _ ⟨i, rfl⟩, refine quotient.sound' (or.inl ⟨i, _⟩),
simp only [pointed_map.map_pt, list.map_append, list.map_repeat],
end
@[simp] theorem list_blank.map_mk {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list Γ) : (list_blank.mk l).map f = list_blank.mk (l.map f) := rfl
@[simp] theorem list_blank.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).head = f l.head :=
begin
conv {to_lhs, rw [← list_blank.cons_head_tail l]},
exact quotient.induction_on' l (λ a, rfl)
end
@[simp] theorem list_blank.tail_map {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).tail = l.tail.map f :=
begin
conv {to_lhs, rw [← list_blank.cons_head_tail l]},
exact quotient.induction_on' l (λ a, rfl)
end
@[simp] theorem list_blank.map_cons {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) (a : Γ) : (l.cons a).map f = (l.map f).cons (f a) :=
begin
refine (list_blank.cons_head_tail _).symm.trans _,
simp only [list_blank.head_map, list_blank.head_cons, list_blank.tail_map, list_blank.tail_cons]
end
@[simp] theorem list_blank.nth_map {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (l : list_blank Γ) (n : ℕ) : (l.map f).nth n = f (l.nth n) :=
l.induction_on begin
intro l, simp only [list.nth_map, list_blank.map_mk, list_blank.nth_mk, list.inth],
cases l.nth n, {exact f.2.symm}, {refl}
end
/-- The `i`-th projection as a pointed map. -/
def proj {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) :
pointed_map (∀ i, Γ i) (Γ i) := ⟨λ a, a i, rfl⟩
theorem proj_map_nth {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι)
(L n) : (list_blank.map (@proj ι Γ _ i) L).nth n = L.nth n i :=
by rw list_blank.nth_map; refl
theorem list_blank.map_modify_nth {Γ Γ'} [inhabited Γ] [inhabited Γ']
(F : pointed_map Γ Γ') (f : Γ → Γ) (f' : Γ' → Γ')
(H : ∀ x, F (f x) = f' (F x)) (n) (L : list_blank Γ) :
(L.modify_nth f n).map F = (L.map F).modify_nth f' n :=
by induction n with n IH generalizing L; simp only [*,
list_blank.head_map, list_blank.modify_nth, list_blank.map_cons, list_blank.tail_map]
/-- Append a list on the left side of a list_blank. -/
@[simp] def list_blank.append {Γ} [inhabited Γ] : list Γ → list_blank Γ → list_blank Γ
| [] L := L
| (a :: l) L := list_blank.cons a (list_blank.append l L)
@[simp] theorem list_blank.append_mk {Γ} [inhabited Γ] (l₁ l₂ : list Γ) :
list_blank.append l₁ (list_blank.mk l₂) = list_blank.mk (l₁ ++ l₂) :=
by induction l₁; simp only [*,
list_blank.append, list.nil_append, list.cons_append, list_blank.cons_mk]
theorem list_blank.append_assoc {Γ} [inhabited Γ] (l₁ l₂ : list Γ) (l₃ : list_blank Γ) :
list_blank.append (l₁ ++ l₂) l₃ = list_blank.append l₁ (list_blank.append l₂ l₃) :=
l₃.induction_on $ by intro; simp only [list_blank.append_mk, list.append_assoc]
/-- The `bind` function on lists is well defined on `list_blank`s provided that the default element
is sent to a sequence of default elements. -/
def list_blank.bind {Γ Γ'} [inhabited Γ] [inhabited Γ']
(l : list_blank Γ) (f : Γ → list Γ')
(hf : ∃ n, f (default _) = list.repeat (default _) n) : list_blank Γ' :=
l.lift_on (λ l, list_blank.mk (list.bind l f)) begin
rintro l _ ⟨i, rfl⟩, cases hf with n e, refine quotient.sound' (or.inl ⟨i * n, _⟩),
rw [list.bind_append, mul_comm], congr,
induction i with i IH, refl,
simp only [IH, e, list.repeat_add, nat.mul_succ, add_comm, list.repeat_succ, list.cons_bind],
end
@[simp] lemma list_blank.bind_mk {Γ Γ'} [inhabited Γ] [inhabited Γ']
(l : list Γ) (f : Γ → list Γ') (hf) :
(list_blank.mk l).bind f hf = list_blank.mk (l.bind f) := rfl
@[simp] lemma list_blank.cons_bind {Γ Γ'} [inhabited Γ] [inhabited Γ']
(a : Γ) (l : list_blank Γ) (f : Γ → list Γ') (hf) :
(l.cons a).bind f hf = (l.bind f hf).append (f a) :=
l.induction_on $ by intro; simp only [list_blank.append_mk,
list_blank.bind_mk, list_blank.cons_mk, list.cons_bind]
/-- The tape of a Turing machine is composed of a head element (which we imagine to be the
current position of the head), together with two `list_blank`s denoting the portions of the tape
going off to the left and right. When the Turing machine moves right, an element is pulled from the
right side and becomes the new head, while the head element is consed onto the left side. -/
structure tape (Γ : Type*) [inhabited Γ] :=
(head : Γ)
(left : list_blank Γ)
(right : list_blank Γ)
instance tape.inhabited {Γ} [inhabited Γ] : inhabited (tape Γ) :=
⟨by constructor; apply default⟩
/-- A direction for the turing machine `move` command, either
left or right. -/
@[derive decidable_eq, derive inhabited]
inductive dir | left | right
/-- The "inclusive" left side of the tape, including both `left` and `head`. -/
def tape.left₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.left.cons T.head
/-- The "inclusive" right side of the tape, including both `right` and `head`. -/
def tape.right₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.right.cons T.head
/-- Move the tape in response to a motion of the Turing machine. Note that `T.move dir.left` makes
`T.left` smaller; the Turing machine is moving left and the tape is moving right. -/
def tape.move {Γ} [inhabited Γ] : dir → tape Γ → tape Γ
| dir.left ⟨a, L, R⟩ := ⟨L.head, L.tail, R.cons a⟩
| dir.right ⟨a, L, R⟩ := ⟨R.head, L.cons a, R.tail⟩
@[simp] theorem tape.move_left_right {Γ} [inhabited Γ] (T : tape Γ) :
(T.move dir.left).move dir.right = T :=
by cases T; simp [tape.move]
@[simp] theorem tape.move_right_left {Γ} [inhabited Γ] (T : tape Γ) :
(T.move dir.right).move dir.left = T :=
by cases T; simp [tape.move]
/-- Construct a tape from a left side and an inclusive right side. -/
def tape.mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : tape Γ := ⟨R.head, L, R.tail⟩
@[simp] theorem tape.mk'_left {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).left = L := rfl
@[simp] theorem tape.mk'_head {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).head = R.head := rfl
@[simp] theorem tape.mk'_right {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).right = R.tail := rfl
@[simp] theorem tape.mk'_right₀ {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).right₀ = R := list_blank.cons_head_tail _
@[simp] theorem tape.mk'_left_right₀ {Γ} [inhabited Γ] (T : tape Γ) :
tape.mk' T.left T.right₀ = T :=
by cases T; simp only [tape.right₀, tape.mk',
list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self]
theorem tape.exists_mk' {Γ} [inhabited Γ] (T : tape Γ) :
∃ L R, T = tape.mk' L R := ⟨_, _, (tape.mk'_left_right₀ _).symm⟩
@[simp] theorem tape.move_left_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).move dir.left = tape.mk' L.tail (R.cons L.head) :=
by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true,
list_blank.cons_head_tail, and_self, list_blank.tail_cons]
@[simp] theorem tape.move_right_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) :
(tape.mk' L R).move dir.right = tape.mk' (L.cons R.head) R.tail :=
by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true,
list_blank.cons_head_tail, and_self, list_blank.tail_cons]
/-- Construct a tape from a left side and an inclusive right side. -/
def tape.mk₂ {Γ} [inhabited Γ] (L R : list Γ) : tape Γ :=
tape.mk' (list_blank.mk L) (list_blank.mk R)
/-- Construct a tape from a list, with the head of the list at the TM head and the rest going
to the right. -/
def tape.mk₁ {Γ} [inhabited Γ] (l : list Γ) : tape Γ :=
tape.mk₂ [] l
/-- The `nth` function of a tape is integer-valued, with index `0` being the head, negative indexes
on the left and positive indexes on the right. (Picture a number line.) -/
def tape.nth {Γ} [inhabited Γ] (T : tape Γ) : ℤ → Γ
| 0 := T.head
| (n+1:ℕ) := T.right.nth n
| -[1+ n] := T.left.nth n
@[simp] theorem tape.nth_zero {Γ} [inhabited Γ] (T : tape Γ) : T.nth 0 = T.1 := rfl
theorem tape.right₀_nth {Γ} [inhabited Γ] (T : tape Γ) (n : ℕ) : T.right₀.nth n = T.nth n :=
by cases n; simp only [tape.nth, tape.right₀, int.coe_nat_zero,
list_blank.nth_zero, list_blank.nth_succ, list_blank.head_cons, list_blank.tail_cons]
@[simp] theorem tape.mk'_nth_nat {Γ} [inhabited Γ] (L R : list_blank Γ) (n : ℕ) :
(tape.mk' L R).nth n = R.nth n :=
by rw [← tape.right₀_nth, tape.mk'_right₀]
@[simp] theorem tape.move_left_nth {Γ} [inhabited Γ] :
∀ (T : tape Γ) (i : ℤ), (T.move dir.left).nth i = T.nth (i-1)
| ⟨a, L, R⟩ -[1+ n] := (list_blank.nth_succ _ _).symm
| ⟨a, L, R⟩ 0 := (list_blank.nth_zero _).symm
| ⟨a, L, R⟩ 1 := (list_blank.nth_zero _).trans (list_blank.head_cons _ _)
| ⟨a, L, R⟩ ((n+1:ℕ)+1) := begin
rw add_sub_cancel,
change (R.cons a).nth (n+1) = R.nth n,
rw [list_blank.nth_succ, list_blank.tail_cons]
end
@[simp] theorem tape.move_right_nth {Γ} [inhabited Γ] (T : tape Γ) (i : ℤ) :
(T.move dir.right).nth i = T.nth (i+1) :=
by conv {to_rhs, rw ← T.move_right_left}; rw [tape.move_left_nth, add_sub_cancel]
@[simp] theorem tape.move_right_n_head {Γ} [inhabited Γ] (T : tape Γ) (i : ℕ) :
((tape.move dir.right)^[i] T).head = T.nth i :=
by induction i generalizing T; [refl, simp only [*,
tape.move_right_nth, int.coe_nat_succ, iterate_succ]]
/-- Replace the current value of the head on the tape. -/
def tape.write {Γ} [inhabited Γ] (b : Γ) (T : tape Γ) : tape Γ := {head := b, ..T}
@[simp] theorem tape.write_self {Γ} [inhabited Γ] : ∀ (T : tape Γ), T.write T.1 = T :=
by rintro ⟨⟩; refl
@[simp] theorem tape.write_nth {Γ} [inhabited Γ] (b : Γ) :
∀ (T : tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i
| ⟨a, L, R⟩ 0 := rfl
| ⟨a, L, R⟩ (n+1:ℕ) := rfl
| ⟨a, L, R⟩ -[1+ n] := rfl
@[simp] theorem tape.write_mk' {Γ} [inhabited Γ] (a b : Γ) (L R : list_blank Γ) :
(tape.mk' L (R.cons a)).write b = tape.mk' L (R.cons b) :=
by simp only [tape.write, tape.mk', list_blank.head_cons, list_blank.tail_cons,
eq_self_iff_true, and_self]
/-- Apply a pointed map to a tape to change the alphabet. -/
def tape.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) : tape Γ' :=
⟨f T.1, T.2.map f, T.3.map f⟩
@[simp] theorem tape.map_fst {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') : ∀ (T : tape Γ), (T.map f).1 = f T.1 :=
by rintro ⟨⟩; refl
@[simp] theorem tape.map_write {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (b : Γ) :
∀ (T : tape Γ), (T.write b).map f = (T.map f).write (f b) :=
by rintro ⟨⟩; refl
@[simp] theorem tape.write_move_right_n {Γ} [inhabited Γ] (f : Γ → Γ) (L R : list_blank Γ) (n : ℕ) :
((tape.move dir.right)^[n] (tape.mk' L R)).write (f (R.nth n)) =
((tape.move dir.right)^[n] (tape.mk' L (R.modify_nth f n))) :=
begin
induction n with n IH generalizing L R,
{ simp only [list_blank.nth_zero, list_blank.modify_nth, iterate_zero_apply],
rw [← tape.write_mk', list_blank.cons_head_tail] },
simp only [list_blank.head_cons, list_blank.nth_succ, list_blank.modify_nth,
tape.move_right_mk', list_blank.tail_cons, iterate_succ_apply, IH]
end
theorem tape.map_move {Γ Γ'} [inhabited Γ] [inhabited Γ']
(f : pointed_map Γ Γ') (T : tape Γ) (d) : (T.move d).map f = (T.map f).move d :=
by cases T; cases d; simp only [tape.move, tape.map,
list_blank.head_map, eq_self_iff_true, list_blank.map_cons, and_self, list_blank.tail_map]
theorem tape.map_mk' {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ')
(L R : list_blank Γ) : (tape.mk' L R).map f = tape.mk' (L.map f) (R.map f) :=
by simp only [tape.mk', tape.map, list_blank.head_map,
eq_self_iff_true, and_self, list_blank.tail_map]
theorem tape.map_mk₂ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ')
(L R : list Γ) : (tape.mk₂ L R).map f = tape.mk₂ (L.map f) (R.map f) :=
by simp only [tape.mk₂, tape.map_mk', list_blank.map_mk]
theorem tape.map_mk₁ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ')
(l : list Γ) : (tape.mk₁ l).map f = tape.mk₁ (l.map f) := tape.map_mk₂ _ _ _
/-- Run a state transition function `σ → option σ` "to completion". The return value is the last
state returned before a `none` result. If the state transition function always returns `some`,
then the computation diverges, returning `part.none`. -/
def eval {σ} (f : σ → option σ) : σ → part σ :=
pfun.fix (λ s, part.some $ (f s).elim (sum.inl s) sum.inr)
/-- The reflexive transitive closure of a state transition function. `reaches f a b` means
there is a finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`.
This relation permits zero steps of the state transition function. -/
def reaches {σ} (f : σ → option σ) : σ → σ → Prop :=
refl_trans_gen (λ a b, b ∈ f a)
/-- The transitive closure of a state transition function. `reaches₁ f a b` means there is a
nonempty finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`.
This relation does not permit zero steps of the state transition function. -/
def reaches₁ {σ} (f : σ → option σ) : σ → σ → Prop :=
trans_gen (λ a b, b ∈ f a)
theorem reaches₁_eq {σ} {f : σ → option σ} {a b c}
(h : f a = f b) : reaches₁ f a c ↔ reaches₁ f b c :=
trans_gen.head'_iff.trans (trans_gen.head'_iff.trans $ by rw h).symm
theorem reaches_total {σ} {f : σ → option σ}
{a b c} (hab : reaches f a b) (hac : reaches f a c) :
reaches f b c ∨ reaches f c b :=
refl_trans_gen.total_of_right_unique (λ _ _ _, option.mem_unique) hab hac
theorem reaches₁_fwd {σ} {f : σ → option σ}
{a b c} (h₁ : reaches₁ f a c) (h₂ : b ∈ f a) : reaches f b c :=
begin
rcases trans_gen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩,
cases option.mem_unique hab h₂, exact hbc
end
/-- A variation on `reaches`. `reaches₀ f a b` holds if whenever `reaches₁ f b c` then
`reaches₁ f a c`. This is a weaker property than `reaches` and is useful for replacing states with
equivalent states without taking a step. -/
def reaches₀ {σ} (f : σ → option σ) (a b : σ) : Prop :=
∀ c, reaches₁ f b c → reaches₁ f a c
theorem reaches₀.trans {σ} {f : σ → option σ} {a b c : σ}
(h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c
| d h₃ := h₁ _ (h₂ _ h₃)
@[refl] theorem reaches₀.refl {σ} {f : σ → option σ} (a : σ) : reaches₀ f a a
| b h := h
theorem reaches₀.single {σ} {f : σ → option σ} {a b : σ}
(h : b ∈ f a) : reaches₀ f a b
| c h₂ := h₂.head h
theorem reaches₀.head {σ} {f : σ → option σ} {a b c : σ}
(h : b ∈ f a) (h₂ : reaches₀ f b c) : reaches₀ f a c :=
(reaches₀.single h).trans h₂
theorem reaches₀.tail {σ} {f : σ → option σ} {a b c : σ}
(h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c :=
h₁.trans (reaches₀.single h)
theorem reaches₀_eq {σ} {f : σ → option σ} {a b}
(e : f a = f b) : reaches₀ f a b
| d h := (reaches₁_eq e).2 h
theorem reaches₁.to₀ {σ} {f : σ → option σ} {a b : σ}
(h : reaches₁ f a b) : reaches₀ f a b
| c h₂ := h.trans h₂
theorem reaches.to₀ {σ} {f : σ → option σ} {a b : σ}
(h : reaches f a b) : reaches₀ f a b
| c h₂ := h₂.trans_right h
theorem reaches₀.tail' {σ} {f : σ → option σ} {a b c : σ}
(h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c :=
h _ (trans_gen.single h₂)
/-- (co-)Induction principle for `eval`. If a property `C` holds of any point `a` evaluating to `b`
which is either terminal (meaning `a = b`) or where the next point also satisfies `C`, then it
holds of any point where `eval f a` evaluates to `b`. This formalizes the notion that if
`eval f a` evaluates to `b` then it reaches terminal state `b` in finitely many steps. -/
@[elab_as_eliminator] def eval_induction {σ}
{f : σ → option σ} {b : σ} {C : σ → Sort*} {a : σ} (h : b ∈ eval f a)
(H : ∀ a, b ∈ eval f a →
(∀ a', b ∈ eval f a' → f a = some a' → C a') → C a) : C a :=
pfun.fix_induction h (λ a' ha' h', H _ ha' $ λ b' hb' e, h' _ hb' $
part.mem_some_iff.2 $ by rw e; refl)
theorem mem_eval {σ} {f : σ → option σ} {a b} :
b ∈ eval f a ↔ reaches f a b ∧ f b = none :=
⟨λ h, begin
refine eval_induction h (λ a h IH, _),
cases e : f a with a',
{ rw part.mem_unique h (pfun.mem_fix_iff.2 $ or.inl $
part.mem_some_iff.2 $ by rw e; refl),
exact ⟨refl_trans_gen.refl, e⟩ },
{ rcases pfun.mem_fix_iff.1 h with h | ⟨_, h, h'⟩;
rw e at h; cases part.mem_some_iff.1 h,
cases IH a' h' (by rwa e) with h₁ h₂,
exact ⟨refl_trans_gen.head e h₁, h₂⟩ }
end, λ ⟨h₁, h₂⟩, begin
refine refl_trans_gen.head_induction_on h₁ _ (λ a a' h _ IH, _),
{ refine pfun.mem_fix_iff.2 (or.inl _),
rw h₂, apply part.mem_some },
{ refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH⟩),
rw show f a = _, from h,
apply part.mem_some }
end⟩
theorem eval_maximal₁ {σ} {f : σ → option σ} {a b}
(h : b ∈ eval f a) (c) : ¬ reaches₁ f b c | bc :=
let ⟨ab, b0⟩ := mem_eval.1 h, ⟨b', h', _⟩ := trans_gen.head'_iff.1 bc in
by cases b0.symm.trans h'
theorem eval_maximal {σ} {f : σ → option σ} {a b}
(h : b ∈ eval f a) {c} : reaches f b c ↔ c = b :=
let ⟨ab, b0⟩ := mem_eval.1 h in
refl_trans_gen_iff_eq $ λ b' h', by cases b0.symm.trans h'
theorem reaches_eval {σ} {f : σ → option σ} {a b}
(ab : reaches f a b) : eval f a = eval f b :=
part.ext $ λ c,
⟨λ h, let ⟨ac, c0⟩ := mem_eval.1 h in
mem_eval.2 ⟨(or_iff_left_of_imp $ by exact
λ cb, (eval_maximal h).1 cb ▸ refl_trans_gen.refl).1
(reaches_total ab ac), c0⟩,
λ h, let ⟨bc, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨ab.trans bc, c0⟩,⟩
/-- Given a relation `tr : σ₁ → σ₂ → Prop` between state spaces, and state transition functions
`f₁ : σ₁ → option σ₁` and `f₂ : σ₂ → option σ₂`, `respects f₁ f₂ tr` means that if `tr a₁ a₂` holds
initially and `f₁` takes a step to `a₂` then `f₂` will take one or more steps before reaching a
state `b₂` satisfying `tr a₂ b₂`, and if `f₁ a₁` terminates then `f₂ a₂` also terminates.
Such a relation `tr` is also known as a refinement. -/
def respects {σ₁ σ₂}
(f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂ → Prop) :=
∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with
| some b₁ := ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂
| none := f₂ a₂ = none
end : Prop)
theorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches₁ f₁ a₁ b₁) :
∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ :=
begin
induction ab with c₁ ac c₁ d₁ ac cd IH,
{ have := H aa,
rwa (show f₁ a₁ = _, from ac) at this },
{ rcases IH with ⟨c₂, cc, ac₂⟩,
have := H cc,
rw (show f₁ c₁ = _, from cd) at this,
rcases this with ⟨d₂, dd, cd₂⟩,
exact ⟨_, dd, ac₂.trans cd₂⟩ }
end
theorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches f₁ a₁ b₁) :
∃ b₂, tr b₁ b₂ ∧ reaches f₂ a₂ b₂ :=
begin
rcases refl_trans_gen_iff_eq_or_trans_gen.1 ab with rfl | ab,
{ exact ⟨_, aa, refl_trans_gen.refl⟩ },
{ exact let ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab in
⟨b₂, bb, h.to_refl⟩ }
end
theorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₂} (ab : reaches f₂ a₂ b₂) :
∃ c₁ c₂, reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ :=
begin
induction ab with c₂ d₂ ac cd IH,
{ exact ⟨_, _, refl_trans_gen.refl, aa, refl_trans_gen.refl⟩ },
{ rcases IH with ⟨e₁, e₂, ce, ee, ae⟩,
rcases refl_trans_gen.cases_head ce with rfl | ⟨d', cd', de⟩,
{ have := H ee, revert this,
cases eg : f₁ e₁ with g₁; simp only [respects, and_imp, exists_imp_distrib],
{ intro c0, cases cd.symm.trans c0 },
{ intros g₂ gg cg,
rcases trans_gen.head'_iff.1 cg with ⟨d', cd', dg⟩,
cases option.mem_unique cd cd',
exact ⟨_, _, dg, gg, ae.tail eg⟩ } },
{ cases option.mem_unique cd cd',
exact ⟨_, _, de, ee, ae⟩ } }
end
theorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ b₁ a₂} (aa : tr a₁ a₂)
(ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ :=
begin
cases mem_eval.1 ab with ab b0,
rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩,
refine ⟨_, bb, mem_eval.2 ⟨ab, _⟩⟩,
have := H bb, rwa b0 at this
end
theorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ b₂ a₂} (aa : tr a₁ a₂)
(ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ :=
begin
cases mem_eval.1 ab with ab b0,
rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩,
cases (refl_trans_gen_iff_eq
(by exact option.eq_none_iff_forall_not_mem.1 b0)).1 bc,
refine ⟨_, cc, mem_eval.2 ⟨ac, _⟩⟩,
have := H cc, cases f₁ c₁ with d₁, {refl},
rcases this with ⟨d₂, dd, bd⟩,
rcases trans_gen.head'_iff.1 bd with ⟨e, h, _⟩,
cases b0.symm.trans h
end
theorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}
(H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) :
(eval f₂ a₂).dom ↔ (eval f₁ a₁).dom :=
⟨λ h, let ⟨b₂, tr, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩ in h,
λ h, let ⟨b₂, tr, h, _⟩ := tr_eval H aa ⟨h, rfl⟩ in h⟩
/-- A simpler version of `respects` when the state transition relation `tr` is a function. -/
def frespects {σ₁ σ₂} (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : option σ₁ → Prop
| (some b₁) := reaches₁ f₂ a₂ (tr b₁)
| none := f₂ a₂ = none
theorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → option σ₂} {tr : σ₁ → σ₂} {a₂ b₂}
(h : f₂ a₂ = f₂ b₂) : ∀ {b₁}, frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁
| (some b₁) := reaches₁_eq h
| none := by unfold frespects; rw h
theorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} :
respects f₁ f₂ (λ a b, tr a = b) ↔ ∀ ⦃a₁⦄, frespects f₂ tr (tr a₁) (f₁ a₁) :=
forall_congr $ λ a₁, by cases f₁ a₁; simp only [frespects, respects, exists_eq_left', forall_eq']
theorem tr_eval' {σ₁ σ₂}
(f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂)
(H : respects f₁ f₂ (λ a b, tr a = b))
(a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ :=
part.ext $ λ b₂,
⟨λ h, let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h in
(part.mem_map_iff _).2 ⟨b₁, hb, bb⟩,
λ h, begin
rcases (part.mem_map_iff _).1 h with ⟨b₁, ab, bb⟩,
rcases tr_eval H rfl ab with ⟨_, rfl, h⟩,
rwa bb at h
end⟩
/-!
## The TM0 model
A TM0 turing machine is essentially a Post-Turing machine, adapted for type theory.
A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function
`Λ → Γ → option (Λ × stmt)`, where a `stmt` can be either `move left`, `move right` or `write a`
for `a : Γ`. The machine works over a "tape", a doubly-infinite sequence of elements of `Γ`, and
an instantaneous configuration, `cfg`, is a label `q : Λ` indicating the current internal state of
the machine, and a `tape Γ` (which is essentially `ℤ →₀ Γ`). The evolution is described by the
`step` function:
* If `M q T.head = none`, then the machine halts.
* If `M q T.head = some (q', s)`, then the machine performs action `s : stmt` and then transitions
to state `q'`.
The initial state takes a `list Γ` and produces a `tape Γ` where the head of the list is the head
of the tape and the rest of the list extends to the right, with the left side all blank. The final
state takes the entire right side of the tape right or equal to the current position of the
machine. (This is actually a `list_blank Γ`, not a `list Γ`, because we don't know, at this level
of generality, where the output ends. If equality to `default Γ` is decidable we can trim the list
to remove the infinite tail of blanks.)
-/
namespace TM0
section
parameters (Γ : Type*) [inhabited Γ] -- type of tape symbols
parameters (Λ : Type*) [inhabited Λ] -- type of "labels" or TM states
/-- A Turing machine "statement" is just a command to either move
left or right, or write a symbol on the tape. -/
inductive stmt
| move : dir → stmt
| write : Γ → stmt
instance stmt.inhabited : inhabited stmt := ⟨stmt.write (default _)⟩
/-- A Post-Turing machine with symbol type `Γ` and label type `Λ`
is a function which, given the current state `q : Λ` and
the tape head `a : Γ`, either halts (returns `none`) or returns
a new state `q' : Λ` and a `stmt` describing what to do,
either a move left or right, or a write command.
Both `Λ` and `Γ` are required to be inhabited; the default value
for `Γ` is the "blank" tape value, and the default value of `Λ` is
the initial state. -/
@[nolint unused_arguments] -- [inhabited Λ]: this is a deliberate addition, see comment
def machine := Λ → Γ → option (Λ × stmt)
instance machine.inhabited : inhabited machine := by unfold machine; apply_instance
/-- The configuration state of a Turing machine during operation
consists of a label (machine state), and a tape, represented in
the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R`
with the machine currently reading the `a`. The lists are
automatically extended with blanks as the machine moves around. -/
structure cfg :=
(q : Λ)
(tape : tape Γ)
instance cfg.inhabited : inhabited cfg := ⟨⟨default _, default _⟩⟩
parameters {Γ Λ}
/-- Execution semantics of the Turing machine. -/
def step (M : machine) : cfg → option cfg
| ⟨q, T⟩ := (M q T.1).map (λ ⟨q', a⟩, ⟨q',
match a with
| stmt.move d := T.move d
| stmt.write a := T.write a
end⟩)
/-- The statement `reaches M s₁ s₂` means that `s₂` is obtained
starting from `s₁` after a finite number of steps from `s₂`. -/
def reaches (M : machine) : cfg → cfg → Prop :=
refl_trans_gen (λ a b, b ∈ step M a)
/-- The initial configuration. -/
def init (l : list Γ) : cfg :=
⟨default Λ, tape.mk₁ l⟩
/-- Evaluate a Turing machine on initial input to a final state,
if it terminates. -/
def eval (M : machine) (l : list Γ) : part (list_blank Γ) :=
(eval (step M) (init l)).map (λ c, c.tape.right₀)
/-- The raw definition of a Turing machine does not require that
`Γ` and `Λ` are finite, and in practice we will be interested
in the infinite `Λ` case. We recover instead a notion of
"effectively finite" Turing machines, which only make use of a
finite subset of their states. We say that a set `S ⊆ Λ`
supports a Turing machine `M` if `S` is closed under the
transition function and contains the initial state. -/
def supports (M : machine) (S : set Λ) :=
default Λ ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S
theorem step_supports (M : machine) {S}
(ss : supports M S) : ∀ {c c' : cfg},
c' ∈ step M c → c.q ∈ S → c'.q ∈ S
| ⟨q, T⟩ c' h₁ h₂ := begin
rcases option.map_eq_some'.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩,
exact ss.2 h h₂,
end
theorem univ_supports (M : machine) : supports M set.univ :=
⟨trivial, λ q a q' s h₁ h₂, trivial⟩
end
section
variables {Γ : Type*} [inhabited Γ]
variables {Γ' : Type*} [inhabited Γ']
variables {Λ : Type*} [inhabited Λ]
variables {Λ' : Type*} [inhabited Λ']
/-- Map a TM statement across a function. This does nothing to move statements and maps the write
values. -/
def stmt.map (f : pointed_map Γ Γ') : stmt Γ → stmt Γ'
| (stmt.move d) := stmt.move d
| (stmt.write a) := stmt.write (f a)
/-- Map a configuration across a function, given `f : Γ → Γ'` a map of the alphabets and
`g : Λ → Λ'` a map of the machine states. -/
def cfg.map (f : pointed_map Γ Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ'
| ⟨q, T⟩ := ⟨g q, T.map f⟩
variables (M : machine Γ Λ)
(f₁ : pointed_map Γ Γ') (f₂ : pointed_map Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ)
/-- Because the state transition function uses the alphabet and machine states in both the input
and output, to map a machine from one alphabet and machine state space to another we need functions
in both directions, essentially an `equiv` without the laws. -/
def machine.map : machine Γ' Λ'
| q l := (M (g₂ q) (f₂ l)).map (prod.map g₁ (stmt.map f₁))
theorem machine.map_step {S : set Λ}
(f₂₁ : function.right_inverse f₁ f₂)
(g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) :
∀ c : cfg Γ Λ, c.q ∈ S →
(step M c).map (cfg.map f₁ g₁) =
step (M.map f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c)
| ⟨q, T⟩ h := begin
unfold step machine.map cfg.map,
simp only [turing.tape.map_fst, g₂₁ q h, f₂₁ _],
rcases M q T.1 with _|⟨q', d|a⟩, {refl},
{ simp only [step, cfg.map, option.map_some', tape.map_move f₁], refl },
{ simp only [step, cfg.map, option.map_some', tape.map_write], refl }
end
theorem map_init (g₁ : pointed_map Λ Λ') (l : list Γ) :
(init l).map f₁ g₁ = init (l.map f₁) :=
congr (congr_arg cfg.mk g₁.map_pt) (tape.map_mk₁ _ _)
theorem machine.map_respects
(g₁ : pointed_map Λ Λ') (g₂ : Λ' → Λ)
{S} (ss : supports M S)
(f₂₁ : function.right_inverse f₁ f₂)
(g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) :
respects (step M) (step (M.map f₁ f₂ g₁ g₂))
(λ a b, a.q ∈ S ∧ cfg.map f₁ g₁ a = b)
| c _ ⟨cs, rfl⟩ := begin
cases e : step M c with c'; unfold respects,
{ rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], refl },
{ refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, trans_gen.single _⟩,
rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], exact rfl }
end
end
end TM0
/-!
## The TM1 model
The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of
Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables
that may be accessed and updated at any time.
A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which
is a `stmt`. Most of the regular commands are allowed to use the current value `a` of the local
variables and the value `T.head` on the tape to calculate what to write or how to change local
state, but the statements themselves have a fixed structure. The `stmt`s can be as follows:
* `move d q`: move left or right, and then do `q`
* `write (f : Γ → σ → Γ) q`: write `f a T.head` to the tape, then do `q`
* `load (f : Γ → σ → σ) q`: change the internal state to `f a T.head`
* `branch (f : Γ → σ → bool) qtrue qfalse`: If `f a T.head` is true, do `qtrue`, else `qfalse`
* `goto (f : Γ → σ → Λ)`: Go to label `f a T.head`
* `halt`: Transition to the halting state, which halts on the following step
Note that here most statements do not have labels; `goto` commands can only go to a new function.
Only the `goto` and `halt` statements actually take a step; the rest is done by recursion on
statements and so take 0 steps. (There is a uniform bound on many statements can be executed before
the next `goto`, so this is an `O(1)` speedup with the constant depending on the machine.)
The `halt` command has a one step stutter before actually halting so that any changes made before
the halt have a chance to be "committed", since the `eval` relation uses the final configuration
before the halt as the output, and `move` and `write` etc. take 0 steps in this model.
-/
namespace TM1
section
parameters (Γ : Type*) [inhabited Γ] -- Type of tape symbols
parameters (Λ : Type*) -- Type of function labels
parameters (σ : Type*) -- Type of variable settings
/-- The TM1 model is a simplification and extension of TM0
(Post-Turing model) in the direction of Wang B-machines. The machine's
internal state is extended with a (finite) store `σ` of variables
that may be accessed and updated at any time.
A machine is given by a `Λ` indexed set of procedures or functions.
Each function has a body which is a `stmt`, which can either be a
`move` or `write` command, a `branch` (if statement based on the
current tape value), a `load` (set the variable value),
a `goto` (call another function), or `halt`. Note that here
most statements do not have labels; `goto` commands can only
go to a new function. All commands have access to the variable value
and current tape value. -/
inductive stmt
| move : dir → stmt → stmt
| write : (Γ → σ → Γ) → stmt → stmt
| load : (Γ → σ → σ) → stmt → stmt
| branch : (Γ → σ → bool) → stmt → stmt → stmt
| goto : (Γ → σ → Λ) → stmt
| halt : stmt
open stmt
instance stmt.inhabited : inhabited stmt := ⟨halt⟩
/-- The configuration of a TM1 machine is given by the currently
evaluating statement, the variable store value, and the tape. -/
structure cfg :=
(l : option Λ)
(var : σ)
(tape : tape Γ)
instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩
parameters {Γ Λ σ}
/-- The semantics of TM1 evaluation. -/
def step_aux : stmt → σ → tape Γ → cfg
| (move d q) v T := step_aux q v (T.move d)
| (write a q) v T := step_aux q v (T.write (a T.1 v))
| (load s q) v T := step_aux q (s T.1 v) T
| (branch p q₁ q₂) v T := cond (p T.1 v) (step_aux q₁ v T) (step_aux q₂ v T)
| (goto l) v T := ⟨some (l T.1 v), v, T⟩
| halt v T := ⟨none, v, T⟩
/-- The state transition function. -/
def step (M : Λ → stmt) : cfg → option cfg
| ⟨none, v, T⟩ := none
| ⟨some l, v, T⟩ := some (step_aux (M l) v T)
/-- A set `S` of labels supports the statement `q` if all the `goto`
statements in `q` refer only to other functions in `S`. -/
def supports_stmt (S : finset Λ) : stmt → Prop
| (move d q) := supports_stmt q
| (write a q) := supports_stmt q
| (load s q) := supports_stmt q
| (branch p q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂
| (goto l) := ∀ a v, l a v ∈ S
| halt := true
open_locale classical
/-- The subterm closure of a statement. -/
noncomputable def stmts₁ : stmt → finset stmt
| Q@(move d q) := insert Q (stmts₁ q)
| Q@(write a q) := insert Q (stmts₁ q)
| Q@(load s q) := insert Q (stmts₁ q)
| Q@(branch p q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂)
| Q := {Q}
theorem stmts₁_self {q} : q ∈ stmts₁ q :=
by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self]
theorem stmts₁_trans {q₁ q₂} :
q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ :=
begin
intros h₁₂ q₀ h₀₁,
induction q₂ with _ q IH _ q IH _ q IH;
simp only [stmts₁] at h₁₂ ⊢;
simp only [finset.mem_insert, finset.mem_union, finset.mem_singleton] at h₁₂,
iterate 3 {
rcases h₁₂ with rfl | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (IH h₁₂) } },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
rcases h₁₂ with rfl | h₁₂ | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (finset.mem_union_left _ $ IH₁ h₁₂) },
{ exact finset.mem_insert_of_mem (finset.mem_union_right _ $ IH₂ h₁₂) } },
case TM1.stmt.goto : l {
subst h₁₂, exact h₀₁ },
case TM1.stmt.halt {
subst h₁₂, exact h₀₁ }
end
theorem stmts₁_supports_stmt_mono {S q₁ q₂}
(h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ :=
begin
induction q₂ with _ q IH _ q IH _ q IH;
simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union,
finset.mem_singleton] at h hs,
iterate 3 { rcases h with rfl | h; [exact hs, exact IH h hs] },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] },
case TM1.stmt.goto : l { subst h, exact hs },
case TM1.stmt.halt { subst h, trivial }
end
/-- The set of all statements in a turing machine, plus one extra value `none` representing the
halt state. This is used in the TM1 to TM0 reduction. -/
noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) :=
(S.bUnion (λ q, stmts₁ (M q))).insert_none
theorem stmts_trans {M : Λ → stmt} {S q₁ q₂}
(h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩
variable [inhabited Λ]
/-- A set `S` of labels supports machine `M` if all the `goto`
statements in the functions in `S` refer only to other functions
in `S`. -/
def supports (M : Λ → stmt) (S : finset Λ) :=
default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q)
theorem stmts_supports_stmt {M : Λ → stmt} {S q}
(ss : supports M S) : some q ∈ stmts M S → supports_stmt S q :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls)
theorem step_supports (M : Λ → stmt) {S}
(ss : supports M S) : ∀ {c c' : cfg},
c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none
| ⟨some l₁, v, T⟩ c' h₁ h₂ := begin
replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂),
simp only [step, option.mem_def] at h₁, subst c',
revert h₂, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T;
intro hs,
iterate 3 { exact IH _ _ hs },
case TM1.stmt.branch : p q₁' q₂' IH₁ IH₂ {
unfold step_aux, cases p T.1 v,
{ exact IH₂ _ _ hs.2 },
{ exact IH₁ _ _ hs.1 } },
case TM1.stmt.goto { exact finset.some_mem_insert_none.2 (hs _ _) },
case TM1.stmt.halt { apply multiset.mem_cons_self }
end
variable [inhabited σ]
/-- The initial state, given a finite input that is placed on the tape starting at the TM head and
going to the right. -/
def init (l : list Γ) : cfg :=
⟨some (default _), default _, tape.mk₁ l⟩
/-- Evaluate a TM to completion, resulting in an output list on the tape (with an indeterminate
number of blanks on the end). -/
def eval (M : Λ → stmt) (l : list Γ) : part (list_blank Γ) :=
(eval (step M) (init l)).map (λ c, c.tape.right₀)
end
end TM1
/-!
## TM1 emulator in TM0
To prove that TM1 computable functions are TM0 computable, we need to reduce each TM1 program to a
TM0 program. So suppose a TM1 program is given. We take the following:
* The alphabet `Γ` is the same for both TM1 and TM0
* The set of states `Λ'` is defined to be `option stmt₁ × σ`, that is, a TM1 statement or `none`
representing halt, and the possible settings of the internal variables.
Note that this is an infinite set, because `stmt₁` is infinite. This is okay because we assume
that from the initial TM1 state, only finitely many other labels are reachable, and there are
only finitely many statements that appear in all of these functions.
Even though `stmt₁` contains a statement called `halt`, we must separate it from `none`
(`some halt` steps to `none` and `none` actually halts) because there is a one step stutter in the
TM1 semantics.
-/
namespace TM1to0
section
parameters {Γ : Type*} [inhabited Γ]
parameters {Λ : Type*} [inhabited Λ]
parameters {σ : Type*} [inhabited σ]
local notation `stmt₁` := TM1.stmt Γ Λ σ
local notation `cfg₁` := TM1.cfg Γ Λ σ
local notation `stmt₀` := TM0.stmt Γ
parameters (M : Λ → stmt₁)
include M
/-- The base machine state space is a pair of an `option stmt₁` representing the current program
to be executed, or `none` for the halt state, and a `σ` which is the local state (stored in the TM,
not the tape). Because there are an infinite number of programs, this state space is infinite, but
for a finitely supported TM1 machine and a finite type `σ`, only finitely many of these states are
reachable. -/
@[nolint unused_arguments] -- [inhabited Λ] [inhabited σ] (M : Λ → stmt₁): We need the M assumption
-- because of the inhabited instance, but we could avoid the inhabited instances on Λ and σ here.
-- But they are parameters so we cannot easily skip them for just this definition.
def Λ' := option stmt₁ × σ
instance : inhabited Λ' := ⟨(some (M (default _)), default _)⟩
open TM0.stmt
/-- The core TM1 → TM0 translation function. Here `s` is the current value on the tape, and the
`stmt₁` is the TM1 statement to translate, with local state `v : σ`. We evaluate all regular
instructions recursively until we reach either a `move` or `write` command, or a `goto`; in the
latter case we emit a dummy `write s` step and transition to the new target location. -/
def tr_aux (s : Γ) : stmt₁ → σ → Λ' × stmt₀
| (TM1.stmt.move d q) v := ((some q, v), move d)
| (TM1.stmt.write a q) v := ((some q, v), write (a s v))
| (TM1.stmt.load a q) v := tr_aux q (a s v)
| (TM1.stmt.branch p q₁ q₂) v := cond (p s v) (tr_aux q₁ v) (tr_aux q₂ v)
| (TM1.stmt.goto l) v := ((some (M (l s v)), v), write s)
| TM1.stmt.halt v := ((none, v), write s)
local notation `cfg₀` := TM0.cfg Γ Λ'
/-- The translated TM0 machine (given the TM1 machine input). -/
def tr : TM0.machine Γ Λ'
| (none, v) s := none
| (some q, v) s := some (tr_aux s q v)
/-- Translate configurations from TM1 to TM0. -/
def tr_cfg : cfg₁ → cfg₀
| ⟨l, v, T⟩ := ⟨(l.map M, v), T⟩
theorem tr_respects : respects (TM1.step M) (TM0.step tr)
(λ c₁ c₂, tr_cfg c₁ = c₂) :=
fun_respects.2 $ λ ⟨l₁, v, T⟩, begin
cases l₁ with l₁, {exact rfl},
unfold tr_cfg TM1.step frespects option.map function.comp option.bind,
induction M l₁ with _ q IH _ q IH _ q IH generalizing v T,
case TM1.stmt.move : d q IH { exact trans_gen.head rfl (IH _ _) },
case TM1.stmt.write : a q IH { exact trans_gen.head rfl (IH _ _) },
case TM1.stmt.load : a q IH { exact (reaches₁_eq (by refl)).2 (IH _ _) },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
unfold TM1.step_aux, cases e : p T.1 v,
{ exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₂ _ _) },
{ exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₁ _ _) } },
iterate 2 {
exact trans_gen.single (congr_arg some
(congr (congr_arg TM0.cfg.mk rfl) (tape.write_self T))) }
end
theorem tr_eval (l : list Γ) : TM0.eval tr l = TM1.eval M l :=
(congr_arg _ (tr_eval' _ _ _ tr_respects ⟨some _, _, _⟩)).trans begin
rw [part.map_eq_map, part.map_map, TM1.eval],
congr' with ⟨⟩, refl
end
variables [fintype σ]
/-- Given a finite set of accessible `Λ` machine states, there is a finite set of accessible
machine states in the target (even though the type `Λ'` is infinite). -/
noncomputable def tr_stmts (S : finset Λ) : finset Λ' :=
(TM1.stmts M S).product finset.univ
open_locale classical
local attribute [simp] TM1.stmts₁_self
theorem tr_supports {S : finset Λ} (ss : TM1.supports M S) :
TM0.supports tr (↑(tr_stmts S)) :=
⟨finset.mem_product.2 ⟨finset.some_mem_insert_none.2
(finset.mem_bUnion.2 ⟨_, ss.1, TM1.stmts₁_self⟩),
finset.mem_univ _⟩,
λ q a q' s h₁ h₂, begin
rcases q with ⟨_|q, v⟩, {cases h₁},
cases q' with q' v', simp only [tr_stmts, finset.mem_coe,
finset.mem_product, finset.mem_univ, and_true] at h₂ ⊢,
cases q', {exact multiset.mem_cons_self _ _},
simp only [tr, option.mem_def] at h₁,
have := TM1.stmts_supports_stmt ss h₂,
revert this, induction q generalizing v; intro hs,
case TM1.stmt.move : d q {
cases h₁, refine TM1.stmts_trans _ h₂,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem TM1.stmts₁_self },
case TM1.stmt.write : b q {
cases h₁, refine TM1.stmts_trans _ h₂,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem TM1.stmts₁_self },
case TM1.stmt.load : b q IH {
refine IH (TM1.stmts_trans _ h₂) _ h₁ hs,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem TM1.stmts₁_self },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
change cond (p a v) _ _ = ((some q', v'), s) at h₁,
cases p a v,
{ refine IH₂ (TM1.stmts_trans _ h₂) _ h₁ hs.2,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem (finset.mem_union_right _ TM1.stmts₁_self) },
{ refine IH₁ (TM1.stmts_trans _ h₂) _ h₁ hs.1,
unfold TM1.stmts₁,
exact finset.mem_insert_of_mem (finset.mem_union_left _ TM1.stmts₁_self) } },
case TM1.stmt.goto : l {
cases h₁, exact finset.some_mem_insert_none.2
(finset.mem_bUnion.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) },
case TM1.stmt.halt { cases h₁ }
end⟩
end
end TM1to0
/-!
## TM1(Γ) emulator in TM1(bool)
The most parsimonious Turing machine model that is still Turing complete is `TM0` with `Γ = bool`.
Because our construction in the previous section reducing `TM1` to `TM0` doesn't change the
alphabet, we can do the alphabet reduction on `TM1` instead of `TM0` directly.
The basic idea is to use a bijection between `Γ` and a subset of `vector bool n`, where `n` is a
fixed constant. Each tape element is represented as a block of `n` bools. Whenever the machine
wants to read a symbol from the tape, it traverses over the block, performing `n` `branch`
instructions to each any of the `2^n` results.
For the `write` instruction, we have to use a `goto` because we need to follow a different code
path depending on the local state, which is not available in the TM1 model, so instead we jump to
a label computed using the read value and the local state, which performs the writing and returns
to normal execution.
Emulation overhead is `O(1)`. If not for the above `write` behavior it would be 1-1 because we are
exploiting the 0-step behavior of regular commands to avoid taking steps, but there are
nevertheless a bounded number of `write` calls between `goto` statements because TM1 statements are
finitely long.
-/
namespace TM1to1
open TM1
section
parameters {Γ : Type*} [inhabited Γ]
theorem exists_enc_dec [fintype Γ] :
∃ n (enc : Γ → vector bool n) (dec : vector bool n → Γ),
enc (default _) = vector.repeat ff n ∧ ∀ a, dec (enc a) = a :=
begin
letI := classical.dec_eq Γ,
let n := fintype.card Γ,
obtain ⟨F⟩ := fintype.trunc_equiv_fin Γ,
let G : fin n ↪ fin n → bool := ⟨λ a b, a = b,
λ a b h, of_to_bool_true $ (congr_fun h b).trans $ to_bool_tt rfl⟩,
let H := (F.to_embedding.trans G).trans
(equiv.vector_equiv_fin _ _).symm.to_embedding,
classical,
let enc := H.set_value (default _) (vector.repeat ff n),
exact ⟨_, enc, function.inv_fun enc,
H.set_value_eq _ _, function.left_inverse_inv_fun enc.2⟩
end
parameters {Λ : Type*} [inhabited Λ]
parameters {σ : Type*} [inhabited σ]
local notation `stmt₁` := stmt Γ Λ σ
local notation `cfg₁` := cfg Γ Λ σ
/-- The configuration state of the TM. -/
inductive Λ' : Type (max u_1 u_2 u_3)
| normal : Λ → Λ'
| write : Γ → stmt₁ → Λ'
instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩
local notation `stmt'` := stmt bool Λ' σ
local notation `cfg'` := cfg bool Λ' σ
/-- Read a vector of length `n` from the tape. -/
def read_aux : ∀ n, (vector bool n → stmt') → stmt'
| 0 f := f vector.nil
| (i+1) f := stmt.branch (λ a s, a)
(stmt.move dir.right $ read_aux i (λ v, f (tt ::ᵥ v)))
(stmt.move dir.right $ read_aux i (λ v, f (ff ::ᵥ v)))
parameters {n : ℕ} (enc : Γ → vector bool n) (dec : vector bool n → Γ)
/-- A move left or right corresponds to `n` moves across the super-cell. -/
def move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q
/-- To read a symbol from the tape, we use `read_aux` to traverse the symbol,
then return to the original position with `n` moves to the left. -/
def read (f : Γ → stmt') : stmt' :=
read_aux n (λ v, move dir.left $ f (dec v))
/-- Write a list of bools on the tape. -/
def write : list bool → stmt' → stmt'
| [] q := q
| (a :: l) q := stmt.write (λ _ _, a) $ stmt.move dir.right $ write l q
/-- Translate a normal instruction. For the `write` command, we use a `goto` indirection so that
we can access the current value of the tape. -/
def tr_normal : stmt₁ → stmt'
| (stmt.move d q) := move d $ tr_normal q
| (stmt.write f q) := read $ λ a, stmt.goto $ λ _ s, Λ'.write (f a s) q
| (stmt.load f q) := read $ λ a, stmt.load (λ _ s, f a s) $ tr_normal q
| (stmt.branch p q₁ q₂) := read $ λ a, stmt.branch (λ _ s, p a s) (tr_normal q₁) (tr_normal q₂)
| (stmt.goto l) := read $ λ a, stmt.goto $ λ _ s, Λ'.normal (l a s)
| stmt.halt := stmt.halt
theorem step_aux_move (d q v T) :
step_aux (move d q) v T =
step_aux q v ((tape.move d)^[n] T) :=
begin
suffices : ∀ i,
step_aux (stmt.move d^[i] q) v T =
step_aux q v (tape.move d^[i] T), from this n,
intro, induction i with i IH generalizing T, {refl},
rw [iterate_succ', step_aux, IH, iterate_succ]
end
theorem supports_stmt_move {S d q} :
supports_stmt S (move d q) = supports_stmt S q :=
suffices ∀ {i}, supports_stmt S (stmt.move d^[i] q) = _, from this,
by intro; induction i generalizing q; simp only [*, iterate]; refl
theorem supports_stmt_write {S l q} :
supports_stmt S (write l q) = supports_stmt S q :=
by induction l with a l IH; simp only [write, supports_stmt, *]
theorem supports_stmt_read {S} : ∀ {f : Γ → stmt'},
(∀ a, supports_stmt S (f a)) → supports_stmt S (read f) :=
suffices ∀ i (f : vector bool i → stmt'),
(∀ v, supports_stmt S (f v)) → supports_stmt S (read_aux i f),
from λ f hf, this n _ (by intro; simp only [supports_stmt_move, hf]),
λ i f hf, begin
induction i with i IH, {exact hf _},
split; apply IH; intro; apply hf,
end
parameter (enc0 : enc (default _) = vector.repeat ff n)
section
parameter {enc}
include enc0
/-- The low level tape corresponding to the given tape over alphabet `Γ`. -/
def tr_tape' (L R : list_blank Γ) : tape bool :=
begin
refine tape.mk'
(L.bind (λ x, (enc x).to_list.reverse) ⟨n, _⟩)
(R.bind (λ x, (enc x).to_list) ⟨n, _⟩);
simp only [enc0, vector.repeat,
list.reverse_repeat, bool.default_bool, vector.to_list_mk]
end
/-- The low level tape corresponding to the given tape over alphabet `Γ`. -/
def tr_tape (T : tape Γ) : tape bool := tr_tape' T.left T.right₀
theorem tr_tape_mk' (L R : list_blank Γ) : tr_tape (tape.mk' L R) = tr_tape' L R :=
by simp only [tr_tape, tape.mk'_left, tape.mk'_right₀]
end
parameters (M : Λ → stmt₁)
/-- The top level program. -/
def tr : Λ' → stmt'
| (Λ'.normal l) := tr_normal (M l)
| (Λ'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q
/-- The machine configuration translation. -/
def tr_cfg : cfg₁ → cfg'
| ⟨l, v, T⟩ := ⟨l.map Λ'.normal, v, tr_tape T⟩
parameter {enc}
include enc0
theorem tr_tape'_move_left (L R) :
(tape.move dir.left)^[n] (tr_tape' L R) =
(tr_tape' L.tail (R.cons L.head)) :=
begin
obtain ⟨a, L, rfl⟩ := L.exists_cons,
simp only [tr_tape', list_blank.cons_bind, list_blank.head_cons, list_blank.tail_cons],
suffices : ∀ {L' R' l₁ l₂}
(e : vector.to_list (enc a) = list.reverse_core l₁ l₂),
tape.move dir.left^[l₁.length]
(tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) =
tape.mk' L' (list_blank.append (vector.to_list (enc a)) R'),
{ simpa only [list.length_reverse, vector.to_list_length]
using this (list.reverse_reverse _).symm },
intros, induction l₁ with b l₁ IH generalizing l₂,
{ cases e, refl },
simp only [list.length, list.cons_append, iterate_succ_apply],
convert IH e,
simp only [list_blank.tail_cons, list_blank.append, tape.move_left_mk', list_blank.head_cons]
end
theorem tr_tape'_move_right (L R) :
(tape.move dir.right)^[n] (tr_tape' L R) =
(tr_tape' (L.cons R.head) R.tail) :=
begin
suffices : ∀ i L, (tape.move dir.right)^[i] ((tape.move dir.left)^[i] L) = L,
{ refine (eq.symm _).trans (this n _),
simp only [tr_tape'_move_left, list_blank.cons_head_tail,
list_blank.head_cons, list_blank.tail_cons] },
intros, induction i with i IH, {refl},
rw [iterate_succ_apply, iterate_succ_apply', tape.move_left_right, IH]
end
theorem step_aux_write (q v a b L R) :
step_aux (write (enc a).to_list q) v (tr_tape' L (list_blank.cons b R)) =
step_aux q v (tr_tape' (list_blank.cons a L) R) :=
begin
simp only [tr_tape', list.cons_bind, list.append_assoc],
suffices : ∀ {L' R'} (l₁ l₂ l₂' : list bool)
(e : l₂'.length = l₂.length),
step_aux (write l₂ q) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂' R')) =
step_aux q v (tape.mk' (L'.append (list.reverse_core l₂ l₁)) R'),
{ convert this [] _ _ ((enc b).2.trans (enc a).2.symm);
rw list_blank.cons_bind; refl },
clear a b L R, intros,
induction l₂ with a l₂ IH generalizing l₁ l₂',
{ cases list.length_eq_zero.1 e, refl },
cases l₂' with b l₂'; injection e with e,
dunfold write step_aux,
convert IH _ _ e using 1,
simp only [list_blank.head_cons, list_blank.tail_cons,
list_blank.append, tape.move_right_mk', tape.write_mk']
end
parameters (encdec : ∀ a, dec (enc a) = a)
include encdec
theorem step_aux_read (f v L R) :
step_aux (read f) v (tr_tape' L R) =
step_aux (f R.head) v (tr_tape' L R) :=
begin
suffices : ∀ f,
step_aux (read_aux n f) v (tr_tape' enc0 L R) =
step_aux (f (enc R.head)) v
(tr_tape' enc0 (L.cons R.head) R.tail),
{ rw [read, this, step_aux_move, encdec, tr_tape'_move_left enc0],
simp only [list_blank.head_cons, list_blank.cons_head_tail, list_blank.tail_cons] },
obtain ⟨a, R, rfl⟩ := R.exists_cons,
simp only [list_blank.head_cons, list_blank.tail_cons,
tr_tape', list_blank.cons_bind, list_blank.append_assoc],
suffices : ∀ i f L' R' l₁ l₂ h,
step_aux (read_aux i f) v
(tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) =
step_aux (f ⟨l₂, h⟩) v
(tape.mk' (list_blank.append (l₂.reverse_core l₁) L') R'),
{ intro f, convert this n f _ _ _ _ (enc a).2; simp },
clear f L a R, intros, subst i,
induction l₂ with a l₂ IH generalizing l₁, {refl},
transitivity step_aux
(read_aux l₂.length (λ v, f (a ::ᵥ v))) v
(tape.mk' ((L'.append l₁).cons a) (R'.append l₂)),
{ dsimp [read_aux, step_aux], simp, cases a; refl },
rw [← list_blank.append, IH], refl
end
theorem tr_respects : respects (step M) (step tr)
(λ c₁ c₂, tr_cfg c₁ = c₂) :=
fun_respects.2 $ λ ⟨l₁, v, T⟩, begin
obtain ⟨L, R, rfl⟩ := T.exists_mk',
cases l₁ with l₁, {exact rfl},
suffices : ∀ q R, reaches (step (tr enc dec M))
(step_aux (tr_normal dec q) v (tr_tape' enc0 L R))
(tr_cfg enc0 (step_aux q v (tape.mk' L R))),
{ refine trans_gen.head' rfl _, rw tr_tape_mk', exact this _ R },
clear R l₁, intros,
induction q with _ q IH _ q IH _ q IH generalizing v L R,
case TM1.stmt.move : d q IH {
cases d; simp only [tr_normal, iterate, step_aux_move, step_aux,
list_blank.head_cons, tape.move_left_mk',
list_blank.cons_head_tail, list_blank.tail_cons,
tr_tape'_move_left enc0, tr_tape'_move_right enc0];
apply IH },
case TM1.stmt.write : f q IH {
simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux],
refine refl_trans_gen.head rfl _,
obtain ⟨a, R, rfl⟩ := R.exists_cons,
rw [tr, tape.mk'_head, step_aux_write, list_blank.head_cons,
step_aux_move, tr_tape'_move_left enc0, list_blank.head_cons,
list_blank.tail_cons, tape.write_mk'],
apply IH },
case TM1.stmt.load : a q IH {
simp only [tr_normal, step_aux_read dec enc0 encdec],
apply IH },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux],
cases p R.head v; [apply IH₂, apply IH₁] },
case TM1.stmt.goto : l {
simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux, tr_cfg, tr_tape_mk'],
apply refl_trans_gen.refl },
case TM1.stmt.halt {
simp only [tr_normal, step_aux, tr_cfg, step_aux_move,
tr_tape'_move_left enc0, tr_tape'_move_right enc0, tr_tape_mk'],
apply refl_trans_gen.refl }
end
omit enc0 encdec
open_locale classical
parameters [fintype Γ]
/-- The set of accessible `Λ'.write` machine states. -/
noncomputable def writes : stmt₁ → finset Λ'
| (stmt.move d q) := writes q
| (stmt.write f q) := finset.univ.image (λ a, Λ'.write a q) ∪ writes q
| (stmt.load f q) := writes q
| (stmt.branch p q₁ q₂) := writes q₁ ∪ writes q₂
| (stmt.goto l) := ∅
| stmt.halt := ∅
/-- The set of accessible machine states, assuming that the input machine is supported on `S`,
are the normal states embedded from `S`, plus all write states accessible from these states. -/
noncomputable def tr_supp (S : finset Λ) : finset Λ' :=
S.bUnion (λ l, insert (Λ'.normal l) (writes (M l)))
theorem tr_supports {S} (ss : supports M S) :
supports tr (tr_supp S) :=
⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert_self _ _⟩,
λ q h, begin
suffices : ∀ q, supports_stmt S q →
(∀ q' ∈ writes q, q' ∈ tr_supp M S) →
supports_stmt (tr_supp M S) (tr_normal dec q) ∧
∀ q' ∈ writes q, supports_stmt (tr_supp M S) (tr enc dec M q'),
{ rcases finset.mem_bUnion.1 h with ⟨l, hl, h⟩,
have := this _ (ss.2 _ hl) (λ q' hq,
finset.mem_bUnion.2 ⟨_, hl, finset.mem_insert_of_mem hq⟩),
rcases finset.mem_insert.1 h with rfl | h,
exacts [this.1, this.2 _ h] },
intros q hs hw, induction q,
case TM1.stmt.move : d q IH {
unfold writes at hw ⊢,
replace IH := IH hs hw, refine ⟨_, IH.2⟩,
cases d; simp only [tr_normal, iterate, supports_stmt_move, IH] },
case TM1.stmt.write : f q IH {
unfold writes at hw ⊢,
simp only [finset.mem_image, finset.mem_union, finset.mem_univ,
exists_prop, true_and] at hw ⊢,
replace IH := IH hs (λ q hq, hw q (or.inr hq)),
refine ⟨supports_stmt_read _ $ λ a _ s,
hw _ (or.inl ⟨_, rfl⟩), λ q' hq, _⟩,
rcases hq with ⟨a, q₂, rfl⟩ | hq,
{ simp only [tr, supports_stmt_write, supports_stmt_move, IH.1] },
{ exact IH.2 _ hq } },
case TM1.stmt.load : a q IH {
unfold writes at hw ⊢,
replace IH := IH hs hw,
refine ⟨supports_stmt_read _ (λ a, IH.1), IH.2⟩ },
case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {
unfold writes at hw ⊢,
simp only [finset.mem_union] at hw ⊢,
replace IH₁ := IH₁ hs.1 (λ q hq, hw q (or.inl hq)),
replace IH₂ := IH₂ hs.2 (λ q hq, hw q (or.inr hq)),
exact ⟨supports_stmt_read _ (λ a, ⟨IH₁.1, IH₂.1⟩),
λ q, or.rec (IH₁.2 _) (IH₂.2 _)⟩ },
case TM1.stmt.goto : l {
refine ⟨_, λ _, false.elim⟩,
refine supports_stmt_read _ (λ a _ s, _),
exact finset.mem_bUnion.2 ⟨_, hs _ _, finset.mem_insert_self _ _⟩ },
case TM1.stmt.halt {
refine ⟨_, λ _, false.elim⟩,
simp only [supports_stmt, supports_stmt_move, tr_normal] }
end⟩
end
end TM1to1
/-!
## TM0 emulator in TM1
To establish that TM0 and TM1 are equivalent computational models, we must also have a TM0 emulator
in TM1. The main complication here is that TM0 allows an action to depend on the value at the head
and local state, while TM1 doesn't (in order to have more programming language-like semantics).
So we use a computed `goto` to go to a state that performes the desired action and then returns to
normal execution.
One issue with this is that the `halt` instruction is supposed to halt immediately, not take a step
to a halting state. To resolve this we do a check for `halt` first, then `goto` (with an
unreachable branch).
-/
namespace TM0to1
section
parameters {Γ : Type*} [inhabited Γ]
parameters {Λ : Type*} [inhabited Λ]
/-- The machine states for a TM1 emulating a TM0 machine. States of the TM0 machine are embedded
as `normal q` states, but the actual operation is split into two parts, a jump to `act s q`
followed by the action and a jump to the next `normal` state. -/
inductive Λ'
| normal : Λ → Λ'
| act : TM0.stmt Γ → Λ → Λ'
instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩
local notation `cfg₀` := TM0.cfg Γ Λ
local notation `stmt₁` := TM1.stmt Γ Λ' unit
local notation `cfg₁` := TM1.cfg Γ Λ' unit
parameters (M : TM0.machine Γ Λ)
open TM1.stmt
/-- The program. -/
def tr : Λ' → stmt₁
| (Λ'.normal q) :=
branch (λ a _, (M q a).is_none) halt $
goto (λ a _, match M q a with
| none := default _ -- unreachable
| some (q', s) := Λ'.act s q'
end)
| (Λ'.act (TM0.stmt.move d) q) := move d $ goto (λ _ _, Λ'.normal q)
| (Λ'.act (TM0.stmt.write a) q) := write (λ _ _, a) $ goto (λ _ _, Λ'.normal q)
/-- The configuration translation. -/
def tr_cfg : cfg₀ → cfg₁
| ⟨q, T⟩ := ⟨cond (M q T.1).is_some (some (Λ'.normal q)) none, (), T⟩
theorem tr_respects : respects (TM0.step M) (TM1.step tr)
(λ a b, tr_cfg a = b) :=
fun_respects.2 $ λ ⟨q, T⟩, begin
cases e : M q T.1,
{ simp only [TM0.step, tr_cfg, e]; exact eq.refl none },
cases val with q' s,
simp only [frespects, TM0.step, tr_cfg, e, option.is_some, cond, option.map_some'],
have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ =
some ⟨some (Λ'.normal q'), (), TM0.step._match_1 T s⟩,
{ cases s with d a; refl },
refine trans_gen.head _ (trans_gen.head' this _),
{ unfold TM1.step TM1.step_aux tr has_mem.mem,
rw e, refl },
cases e' : M q' _,
{ apply refl_trans_gen.single,
unfold TM1.step TM1.step_aux tr has_mem.mem,
rw e', refl },
{ refl }
end
end
end TM0to1
/-!
## The TM2 model
The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite)
collection of stacks, each with elements of different types (the alphabet of stack `k : K` is
`Γ k`). The statements are:
* `push k (f : σ → Γ k) q` puts `f a` on the `k`-th stack, then does `q`.
* `pop k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the
value of the `k`-th stack, and removes this element from the stack, then does `q`.
* `peek k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the
value of the `k`-th stack, then does `q`.
* `load (f : σ → σ) q` reads nothing but applies `f` to the internal state, then does `q`.
* `branch (f : σ → bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`.
* `goto (f : σ → Λ)` jumps to label `f a`.
* `halt` halts on the next step.
The configuration is a tuple `(l, var, stk)` where `l : option Λ` is the current label to run or
`none` for the halting state, `var : σ` is the (finite) internal state, and `stk : ∀ k, list (Γ k)`
is the collection of stacks. (Note that unlike the `TM0` and `TM1` models, these are not
`list_blank`s, they have definite ends that can be detected by the `pop` command.)
Given a designated stack `k` and a value `L : list (Γ k)`, the initial configuration has all the
stacks empty except the designated "input" stack; in `eval` this designated stack also functions
as the output stack.
-/
namespace TM2
section
parameters {K : Type*} [decidable_eq K] -- Index type of stacks
parameters (Γ : K → Type*) -- Type of stack elements
parameters (Λ : Type*) -- Type of function labels
parameters (σ : Type*) -- Type of variable settings
/-- The TM2 model removes the tape entirely from the TM1 model,
replacing it with an arbitrary (finite) collection of stacks.
The operation `push` puts an element on one of the stacks,
and `pop` removes an element from a stack (and modifying the
internal state based on the result). `peek` modifies the
internal state but does not remove an element. -/
inductive stmt
| push : ∀ k, (σ → Γ k) → stmt → stmt
| peek : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt
| pop : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt
| load : (σ → σ) → stmt → stmt
| branch : (σ → bool) → stmt → stmt → stmt
| goto : (σ → Λ) → stmt
| halt : stmt
open stmt
instance stmt.inhabited : inhabited stmt := ⟨halt⟩
/-- A configuration in the TM2 model is a label (or `none` for the halt state), the state of
local variables, and the stacks. (Note that the stacks are not `list_blank`s, they have a definite
size.) -/
structure cfg :=
(l : option Λ)
(var : σ)
(stk : ∀ k, list (Γ k))
instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩
parameters {Γ Λ σ K}
/-- The step function for the TM2 model. -/
@[simp] def step_aux : stmt → σ → (∀ k, list (Γ k)) → cfg
| (push k f q) v S := step_aux q v (update S k (f v :: S k))
| (peek k f q) v S := step_aux q (f v (S k).head') S
| (pop k f q) v S := step_aux q (f v (S k).head') (update S k (S k).tail)
| (load a q) v S := step_aux q (a v) S
| (branch f q₁ q₂) v S :=
cond (f v) (step_aux q₁ v S) (step_aux q₂ v S)
| (goto f) v S := ⟨some (f v), v, S⟩
| halt v S := ⟨none, v, S⟩
/-- The step function for the TM2 model. -/
@[simp] def step (M : Λ → stmt) : cfg → option cfg
| ⟨none, v, S⟩ := none
| ⟨some l, v, S⟩ := some (step_aux (M l) v S)
/-- The (reflexive) reachability relation for the TM2 model. -/
def reaches (M : Λ → stmt) : cfg → cfg → Prop :=
refl_trans_gen (λ a b, b ∈ step M a)
/-- Given a set `S` of states, `support_stmt S q` means that `q` only jumps to states in `S`. -/
def supports_stmt (S : finset Λ) : stmt → Prop
| (push k f q) := supports_stmt q
| (peek k f q) := supports_stmt q
| (pop k f q) := supports_stmt q
| (load a q) := supports_stmt q
| (branch f q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂
| (goto l) := ∀ v, l v ∈ S
| halt := true
open_locale classical
/-- The set of subtree statements in a statement. -/
noncomputable def stmts₁ : stmt → finset stmt
| Q@(push k f q) := insert Q (stmts₁ q)
| Q@(peek k f q) := insert Q (stmts₁ q)
| Q@(pop k f q) := insert Q (stmts₁ q)
| Q@(load a q) := insert Q (stmts₁ q)
| Q@(branch f q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂)
| Q@(goto l) := {Q}
| Q@halt := {Q}
theorem stmts₁_self {q} : q ∈ stmts₁ q :=
by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self]
theorem stmts₁_trans {q₁ q₂} :
q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ :=
begin
intros h₁₂ q₀ h₀₁,
induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH;
simp only [stmts₁] at h₁₂ ⊢;
simp only [finset.mem_insert, finset.mem_singleton, finset.mem_union] at h₁₂,
iterate 4 {
rcases h₁₂ with rfl | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (IH h₁₂) } },
case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ {
rcases h₁₂ with rfl | h₁₂ | h₁₂,
{ unfold stmts₁ at h₀₁, exact h₀₁ },
{ exact finset.mem_insert_of_mem (finset.mem_union_left _ (IH₁ h₁₂)) },
{ exact finset.mem_insert_of_mem (finset.mem_union_right _ (IH₂ h₁₂)) } },
case TM2.stmt.goto : l {
subst h₁₂, exact h₀₁ },
case TM2.stmt.halt {
subst h₁₂, exact h₀₁ }
end
theorem stmts₁_supports_stmt_mono {S q₁ q₂}
(h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ :=
begin
induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH;
simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union,
finset.mem_singleton] at h hs,
iterate 4 { rcases h with rfl | h; [exact hs, exact IH h hs] },
case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ {
rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] },
case TM2.stmt.goto : l { subst h, exact hs },
case TM2.stmt.halt { subst h, trivial }
end
/-- The set of statements accessible from initial set `S` of labels. -/
noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) :=
(S.bUnion (λ q, stmts₁ (M q))).insert_none
theorem stmts_trans {M : Λ → stmt} {S q₁ q₂}
(h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩
variable [inhabited Λ]
/-- Given a TM2 machine `M` and a set `S` of states, `supports M S` means that all states in
`S` jump only to other states in `S`. -/
def supports (M : Λ → stmt) (S : finset Λ) :=
default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q)
theorem stmts_supports_stmt {M : Λ → stmt} {S q}
(ss : supports M S) : some q ∈ stmts M S → supports_stmt S q :=
by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion,
option.mem_def, forall_eq', exists_imp_distrib];
exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls)
theorem step_supports (M : Λ → stmt) {S}
(ss : supports M S) : ∀ {c c' : cfg},
c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none
| ⟨some l₁, v, T⟩ c' h₁ h₂ := begin
replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂),
simp only [step, option.mem_def] at h₁, subst c',
revert h₂, induction M l₁ with _ _ q IH _ _ q IH _ _ q IH _ q IH generalizing v T;
intro hs,
iterate 4 { exact IH _ _ hs },
case TM2.stmt.branch : p q₁' q₂' IH₁ IH₂ {
unfold step_aux, cases p v,
{ exact IH₂ _ _ hs.2 },
{ exact IH₁ _ _ hs.1 } },
case TM2.stmt.goto { exact finset.some_mem_insert_none.2 (hs _) },
case TM2.stmt.halt { apply multiset.mem_cons_self }
end
variable [inhabited σ]
/-- The initial state of the TM2 model. The input is provided on a designated stack. -/
def init (k) (L : list (Γ k)) : cfg :=
⟨some (default _), default _, update (λ _, []) k L⟩
/-- Evaluates a TM2 program to completion, with the output on the same stack as the input. -/
def eval (M : Λ → stmt) (k) (L : list (Γ k)) : part (list (Γ k)) :=
(eval (step M) (init k L)).map $ λ c, c.stk k
end
end TM2
/-!
## TM2 emulator in TM1
To prove that TM2 computable functions are TM1 computable, we need to reduce each TM2 program to a
TM1 program. So suppose a TM2 program is given. This program has to maintain a whole collection of
stacks, but we have only one tape, so we must "multiplex" them all together. Pictorially, if stack
1 contains `[a, b]` and stack 2 contains `[c, d, e, f]` then the tape looks like this:
```
bottom: ... | _ | T | _ | _ | _ | _ | ...
stack 1: ... | _ | b | a | _ | _ | _ | ...
stack 2: ... | _ | f | e | d | c | _ | ...
```
where a tape element is a vertical slice through the diagram. Here the alphabet is
`Γ' := bool × ∀ k, option (Γ k)`, where:
* `bottom : bool` is marked only in one place, the initial position of the TM, and represents the
tail of all stacks. It is never modified.
* `stk k : option (Γ k)` is the value of the `k`-th stack, if in range, otherwise `none` (which is
the blank value). Note that the head of the stack is at the far end; this is so that push and pop
don't have to do any shifting.
In "resting" position, the TM is sitting at the position marked `bottom`. For non-stack actions,
it operates in place, but for the stack actions `push`, `peek`, and `pop`, it must shuttle to the
end of the appropriate stack, make its changes, and then return to the bottom. So the states are:
* `normal (l : Λ)`: waiting at `bottom` to execute function `l`
* `go k (s : st_act k) (q : stmt₂)`: travelling to the right to get to the end of stack `k` in
order to perform stack action `s`, and later continue with executing `q`
* `ret (q : stmt₂)`: travelling to the left after having performed a stack action, and executing
`q` once we arrive
Because of the shuttling, emulation overhead is `O(n)`, where `n` is the current maximum of the
length of all stacks. Therefore a program that takes `k` steps to run in TM2 takes `O((m+k)k)`
steps to run when emulated in TM1, where `m` is the length of the input.
-/
namespace TM2to1
-- A displaced lemma proved in unnecessary generality
theorem stk_nth_val {K : Type*} {Γ : K → Type*} {L : list_blank (∀ k, option (Γ k))} {k S} (n)
(hL : list_blank.map (proj k) L = list_blank.mk (list.map some S).reverse) :
L.nth n k = S.reverse.nth n :=
begin
rw [← proj_map_nth, hL, ← list.map_reverse, list_blank.nth_mk, list.inth, list.nth_map],
cases S.reverse.nth n; refl
end
section
parameters {K : Type*} [decidable_eq K]
parameters {Γ : K → Type*}
parameters {Λ : Type*} [inhabited Λ]
parameters {σ : Type*} [inhabited σ]
local notation `stmt₂` := TM2.stmt Γ Λ σ
local notation `cfg₂` := TM2.cfg Γ Λ σ
/-- The alphabet of the TM2 simulator on TM1 is a marker for the stack bottom,
plus a vector of stack elements for each stack, or none if the stack does not extend this far. -/
@[nolint unused_arguments] -- [decidable_eq K]: Because K is a parameter, we cannot easily skip
-- the decidable_eq assumption, and this is a local definition anyway so it's not important.
def Γ' := bool × ∀ k, option (Γ k)
instance Γ'.inhabited : inhabited Γ' := ⟨⟨ff, λ _, none⟩⟩
instance Γ'.fintype [fintype K] [∀ k, fintype (Γ k)] : fintype Γ' :=
prod.fintype _ _
/-- The bottom marker is fixed throughout the calculation, so we use the `add_bottom` function
to express the program state in terms of a tape with only the stacks themselves. -/
def add_bottom (L : list_blank (∀ k, option (Γ k))) : list_blank Γ' :=
list_blank.cons (tt, L.head) (L.tail.map ⟨prod.mk ff, rfl⟩)
theorem add_bottom_map (L) : (add_bottom L).map ⟨prod.snd, rfl⟩ = L :=
begin
simp only [add_bottom, list_blank.map_cons]; convert list_blank.cons_head_tail _,
generalize : list_blank.tail L = L',
refine L'.induction_on _, intro l, simp,
rw (_ : _ ∘ _ = id), {simp},
funext a, refl
end
theorem add_bottom_modify_nth (f : (∀ k, option (Γ k)) → (∀ k, option (Γ k))) (L n) :
(add_bottom L).modify_nth (λ a, (a.1, f a.2)) n = add_bottom (L.modify_nth f n) :=
begin
cases n; simp only [add_bottom,
list_blank.head_cons, list_blank.modify_nth, list_blank.tail_cons],
congr, symmetry, apply list_blank.map_modify_nth, intro, refl
end
theorem add_bottom_nth_snd (L n) : ((add_bottom L).nth n).2 = L.nth n :=
by conv {to_rhs, rw [← add_bottom_map L, list_blank.nth_map]}; refl
theorem add_bottom_nth_succ_fst (L n) : ((add_bottom L).nth (n+1)).1 = ff :=
by rw [list_blank.nth_succ, add_bottom, list_blank.tail_cons, list_blank.nth_map]; refl
theorem add_bottom_head_fst (L) : (add_bottom L).head.1 = tt :=
by rw [add_bottom, list_blank.head_cons]; refl
/-- A stack action is a command that interacts with the top of a stack. Our default position
is at the bottom of all the stacks, so we have to hold on to this action while going to the end
to modify the stack. -/
inductive st_act (k : K)
| push : (σ → Γ k) → st_act
| peek : (σ → option (Γ k) → σ) → st_act
| pop : (σ → option (Γ k) → σ) → st_act
instance st_act.inhabited {k} : inhabited (st_act k) := ⟨st_act.peek (λ s _, s)⟩
section
open st_act
/-- The TM2 statement corresponding to a stack action. -/
@[nolint unused_arguments] -- [inhabited Λ]: as this is a local definition it is more trouble than
-- it is worth to omit the typeclass assumption without breaking the parameters
def st_run {k : K} : st_act k → stmt₂ → stmt₂
| (push f) := TM2.stmt.push k f
| (peek f) := TM2.stmt.peek k f
| (pop f) := TM2.stmt.pop k f
/-- The effect of a stack action on the local variables, given the value of the stack. -/
def st_var {k : K} (v : σ) (l : list (Γ k)) : st_act k → σ
| (push f) := v
| (peek f) := f v l.head'
| (pop f) := f v l.head'
/-- The effect of a stack action on the stack. -/
def st_write {k : K} (v : σ) (l : list (Γ k)) : st_act k → list (Γ k)
| (push f) := f v :: l
| (peek f) := l
| (pop f) := l.tail
/-- We have partitioned the TM2 statements into "stack actions", which require going to the end
of the stack, and all other actions, which do not. This is a modified recursor which lumps the
stack actions into one. -/
@[elab_as_eliminator] def {l} stmt_st_rec
{C : stmt₂ → Sort l}
(H₁ : Π k (s : st_act k) q (IH : C q), C (st_run s q))
(H₂ : Π a q (IH : C q), C (TM2.stmt.load a q))
(H₃ : Π p q₁ q₂ (IH₁ : C q₁) (IH₂ : C q₂), C (TM2.stmt.branch p q₁ q₂))
(H₄ : Π l, C (TM2.stmt.goto l))
(H₅ : C TM2.stmt.halt) : ∀ n, C n
| (TM2.stmt.push k f q) := H₁ _ (push f) _ (stmt_st_rec q)
| (TM2.stmt.peek k f q) := H₁ _ (peek f) _ (stmt_st_rec q)
| (TM2.stmt.pop k f q) := H₁ _ (pop f) _ (stmt_st_rec q)
| (TM2.stmt.load a q) := H₂ _ _ (stmt_st_rec q)
| (TM2.stmt.branch a q₁ q₂) := H₃ _ _ _ (stmt_st_rec q₁) (stmt_st_rec q₂)
| (TM2.stmt.goto l) := H₄ _
| TM2.stmt.halt := H₅
theorem supports_run (S : finset Λ) {k} (s : st_act k) (q) :
TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q :=
by rcases s with _|_|_; refl
end
/-- The machine states of the TM2 emulator. We can either be in a normal state when waiting for the
next TM2 action, or we can be in the "go" and "return" states to go to the top of the stack and
return to the bottom, respectively. -/
inductive Λ' : Type (max u_1 u_2 u_3 u_4)
| normal : Λ → Λ'
| go (k) : st_act k → stmt₂ → Λ'
| ret : stmt₂ → Λ'
open Λ'
instance Λ'.inhabited : inhabited Λ' := ⟨normal (default _)⟩
local notation `stmt₁` := TM1.stmt Γ' Λ' σ
local notation `cfg₁` := TM1.cfg Γ' Λ' σ
open TM1.stmt
/-- The program corresponding to state transitions at the end of a stack. Here we start out just
after the top of the stack, and should end just after the new top of the stack. -/
def tr_st_act {k} (q : stmt₁) : st_act k → stmt₁
| (st_act.push f) := write (λ a s, (a.1, update a.2 k $ some $ f s)) $ move dir.right q
| (st_act.peek f) := move dir.left $ load (λ a s, f s (a.2 k)) $ move dir.right q
| (st_act.pop f) :=
branch (λ a _, a.1)
( load (λ a s, f s none) q )
( move dir.left $
load (λ a s, f s (a.2 k)) $
write (λ a s, (a.1, update a.2 k none)) q )
/-- The initial state for the TM2 emulator, given an initial TM2 state. All stacks start out empty
except for the input stack, and the stack bottom mark is set at the head. -/
def tr_init (k) (L : list (Γ k)) : list Γ' :=
let L' : list Γ' := L.reverse.map (λ a, (ff, update (λ _, none) k a)) in
(tt, L'.head.2) :: L'.tail
theorem step_run {k : K} (q v S) : ∀ s : st_act k,
TM2.step_aux (st_run s q) v S =
TM2.step_aux q (st_var v (S k) s) (update S k (st_write v (S k) s))
| (st_act.push f) := rfl
| (st_act.peek f) := by unfold st_write; rw function.update_eq_self; refl
| (st_act.pop f) := rfl
/-- The translation of TM2 statements to TM1 statements. regular actions have direct equivalents,
but stack actions are deferred by going to the corresponding `go` state, so that we can find the
appropriate stack top. -/
def tr_normal : stmt₂ → stmt₁
| (TM2.stmt.push k f q) := goto (λ _ _, go k (st_act.push f) q)
| (TM2.stmt.peek k f q) := goto (λ _ _, go k (st_act.peek f) q)
| (TM2.stmt.pop k f q) := goto (λ _ _, go k (st_act.pop f) q)
| (TM2.stmt.load a q) := load (λ _, a) (tr_normal q)
| (TM2.stmt.branch f q₁ q₂) := branch (λ a, f) (tr_normal q₁) (tr_normal q₂)
| (TM2.stmt.goto l) := goto (λ a s, normal (l s))
| TM2.stmt.halt := halt
theorem tr_normal_run {k} (s q) : tr_normal (st_run s q) = goto (λ _ _, go k s q) :=
by rcases s with _|_|_; refl
open_locale classical
/-- The set of machine states accessible from an initial TM2 statement. -/
noncomputable def tr_stmts₁ : stmt₂ → finset Λ'
| (TM2.stmt.push k f q) := {go k (st_act.push f) q, ret q} ∪ tr_stmts₁ q
| (TM2.stmt.peek k f q) := {go k (st_act.peek f) q, ret q} ∪ tr_stmts₁ q
| (TM2.stmt.pop k f q) := {go k (st_act.pop f) q, ret q} ∪ tr_stmts₁ q
| (TM2.stmt.load a q) := tr_stmts₁ q
| (TM2.stmt.branch f q₁ q₂) := tr_stmts₁ q₁ ∪ tr_stmts₁ q₂
| _ := ∅
theorem tr_stmts₁_run {k s q} : tr_stmts₁ (st_run s q) = {go k s q, ret q} ∪ tr_stmts₁ q :=
by rcases s with _|_|_; unfold tr_stmts₁ st_run
theorem tr_respects_aux₂
{k q v} {S : Π k, list (Γ k)} {L : list_blank (∀ k, option (Γ k))}
(hL : ∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) (o) :
let v' := st_var v (S k) o,
Sk' := st_write v (S k) o,
S' := update S k Sk' in
∃ (L' : list_blank (∀ k, option (Γ k))),
(∀ k, L'.map (proj k) = list_blank.mk ((S' k).map some).reverse) ∧
TM1.step_aux (tr_st_act q o) v
((tape.move dir.right)^[(S k).length] (tape.mk' ∅ (add_bottom L))) =
TM1.step_aux q v'
((tape.move dir.right)^[(S' k).length] (tape.mk' ∅ (add_bottom L'))) :=
begin
dsimp only, simp, cases o;
simp only [st_write, st_var, tr_st_act, TM1.step_aux],
case TM2to1.st_act.push : f {
have := tape.write_move_right_n (λ a : Γ', (a.1, update a.2 k (some (f v)))),
dsimp only at this,
refine ⟨_, λ k', _, by rw [
tape.move_right_n_head, list.length, tape.mk'_nth_nat, this,
add_bottom_modify_nth (λ a, update a k (some (f v))),
nat.add_one, iterate_succ']⟩,
refine list_blank.ext (λ i, _),
rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val],
by_cases h' : k' = k,
{ subst k', split_ifs; simp only [list.reverse_cons,
function.update_same, list_blank.nth_mk, list.inth, list.map],
{ rw [list.nth_le_nth, list.nth_le_append_right];
simp only [h, list.nth_le_singleton, list.length_map, list.length_reverse, nat.succ_pos',
list.length_append, lt_add_iff_pos_right, list.length] },
rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth],
cases lt_or_gt_of_ne h with h h,
{ rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h },
{ rw gt_iff_lt at h,
rw [list.nth_len_le, list.nth_len_le];
simp only [nat.add_one_le_iff, h, list.length, le_of_lt,
list.length_reverse, list.length_append, list.length_map] } },
{ split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL],
rw function.update_noteq h' } },
case TM2to1.st_act.peek : f {
rw function.update_eq_self,
use [L, hL], rw [tape.move_left_right], congr,
cases e : S k, {refl},
rw [list.length_cons, iterate_succ', tape.move_right_left, tape.move_right_n_head,
tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hL k), e,
list.reverse_cons, ← list.length_reverse, list.nth_concat_length], refl },
case TM2to1.st_act.pop : f {
cases e : S k,
{ simp only [tape.mk'_head, list_blank.head_cons, tape.move_left_mk',
list.length, tape.write_mk', list.head', iterate_zero_apply, list.tail_nil],
rw [← e, function.update_eq_self], exact ⟨L, hL, by rw [add_bottom_head_fst, cond]⟩ },
{ refine ⟨_, λ k', _, by rw [
list.length_cons, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst,
cond, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat,
tape.write_move_right_n (λ a:Γ', (a.1, update a.2 k none)),
add_bottom_modify_nth (λ a, update a k none),
add_bottom_nth_snd, stk_nth_val _ (hL k), e,
show (list.cons hd tl).reverse.nth tl.length = some hd,
by rw [list.reverse_cons, ← list.length_reverse, list.nth_concat_length]; refl,
list.head', list.tail]⟩,
refine list_blank.ext (λ i, _),
rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val],
by_cases h' : k' = k,
{ subst k', split_ifs; simp only [
function.update_same, list_blank.nth_mk, list.tail, list.inth],
{ rw [list.nth_len_le], {refl}, rw [h, list.length_reverse, list.length_map] },
rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth, e, list.map, list.reverse_cons],
cases lt_or_gt_of_ne h with h h,
{ rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h },
{ rw gt_iff_lt at h, rw [list.nth_len_le, list.nth_len_le];
simp only [nat.add_one_le_iff, h, list.length, le_of_lt,
list.length_reverse, list.length_append, list.length_map] } },
{ split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL],
rw function.update_noteq h' } } },
end
parameters (M : Λ → stmt₂)
include M
/-- The TM2 emulator machine states written as a TM1 program.
This handles the `go` and `ret` states, which shuttle to and from a stack top. -/
def tr : Λ' → stmt₁
| (normal q) := tr_normal (M q)
| (go k s q) :=
branch (λ a s, (a.2 k).is_none) (tr_st_act (goto (λ _ _, ret q)) s)
(move dir.right $ goto (λ _ _, go k s q))
| (ret q) :=
branch (λ a s, a.1) (tr_normal q)
(move dir.left $ goto (λ _ _, ret q))
local attribute [pp_using_anonymous_constructor] turing.TM1.cfg
/-- The relation between TM2 configurations and TM1 configurations of the TM2 emulator. -/
inductive tr_cfg : cfg₂ → cfg₁ → Prop
| mk {q v} {S : ∀ k, list (Γ k)} (L : list_blank (∀ k, option (Γ k))) :
(∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) →
tr_cfg ⟨q, v, S⟩ ⟨q.map normal, v, tape.mk' ∅ (add_bottom L)⟩
theorem tr_respects_aux₁ {k} (o q v) {S : list (Γ k)} {L : list_blank (∀ k, option (Γ k))}
(hL : L.map (proj k) = list_blank.mk (S.map some).reverse) (n ≤ S.length) :
reaches₀ (TM1.step tr)
⟨some (go k o q), v, (tape.mk' ∅ (add_bottom L))⟩
⟨some (go k o q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ :=
begin
induction n with n IH, {refl},
apply (IH (le_of_lt H)).tail,
rw iterate_succ_apply', simp only [TM1.step, TM1.step_aux, tr,
tape.mk'_nth_nat, tape.move_right_n_head, add_bottom_nth_snd,
option.mem_def],
rw [stk_nth_val _ hL, list.nth_le_nth], refl, rwa list.length_reverse
end
theorem tr_respects_aux₃ {q v} {L : list_blank (∀ k, option (Γ k))} (n) :
reaches₀ (TM1.step tr)
⟨some (ret q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩
⟨some (ret q), v, (tape.mk' ∅ (add_bottom L))⟩ :=
begin
induction n with n IH, {refl},
refine reaches₀.head _ IH,
rw [option.mem_def, TM1.step, tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat,
add_bottom_nth_succ_fst, TM1.step_aux, iterate_succ', tape.move_right_left], refl,
end
theorem tr_respects_aux {q v T k} {S : Π k, list (Γ k)}
(hT : ∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse)
(o : st_act k)
(IH : ∀ {v : σ} {S : Π (k : K), list (Γ k)} {T : list_blank (∀ k, option (Γ k))},
(∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) →
(∃ b, tr_cfg (TM2.step_aux q v S) b ∧
reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (tape.mk' ∅ (add_bottom T))) b)) :
∃ b, tr_cfg (TM2.step_aux (st_run o q) v S) b ∧
reaches (TM1.step tr) (TM1.step_aux (tr_normal (st_run o q))
v (tape.mk' ∅ (add_bottom T))) b :=
begin
simp only [tr_normal_run, step_run],
have hgo := tr_respects_aux₁ M o q v (hT k) _ (le_refl _),
obtain ⟨T', hT', hrun⟩ := tr_respects_aux₂ hT o,
have hret := tr_respects_aux₃ M _,
have := hgo.tail' rfl,
rw [tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd,
stk_nth_val _ (hT k), list.nth_len_le (le_of_eq (list.length_reverse _)),
option.is_none, cond, hrun, TM1.step_aux] at this,
obtain ⟨c, gc, rc⟩ := IH hT',
refine ⟨c, gc, (this.to₀.trans hret c (trans_gen.head' rfl _)).to_refl⟩,
rw [tr, TM1.step_aux, tape.mk'_head, add_bottom_head_fst],
exact rc,
end
local attribute [simp] respects TM2.step TM2.step_aux tr_normal
theorem tr_respects : respects (TM2.step M) (TM1.step tr) tr_cfg :=
λ c₁ c₂ h, begin
cases h with l v S L hT, clear h,
cases l, {constructor},
simp only [TM2.step, respects, option.map_some'],
suffices : ∃ b, _ ∧ reaches (TM1.step (tr M)) _ _,
from let ⟨b, c, r⟩ := this in ⟨b, c, trans_gen.head' rfl r⟩,
rw [tr],
revert v S L hT, refine stmt_st_rec _ _ _ _ _ (M l); intros,
{ exact tr_respects_aux M hT s @IH },
{ exact IH _ hT },
{ unfold TM2.step_aux tr_normal TM1.step_aux,
cases p v; [exact IH₂ _ hT, exact IH₁ _ hT] },
{ exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ },
{ exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ }
end
theorem tr_cfg_init (k) (L : list (Γ k)) :
tr_cfg (TM2.init k L) (TM1.init (tr_init k L)) :=
begin
rw (_ : TM1.init _ = _),
{ refine ⟨list_blank.mk (L.reverse.map $ λ a, update (default _) k (some a)), λ k', _⟩,
refine list_blank.ext (λ i, _),
rw [list_blank.map_mk, list_blank.nth_mk, list.inth, list.map_map, (∘),
list.nth_map, proj, pointed_map.mk_val],
by_cases k' = k,
{ subst k', simp only [function.update_same],
rw [list_blank.nth_mk, list.inth, ← list.map_reverse, list.nth_map] },
{ simp only [function.update_noteq h],
rw [list_blank.nth_mk, list.inth, list.map, list.reverse_nil, list.nth],
cases L.reverse.nth i; refl } },
{ rw [tr_init, TM1.init], dsimp only, congr; cases L.reverse; try {refl},
simp only [list.map_map, list.tail_cons, list.map], refl }
end
theorem tr_eval_dom (k) (L : list (Γ k)) :
(TM1.eval tr (tr_init k L)).dom ↔ (TM2.eval M k L).dom :=
tr_eval_dom tr_respects (tr_cfg_init _ _)
theorem tr_eval (k) (L : list (Γ k)) {L₁ L₂}
(H₁ : L₁ ∈ TM1.eval tr (tr_init k L))
(H₂ : L₂ ∈ TM2.eval M k L) :
∃ (S : ∀ k, list (Γ k)) (L' : list_blank (∀ k, option (Γ k))),
add_bottom L' = L₁ ∧
(∀ k, L'.map (proj k) = list_blank.mk ((S k).map some).reverse) ∧
S k = L₂ :=
begin
obtain ⟨c₁, h₁, rfl⟩ := (part.mem_map_iff _).1 H₁,
obtain ⟨c₂, h₂, rfl⟩ := (part.mem_map_iff _).1 H₂,
obtain ⟨_, ⟨q, v, S, L', hT⟩, h₃⟩ := tr_eval (tr_respects M) (tr_cfg_init M k L) h₂,
cases part.mem_unique h₁ h₃,
exact ⟨S, L', by simp only [tape.mk'_right₀], hT, rfl⟩
end
/-- The support of a set of TM2 states in the TM2 emulator. -/
noncomputable def tr_supp (S : finset Λ) : finset Λ' :=
S.bUnion (λ l, insert (normal l) (tr_stmts₁ (M l)))
theorem tr_supports {S} (ss : TM2.supports M S) :
TM1.supports tr (tr_supp S) :=
⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert.2 $ or.inl rfl⟩,
λ l' h, begin
suffices : ∀ q (ss' : TM2.supports_stmt S q)
(sub : ∀ x ∈ tr_stmts₁ q, x ∈ tr_supp M S),
TM1.supports_stmt (tr_supp M S) (tr_normal q) ∧
(∀ l' ∈ tr_stmts₁ q, TM1.supports_stmt (tr_supp M S) (tr M l')),
{ rcases finset.mem_bUnion.1 h with ⟨l, lS, h⟩,
have := this _ (ss.2 l lS) (λ x hx,
finset.mem_bUnion.2 ⟨_, lS, finset.mem_insert_of_mem hx⟩),
rcases finset.mem_insert.1 h with rfl | h;
[exact this.1, exact this.2 _ h] },
clear h l', refine stmt_st_rec _ _ _ _ _; intros,
{ -- stack op
rw TM2to1.supports_run at ss',
simp only [TM2to1.tr_stmts₁_run, finset.mem_union,
finset.mem_insert, finset.mem_singleton] at sub,
have hgo := sub _ (or.inl $ or.inl rfl),
have hret := sub _ (or.inl $ or.inr rfl),
cases IH ss' (λ x hx, sub x $ or.inr hx) with IH₁ IH₂,
refine ⟨by simp only [tr_normal_run, TM1.supports_stmt]; intros; exact hgo, λ l h, _⟩,
rw [tr_stmts₁_run] at h,
simp only [TM2to1.tr_stmts₁_run, finset.mem_union,
finset.mem_insert, finset.mem_singleton] at h,
rcases h with ⟨rfl | rfl⟩ | h,
{ unfold TM1.supports_stmt TM2to1.tr,
rcases s with _|_|_,
{ exact ⟨λ _ _, hret, λ _ _, hgo⟩ },
{ exact ⟨λ _ _, hret, λ _ _, hgo⟩ },
{ exact ⟨⟨λ _ _, hret, λ _ _, hret⟩, λ _ _, hgo⟩ } },
{ unfold TM1.supports_stmt TM2to1.tr,
exact ⟨IH₁, λ _ _, hret⟩ },
{ exact IH₂ _ h } },
{ -- load
unfold TM2to1.tr_stmts₁ at ss' sub ⊢,
exact IH ss' sub },
{ -- branch
unfold TM2to1.tr_stmts₁ at sub,
cases IH₁ ss'.1 (λ x hx, sub x $ finset.mem_union_left _ hx) with IH₁₁ IH₁₂,
cases IH₂ ss'.2 (λ x hx, sub x $ finset.mem_union_right _ hx) with IH₂₁ IH₂₂,
refine ⟨⟨IH₁₁, IH₂₁⟩, λ l h, _⟩,
rw [tr_stmts₁] at h,
rcases finset.mem_union.1 h with h | h;
[exact IH₁₂ _ h, exact IH₂₂ _ h] },
{ -- goto
rw tr_stmts₁, unfold TM2to1.tr_normal TM1.supports_stmt,
unfold TM2.supports_stmt at ss',
exact ⟨λ _ v, finset.mem_bUnion.2 ⟨_, ss' v, finset.mem_insert_self _ _⟩, λ _, false.elim⟩ },
{ exact ⟨trivial, λ _, false.elim⟩ } -- halt
end⟩
end
end TM2to1
end turing
|
b4de676630d43c519d8fc9f1876135eb4fee1a93 | 37a833c924892ee3ecb911484775a6d6ebb8984d | /src/category_theory/examples/rings/others.lean | 4880b3729c1d897792eeaf53fc2c1f6f966a133f | [] | no_license | silky/lean-category-theory | 28126e80564a1f99e9c322d86b3f7d750da0afa1 | 0f029a2364975f56ac727d31d867a18c95c22fd8 | refs/heads/master | 1,589,555,811,646 | 1,554,673,665,000 | 1,554,673,665,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,498 | lean | -- import ring_theory.ideals
-- import linear_algebra.quotient_module
-- import ..rings
-- import category_theory.limits
-- import category_theory.filtered
-- universes u v w
-- namespace category_theory.examples
-- open category_theory
-- open category_theory.limits
-- variables {α : Type v}
-- def coequalizer_ideal {R S : CommRing} (f g : R ⟶ S) : set S.1 :=
-- span (set.range (λ x : R, f x - g x))
-- instance {R S : CommRing} (f g : R ⟶ S) : is_ideal (coequalizer_ideal f g) := sorry
-- local attribute [instance] classical.prop_decidable
-- instance : has_coequalizers.{v+1 v} CommRing :=
-- { cofork := λ R S f g,
-- { X := { α := quotient_ring.quotient (coequalizer_ideal f g) },
-- π := ⟨ quotient_ring.mk, by apply_instance ⟩,
-- w' := sorry /- almost there: -/
-- /- begin
-- ext, dsimp, apply quotient.sound, fsplit,
-- exact finsupp.single 1 (f.map x - g.map x), obviously,
-- sorry, sorry
-- end -/ },
-- is_coequalizer := λ R S f g,
-- { desc := λ s,
-- { val := sorry,
-- property := sorry, },
-- fac' := sorry,
-- uniq' := sorry }
-- }
-- instance : has_colimits.{v+1 v} CommRing := sorry
-- section
-- variables {J : Type v} [𝒥 : small_category J] [filtered.{v v} J]
-- include 𝒥
-- -- This is stupid; we just need one map in the condition.
-- def matching (F : J ⥤ CommRing) (a b : Σ j : J, (F j).1) : Prop :=
-- ∃ (j : J) (f_a : a.1 ⟶ j) (f_b : b.1 ⟶ j),
-- (F.map f_a) a.2 = (F.map f_b) b.2
-- def filtered_colimit (F : J ⥤ CommRing) :=
-- @quot (Σ j : J, (F j).1) (matching F)
-- local attribute [elab_with_expected_type] quot.lift
-- def filtered_colimit.zero (F : J ⥤ CommRing) : filtered_colimit F :=
-- quot.mk _ ⟨ filtered.default.{v v} J, 0 ⟩
-- -- TODO do this in two steps.
-- def filtered_colimit.add (F : J ⥤ CommRing) (x y : filtered_colimit F) : filtered_colimit F :=
-- quot.lift (λ p : Σ j, (F j).1,
-- quot.lift (λ q : Σ j, (F j).1,
-- quot.mk _ (begin
-- have s := filtered.obj_bound.{v v} p.1 q.1,
-- exact ⟨ s.X, ((F.map s.ι₁) p.2) + ((F.map s.ι₂) q.2) ⟩
-- end : Σ j, (F j).1))
-- (λ q q' (r : matching F q q'), @quot.sound _ (matching F) _ _
-- begin
-- dunfold matching,
-- dsimp,
-- dsimp [matching] at r,
-- rcases r with ⟨j, f_a, f_b, e⟩,
-- /- this is messy, but doable -/
-- sorry
-- end))
-- (λ p p' (r : matching F p p'), funext $ λ q, begin dsimp, /- no idea -/ sorry end) x y
-- def filtered_colimit_is_comm_ring (F : J ⥤ CommRing) : comm_ring (filtered_colimit F) :=
-- { add := filtered_colimit.add F,
-- neg := sorry,
-- mul := sorry,
-- zero := filtered_colimit.zero F,
-- one := sorry,
-- add_comm := sorry,
-- add_assoc := sorry,
-- zero_add := sorry,
-- add_zero := sorry,
-- add_left_neg := sorry,
-- mul_comm := sorry,
-- mul_assoc := sorry,
-- one_mul := sorry,
-- mul_one := sorry,
-- left_distrib := sorry,
-- right_distrib := sorry }
-- end
-- -- instance : has_filtered_colimits.{v+1 v} CommRing :=
-- -- { colimit := λ J 𝒥 f F,
-- -- begin
-- -- resetI, exact
-- -- { X := { α := filtered_colimit F, str := filtered_colimit_is_comm_ring F },
-- -- ι := λ j, { val := λ x, begin sorry end,
-- -- property := sorry },
-- -- w' := sorry, }
-- -- end,
-- -- is_colimit := sorry }
-- end category_theory.examples |
bb27fce4d13d7860a7d4a6be6a2af9ed11dcad99 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/346.lean | 2c1be478532454d37cf1d575d8b8e7f0a787bf32 | [
"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 | 144 | lean | inductive SomeType
| x : SomeType
namespace SomeType
def a : SomeType := SomeType.x
end SomeType
#eval SomeType.b
def f (x : Nat) :=
x.z
|
537b524da4186ef87c5ccd427070dcf6159bbb58 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/t5.lean | 750632b64f1819cdfdf92636f0dfc4c3b592ba8b | [
"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 | 287 | lean | constant N : Type.{1}
constant f : N → N
constant a : N
noncomputable definition g (a : N) : N := f a
check g
namespace foo
noncomputable definition h : N := f a
check h
private noncomputable definition q : N := f a
check q
end foo
check foo.h
check q -- Error q is now hidden
|
f7f3a9e3216497919c83db7ff3eb3f8a27798ba2 | f00cc9c04d77f9621aa57d1406d35c522c3ff82c | /library/init/data/nat/bitwise.lean | 8ceea3c316f7dcb55129435f35e7da6a446db773 | [
"Apache-2.0"
] | permissive | shonfeder/lean | 444c66a74676d74fb3ef682d88cd0f5c1bf928a5 | 24d5a1592d80cefe86552d96410c51bb07e6d411 | refs/heads/master | 1,619,338,440,905 | 1,512,842,340,000 | 1,512,842,340,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,847 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
prelude
import init.data.nat.lemmas init.meta.well_founded_tactics
universe u
namespace nat
def bodd_div2 : ℕ → bool × ℕ
| 0 := (ff, 0)
| (succ n) :=
match bodd_div2 n with
| (ff, m) := (tt, m)
| (tt, m) := (ff, succ m)
end
def div2 (n : ℕ) : ℕ := (bodd_div2 n).2
def bodd (n : ℕ) : bool := (bodd_div2 n).1
@[simp] lemma bodd_zero : bodd 0 = ff := rfl
@[simp] lemma bodd_one : bodd 1 = tt := rfl
@[simp] lemma bodd_two : bodd 2 = ff := rfl
@[simp] lemma bodd_succ (n : ℕ) : bodd (succ n) = bnot (bodd n) :=
by unfold bodd bodd_div2; cases bodd_div2 n; cases fst; refl
@[simp] lemma bodd_add (m n : ℕ) : bodd (m + n) = bxor (bodd m) (bodd n) :=
begin
induction n with n IH,
{ simp, cases bodd m; refl },
{ simp [IH], cases bodd m; cases bodd n; refl }
end
@[simp] lemma bodd_mul (m n : ℕ) : bodd (m * n) = bodd m && bodd n :=
begin
induction n with n IH,
{ simp, cases bodd m; refl },
{ simp [mul_succ, IH], cases bodd m; cases bodd n; refl }
end
lemma mod_two_of_bodd (n : ℕ) : n % 2 = cond (bodd n) 1 0 :=
begin
have := congr_arg bodd (mod_add_div n 2),
simp [bnot] at this,
rw [show ∀ b, ff && b = ff, by intros; cases b; refl,
show ∀ b, bxor b ff = b, by intros; cases b; refl] at this,
rw [← this],
cases mod_two_eq_zero_or_one n with h h; rw h; refl
end
@[simp] lemma div2_zero : div2 0 = 0 := rfl
@[simp] lemma div2_one : div2 1 = 0 := rfl
@[simp] lemma div2_two : div2 2 = 1 := rfl
@[simp] lemma div2_succ (n : ℕ) : div2 (succ n) = cond (bodd n) (succ (div2 n)) (div2 n) :=
by unfold bodd div2 bodd_div2; cases bodd_div2 n; cases fst; refl
local attribute [simp] add_comm add_assoc add_left_comm mul_comm mul_assoc mul_left_comm
theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n
| 0 := rfl
| (succ n) := begin
simp,
refine eq.trans _ (congr_arg succ (bodd_add_div2 n)),
cases bodd n; simp [cond, bnot],
{ rw add_comm; refl },
{ rw [succ_mul, add_comm 1] }
end
theorem div2_val (n) : div2 n = n / 2 :=
by refine eq_of_mul_eq_mul_left dec_trivial
(nat.add_left_cancel (eq.trans _ (mod_add_div n 2).symm));
rw [mod_two_of_bodd, bodd_add_div2]
def bit (b : bool) : ℕ → ℕ := cond b bit1 bit0
lemma bit0_val (n : nat) : bit0 n = 2 * n := (two_mul _).symm
lemma bit1_val (n : nat) : bit1 n = 2 * n + 1 := congr_arg succ (bit0_val _)
lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 :=
by { cases b, apply bit0_val, apply bit1_val }
lemma bit_decomp (n : nat) : bit (bodd n) (div2 n) = n :=
(bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _
def bit_cases_on {C : nat → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n :=
by rw [← bit_decomp n]; apply h
@[simp] lemma bit_zero : bit ff 0 = 0 := rfl
def shiftl' (b : bool) (m : ℕ) : ℕ → ℕ
| 0 := m
| (n+1) := bit b (shiftl' n)
def shiftl : ℕ → ℕ → ℕ := shiftl' ff
@[simp] theorem shiftl_zero (m) : shiftl m 0 = m := rfl
@[simp] theorem shiftl_succ (m n) : shiftl m (n + 1) = bit0 (shiftl m n) := rfl
def shiftr : ℕ → ℕ → ℕ
| m 0 := m
| m (n+1) := div2 (shiftr m n)
def test_bit (m n : ℕ) : bool := bodd (shiftr m n)
def binary_rec {C : nat → Sort u} (z : C 0) (f : ∀ b n, C n → C (bit b n)) : Π n, C n
| n := if n0 : n = 0 then by rw n0; exact z else let n' := div2 n in
have n' < n, begin
change div2 n < n, rw div2_val,
apply (div_lt_iff_lt_mul _ _ (succ_pos 1)).2,
have := nat.mul_lt_mul_of_pos_left (lt_succ_self 1)
(lt_of_le_of_ne (zero_le _) (ne.symm n0)),
rwa mul_one at this
end,
by rw [← show bit (bodd n) n' = n, from bit_decomp n]; exact
f (bodd n) n' (binary_rec n')
def size : ℕ → ℕ := binary_rec 0 (λ_ _, succ)
def bits : ℕ → list bool := binary_rec [] (λb _ IH, b :: IH)
def bitwise (f : bool → bool → bool) : ℕ → ℕ → ℕ :=
binary_rec
(λn, cond (f ff tt) n 0)
(λa m Ia, binary_rec
(cond (f tt ff) (bit a m) 0)
(λb n _, bit (f a b) (Ia n)))
def lor : ℕ → ℕ → ℕ := bitwise bor
def land : ℕ → ℕ → ℕ := bitwise band
def ldiff : ℕ → ℕ → ℕ := bitwise (λ a b, a && bnot b)
def lxor : ℕ → ℕ → ℕ := bitwise bxor
@[simp] lemma binary_rec_zero {C : nat → Sort u} (z : C 0) (f : ∀ b n, C n → C (bit b n)) :
binary_rec z f 0 = z :=
by {rw [binary_rec], refl}
/- bitwise ops -/
lemma bodd_bit (b n) : bodd (bit b n) = b :=
by rw bit_val; simp; cases b; cases bodd n; refl
lemma div2_bit (b n) : div2 (bit b n) = n :=
by rw [bit_val, div2_val, add_comm, add_mul_div_left, div_eq_of_lt, zero_add];
cases b; exact dec_trivial
lemma shiftl'_add (b m n) : ∀ k, shiftl' b m (n + k) = shiftl' b (shiftl' b m n) k
| 0 := rfl
| (k+1) := congr_arg (bit b) (shiftl'_add k)
lemma shiftl_add : ∀ m n k, shiftl m (n + k) = shiftl (shiftl m n) k := shiftl'_add _
lemma shiftr_add (m n) : ∀ k, shiftr m (n + k) = shiftr (shiftr m n) k
| 0 := rfl
| (k+1) := congr_arg div2 (shiftr_add k)
lemma shiftl'_sub (b m) : ∀ {n k}, k ≤ n → shiftl' b m (n - k) = shiftr (shiftl' b m n) k
| n 0 h := rfl
| (n+1) (k+1) h := begin
simp [shiftl'], rw [add_comm, shiftr_add],
simp [shiftr, div2_bit],
apply shiftl'_sub (nat.le_of_succ_le_succ h)
end
lemma shiftl_sub : ∀ m {n k}, k ≤ n → shiftl m (n - k) = shiftr (shiftl m n) k := shiftl'_sub _
lemma shiftl_eq_mul_pow (m) : ∀ n, shiftl m n = m * 2 ^ n
| 0 := (mul_one _).symm
| (k+1) := show bit0 (shiftl m k) = m * (2^k * 2), by rw [bit0_val, shiftl_eq_mul_pow]; simp
lemma shiftl'_tt_eq_mul_pow (m) : ∀ n, shiftl' tt m n + 1 = (m + 1) * 2 ^ n
| 0 := by simp [shiftl, shiftl']
| (k+1) := begin
change bit1 (shiftl' tt m k) + 1 = (m + 1) * (2^k * 2),
rw bit1_val,
change 2 * (shiftl' tt m k + 1) = _,
rw shiftl'_tt_eq_mul_pow; simp
end
lemma one_shiftl (n) : shiftl 1 n = 2 ^ n :=
(shiftl_eq_mul_pow _ _).trans (one_mul _)
@[simp] lemma zero_shiftl (n) : shiftl 0 n = 0 :=
(shiftl_eq_mul_pow _ _).trans (zero_mul _)
lemma shiftr_eq_div_pow (m) : ∀ n, shiftr m n = m / 2 ^ n
| 0 := (nat.div_one _).symm
| (k+1) := (congr_arg div2 (shiftr_eq_div_pow k)).trans $
by rw [div2_val, nat.div_div_eq_div_mul]; refl
@[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 :=
(shiftr_eq_div_pow _ _).trans (nat.zero_div _)
@[simp] lemma test_bit_zero (b n) : test_bit (bit b n) 0 = b := bodd_bit _ _
lemma test_bit_succ (m b n) : test_bit (bit b n) (succ m) = test_bit n m :=
have bodd (shiftr (shiftr (bit b n) 1) m) = bodd (shiftr n m),
by dsimp [shiftr]; rw div2_bit,
by rw [← shiftr_add, add_comm] at this; exact this
lemma binary_rec_eq {C : nat → Sort u} {z : C 0} {f : ∀ b n, C n → C (bit b n)}
(h : f ff 0 z = z) (b n) :
binary_rec z f (bit b n) = f b n (binary_rec z f n) :=
begin
rw [binary_rec],
by_cases (bit b n = 0) with h',
{simp [dif_pos h'],
generalize : binary_rec._main._pack._proof_1 (bit b n) h' = e,
revert e,
have bf := bodd_bit b n,
have n0 := div2_bit b n,
rw h' at bf n0,
simp at bf n0,
rw [← bf, ← n0, binary_rec_zero],
intros, exact h.symm },
{simp [dif_neg h'],
generalize : binary_rec._main._pack._proof_2 (bit b n) = e,
revert e,
rw [bodd_bit, div2_bit],
intros, refl}
end
lemma bitwise_bit_aux {f : bool → bool → bool} (h : f ff ff = ff) :
@binary_rec (λ_, ℕ)
(cond (f tt ff) (bit ff 0) 0)
(λ b n _, bit (f ff b) (cond (f ff tt) n 0)) =
λ (n : ℕ), cond (f ff tt) n 0 :=
begin
funext n,
apply bit_cases_on n, intros b n, rw [binary_rec_eq],
{ cases b; try {rw h}; induction fft : f ff tt; simp [cond]; refl },
{ rw [h, show cond (f ff tt) 0 0 = 0, by cases f ff tt; refl,
show cond (f tt ff) (bit ff 0) 0 = 0, by cases f tt ff; refl]; refl }
end
@[simp] lemma bitwise_zero_left (f : bool → bool → bool) (n) :
bitwise f 0 n = cond (f ff tt) n 0 :=
by unfold bitwise; rw [binary_rec_zero]
@[simp] lemma bitwise_zero_right (f : bool → bool → bool) (h : f ff ff = ff) (m) :
bitwise f m 0 = cond (f tt ff) m 0 :=
by unfold bitwise; apply bit_cases_on m; intros;
rw [binary_rec_eq, binary_rec_zero]; exact bitwise_bit_aux h
@[simp] lemma bitwise_zero (f : bool → bool → bool) :
bitwise f 0 0 = 0 :=
by rw bitwise_zero_left; cases f ff tt; refl
@[simp] lemma bitwise_bit {f : bool → bool → bool} (h : f ff ff = ff) (a m b n) :
bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) :=
begin
unfold bitwise,
rw [binary_rec_eq, binary_rec_eq],
{ induction ftf : f tt ff; dsimp [cond],
rw [show f a ff = ff, by cases a; assumption],
apply @congr_arg _ _ _ 0 (bit ff), tactic.swap,
rw [show f a ff = a, by cases a; assumption],
apply congr_arg (bit a),
all_goals {
apply bit_cases_on m, intros a m,
rw [binary_rec_eq, binary_rec_zero],
rw [← bitwise_bit_aux h, ftf], refl } },
{ exact bitwise_bit_aux h }
end
theorem bitwise_swap {f : bool → bool → bool} (h : f ff ff = ff) :
bitwise (function.swap f) = function.swap (bitwise f) :=
begin
funext m n, revert n,
dsimp [function.swap],
apply binary_rec _ (λ a m' IH, _) m; intro n,
{ rw [bitwise_zero_left, bitwise_zero_right], exact h },
apply bit_cases_on n; intros b n',
rw [bitwise_bit, bitwise_bit, IH]; exact h
end
@[simp] lemma lor_bit : ∀ (a m b n),
lor (bit a m) (bit b n) = bit (a || b) (lor m n) := bitwise_bit rfl
@[simp] lemma land_bit : ∀ (a m b n),
land (bit a m) (bit b n) = bit (a && b) (land m n) := bitwise_bit rfl
@[simp] lemma ldiff_bit : ∀ (a m b n),
ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := bitwise_bit rfl
@[simp] lemma lxor_bit : ∀ (a m b n),
lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := bitwise_bit rfl
@[simp] lemma test_bit_bitwise {f : bool → bool → bool} (h : f ff ff = ff) (m n k) :
test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) :=
begin
revert m n; induction k with k IH; intros m n;
apply bit_cases_on m; intros a m';
apply bit_cases_on n; intros b n';
rw bitwise_bit h,
{ simp [test_bit_zero] },
{ simp [test_bit_succ, IH] }
end
@[simp] lemma test_bit_lor : ∀ (m n k),
test_bit (lor m n) k = test_bit m k || test_bit n k := test_bit_bitwise rfl
@[simp] lemma test_bit_land : ∀ (m n k),
test_bit (land m n) k = test_bit m k && test_bit n k := test_bit_bitwise rfl
@[simp] lemma test_bit_ldiff : ∀ (m n k),
test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := test_bit_bitwise rfl
@[simp] lemma test_bit_lxor : ∀ (m n k),
test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := test_bit_bitwise rfl
end nat
|
861e15ee8aa10f2c00d8667efd6e89cc40d3ff77 | 86f6f4f8d827a196a32bfc646234b73328aeb306 | /examples/basics/unnamed_293.lean | 24aa28c667e7146230479a539c81fe4089273a38 | [] | no_license | jamescheuk91/mathematics_in_lean | 09f1f87d2b0dce53464ff0cbe592c568ff59cf5e | 4452499264e2975bca2f42565c0925506ba5dda3 | refs/heads/master | 1,679,716,410,967 | 1,613,957,947,000 | 1,613,957,947,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 237 | lean | import data.real.basic
variables a b : ℝ
-- BEGIN
example : (a + b) * (a + b) = a * a + 2 * (a * b) + b * b :=
begin
rw [mul_add, add_mul, add_mul],
rw [←add_assoc, add_assoc (a * a)],
rw [mul_comm b a, ←two_mul]
end
-- END |
a4a30bd8ba137a8a04f5c27332a3c74b77604092 | 3618c6e11aa822fd542440674dfb9a7b9921dba0 | /scratch/coprod/coproduct.lean | 41bb53b659a53a026e99a1045ffa6383db3ddc56 | [] | no_license | ChrisHughes24/single_relation | 99ceedcc02d236ce46d6c65d72caa669857533c5 | 057e157a59de6d0e43b50fcb537d66792ec20450 | refs/heads/master | 1,683,652,062,698 | 1,683,360,089,000 | 1,683,360,089,000 | 279,346,432 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,495 | lean | import tactic.equiv_rw tactic group_theory.subgroup group_theory.semidirect_product
universes u v w x y z
def mul_left {G : Type*} [group G] : G →* equiv.perm G :=
{ to_fun := λ g,
{ to_fun := λ h, g * h,
inv_fun := λ h, g⁻¹ * h,
left_inv := λ _, by simp [mul_assoc],
right_inv := λ _, by simp [mul_assoc] },
map_one' := by ext; simp,
map_mul' := λ _ _, by ext; simp [mul_assoc] }
@[simp] lemma coe_fn_mul_left {G : Type*} [group G] (g : G) : (⇑(mul_left g) : G → G) = (*) g := rfl
@[simp] lemma coe_fn_mul_left_symm {G : Type*} [group G] (g : G) : (⇑(mul_left g).symm : G → G) = (*) g⁻¹ := rfl
noncomputable theory
def reduced {ι : Type u} {G : ι → Type v} [Π i, group (G i)] (l : list (Σ i : ι, G i)) : Prop :=
l.chain' (λ a b, a.1 ≠ b.1) ∧ ∀ a : Σ i, G i, a ∈ l → a.2 ≠ 1
def coprod {ι : Type u} (G : ι → Type v) [Π i, group (G i)] : Type (max u v) :=
{ l : list (Σ i, G i) // reduced l }
--protected constant coprod.monoid [Π i, monoid (G i)] : monoid (coprod G)
protected constant coprod.group {ι : Type u} {G : ι → Type v} [Π i, group (G i)] : group (coprod G)
attribute [instance] coprod.group
namespace coprod
variables {ι : Type u} [decidable_eq ι] {G : ι → Type v} [Π i, group (G i)] {M : Type w}
variables {α : Type*} {β : Type*} {γ : Type*} [decidable_eq α] [decidable_eq β] [decidable_eq γ]
constant of : Π i : ι, G i →* coprod G
@[simp] lemma cons_eq_of_mul {l : list (Σ i, G i)}
(g : Σ i , G i) (h) :
@eq (coprod G) (⟨g :: l, h⟩ : coprod G) (of g.1 g.2 * ⟨l, sorry⟩) := sorry
@[simp] lemma append_eq_mul (l₁ l₂ : list (Σ i, G i)) (hl):
@eq (coprod G) ⟨l₁ ++ l₂, hl⟩ (⟨l₁, sorry⟩ * ⟨l₂, sorry⟩) := sorry
@[simp] lemma eta (w : coprod G) : (⟨w.1, w.2⟩ : coprod G) = w := by cases w; refl
constant lift [monoid M] (f : Π i, G i →* M) : coprod G →* M
protected constant decidable_eq : decidable_eq (coprod G)
attribute [instance] coprod.decidable_eq
@[simp] lemma lift_of [monoid M] (f : Π i, G i →* M) {i : ι} (g : G i) :
lift f (of i g) = f i g := sorry
@[simp] lemma lift_comp_of [monoid M] (f : Π i, G i →* M) (i : ι) :
(lift f).comp (of i) = f i :=
by ext; simp
@[elab_as_eliminator]
constant rec_on {C : coprod G → Sort*} (g : coprod G) (h1 : C 1)
(f : Π (g : Σ i, G i) (h : coprod G), C h → C (of g.1 g.2 * h)) : C g
@[simp] lemma rec_on_one {C : coprod G → Sort*} (h1 : C 1)
(f : Π (g : Σ i, G i) (h : coprod G), C h → C (of g.1 g.2 * h)) :
(rec_on (1 : coprod G) h1 f : C 1) = h1 := sorry
lemma rec_on_mul {C : coprod G → Sort*} {i j : ι} (hij : i ≠ j)
(g : G i) (h : G j) (x : coprod G) (hg1 : g ≠ 1) (hh1 : h ≠ 1)
(h1 : C 1) (f : Π (g : Σ i, G i) (h : coprod G), C h → C (of g.1 g.2 * h)) :
(rec_on (of i g * (of j h * x)) h1 f : C (of i g * (of j h * x))) =
f ⟨i, g⟩ (of j h * x) (rec_on (of j h * x) h1 f) := sorry
lemma hom_ext [monoid M] {f g : coprod G →* M}
(h : ∀ i : ι, f.comp (of i) = g.comp (of i)) : f = g :=
begin
ext,
refine coprod.rec_on x _ _,
{ simp },
{ rintros ⟨i, k⟩ x hfg,
have := monoid_hom.ext_iff.1 (h i) k,
erw [monoid_hom.map_mul, monoid_hom.map_mul, this, hfg], dsimp, refl, }
end
lemma mul_equiv_ext [monoid M] {f g : coprod G ≃* M}
(h : ∀ i : ι, f.to_monoid_hom.comp (of i) = g.to_monoid_hom.comp (of i)) :
f = g :=
sorry
end coprod
notation `C∞` := multiplicative ℤ
def ii : C∞ := show ℤ, from 1
def free_group (ι : Type*) := coprod (λ i : ι, multiplicative ℤ)
namespace free_group
variables {ι : Type u} [decidable_eq ι] {M : Type w}
variables {α : Type*} {β : Type*} {γ : Type*} [decidable_eq α] [decidable_eq β] [decidable_eq γ]
open function
instance : group (free_group ι) := coprod.group
instance : decidable_eq (free_group ι) := coprod.decidable_eq
def of (i : ι) : free_group ι := coprod.of i ii
def of' (i : ι) : multiplicative ℤ →* free_group ι := coprod.of i
@[simp] lemma cons_eq_of'_mul (l : list (Σ i : ι, multiplicative ℤ))
(g : Σ i : ι, multiplicative ℤ) (h) :
@eq (free_group ι) ⟨g :: l, h⟩ (of' g.1 g.2 * ⟨l, sorry⟩) :=
sorry
lemma of'_eq_pow (i : ι) (n : C∞) : of' i n = (of i) ^ n.to_add := sorry
@[simp] lemma append_eq_mul (l₁ l₂ : list (Σ i : ι, multiplicative ℤ)) (hl):
@eq (free_group ι) ⟨l₁ ++ l₂, hl⟩ (⟨l₁, sorry⟩ * ⟨l₂, sorry⟩) := sorry
@[simp] lemma nil_eq_one : @eq (free_group ι) ⟨[], sorry⟩ 1 := sorry
-- @[simp] lemma cons_eq_of'_mul' (l : list (Σ i : ι, multiplicative ℤ))
-- (hl : reduced l) (g : multiplicative ℤ) (h) :
-- (⟨⟨i, g⟩ :: l, h⟩ : free_group ι) = @has_mul.mul (free_group ι) _ (of' i g) ⟨l, hl⟩ := sorry
@[simp] lemma eta (w : free_group ι) : (⟨w.1, w.2⟩ : free_group ι) = w := by cases w; refl
lemma of_eq_of' (i : ι) : of i = of' i ii := rfl
def lift' [monoid M] (f : Π i : ι, multiplicative ℤ →* M) : free_group ι →* M :=
coprod.lift f
def lift [group M] (f : ι → M) : free_group ι →* M :=
lift' (λ i, gpowers_hom _ (f i))
@[simp] lemma lift'_of' [monoid M] (f : Π i : ι, multiplicative ℤ →* M) (i : ι) (n : multiplicative ℤ) :
lift' f (of' i n) = f i n := by simp [lift', of']
@[simp] lemma lift_of [group M] (f : Π i : ι, M) (i : ι) :
lift f (of i) = f i := by simp [lift, of_eq_of', gpowers_hom, ii,
multiplicative.to_add]
@[simp] lemma lift'_comp_of' [monoid M] (f : Π i : ι, multiplicative ℤ →* M) (i : ι) :
(lift' f).comp (of' i) = f i := by ext; simp
@[elab_as_eliminator]
def rec_on' {C : free_group ι → Sort*} (g : free_group ι) (h1 : C 1)
(f : Π (g : Σ i, multiplicative ℤ) (h : free_group ι), C h → C (of' g.1 g.2 * h)) : C g :=
by exact coprod.rec_on g h1 f
@[simp] lemma rec_on'_one {C : free_group ι → Sort*} (h1 : C 1)
(f : Π (g : Σ i : ι, multiplicative ℤ) (h : free_group ι), C h → C (of' g.1 g.2 * h)) :
(rec_on' (1 : free_group ι) h1 f : C 1) = h1 := coprod.rec_on_one h1 f
lemma rec_on'_mul {C : free_group ι → Sort*} {i j : ι} (hij : i ≠ j)
(g h : ℤ) (x : free_group ι) (hg0 : g ≠ 0) (hh0 : h ≠ 0) (h1 : C 1)
(f : Π (g : Σ i : ι, multiplicative ℤ) (h : free_group ι), C h → C (of' g.1 g.2 * h)) :
(rec_on' (of' i g * (of' j h * x)) h1 f : C (of' i g * (of' j h * x))) =
f ⟨i, g⟩ (of' j h * x) (rec_on' (of' j h * x) h1 f) :=
coprod.rec_on_mul hij g h x hg0 hh0 h1 f
@[elab_as_eliminator]
def rec_on {C : free_group ι → Sort*} (g : free_group ι) (h1 : C 1)
(f : Π (i : ι) (h : free_group ι), C h → C (of i * h)) : C g :=
sorry
protected constant embedding (e : α ↪ β) : free_group α →* free_group β
@[simp] lemma embedding_id : free_group.embedding (embedding.refl α) = monoid_hom.id _ := sorry
@[simp] lemma embedding_trans (e₁ : α ↪ β) (e₂ : β ↪ γ) :
free_group.embedding (e₁.trans e₂) = (free_group.embedding e₂).comp (free_group.embedding e₁) := sorry
@[simp] lemma embedding_of' (e : α ↪ β) (a : α) (n : multiplicative ℤ) :
free_group.embedding e (of' a n) = of' (e a) n := sorry
protected constant equiv (e : α ≃ β) : free_group α ≃* free_group β
@[simp] lemma equiv_refl : free_group.equiv (equiv.refl α) = mul_equiv.refl _ := sorry
@[simp] lemma equiv_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) :
free_group.equiv (e₁.trans e₂) = (free_group.equiv e₁).trans (free_group.equiv e₂) := sorry
@[simp] lemma equiv_of' (e : α ≃ β) (a : α) (n : multiplicative ℤ) :
free_group.equiv e (of' a n) = of' (e a) n := sorry
lemma hom_ext [monoid M] {f g : free_group ι →* M}
(h : ∀ i, f (of i) = g (of i)) : f = g :=
coprod.hom_ext (λ i, monoid_hom.ext (λ x, sorry))
lemma mul_equiv_ext [monoid M] {f g : free_group ι ≃* M}
(h : ∀ i, f (of i) = g (of i)) : f = g :=
sorry
def exp_sum (i : ι) : free_group ι →* multiplicative ℤ :=
free_group.lift' (λ j, if i = j then monoid_hom.id _ else 1)
/-- `closure_var` is the group closure of a set of variables -/
def closure_var (T : set ι) : subgroup (free_group ι) :=
subgroup.closure (of '' T)
instance (T : set ι) [decidable_pred T] (g : free_group ι) : decidable (g ∈ closure_var T) := sorry
constant vars (w : free_group ι) : finset ι
end free_group
variables (G H : Type u) [group G] [group H] {M : Type*} [monoid M]
def bicoprod_group_aux (b : bool) :
group (cond b G H) := by cases b; dunfold cond; apply_instance
local attribute [instance] bicoprod_group_aux
def bicoprod := coprod (λ b : bool, cond b G H)
namespace bicoprod
infixr ` ⋆ `: 30 := bicoprod
instance : group (G ⋆ H) := coprod.group
variables {G H}
def inl : G →* G ⋆ H :=
@coprod.of bool _ (λ b, cond b G H) _ tt
def inr : H →* G ⋆ H :=
@coprod.of bool _ (λ b, cond b G H) _ ff
def lift (f : G →* M) (g : H →* M) : G ⋆ H →* M :=
coprod.lift (λ b, bool.rec_on b g f)
@[simp] lemma lift_comp_inl (f₁ : G →* M) (f₂ : H →* M) :
(lift f₁ f₂).comp inl = f₁ := coprod.lift_comp_of _ _
@[simp] lemma lift_comp_inr (f₁ : G →* M) (f₂ : H →* M) :
(lift f₁ f₂).comp inr = f₂ := coprod.lift_comp_of _ _
@[simp] lemma lift_inl (f₁ : G →* M) (f₂ : H →* M) (g : G) :
(lift f₁ f₂) (inl g) = f₁ g := coprod.lift_of _ _
@[simp] lemma lift_inr (f₁ : G →* M) (f₂ : H →* M) (h : H) :
(lift f₁ f₂) (inr h) = f₂ h := coprod.lift_of _ _
end bicoprod
|
da041628638028bc759b1055ff38e34472b6168a | a339bc2ac96174381fb610f4b2e1ba42df2be819 | /hott/types/unit.hlean | 31e4afd2ecf5ff9ae8811ddbb73096aeb804e881 | [
"Apache-2.0"
] | permissive | kalfsvag/lean2 | 25b2dccc07a98e5aa20f9a11229831f9d3edf2e7 | 4d4a0c7c53a9922c5f630f6f8ebdccf7ddef2cc7 | refs/heads/master | 1,610,513,122,164 | 1,483,135,198,000 | 1,483,135,198,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,384 | 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
Theorems about the unit type
-/
open is_equiv equiv option eq pointed is_trunc function
namespace unit
protected definition eta : Π(u : unit), ⋆ = u
| eta ⋆ := idp
definition unit_equiv_option_empty [constructor] : unit ≃ option empty :=
begin
fapply equiv.MK,
{ intro u, exact none},
{ intro e, exact star},
{ intro e, cases e, reflexivity, contradiction},
{ intro u, cases u, reflexivity},
end
-- equivalences involving unit and other type constructors are in the file
-- of the other constructor
/- pointed and truncated unit -/
definition punit [constructor] : Set* :=
pSet.mk' unit
notation `unit*` := punit
definition unit_arrow_eq {X : Type} (f : unit → X) : (λx, f ⋆) = f :=
by apply eq_of_homotopy; intro u; induction u; reflexivity
open funext
definition unit_arrow_eq_compose {X Y : Type} (g : X → Y) (f : unit → X) :
unit_arrow_eq (g ∘ f) = ap (λf, g ∘ f) (unit_arrow_eq f) :=
begin
apply eq_of_fn_eq_fn' apd10,
refine right_inv apd10 _ ⬝ _,
refine _ ⬝ ap apd10 (!compose_eq_of_homotopy)⁻¹,
refine _ ⬝ (right_inv apd10 _)⁻¹,
apply eq_of_homotopy, intro u, induction u, reflexivity
end
end unit
|
8fda5a200afe212c251624beb708f777290de363 | 92e157ec9825b5e4597a6d715a8928703bc8e3b2 | /src/mywork/lecture_2.lean | 50b2b151d631e04e00f8f7ff7906e8db6e19296e | [] | no_license | exb3dg/cs2120f21 | 9e566bc508762573c023d3e70f83cb839c199ec8 | 319b8bf0d63bf96437bf17970ce0198d0b3525cd | refs/heads/main | 1,692,970,909,568 | 1,634,584,540,000 | 1,634,584,540,000 | 399,947,025 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,558 | lean | /-
INFERENCE RULE #1/2: EQUALITY IS REFLEXIVE
Everything is equal to itself. A bit more formally,
if one is given a type, T, and a value, t, of this
type, then you may have a proof of t = t "for free."
-/
axiom eq_refl :
∀ (T : Type) -- if T is any type (of thing)
(t : T), -- and t is thing of that type, T
t = t -- the result type: proof of t = t
/-
Ok, you actually have to *apply* the axiom of reflexive equality.
-/
example : 1 = 1 := eq_refl ℕ 1 -- Our definition
example : 1 = 1 := @eq.refl ℕ 1 -- Lean, with inference turned off by @
example : 1 = 1 := eq.refl 1 -- Lean's definition with T=ℕ inferred
/-
INFERENCE RULE #2/2: SUBSTITUTION OF EQUALS FOR EQUALS
Given any type, T, of objects, and any *property*, P,
of objects of this type, if you know x has property P
(written as P x) and you know that x = y, then you can
deduce that y has property P.
-/
axiom eq_subst :
∀ (T : Type) -- if T is a type
(P : T → Prop) -- and P is a property of T objects
(x y : T) -- and x and y are T objects
(e : x = y) -- and you have a proof that x = y
(px : P x), -- and you have a proof that x has property P
P y -- then you can deduce (and get a proof) of P y
-- EXAMPLES
-- a proposition and a predicate
def eq_3_3 : Prop := 3 = 3
def eq_n_3 (n : ℕ) : Prop := n = 3
-- predicates applied to values yield propositions
#reduce eq_n_3 2
#reduce eq_n_3 3
#reduce eq_n_3 4
--
axioms
(T : Type) -- e.g., nat
(P : T → Prop) -- e.g., eq_n_3
(x y : T) -- arbitary nats
(e : x = y) -- a proof x = y
(px : P x) -- proof of is3 x
theorem deduction : P y :=
eq_subst T P x y e px -- e.g., proof is is3 y
/-
REFLEXIVITY OF EQUALITY
-/
/-
A binary relation is specified by a
two-place predicate. In other words,
you can think of it as a function that
takes two values and yields a proposition
about them. Equality is such a relation.
You can write x = y, but you can also
write eq x y to mean the same thing.
Writing it this way makes it clear
that equality takes two arguments
and returns a proposition.
Examples:
eq 3 4 -- the proposition that 3 = 4
eq 3 3 -- the proposition that 3 = 3
You can understand the following
general explanation by taking eq as
a possible relation in place of "R"
in the following.
-/
-- We've already assumed T can be any type
-- Next assume we have an arbitrary binary relation, R, on T
axiom R : T → T → Prop
-- here's a formal definition of what it means for R to be reflexive
def rel_reflexive := ∀ (x : T), (R x x)
def rel_symmetric := ∀ (x y : T), (R x y) → (R y x)
def rel_transitive :=
∀ (x y z : T), (R x y) → (R y z) → (R x z)
/-
So now, from only our two axioms, let's prove that
equality is not only reflexive, but also symmetric
and transitive!
-/
/-
Theorem: *equality is symmetric*
Proof: We'll *assume* the premises of the conjecture:
that T is a type; x and y are values of that type; and
it's true (and we have a proof, h) x = y. Now *in the
context* of these assumptions, we need to construct a
proof that y = x. We can do that by applying the axiom
of the substitutability of equals to the proposition
to be proved, using our proof of x = y as an argument,
to substitute y for x whereever x appears. The result
is that we must now only prove y = y. And that is done
by applying the axiom of reflexivity of equality.
-/
/-
Here's a formal proof. What's most important at this
point is that you be able to follow how the *context*
of the proof evolves as we make each of our "moves"
in the construction of the final proof. Use SHIFT +
CMD/CTRL + ENTER to open the Lean Information View,
which will present the evolving proof context, then
click on each line of the proof-constructing script
we've give you here to see how each move affects the
context.
-/
theorem eq_symm :
∀ (T : Type) (x y : T), x = y → y = x :=
begin
assume T,
assume x y,
assume h,
rw h,
-- rw applies eq.refl automatically to complete the proof
end
/-
TRANSITIVITY OF EQUALITY
If x, y, and z are objects of some type, T, and we
know (have proofs or axioms) that x = y and y = z,
then we can deduce (and have a proof) that x = z.
-/
theorem eq_trans :
∀ (T : Type)
(x y z : T)
(e1 : x = y)
(e2 : y = z),
x = z :=
begin
assume (T : Type), -- take as temporary axiom!
assume (x y z : T), -- another one: context!
assume (e1 : x = y),
assume (e2 : y = z),
rw e1,
rw e2, -- eq.refl applied automatically
end
|
93819382a6ca0b1b5cffcd8e36d4deeb9ac49d13 | 367134ba5a65885e863bdc4507601606690974c1 | /src/linear_algebra/direct_sum_module.lean | dad206486c9d4ad9abbbe9f5da7c5934fd7d0fed | [
"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 | 5,101 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
Direct sum of modules over commutative rings, indexed by a discrete type.
-/
import algebra.direct_sum
import linear_algebra.dfinsupp
/-!
# Direct sum of modules over commutative rings, indexed by a discrete type.
This file provides constructors for finite direct sums of modules.
It provides a construction of the direct sum using the universal property and proves
its uniqueness.
## Implementation notes
All of this file assumes that
* `R` is a commutative ring,
* `ι` is a discrete type,
* `S` is a finite set in `ι`,
* `M` is a family of `R` semimodules indexed over `ι`.
-/
universes u v w u₁
variables (R : Type u) [semiring R]
variables (ι : Type v) [dec_ι : decidable_eq ι] (M : ι → Type w)
variables [Π i, add_comm_monoid (M i)] [Π i, semimodule R (M i)]
include R
namespace direct_sum
open_locale direct_sum
variables {R ι M}
instance : semimodule R (⨁ i, M i) := dfinsupp.semimodule
instance {S : Type*} [semiring S] [Π i, semimodule S (M i)] [Π i, smul_comm_class R S (M i)] :
smul_comm_class R S (⨁ i, M i) := dfinsupp.smul_comm_class
instance {S : Type*} [semiring S] [has_scalar R S] [Π i, semimodule S (M i)]
[Π i, is_scalar_tower R S (M i)] :
is_scalar_tower R S (⨁ i, M i) := dfinsupp.is_scalar_tower
lemma smul_apply (b : R) (v : ⨁ i, M i) (i : ι) :
(b • v) i = b • (v i) := dfinsupp.smul_apply _ _ _
include dec_ι
variables R ι M
/-- Create the direct sum given a family `M` of `R` semimodules indexed over `ι`. -/
def lmk : Π s : finset ι, (Π i : (↑s : set ι), M i.val) →ₗ[R] (⨁ i, M i) :=
dfinsupp.lmk
/-- Inclusion of each component into the direct sum. -/
def lof : Π i : ι, M i →ₗ[R] (⨁ i, M i) :=
dfinsupp.lsingle
variables {ι M}
lemma single_eq_lof (i : ι) (b : M i) :
dfinsupp.single i b = lof R ι M i b := rfl
/-- Scalar multiplication commutes with direct sums. -/
theorem mk_smul (s : finset ι) (c : R) (x) : mk M s (c • x) = c • mk M s x :=
(lmk R ι M s).map_smul c x
/-- Scalar multiplication commutes with the inclusion of each component into the direct sum. -/
theorem of_smul (i : ι) (c : R) (x) : of M i (c • x) = c • of M i x :=
(lof R ι M i).map_smul c x
variables {R}
lemma support_smul [Π (i : ι) (x : M i), decidable (x ≠ 0)]
(c : R) (v : ⨁ i, M i) : (c • v).support ⊆ v.support := dfinsupp.support_smul _ _
variables {N : Type u₁} [add_comm_monoid N] [semimodule R N]
variables (φ : Π i, M i →ₗ[R] N)
variables (R ι N φ)
/-- The linear map constructed using the universal property of the coproduct. -/
def to_module : (⨁ i, M i) →ₗ[R] N :=
dfinsupp.lsum ℕ φ
variables {ι N φ}
/-- The map constructed using the universal property gives back the original maps when
restricted to each component. -/
@[simp] lemma to_module_lof (i) (x : M i) : to_module R ι N φ (lof R ι M i x) = φ i x :=
to_add_monoid_of (λ i, (φ i).to_add_monoid_hom) i x
variables (ψ : (⨁ i, M i) →ₗ[R] N)
/-- Every linear map from a direct sum agrees with the one obtained by applying
the universal property to each of its components. -/
theorem to_module.unique (f : ⨁ i, M i) : ψ f = to_module R ι N (λ i, ψ.comp $ lof R ι M i) f :=
to_add_monoid.unique ψ.to_add_monoid_hom f
variables {ψ} {ψ' : (⨁ i, M i) →ₗ[R] N}
theorem to_module.ext (H : ∀ i, ψ.comp (lof R ι M i) = ψ'.comp (lof R ι M i)) (f : ⨁ i, M i) :
ψ f = ψ' f :=
by rw dfinsupp.lhom_ext' H
/--
The inclusion of a subset of the direct summands
into a larger subset of the direct summands, as a linear map.
-/
def lset_to_set (S T : set ι) (H : S ⊆ T) :
(⨁ (i : S), M i) →ₗ (⨁ (i : T), M i) :=
to_module R _ _ $ λ i, lof R T (λ (i : subtype T), M i) ⟨i, H i.prop⟩
omit dec_ι
/-- The natural linear equivalence between `⨁ _ : ι, M` and `M` when `unique ι`. -/
protected def lid (M : Type v) (ι : Type* := punit) [add_comm_monoid M] [semimodule R M]
[unique ι] :
(⨁ (_ : ι), M) ≃ₗ M :=
{ .. direct_sum.id M ι,
.. to_module R ι M (λ i, linear_map.id) }
variables (ι M)
/-- The projection map onto one component, as a linear map. -/
def component (i : ι) : (⨁ i, M i) →ₗ[R] M i :=
dfinsupp.lapply i
variables {ι M}
lemma apply_eq_component (f : ⨁ i, M i) (i : ι) :
f i = component R ι M i f := rfl
@[ext] lemma ext {f g : ⨁ i, M i}
(h : ∀ i, component R ι M i f = component R ι M i g) : f = g :=
dfinsupp.ext h
lemma ext_iff {f g : ⨁ i, M i} : f = g ↔
∀ i, component R ι M i f = component R ι M i g :=
⟨λ h _, by rw h, ext R⟩
include dec_ι
@[simp] lemma lof_apply (i : ι) (b : M i) : ((lof R ι M i) b) i = b :=
dfinsupp.single_eq_same
@[simp] lemma component.lof_self (i : ι) (b : M i) :
component R ι M i ((lof R ι M i) b) = b :=
lof_apply R i b
lemma component.of (i j : ι) (b : M j) :
component R ι M i ((lof R ι M j) b) =
if h : j = i then eq.rec_on h b else 0 :=
dfinsupp.single_apply
end direct_sum
|
5c1130cd86de118f324cfc1c2b5ccf2bbb4c8f01 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/data/examples/depchoice.lean | 4dd12d1ffed899779d84c378002409bc537a7153 | [
"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 | 3,080 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import data.encodable
open nat encodable
/-
In mathematics, the axiom of dependent choice is a weak form of the axiom of choice that is
sufficient to develop most of real analysis. See http://en.wikipedia.org/wiki/Axiom_of_dependent_choice.
We can state it as follows:
-/
definition dependent_choice {A : Type} (R : A → A → Prop) :=
(∀ a : A, ∃ b : A, R a b) → (∀ a : A, ∃ f : nat → A, f 0 = a ∧ ∀ n, R (f n) (f (n+1)))
/-
If A is an encodable type, and R is a decidable relation, we can prove (dependent_choice R) using the
constructive choice function "choose"
-/
section depchoice
parameters {A : Type} {R : A → A → Prop}
parameters [encA : encodable A] [decR : decidable_rel R]
include encA decR
local infix `~` := R
private definition f_aux (a : A) (H : ∀ a, ∃ b, a ~ b) : nat → A
| 0 := a
| (n+1) := choose (H (f_aux n))
theorem dependent_choice_of_encodable_of_decidable : dependent_choice R :=
assume H : ∀ a, ∃ b, a ~ b,
take a : A,
let f : nat → A := f_aux a H in
have f_zero : f 0 = a, from rfl,
have R_seq : ∀ n, f n ~ f (n+1), from
take n, show f n ~ choose (H (f n)), from !choose_spec,
exists.intro f (and.intro f_zero R_seq)
/-
The following slightly stronger version can be proved, where we also "return" the constructed function f.
We just have to use Σ instead of ∃, and use Σ-constructor instead of exists.intro.
Recall that ⟨f, H⟩ is notation for (sigma.mk f H)
-/
theorem stronger_dependent_choice_of_encodable_of_decidable
: (∀ a, ∃ b, R a b) → (∀ a, Σ f, f (0:nat) = a ∧ ∀ n, f n ~ f (n+1)) :=
assume H : ∀ a, ∃ b, a ~ b,
take a : A,
let f : nat → A := f_aux a H in
have f_zero : f 0 = a, from rfl,
have R_seq : ∀ n, f n ~ f (n+1), from
take n, show f n ~ choose (H (f n)), from !choose_spec,
⟨f, and.intro f_zero R_seq⟩
end depchoice
/-
If we encode dependent_choice using Σ instead of ∃.
Then, we can prove this version without using any extra hypothesis (e.g., A is encodable or R is decidable).
The function f can be constructed directly from the hypothesis: ∀ a : A, Σ b : A, R a b
because Σ "carries" the witness 'b'. That is, we don't have to search for anything using "choose".
-/
open sigma.ops
section sigma_depchoice
parameters {A : Type} {R : A → A → Prop}
local infix `~` := R
private definition f_aux (a : A) (H : ∀ a, Σ b, a ~ b) : nat → A
| 0 := a
| (n+1) := (H (f_aux n)).1
theorem sigma_dependent_choice : (∀ a, Σ b, R a b) → (∀ a, Σ f, f (0:nat) = a ∧ ∀ n, f n ~ f (n+1)) :=
assume H : ∀ a, Σ b, a ~ b,
take a : A,
let f : nat → A := f_aux a H in
have f_zero : f 0 = a, from rfl,
have R_seq : ∀ n, f n ~ f (n+1), from take n, (H (f n)).2,
⟨f, and.intro f_zero R_seq⟩
end sigma_depchoice
|
09544934245b22bdbca4ebb82d9cbc4bafab4522 | 67190c9aacc0cac64fb4463d93e84c696a5be896 | /Lists of exercises/List 3/HAM-LucasDomingues.lean | c8a6e1a34a3c7263600140eb711d3a3e23e4e176 | [] | no_license | lucasresck/Discrete-Mathematics | ffbaf55943e7ce2c7bc50cef7e3ef66a0212f738 | 0a08081c5f393e5765259d3f1253c3a6dd043dac | refs/heads/master | 1,596,627,857,734 | 1,573,411,500,000 | 1,573,411,500,000 | 212,489,764 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,730 | lean | -- Reduction of Hamiltonian path to SAT problem
-- My graph is G = {(1, 2), (1, 3), (1, 4), (2, 3)}
-- x_ij means the ith position of Hamiltonian path is occupied by node j
variables x11 x12 x13 x14
x21 x22 x23 x24
x31 x32 x33 x34
x41 x42 x43 x44 : Prop
-- Any path:
variables path: ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧
x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧
¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44
-- Now I have to show that this path satisfies (or not) the conditions of a Hamiltonian path.
-- Every node needs to appear in the path:
theorem node_1_in_the_path (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) : x11 ∨ x21 ∨ x31 ∨ x41 :=
or.inr (or.inl path.right.right.right.right.left)
theorem node_2_in_the_path (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) : x12 ∨ x22 ∨ x32 ∨ x42 :=
or.inr (or.inr (or.inl path.right.right.right.right.right.right.right.right.right.left))
theorem node_3_in_the_path (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) : x13 ∨ x23 ∨ x33 ∨ x43 :=
or.inr (or.inr (or.inr path.right.right.right.right.right.right.right.right.right.right.right.right.right.right.left))
theorem node_4_in_the_path (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) : x14 ∨ x24 ∨ x34 ∨ x44 :=
or.inl path.right.right.right.left
-- No node appears twice in the path:
theorem node_1_not_twice (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) :
(¬ x11 ∨ ¬ x21) ∧ (¬ x11 ∨ ¬ x31) ∧ (¬ x11 ∨ ¬ x41) ∧
(¬ x21 ∨ ¬ x31) ∧ (¬ x21 ∨ ¬ x41) ∧ (¬ x31 ∨ ¬ x41) :=
have h₁ : ¬ x11, from path.left,
have h₂ : ¬ x31, from path.right.right.right.right.right.right.right.right.left,
have h₃ : ¬ x41, from path.right.right.right.right.right.right.right.right.right.right.right.right.left,
and.intro (or.inl h₁) (and.intro (or.inl h₁) (and.intro (or.inl h₁)
(and.intro (or.inr h₂) (and.intro (or.inr h₃) (or.inr h₃)))))
theorem node_2_not_twice (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) :
(¬ x12 ∨ ¬ x22) ∧ (¬ x12 ∨ ¬ x32) ∧ (¬ x12 ∨ ¬ x42) ∧
(¬ x22 ∨ ¬ x32) ∧ (¬ x22 ∨ ¬ x42) ∧ (¬ x32 ∨ ¬ x42) :=
have h₁ : ¬ x12, from path.right.left,
have h₂ : ¬ x22, from path.right.right.right.right.right.left,
have h₃ : ¬ x42, from path.right.right.right.right.right.right.right.right.right.right.right.right.right.left,
and.intro (or.inl h₁) (and.intro (or.inl h₁) (and.intro (or.inl h₁)
(and.intro (or.inl h₂) (and.intro (or.inr h₃) (or.inr h₃)))))
theorem node_3_not_twice (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) :
(¬ x13 ∨ ¬ x23) ∧ (¬ x13 ∨ ¬ x33) ∧ (¬ x13 ∨ ¬ x43) ∧
(¬ x23 ∨ ¬ x33) ∧ (¬ x23 ∨ ¬ x43) ∧ (¬ x33 ∨ ¬ x43) :=
have h₁ : ¬ x13, from path.right.right.left,
have h₂ : ¬ x23, from path.right.right.right.right.right.right.left,
have h₃ : ¬ x33, from path.right.right.right.right.right.right.right.right.right.right.left,
and.intro (or.inl h₁) (and.intro (or.inl h₁) (and.intro (or.inl h₁)
(and.intro (or.inl h₂) (and.intro (or.inl h₂) (or.inl h₃)))))
theorem node_4_not_twice (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) :
(¬ x14 ∨ ¬ x24) ∧ (¬ x14 ∨ ¬ x34) ∧ (¬ x14 ∨ ¬ x44) ∧
(¬ x24 ∨ ¬ x34) ∧ (¬ x24 ∨ ¬ x44) ∧ (¬ x34 ∨ ¬ x44) :=
have h₁ : ¬ x24, from path.right.right.right.right.right.right.right.left,
have h₂ : ¬ x34, from path.right.right.right.right.right.right.right.right.right.right.right.left,
have h₃ : ¬ x44, from path.right.right.right.right.right.right.right.right.right.right.right.right.right.right.right,
and.intro (or.inr h₁) (and.intro (or.inr h₂) (and.intro (or.inr h₃)
(and.intro (or.inr h₂) (and.intro (or.inr h₃) (or.inr h₃)))))
-- Every position must be occupied:
theorem position_1_occupied (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) : x11 ∨ x12 ∨ x13 ∨ x14 :=
or.inr (or.inr (or.inr path.right.right.right.left))
theorem position_2_occupied (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) : x21 ∨ x22 ∨ x23 ∨ x24 :=
or.inl path.right.right.right.right.left
theorem position_3_occupied (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) : x31 ∨ x32 ∨ x33 ∨ x34 :=
or.inr (or.inl path.right.right.right.right.right.right.right.right.right.left)
theorem position_4_occupied (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) : x41 ∨ x42 ∨ x43 ∨ x44 :=
or.inr (or.inr (or.inl path.right.right.right.right.right.right.right.right.right.right.right.right.right.right.left))
-- No two nodes can occupy the same position
theorem position_1_not_twice (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) :
(¬ x11 ∨ ¬ x12) ∧ (¬ x11 ∨ ¬ x13) ∧ (¬ x11 ∨ ¬ x14) ∧
(¬ x12 ∨ ¬ x13) ∧ (¬ x12 ∨ ¬ x14) ∧ (¬ x13 ∨ ¬ x14) :=
have h₁ : ¬ x11, from path.left,
have h₂ : ¬ x12, from path.right.left,
have h₃ : ¬ x13, from path.right.right.left,
and.intro (or.inr h₂) (and.intro (or.inr h₃) (and.intro (or.inl h₁)
(and.intro (or.inr h₃) (and.intro (or.inl h₂) (or.inl h₃)))))
theorem position_2_not_twice (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) :
(¬ x21 ∨ ¬ x22) ∧ (¬ x21 ∨ ¬ x23) ∧ (¬ x21 ∨ ¬ x24) ∧
(¬ x22 ∨ ¬ x23) ∧ (¬ x22 ∨ ¬ x24) ∧ (¬ x23 ∨ ¬ x24) :=
have h₁ : ¬ x22, from path.right.right.right.right.right.left,
have h₂ : ¬ x23, from path.right.right.right.right.right.right.left,
have h₃ : ¬ x24, from path.right.right.right.right.right.right.right.left,
and.intro (or.inr h₁) (and.intro (or.inr h₂) (and.intro (or.inr h₃)
(and.intro (or.inr h₂) (and.intro (or.inr h₃) (or.inr h₃)))))
theorem position_3_not_twice (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) :
(¬ x31 ∨ ¬ x32) ∧ (¬ x31 ∨ ¬ x33) ∧ (¬ x31 ∨ ¬ x34) ∧
(¬ x32 ∨ ¬ x33) ∧ (¬ x32 ∨ ¬ x34) ∧ (¬ x33 ∨ ¬ x34) :=
have h₁ : ¬ x31, from path.right.right.right.right.right.right.right.right.left,
have h₂ : ¬ x33, from path.right.right.right.right.right.right.right.right.right.right.left,
have h₃ : ¬ x34, from path.right.right.right.right.right.right.right.right.right.right.right.left,
and.intro (or.inl h₁) (and.intro (or.inr h₂) (and.intro (or.inr h₃)
(and.intro (or.inr h₂) (and.intro (or.inr h₃) (or.inr h₃)))))
theorem position_4_not_twice (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) :
(¬ x41 ∨ ¬ x42) ∧ (¬ x41 ∨ ¬ x43) ∧ (¬ x41 ∨ ¬ x44) ∧
(¬ x42 ∨ ¬ x43) ∧ (¬ x42 ∨ ¬ x44) ∧ (¬ x43 ∨ ¬ x44) :=
have h₁ : ¬ x41, from path.right.right.right.right.right.right.right.right.right.right.right.right.left,
have h₂ : ¬ x42, from path.right.right.right.right.right.right.right.right.right.right.right.right.right.left,
have h₃ : ¬ x44, from path.right.right.right.right.right.right.right.right.right.right.right.right.right.right.right,
and.intro (or.inr h₂) (and.intro (or.inl h₁) (and.intro (or.inr h₃)
(and.intro (or.inl h₂) (and.intro (or.inr h₃) (or.inr h₃)))))
-- Non adjacent nodes cannot be adjacent in the path.
-- My graph is G = {(1, 2), (1, 3), (1, 4), (2, 3)}, so (2, 4) and (3, 4) don't belong to G.
-- If (2, 4) doesn't belong to G, nodes 2 and 4 aren't adjacent, so they can't be adjacent in the path:
theorem first_non_adjacent (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) :
(¬ x12 ∨ ¬ x24) ∧ (¬ x22 ∨ ¬ x34) ∧ (¬ x32 ∨ ¬ x44) :=
have h₁ : ¬ x12, from path.right.left,
have h₂ : ¬ x22, from path.right.right.right.right.right.left,
have h₃ : ¬ x44, from path.right.right.right.right.right.right.right.right.right.right.right.right.right.right.right,
and.intro (or.inl h₁) (and.intro (or.inl h₂) (or.inr h₃))
-- The same for (3, 4):
theorem second_non_adjacent (path : ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ x14 ∧ x21 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧
¬ x31 ∧ x32 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ x43 ∧ ¬ x44) :
(¬ x13 ∨ ¬ x24) ∧ (¬ x23 ∨ ¬ x34) ∧ (¬ x33 ∨ ¬ x44) :=
have h₁ : ¬ x13, from path.right.right.left,
have h₂ : ¬ x23, from path.right.right.right.right.right.right.left,
have h₃ : ¬ x44, from path.right.right.right.right.right.right.right.right.right.right.right.right.right.right.right,
and.intro (or.inl h₁) (and.intro (or.inl h₂) (or.inr h₃))
-- We can conclude that my path for graph G is Hamiltonian.
|
ce99fff3782a451049cf7d01b589fc2aa2f7f9ef | f10d66a159ce037d07005bd6021cee6bbd6d5ff0 | /to_comm_semiring.lean | eca54fdf98f726f4a0e0ec1688bb97a61d98cac1 | [] | no_license | johoelzl/mason-stother | 0c78bca183eb729d7f0f93e87ce073bc8cd8808d | 573ecfaada288176462c03c87b80ad05bdab4644 | refs/heads/master | 1,631,751,973,492 | 1,528,923,934,000 | 1,528,923,934,000 | 109,133,224 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 9,974 | lean | import data.finsupp
import algebra.ring
import .to_finset
import .to_multiset
import to_semiring
noncomputable theory
local infix ^ := monoid.pow
open classical multiset
local attribute [instance] prop_decidable
--can the priority be set better? Because now we often have to provide parentheses
local notation a `~ᵤ` b : 50 := associated a b
universe u
variable {α : Type u}
variable [comm_semiring α]
def unit_of_mul_eq_one {a b : α} (h1 : a * b = 1) : units α :=
units.mk a b h1 (by {rw mul_comm _ _ at h1, exact h1})
--removed protected
@[refl] lemma associated.refl : ∀ (x : α), x ~ᵤ x :=
assume x, let ⟨u, hu⟩ := is_unit_one in ⟨u, by {rw [←hu], rw [one_mul]}⟩
@[symm] lemma associated.symm {x y : α} (h : x ~ᵤ y) : y ~ᵤ x :=
let ⟨u, hu⟩ := h in ⟨u⁻¹, by rw [hu, ←mul_assoc, units.inv_mul, one_mul]⟩
--Why protected??
@[trans] lemma associated.trans {x y z: α} (h1 : x ~ᵤ y)(h2 : y ~ᵤ z): x ~ᵤ z :=
let ⟨u1, hu1⟩ := h1 in
let ⟨u2, hu2⟩ := h2 in
exists.intro (u1 * u2) $ by rw [hu1, hu2, ←mul_assoc, units.mul_coe]
lemma associated.eqv : equivalence (@associated α _) :=
mk_equivalence (@associated α _) (@associated.refl α _) (@associated.symm α _) (@associated.trans α _)
--correct simp?
@[simp] lemma associated_zero_iff_eq_zero {a : α} : (a ~ᵤ (0 : α)) ↔ a = 0 :=
iff.intro
(assume h1, let ⟨u, h2⟩ := h1 in by simp [h2, *])
(assume h1, by rw h1)
lemma associated_of_mul_eq_one {a b : α} (h1 : a * b = 1) : a ~ᵤ b :=
begin
have h2 : b * a = 1,
{ rwa mul_comm a b at h1},
have h3 : a * a * (b * b) = 1,
{ rwa [←mul_assoc, @mul_assoc _ _ a a _, h1, mul_one]},
have h4 : b * b * (a * a) = 1,
{ rwa [mul_comm _ _] at h3},
exact ⟨units.mk (a * a) (b * b) h3 h4, by {rw [units.val_coe], simp [mul_assoc, h1]}⟩,
end
lemma is_unit_left_iff_exists_mul_eq_one [comm_semiring α] {a: α} : (is_unit a) ↔ ∃ b, a * b = 1 :=
begin
apply iff.intro,
{
intro h1,
rcases h1 with ⟨aᵤ, ha⟩,
subst ha,
exact ⟨aᵤ.inv, by {rw [←units.inv_coe, units.mul_inv]}⟩,
},
{
intro h1,
rcases h1 with ⟨b, h2⟩,
have h3 : b * a = 1,
{ rw [mul_comm a b]at h2, exact h2},
exact ⟨⟨a, b, h2, h3⟩, rfl⟩,
}
end
lemma is_unit_right_iff_exists_mul_eq_one {b: α} : (is_unit b) ↔ ∃ a, a * b = 1 :=
begin
have h1 : (is_unit b) ↔ ∃ a, b * a = 1,
from @is_unit_left_iff_exists_mul_eq_one _ _ _ b,
constructor,
{
intro h2,
rw h1 at h2,
let a := some h2,
have h3 : b * a = 1,
from some_spec h2,
rw mul_comm b a at h3,
exact ⟨a, h3⟩
},
{
intro h2,
rw h1,
let a := some h2,
have h3 : a * b = 1,
from some_spec h2,
rw mul_comm a b at h3,
exact ⟨a, h3⟩,
}
end
--Should also make a right.
lemma is_unit_left_of_is_unit_mul {a b : α} : is_unit (a * b) → is_unit a :=
begin
intro h1,
rcases h1 with ⟨u, hu⟩,
have h2 : a * (b* (↑u⁻¹ : α) ) = 1,
{
exact calc a * (b* (↑u⁻¹ : α) ) = (a * b) * (↑u⁻¹ : α) : by rw ← mul_assoc
... = u.val * (↑u⁻¹ : α) : by simp [units.val_coe, *]
... = u.val * u.inv : by rw units.inv_coe
... = 1 : u.val_inv,
},
rw @is_unit_left_iff_exists_mul_eq_one _ _ _ a,
exact ⟨(b * ↑u⁻¹), h2 ⟩,
end
lemma is_unit_right_of_is_unit_mul {a b : α} : is_unit (a * b) → is_unit b :=
begin
rw mul_comm a b,
exact is_unit_left_of_is_unit_mul,
end
lemma is_unit_of_mul_eq_one_left {a b : α} (h : a * b = 1): is_unit a :=
begin
rw is_unit_left_iff_exists_mul_eq_one,
exact ⟨b , h⟩
end
lemma is_unit_of_mul_eq_one_right {a b : α} (h : a * b = 1): is_unit b :=
begin
rw is_unit_right_iff_exists_mul_eq_one,
exact ⟨a , h⟩
end
--naming
lemma prod_not_is_unit_eq_one_iff_eq_zero {p : multiset α}: (∀ a, a ∈ p → (¬ (is_unit a))) → (p.prod = 1 ↔ p = 0) :=
begin
by_cases h1 : (p = 0),
{
simp [h1]
},
{
have h2 : ∃a , a ∈ p,
from multiset.exists_mem_of_ne_zero h1,
let h := some h2,
have h3 : h ∈ p,
from some_spec h2,
have h4 : ∃ t, p = h :: t,
from multiset.exists_cons_of_mem h3,
let t := some h4,
have h5 : p = h :: t,
from some_spec h4,
intro h6,
constructor,
{
intro h7,
rw h5 at h7,
simp at h7,
rw mul_comm h _ at h7,
have h8 : is_unit h,
{
rw is_unit_right_iff_exists_mul_eq_one,
exact ⟨multiset.prod t, h7⟩,
},
have h9 : h ∈ p,
{rw h5, simp},
have : ¬is_unit h,
from h6 h h9,
contradiction,
},
{
intro h7,
simp *,
}
}
end
lemma is_unit_mul_div {a b : α} (h : is_unit a) : a * b ∣ b :=
begin
by_cases h1 : (b = 0),
{
simp * at *,
},
{
rcases h with ⟨u, hu ⟩,
have h1 : b = a * b * u.inv,
{
exact calc b = 1 * b : by simp
... = (u.val*u.inv) * b : by rw [u.val_inv]
... = (a * u.inv) * b : by rw [←units.val_coe u, ← hu]
... = _ : by simp [mul_assoc, mul_comm u.inv b],
},
exact ⟨u.inv, h1⟩
}
end
lemma mul_is_unit_div {a b : α} (h : is_unit a) : b * a ∣ b :=
begin
rw mul_comm b a,
exact is_unit_mul_div h,
end
lemma dvd_of_mem_prod {a x : α} {b : multiset α} (h1 : a = b.prod) (h2 : x ∈ b) : x ∣ a :=
begin
rw ←cons_erase h2 at h1,
simp at h1,
split,
exact h1,
end
lemma is_unit_of_associated {p b : α}(h1 : is_unit p)(h2 : p ~ᵤ b) : is_unit b :=
begin
rw associated at h2,
rw is_unit_left_iff_exists_mul_eq_one at h1,
let u := some h2,
have h3 : p = ↑u * b,
from some_spec h2,
let q := some h1,
have h4 : p * q = 1,
from some_spec h1,
have h5 : (q * ↑u) * b = 1,
{
exact calc (q * ↑u) * b = q * (↑u * b) : by simp only [mul_assoc]
... = q * p : by rw h3
... = p * q : by simp [mul_comm]
... = _ : h4,
},
rw is_unit_right_iff_exists_mul_eq_one,
exact ⟨(q * ↑u), h5⟩
end
lemma dvd_dvd_of_associated {a b : α}
: (a ~ᵤ b) → ( a ∣ b) ∧ ( b ∣ a):=
assume h1, let ⟨u, h2⟩ := h1 in
and.intro
(have h3 : u.inv * a = b, from
(calc u.inv * a = u.inv * (↑u * b) : by rw h2
... = (u.inv * u.val) * b : by {simp [units.val_coe, mul_assoc]}
... = b : by simp [u.inv_val]),
dvd.intro_left _ h3)
(dvd.intro_left _ h2.symm)
lemma asssociated_one_iff_is_unit {a : α} : (a ~ᵤ 1) ↔ is_unit a :=
begin
constructor,
{
intro h1,
rw associated at h1,
let u := some h1,
have h2: a = ↑u * 1,
from some_spec h1,
have h3 : ↑(u⁻¹) * a = 1,
{
exact calc ↑u⁻¹ * a = ↑u⁻¹ * (↑u * 1) : by rw h2
... = (↑u⁻¹ * ↑u) * 1 : by simp
... = 1 : by simp [units.inv_mul]
},
rw is_unit_right_iff_exists_mul_eq_one,
exact ⟨↑u⁻¹, h3⟩,
},
{
intro h1,
rcases h1 with ⟨aᵤ, ha⟩,
exact ⟨aᵤ, by simp *⟩,
}
end
lemma mul_associated_mul_of_associated_of_associated {a b c d : α} (h1 : a ~ᵤ c) (h2: b ~ᵤ d) : (a * b) ~ᵤ (c * d) :=
begin
rcases h1 with ⟨u1, hu1⟩,
rcases h2 with ⟨u2, hu2⟩,
fapply exists.intro,
exact u1 * u2,
rw [hu1, hu2, mul_assoc],
exact calc ↑u1 * (c * (↑u2 * d)) = ↑u1 * ((c * ↑u2) * d): by simp [mul_assoc]
... = ↑u1 * ((↑u2 * c) * d): by simp [mul_comm]
... = ↑u1 * ↑u2 * c * d: by simp [mul_assoc]
... = _ : by rw [units.mul_coe, mul_assoc]
end
lemma associated_of_mul_is_unit {a b c : α} (h1 : is_unit b) (h2 : a * b = c) : (a ~ᵤ c) :=
begin
apply associated.symm,
rcases h1 with ⟨u, hu⟩,
apply exists.intro u,
subst hu,
simp [mul_comm, *],
end
lemma associated.dvd_of_associated {a b c : α} (h1 : a ~ᵤ b) (h2 : b ∣ c) : a ∣ c :=
begin
rcases h1 with ⟨u, hu⟩,
rcases h2 with ⟨d, hd⟩,
fapply exists.intro,
exact u.inv * d,
rw mul_comm _ b at hu,
rw [hu,←mul_assoc],
apply eq.symm,
exact calc b * ↑u * u.inv * d = b * (↑u * u.inv) * d : by simp [mul_assoc]
... = c : by simp [units.val_coe, u.val_inv, hd]
end
lemma is_unit_of_mul_is_unit_left {a b : α} (h : is_unit (a * b)) : is_unit a :=
begin
rcases h with ⟨c, hc⟩,
have h1: a * b * c.inv = 1,
{
rw [hc, units.val_coe c, c.val_inv],
},
rw mul_assoc at h1,
exact is_unit_of_mul_eq_one_left h1,
end
lemma is_unit_of_mul_is_unit_right {a b : α} (h : is_unit (a * b)) : is_unit b :=
begin
rw mul_comm at h,
exact is_unit_of_mul_is_unit_left h,
end
lemma is_unit_mul_iff_is_unit_and_is_unit {a b : α} : is_unit (a * b) ↔ is_unit a ∧ is_unit b :=
begin
split,
{
intros h,
exact ⟨is_unit_of_mul_is_unit_left h, is_unit_of_mul_is_unit_right h⟩,
},
{
intros h,
exact is_unit_mul_of_is_unit_of_is_unit h.1 h.2,
}
end
--Naming?
lemma not_is_unit_of_not_is_unit_dvd {a b : α} (h1 : ¬is_unit a) (h2 : a ∣ b) : ¬is_unit b :=
begin
rcases h2 with ⟨c, hc⟩,
subst hc,
by_contradiction h2,
have : is_unit a,
from is_unit_left_of_is_unit_mul h2,
contradiction,
end
---Gcds
--gcds
class has_gcd (α : Type u) [comm_semiring α] := --can we define it for comm_monoid?
(gcd : α → α → α)
(gcd_right : ∀ a b, gcd a b ∣ b)
(gcd_left : ∀ a b, gcd a b ∣ a)
(gcd_min : ∀ a b g, g ∣ a → g ∣ b → g ∣ gcd a b)
section gcd_sr
variables [has_gcd α] {a b c : α}
def gcd : α → α → α := has_gcd.gcd
def gcd_min := has_gcd.gcd_min a b c --Correct???
def gcd_left := has_gcd.gcd_left a b --use {a b : α}?
def gcd_right := has_gcd.gcd_right a b
def coprime (a b : α) := is_unit (gcd a b)
lemma coprime_def : (coprime a b) = (is_unit $ gcd a b) :=
rfl
@[simp] lemma gcd_zero_zero_eq_zero : gcd (0 : α) 0 = 0 :=
begin
by_contradiction,
have h1 : (0 : α)∣0,
{simp},
have h2 : 0 ∣ (gcd (0 : α) 0),
from gcd_min h1 h1,
have : (gcd (0 : α) 0) = 0,
from eq_zero_of_zero_dvd h2,
contradiction
end
end gcd_sr |
5dcb265b9f851db4ba502b748c4294e9bbc39078 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/topology/algebra/monoid.lean | 89342c880653dce5a248e9420b6c30f49948a6d8 | [
"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 | 6,131 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
Theory of topological monoids.
-/
import topology.continuous_on
import group_theory.submonoid.basic
import algebra.group.prod
open classical set filter topological_space
open_locale classical topological_space big_operators
variables {α : Type*} {β : Type*} {γ : Type*}
/-- Basic hypothesis to talk about a topological additive monoid or a topological additive
semigroup. A topological additive monoid over `α`, for example, is obtained by requiring both the
instances `add_monoid α` and `has_continuous_add α`. -/
class has_continuous_add (α : Type*) [topological_space α] [has_add α] : Prop :=
(continuous_add : continuous (λp:α×α, p.1 + p.2))
/-- Basic hypothesis to talk about a topological monoid or a topological semigroup.
A topological monoid over `α`, for example, is obtained by requiring both the instances `monoid α` and
`has_continuous_mul α`. -/
@[to_additive]
class has_continuous_mul (α : Type*) [topological_space α] [has_mul α] : Prop :=
(continuous_mul : continuous (λp:α×α, p.1 * p.2))
section has_continuous_mul
variables [topological_space α] [has_mul α] [has_continuous_mul α]
@[to_additive]
lemma continuous_mul : continuous (λp:α×α, p.1 * p.2) :=
has_continuous_mul.continuous_mul
@[to_additive, continuity]
lemma continuous.mul [topological_space β] {f : β → α} {g : β → α}
(hf : continuous f) (hg : continuous g) :
continuous (λx, f x * g x) :=
continuous_mul.comp (hf.prod_mk hg)
attribute [continuity] continuous.add
@[to_additive]
lemma continuous_mul_left (a : α) : continuous (λ b:α, a * b) :=
continuous_const.mul continuous_id
@[to_additive]
lemma continuous_mul_right (a : α) : continuous (λ b:α, b * a) :=
continuous_id.mul continuous_const
@[to_additive]
lemma continuous_on.mul [topological_space β] {f : β → α} {g : β → α} {s : set β}
(hf : continuous_on f s) (hg : continuous_on g s) :
continuous_on (λx, f x * g x) s :=
(continuous_mul.comp_continuous_on (hf.prod hg) : _)
@[to_additive]
lemma tendsto_mul {a b : α} : tendsto (λp:α×α, p.fst * p.snd) (𝓝 (a, b)) (𝓝 (a * b)) :=
continuous_iff_continuous_at.mp has_continuous_mul.continuous_mul (a, b)
@[to_additive]
lemma filter.tendsto.mul {f : β → α} {g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, f x * g x) x (𝓝 (a * b)) :=
tendsto_mul.comp (hf.prod_mk_nhds hg)
@[to_additive]
lemma continuous_at.mul [topological_space β] {f : β → α} {g : β → α} {x : β}
(hf : continuous_at f x) (hg : continuous_at g x) :
continuous_at (λx, f x * g x) x :=
hf.mul hg
@[to_additive]
lemma continuous_within_at.mul [topological_space β] {f : β → α} {g : β → α} {s : set β} {x : β}
(hf : continuous_within_at f s x) (hg : continuous_within_at g s x) :
continuous_within_at (λx, f x * g x) s x :=
hf.mul hg
@[to_additive]
instance [topological_space β] [has_mul β] [has_continuous_mul β] : has_continuous_mul (α × β) :=
⟨((continuous_fst.comp continuous_fst).mul (continuous_fst.comp continuous_snd)).prod_mk
((continuous_snd.comp continuous_fst).mul (continuous_snd.comp continuous_snd))⟩
end has_continuous_mul
section has_continuous_mul
variables [topological_space α] [monoid α] [has_continuous_mul α]
@[to_additive]
lemma tendsto_list_prod {f : γ → β → α} {x : filter β} {a : γ → α} :
∀l:list γ, (∀c∈l, tendsto (f c) x (𝓝 (a c))) →
tendsto (λb, (l.map (λc, f c b)).prod) x (𝓝 ((l.map a).prod))
| [] _ := by simp [tendsto_const_nhds]
| (f :: l) h :=
begin
simp only [list.map_cons, list.prod_cons],
exact (h f (list.mem_cons_self _ _)).mul
(tendsto_list_prod l (assume c hc, h c (list.mem_cons_of_mem _ hc)))
end
@[to_additive]
lemma continuous_list_prod [topological_space β] {f : γ → β → α} (l : list γ)
(h : ∀c∈l, continuous (f c)) :
continuous (λa, (l.map (λc, f c a)).prod) :=
continuous_iff_continuous_at.2 $ assume x, tendsto_list_prod l $ assume c hc,
continuous_iff_continuous_at.1 (h c hc) x
-- @[to_additive continuous_smul]
@[continuity]
lemma continuous_pow : ∀ n : ℕ, continuous (λ a : α, a ^ n)
| 0 := by simpa using continuous_const
| (k+1) := show continuous (λ (a : α), a * a ^ k), from continuous_id.mul (continuous_pow _)
@[continuity]
lemma continuous.pow {f : β → α} [topological_space β] (h : continuous f) (n : ℕ) :
continuous (λ b, (f b) ^ n) :=
continuous.comp (continuous_pow n) h
end has_continuous_mul
section
variables [topological_space α] [comm_monoid α]
@[to_additive]
lemma submonoid.mem_nhds_one (β : submonoid α) (oβ : is_open (β : set α)) :
(β : set α) ∈ 𝓝 (1 : α) :=
mem_nhds_sets_iff.2 ⟨β, (by refl), oβ, β.one_mem⟩
variable [has_continuous_mul α]
@[to_additive]
lemma tendsto_multiset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : multiset γ) :
(∀c∈s, tendsto (f c) x (𝓝 (a c))) →
tendsto (λb, (s.map (λc, f c b)).prod) x (𝓝 ((s.map a).prod)) :=
by { rcases s with ⟨l⟩, simp, exact tendsto_list_prod l }
@[to_additive]
lemma tendsto_finset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : finset γ) :
(∀c∈s, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) :=
tendsto_multiset_prod _
@[to_additive, continuity]
lemma continuous_multiset_prod [topological_space β] {f : γ → β → α} (s : multiset γ) :
(∀c∈s, continuous (f c)) → continuous (λa, (s.map (λc, f c a)).prod) :=
by { rcases s with ⟨l⟩, simp, exact continuous_list_prod l }
attribute [continuity] continuous_multiset_sum
@[to_additive, continuity]
lemma continuous_finset_prod [topological_space β] {f : γ → β → α} (s : finset γ) :
(∀c∈s, continuous (f c)) → continuous (λa, ∏ c in s, f c a) :=
continuous_multiset_prod _
attribute [continuity] continuous_finset_sum
end
|
5e5e24813a420f422496c8c1035a77dc897c0c34 | bae21755a4a03bbe0a5c22e258db8633407711ad | /library/init/category/state.lean | 7c0f8cec3ffb2136115a0c8d19fcd79ac663b202 | [
"Apache-2.0"
] | permissive | nor-code/lean | f437357a8f85db0f06f186fa50fcb1bc75f6b122 | aa306af3d7c47de3c7937c98d3aa919eb8da6f34 | refs/heads/master | 1,662,613,329,886 | 1,586,696,014,000 | 1,586,696,014,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,779 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
The state monad transformer.
-/
prelude
import init.category.alternative init.category.lift
import init.category.id init.category.except
universes u v w
structure state_t (σ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) :=
(run : σ → m (α × σ))
attribute [pp_using_anonymous_constructor] state_t
@[reducible] def state (σ α : Type u) : Type u := state_t σ id α
namespace state_t
section
variables {σ : Type u} {m : Type u → Type v}
variable [monad m]
variables {α β : Type u}
@[inline] protected def pure (a : α) : state_t σ m α :=
⟨λ s, pure (a, s)⟩
@[inline] protected def bind (x : state_t σ m α) (f : α → state_t σ m β) : state_t σ m β :=
⟨λ s, do (a, s') ← x.run s,
(f a).run s'⟩
instance : monad (state_t σ m) :=
{ pure := @state_t.pure _ _ _, bind := @state_t.bind _ _ _ }
protected def orelse [alternative m] {α : Type u} (x₁ x₂ : state_t σ m α) : state_t σ m α :=
⟨λ s, x₁.run s <|> x₂.run s⟩
protected def failure [alternative m] {α : Type u} : state_t σ m α :=
⟨λ s, failure⟩
instance [alternative m] : alternative (state_t σ m) :=
{ failure := @state_t.failure _ _ _ _,
orelse := @state_t.orelse _ _ _ _ }
@[inline] protected def get : state_t σ m σ :=
⟨λ s, pure (s, s)⟩
@[inline] protected def put : σ → state_t σ m punit :=
λ s', ⟨λ s, pure (punit.star, s')⟩
@[inline] protected def modify (f : σ → σ) : state_t σ m punit :=
⟨λ s, pure (punit.star, f s)⟩
@[inline] protected def lift {α : Type u} (t : m α) : state_t σ m α :=
⟨λ s, do a ← t, pure (a, s)⟩
instance : has_monad_lift m (state_t σ m) :=
⟨@state_t.lift σ m _⟩
@[inline] protected def monad_map {σ m m'} [monad m] [monad m'] {α} (f : Π {α}, m α → m' α) :
state_t σ m α → state_t σ m' α :=
λ x, ⟨λ st, f (x.run st)⟩
instance (σ m m') [monad m] [monad m'] : monad_functor m m' (state_t σ m) (state_t σ m') :=
⟨@state_t.monad_map σ m m' _ _⟩
protected def adapt {σ σ' σ'' α : Type u} {m : Type u → Type v} [monad m] (split : σ → σ' × σ'')
(join : σ' → σ'' → σ) (x : state_t σ' m α) : state_t σ m α :=
⟨λ st, do let (st, ctx) := split st,
(a, st') ← x.run st,
pure (a, join st' ctx)⟩
instance (ε) [monad_except ε m] : monad_except ε (state_t σ m) :=
{ throw := λ α, state_t.lift ∘ throw,
catch := λ α x c, ⟨λ s, catch (x.run s) (λ e, state_t.run (c e) s)⟩ }
end
end state_t
/-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html).
In contrast to the Haskell implementation, we use overlapping instances to derive instances
automatically from `monad_lift`.
Note: This class can be seen as a simplification of the more "principled" definition
```
class monad_state_lift (σ : out_param (Type u)) (n : Type u → Type u) :=
(lift {α : Type u} : (∀ {m : Type u → Type u} [monad m], state_t σ m α) → n α)
```
which better describes the intent of "we can lift a `state_t` from anywhere in the monad stack".
However, by parametricity the types `∀ m [monad m], σ → m (α × σ)` and `σ → α × σ` should be
equivalent because the only way to obtain an `m` is through `pure`.
-/
class monad_state (σ : out_param (Type u)) (m : Type u → Type v) :=
(lift {α : Type u} : state σ α → m α)
section
variables {σ : Type u} {m : Type u → Type v}
-- NOTE: The ordering of the following two instances determines that the top-most `state_t` monad layer
-- will be picked first
instance monad_state_trans {n : Type u → Type w} [has_monad_lift m n] [monad_state σ m] : monad_state σ n :=
⟨λ α x, monad_lift (monad_state.lift x : m α)⟩
instance [monad m] : monad_state σ (state_t σ m) :=
⟨λ α x, ⟨λ s, pure (x.run s)⟩⟩
variables [monad m] [monad_state σ m]
/-- Obtain the top-most state of a monad stack. -/
@[inline] def get : m σ :=
monad_state.lift state_t.get
/-- Set the top-most state of a monad stack. -/
@[inline] def put (st : σ) : m punit :=
monad_state.lift (state_t.put st)
/-- Map the top-most state of a monad stack.
Note: `modify f` may be preferable to `f <$> get >>= put` because the latter
does not use the state linearly (without sufficient inlining). -/
@[inline] def modify (f : σ → σ) : m punit :=
monad_state.lift (state_t.modify f)
end
/-- Adapt a monad stack, changing the type of its top-most state.
This class is comparable to [Control.Lens.Zoom](https://hackage.haskell.org/package/lens-4.15.4/docs/Control-Lens-Zoom.html#t:Zoom), but does not use lenses (yet?), and is derived automatically for any transformer implementing `monad_functor`.
For zooming into a part of the state, the `split` function should split σ into the part σ' and the "context" σ'' so that the potentially modified σ' and the context can be rejoined by `join` in the end.
In the simplest case, the context can be chosen as the full outer state (ie. `σ'' = σ`), which makes `split` and `join` simpler to define. However, note that the state will not be used linearly in this case.
Example:
```
def zoom_fst {α σ σ' : Type} : state σ α → state (σ × σ') α :=
adapt_state id prod.mk
```
The function can also zoom out into a "larger" state, where the new parts are supplied by `split` and discarded by `join` in the end. The state is therefore not used linearly anymore but merely affinely, which is not a practically relevant distinction in Lean.
Example:
```
def with_snd {α σ σ' : Type} (snd : σ') : state (σ × σ') α → state σ α :=
adapt_state (λ st, ((st, snd), ())) (λ ⟨st,snd⟩ _, st)
```
Note: This class can be seen as a simplification of the more "principled" definition
```
class monad_state_functor (σ σ' : out_param (Type u)) (n n' : Type u → Type u) :=
(map {α : Type u} : (∀ {m : Type u → Type u} [monad m], state_t σ m α → state_t σ' m α) → n α → n' α)
```
which better describes the intent of "we can map a `state_t` anywhere in the monad stack".
If we look at the unfolded type of the first argument `∀ m [monad m], (σ → m (α × σ)) → σ' → m (α × σ')`, we see that it has the lens type `∀ f [functor f], (α → f α) → β → f β` with `f` specialized to `λ σ, m (α × σ)` (exercise: show that this is a lawful functor). We can build all lenses we are insterested in from the functions `split` and `join` as
```
λ f _ st, let (st, ctx) := split st in
(λ st', join st' ctx) <$> f st
```
-/
class monad_state_adapter (σ σ' : out_param (Type u)) (m m' : Type u → Type v) :=
(adapt_state {σ'' α : Type u} (split : σ' → σ × σ'') (join : σ → σ'' → σ') : m α → m' α)
export monad_state_adapter (adapt_state)
section
variables {σ σ' : Type u} {m m' : Type u → Type v}
instance monad_state_adapter_trans {n n' : Type u → Type v} [monad_functor m m' n n'] [monad_state_adapter σ σ' m m'] : monad_state_adapter σ σ' n n' :=
⟨λ σ'' α split join, monad_map (λ α, (adapt_state split join : m α → m' α))⟩
instance [monad m] : monad_state_adapter σ σ' (state_t σ m) (state_t σ' m) :=
⟨λ σ'' α, state_t.adapt⟩
end
instance (σ m out) [monad_run out m] : monad_run (λ α, σ → out (α × σ)) (state_t σ m) :=
⟨λ α x, run ∘ (λ σ, x.run σ)⟩
|
00c85982192c3cea993965028e83b45a28694938 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/measure_theory/function/strongly_measurable_lp.lean | 44f3b46bf86ca34efe4de1952e808ff6231e9bd5 | [
"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 | 2,710 | lean | /-
Copyright (c) 2022 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne
-/
import measure_theory.function.simple_func_dense_lp
import measure_theory.function.strongly_measurable
/-!
# Finitely strongly measurable functions in `Lp`
Functions in `Lp` for `0 < p < ∞` are finitely strongly measurable.
## Main statements
* `mem_ℒp.ae_fin_strongly_measurable`: if `mem_ℒp f p μ` with `0 < p < ∞`, then
`ae_fin_strongly_measurable f μ`.
* `Lp.fin_strongly_measurable`: for `0 < p < ∞`, `Lp` functions are finitely strongly measurable.
## References
* Hytönen, Tuomas, Jan Van Neerven, Mark Veraar, and Lutz Weis. Analysis in Banach spaces.
Springer, 2016.
-/
open measure_theory filter topological_space function
open_locale ennreal topological_space measure_theory
namespace measure_theory
local infixr ` →ₛ `:25 := simple_func
variables {α G : Type*} {p : ℝ≥0∞} {m m0 : measurable_space α} {μ : measure α}
[normed_add_comm_group G]
{f : α → G}
lemma mem_ℒp.fin_strongly_measurable_of_strongly_measurable
(hf : mem_ℒp f p μ) (hf_meas : strongly_measurable f) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) :
fin_strongly_measurable f μ :=
begin
borelize G,
haveI : separable_space (set.range f ∪ {0} : set G) :=
hf_meas.separable_space_range_union_singleton,
let fs := simple_func.approx_on f hf_meas.measurable (set.range f ∪ {0}) 0 (by simp),
refine ⟨fs, _, _⟩,
{ have h_fs_Lp : ∀ n, mem_ℒp (fs n) p μ,
from simple_func.mem_ℒp_approx_on_range hf_meas.measurable hf,
exact λ n, (fs n).measure_support_lt_top_of_mem_ℒp (h_fs_Lp n) hp_ne_zero hp_ne_top },
{ assume x,
apply simple_func.tendsto_approx_on,
apply subset_closure,
simp },
end
lemma mem_ℒp.ae_fin_strongly_measurable (hf : mem_ℒp f p μ) (hp_ne_zero : p ≠ 0)
(hp_ne_top : p ≠ ∞) :
ae_fin_strongly_measurable f μ :=
⟨hf.ae_strongly_measurable.mk f, ((mem_ℒp_congr_ae hf.ae_strongly_measurable.ae_eq_mk).mp hf)
.fin_strongly_measurable_of_strongly_measurable
hf.ae_strongly_measurable.strongly_measurable_mk hp_ne_zero hp_ne_top,
hf.ae_strongly_measurable.ae_eq_mk⟩
lemma integrable.ae_fin_strongly_measurable (hf : integrable f μ) :
ae_fin_strongly_measurable f μ :=
(mem_ℒp_one_iff_integrable.mpr hf).ae_fin_strongly_measurable one_ne_zero ennreal.coe_ne_top
lemma Lp.fin_strongly_measurable (f : Lp G p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) :
fin_strongly_measurable f μ :=
(Lp.mem_ℒp f).fin_strongly_measurable_of_strongly_measurable
(Lp.strongly_measurable f) hp_ne_zero hp_ne_top
end measure_theory
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.