source stringlengths 17 118 | lean4 stringlengths 0 335k |
|---|---|
.lake/packages/mathlib/Mathlib/Data/WSeq/Basic.lean | import Mathlib.Data.Seq.Basic
import Mathlib.Util.CompileInductive
/-!
# Partially defined possibly infinite lists
This file provides a `WSeq α` type representing partially defined possibly infinite lists
(referred here as weak sequences).
-/
namespace Stream'
open Function
universe u v w
/-- Weak sequences.
While the `Seq` structure allows for lists which may not be finite,
a weak sequence also allows the computation of each element to
involve an indeterminate amount of computation, including possibly
an infinite loop. This is represented as a regular `Seq` interspersed
with `none` elements to indicate that computation is ongoing.
This model is appropriate for Haskell style lazy lists, and is closed
under most interesting computation patterns on infinite lists,
but conversely it is difficult to extract elements from it. -/
def WSeq (α) :=
Seq (Option α)
namespace WSeq
variable {α : Type u} {β : Type v} {γ : Type w}
/-- Turn a sequence into a weak sequence -/
@[coe]
def ofSeq : Seq α → WSeq α :=
(· <$> ·) some
/-- Turn a list into a weak sequence -/
@[coe]
def ofList (l : List α) : WSeq α :=
ofSeq l
/-- Turn a stream into a weak sequence -/
@[coe]
def ofStream (l : Stream' α) : WSeq α :=
ofSeq l
instance coeSeq : Coe (Seq α) (WSeq α) :=
⟨ofSeq⟩
instance coeList : Coe (List α) (WSeq α) :=
⟨ofList⟩
instance coeStream : Coe (Stream' α) (WSeq α) :=
⟨ofStream⟩
/-- The empty weak sequence -/
def nil : WSeq α :=
Seq.nil
instance inhabited : Inhabited (WSeq α) :=
⟨nil⟩
/-- Prepend an element to a weak sequence -/
def cons (a : α) : WSeq α → WSeq α :=
Seq.cons (some a)
/-- Compute for one tick, without producing any elements -/
def think : WSeq α → WSeq α :=
Seq.cons none
/-- Destruct a weak sequence, to (eventually possibly) produce either
`none` for `nil` or `some (a, s)` if an element is produced. -/
def destruct : WSeq α → Computation (Option (α × WSeq α)) :=
Computation.corec fun s =>
match Seq.destruct s with
| none => Sum.inl none
| some (none, s') => Sum.inr s'
| some (some a, s') => Sum.inl (some (a, s'))
/-- Recursion principle for weak sequences, compare with `List.recOn`. -/
@[elab_as_elim]
def recOn {motive : WSeq α → Sort v} (s : WSeq α) (nil : motive nil)
(cons : ∀ x s, motive (cons x s)) (think : ∀ s, motive (think s)) : motive s :=
Seq.recOn s nil fun o => Option.recOn o think cons
/-- membership for weak sequences -/
protected def Mem (s : WSeq α) (a : α) :=
Seq.Mem s (some a)
instance membership : Membership α (WSeq α) :=
⟨WSeq.Mem⟩
theorem notMem_nil (a : α) : a ∉ @nil α :=
Seq.notMem_nil (some a)
@[deprecated (since := "2025-05-23")] alias not_mem_nil := notMem_nil
/-- Get the head of a weak sequence. This involves a possibly
infinite computation. -/
def head (s : WSeq α) : Computation (Option α) :=
Computation.map (Prod.fst <$> ·) (destruct s)
/-- Encode a computation yielding a weak sequence into additional
`think` constructors in a weak sequence -/
def flatten : Computation (WSeq α) → WSeq α :=
Seq.corec fun c =>
match Computation.destruct c with
| Sum.inl s => Seq.omap (return ·) (Seq.destruct s)
| Sum.inr c' => some (none, c')
/-- Get the tail of a weak sequence. This doesn't need a `Computation`
wrapper, unlike `head`, because `flatten` allows us to hide this
in the construction of the weak sequence itself. -/
def tail (s : WSeq α) : WSeq α :=
flatten <| (fun o => Option.recOn o nil Prod.snd) <$> destruct s
/-- drop the first `n` elements from `s`. -/
def drop (s : WSeq α) : ℕ → WSeq α
| 0 => s
| n + 1 => tail (drop s n)
/-- Get the nth element of `s`. -/
def get? (s : WSeq α) (n : ℕ) : Computation (Option α) :=
head (drop s n)
/-- Convert `s` to a list (if it is finite and completes in finite time). -/
def toList (s : WSeq α) : Computation (List α) :=
@Computation.corec (List α) (List α × WSeq α)
(fun ⟨l, s⟩ =>
match Seq.destruct s with
| none => Sum.inl l.reverse
| some (none, s') => Sum.inr (l, s')
| some (some a, s') => Sum.inr (a::l, s'))
([], s)
/-- Append two weak sequences. As with `Seq.append`, this may not use
the second sequence if the first one takes forever to compute -/
def append : WSeq α → WSeq α → WSeq α :=
Seq.append
/-- Flatten a sequence of weak sequences. (Note that this allows
empty sequences, unlike `Seq.join`.) -/
def join (S : WSeq (WSeq α)) : WSeq α :=
Seq.join
((fun o : Option (WSeq α) =>
match o with
| none => Seq1.ret none
| some s => (none, s)) <$>
S)
/-- Map a function over a weak sequence -/
def map (f : α → β) : WSeq α → WSeq β :=
Seq.map (Option.map f)
/-- The monadic `return a` is a singleton list containing `a`. -/
def ret (a : α) : WSeq α :=
ofList [a]
/-- Monadic bind operator for weak sequences -/
def bind (s : WSeq α) (f : α → WSeq β) : WSeq β :=
join (map f s)
/-- Unfortunately, `WSeq` is not a lawful monad, because it does not satisfy the monad laws exactly,
only up to sequence equivalence. Furthermore, even quotienting by the equivalence is not sufficient,
because the join operation involves lists of quotient elements, with a lifted equivalence relation,
and pure quotients cannot handle this type of construction. -/
instance monad : Monad WSeq where
map := @map
pure := @ret
bind := @bind
open Computation
@[simp]
theorem destruct_nil : destruct (nil : WSeq α) = Computation.pure none :=
Computation.destruct_eq_pure rfl
@[simp]
theorem destruct_cons (a : α) (s) : destruct (cons a s) = Computation.pure (some (a, s)) :=
Computation.destruct_eq_pure <| by simp [destruct, cons, Computation.rmap]
@[simp]
theorem destruct_think (s : WSeq α) : destruct (think s) = (destruct s).think :=
Computation.destruct_eq_think <| by simp [destruct, think, Computation.rmap]
@[simp]
theorem seq_destruct_nil : Seq.destruct (nil : WSeq α) = none :=
rfl
@[simp]
theorem seq_destruct_cons (a : α) (s) : Seq.destruct (cons a s) = some (some a, s) :=
Seq.destruct_cons _ _
@[simp]
theorem seq_destruct_think (s : WSeq α) : Seq.destruct (think s) = some (none, s) :=
Seq.destruct_cons _ _
@[simp]
theorem head_nil : head (nil : WSeq α) = Computation.pure none := by simp [head]
@[simp]
theorem head_cons (a : α) (s) : head (cons a s) = Computation.pure (some a) := by simp [head]
@[simp]
theorem head_think (s : WSeq α) : head (think s) = (head s).think := by simp [head]
@[simp]
theorem flatten_pure (s : WSeq α) : flatten (Computation.pure s) = s := by
refine Seq.eq_of_bisim (fun s1 s2 => flatten (Computation.pure s2) = s1) ?_ rfl
intro s' s h
rw [← h]
simp only [Seq.BisimO, flatten, Seq.omap, pure_def, Seq.corec_eq, destruct_pure]
cases Seq.destruct s with
| none => simp
| some val =>
obtain ⟨o, s'⟩ := val
simp
@[simp]
theorem flatten_think (c : Computation (WSeq α)) : flatten c.think = think (flatten c) :=
Seq.destruct_eq_cons <| by simp [flatten]
@[simp]
theorem destruct_flatten (c : Computation (WSeq α)) : destruct (flatten c) = c >>= destruct := by
refine
Computation.eq_of_bisim
(fun c1 c2 => c1 = c2 ∨ ∃ c, c1 = destruct (flatten c) ∧ c2 = Computation.bind c destruct) ?_
(Or.inr ⟨c, rfl, rfl⟩)
intro c1 c2 h
exact
match c1, c2, h with
| c, _, Or.inl rfl => by cases c.destruct <;> simp
| _, _, Or.inr ⟨c, rfl, rfl⟩ => by
induction c using Computation.recOn with
| pure a => simp; cases (destruct a).destruct <;> simp
| think c' => simpa using Or.inr ⟨c', rfl, rfl⟩
theorem head_terminates_iff (s : WSeq α) : Terminates (head s) ↔ Terminates (destruct s) :=
terminates_map_iff _ (destruct s)
@[simp]
theorem tail_nil : tail (nil : WSeq α) = nil := by simp [tail]
@[simp]
theorem tail_cons (a : α) (s) : tail (cons a s) = s := by simp [tail]
@[simp]
theorem tail_think (s : WSeq α) : tail (think s) = (tail s).think := by simp [tail]
@[simp]
theorem dropn_nil (n) : drop (nil : WSeq α) n = nil := by induction n <;> simp [*, drop]
@[simp]
theorem dropn_cons (a : α) (s) (n) : drop (cons a s) (n + 1) = drop s n := by
induction n with
| zero => simp [drop]
| succ n n_ih =>
simp [drop, ← n_ih]
@[simp]
theorem dropn_think (s : WSeq α) (n) : drop (think s) n = (drop s n).think := by
induction n <;> simp [*, drop]
theorem dropn_add (s : WSeq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n
| 0 => rfl
| n + 1 => congr_arg tail (dropn_add s m n)
theorem dropn_tail (s : WSeq α) (n) : drop (tail s) n = drop s (n + 1) := by
rw [Nat.add_comm]
symm
apply dropn_add
theorem get?_add (s : WSeq α) (m n) : get? s (m + n) = get? (drop s m) n :=
congr_arg head (dropn_add _ _ _)
theorem get?_tail (s : WSeq α) (n) : get? (tail s) n = get? s (n + 1) :=
congr_arg head (dropn_tail _ _)
@[simp]
theorem join_nil : join nil = (nil : WSeq α) :=
Seq.join_nil
@[simp]
theorem join_think (S : WSeq (WSeq α)) : join (think S) = think (join S) := by
simp only [join, think]
dsimp only [(· <$> ·)]
simp [Seq1.ret]
@[simp]
theorem join_cons (s : WSeq α) (S) : join (cons s S) = think (append s (join S)) := by
simp only [join, think]
dsimp only [(· <$> ·)]
simp [cons, append]
@[simp]
theorem nil_append (s : WSeq α) : append nil s = s :=
Seq.nil_append _
@[simp]
theorem cons_append (a : α) (s t) : append (cons a s) t = cons a (append s t) :=
Seq.cons_append _ _ _
@[simp]
theorem think_append (s t : WSeq α) : append (think s) t = think (append s t) :=
Seq.cons_append _ _ _
@[simp]
theorem append_nil (s : WSeq α) : append s nil = s :=
Seq.append_nil _
@[simp]
theorem append_assoc (s t u : WSeq α) : append (append s t) u = append s (append t u) :=
Seq.append_assoc _ _ _
/-- auxiliary definition of tail over weak sequences -/
@[simp]
def tail.aux : Option (α × WSeq α) → Computation (Option (α × WSeq α))
| none => Computation.pure none
| some (_, s) => destruct s
theorem destruct_tail (s : WSeq α) : destruct (tail s) = destruct s >>= tail.aux := by
simp only [tail, destruct_flatten]; rw [← bind_pure_comp, LawfulMonad.bind_assoc]
apply congr_arg; ext1 (_ | ⟨a, s⟩) <;> apply (@pure_bind Computation _ _ _ _ _ _).trans _ <;> simp
/-- auxiliary definition of drop over weak sequences -/
@[simp]
def drop.aux : ℕ → Option (α × WSeq α) → Computation (Option (α × WSeq α))
| 0 => Computation.pure
| n + 1 => fun a => tail.aux a >>= drop.aux n
theorem drop.aux_none : ∀ n, @drop.aux α n none = Computation.pure none
| 0 => rfl
| n + 1 =>
show Computation.bind (Computation.pure none) (drop.aux n) = Computation.pure none by
rw [ret_bind, drop.aux_none n]
theorem destruct_dropn : ∀ (s : WSeq α) (n), destruct (drop s n) = destruct s >>= drop.aux n
| _, 0 => (bind_pure' _).symm
| s, n + 1 => by
rw [← dropn_tail, destruct_dropn _ n, destruct_tail, LawfulMonad.bind_assoc]
rfl
theorem head_terminates_of_head_tail_terminates (s : WSeq α) [T : Terminates (head (tail s))] :
Terminates (head s) :=
(head_terminates_iff _).2 <| by
rcases (head_terminates_iff _).1 T with ⟨⟨a, h⟩⟩
simp? [tail] at h says simp only [tail, destruct_flatten, bind_map_left] at h
rcases exists_of_mem_bind h with ⟨s', h1, _⟩
exact terminates_of_mem h1
theorem destruct_some_of_destruct_tail_some {s : WSeq α} {a} (h : some a ∈ destruct (tail s)) :
∃ a', some a' ∈ destruct s := by
unfold tail Functor.map at h; simp only [destruct_flatten] at h
rcases exists_of_mem_bind h with ⟨t, tm, td⟩; clear h
rcases Computation.exists_of_mem_map tm with ⟨t', ht', ht2⟩; clear tm
rcases t' with - | t' <;> rw [← ht2] at td <;> simp only [destruct_nil] at td
· have := mem_unique td (ret_mem _)
contradiction
· exact ⟨_, ht'⟩
theorem head_some_of_head_tail_some {s : WSeq α} {a} (h : some a ∈ head (tail s)) :
∃ a', some a' ∈ head s := by
unfold head at h
rcases Computation.exists_of_mem_map h with ⟨o, md, e⟩; clear h
rcases o with - | o <;> [injection e; injection e with h']; clear h'
obtain ⟨a, am⟩ := destruct_some_of_destruct_tail_some md
exact ⟨_, Computation.mem_map (@Prod.fst α (WSeq α) <$> ·) am⟩
theorem head_some_of_get?_some {s : WSeq α} {a n} (h : some a ∈ get? s n) :
∃ a', some a' ∈ head s := by
induction n generalizing a with
| zero => exact ⟨_, h⟩
| succ n IH =>
let ⟨a', h'⟩ := head_some_of_head_tail_some h
exact IH h'
theorem get?_terminates_le {s : WSeq α} {m n} (h : m ≤ n) :
Terminates (get? s n) → Terminates (get? s m) := by
induction h with
| refl => exact id
| step _ IH => exact fun T ↦ IH (@head_terminates_of_head_tail_terminates _ _ T)
theorem head_terminates_of_get?_terminates {s : WSeq α} {n} :
Terminates (get? s n) → Terminates (head s) :=
get?_terminates_le (Nat.zero_le n)
theorem destruct_terminates_of_get?_terminates {s : WSeq α} {n} (T : Terminates (get? s n)) :
Terminates (destruct s) :=
(head_terminates_iff _).1 <| head_terminates_of_get?_terminates T
theorem mem_rec_on {C : WSeq α → Prop} {a s} (M : a ∈ s) (h1 : ∀ b s', a = b ∨ C s' → C (cons b s'))
(h2 : ∀ s, C s → C (think s)) : C s := by
apply Seq.mem_rec_on M
intro o s' h; rcases o with - | b
· apply h2
cases h
· contradiction
· assumption
· apply h1
apply Or.imp_left _ h
intro h
injection h
@[simp]
theorem mem_think (s : WSeq α) (a) : a ∈ think s ↔ a ∈ s := by
obtain ⟨f, al⟩ := s
change (some (some a) ∈ some none::f) ↔ some (some a) ∈ f
constructor <;> intro h
· apply (Stream'.eq_or_mem_of_mem_cons h).resolve_left
intro
injections
· apply Stream'.mem_cons_of_mem _ h
theorem eq_or_mem_iff_mem {s : WSeq α} {a a' s'} :
some (a', s') ∈ destruct s → (a ∈ s ↔ a = a' ∨ a ∈ s') := by
generalize e : destruct s = c; intro h
revert s
apply Computation.memRecOn h <;> [skip; intro c IH] <;> intro s <;>
induction s using WSeq.recOn <;>
intro m <;>
have := congr_arg Computation.destruct m <;>
simp at this
· obtain ⟨i1, i2⟩ := this
rw [i1, i2]
obtain ⟨f, al⟩ := s'
dsimp only [cons, Membership.mem, WSeq.Mem, Seq.Mem, Seq.cons]
have h_a_eq_a' : a = a' ↔ some (some a) = some (some a') := by simp
rw [h_a_eq_a']
refine ⟨Stream'.eq_or_mem_of_mem_cons, fun o => ?_⟩
· rcases o with e | m
· rw [e]
apply Stream'.mem_cons
· exact Stream'.mem_cons_of_mem _ m
· simp [IH this]
@[simp]
theorem mem_cons_iff (s : WSeq α) (b) {a} : a ∈ cons b s ↔ a = b ∨ a ∈ s :=
eq_or_mem_iff_mem <| by simp
theorem mem_cons_of_mem {s : WSeq α} (b) {a} (h : a ∈ s) : a ∈ cons b s :=
(mem_cons_iff _ _).2 (Or.inr h)
theorem mem_cons (s : WSeq α) (a) : a ∈ cons a s :=
(mem_cons_iff _ _).2 (Or.inl rfl)
theorem mem_of_mem_tail {s : WSeq α} {a} : a ∈ tail s → a ∈ s := by
intro h; have := h; obtain ⟨n, e⟩ := h; revert s; simp only [Stream'.get]
induction n <;> intro s <;> induction s using WSeq.recOn <;>
simp <;> intro m e <;> injections
· exact Or.inr m
· exact Or.inr m
case succ.think n IH s =>
apply IH m
rw [e]
cases tail s
rfl
theorem mem_of_mem_dropn {s : WSeq α} {a} : ∀ {n}, a ∈ drop s n → a ∈ s
| 0, h => h
| n + 1, h => @mem_of_mem_dropn s a n (mem_of_mem_tail h)
theorem get?_mem {s : WSeq α} {a n} : some a ∈ get? s n → a ∈ s := by
induction n generalizing s <;> intro h
case zero =>
rcases Computation.exists_of_mem_map h with ⟨o, h1, h2⟩
rcases o with - | o
· injection h2
injection h2 with h'
obtain ⟨a', s'⟩ := o
exact (eq_or_mem_iff_mem h1).2 (Or.inl h'.symm)
case succ n IH =>
have := @IH (tail s)
rw [get?_tail] at this
exact mem_of_mem_tail (this h)
theorem exists_get?_of_mem {s : WSeq α} {a} (h : a ∈ s) : ∃ n, some a ∈ get? s n := by
apply mem_rec_on h
· intro a' s' h
rcases h with h | h
· exists 0
simp only [get?, drop, head_cons]
rw [h]
apply ret_mem
· obtain ⟨n, h⟩ := h
exists n + 1
simpa [get?]
· intro s' h
obtain ⟨n, h⟩ := h
exists n
simp only [get?, dropn_think, head_think]
apply think_mem h
theorem exists_dropn_of_mem {s : WSeq α} {a} (h : a ∈ s) :
∃ n s', some (a, s') ∈ destruct (drop s n) :=
let ⟨n, h⟩ := exists_get?_of_mem h
⟨n, by
rcases (head_terminates_iff _).1 ⟨⟨_, h⟩⟩ with ⟨⟨o, om⟩⟩
have := Computation.mem_unique (Computation.mem_map _ om) h
rcases o with - | o
· injection this
injection this with i
obtain ⟨a', s'⟩ := o
dsimp at i
rw [i] at om
exact ⟨_, om⟩⟩
theorem head_terminates_of_mem {s : WSeq α} {a} (h : a ∈ s) : Terminates (head s) :=
let ⟨_, h⟩ := exists_get?_of_mem h
head_terminates_of_get?_terminates ⟨⟨_, h⟩⟩
theorem of_mem_append {s₁ s₂ : WSeq α} {a : α} : a ∈ append s₁ s₂ → a ∈ s₁ ∨ a ∈ s₂ :=
Seq.of_mem_append
theorem mem_append_left {s₁ s₂ : WSeq α} {a : α} : a ∈ s₁ → a ∈ append s₁ s₂ :=
Seq.mem_append_left
theorem exists_of_mem_map {f} {b : β} : ∀ {s : WSeq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b
| ⟨g, al⟩, h => by
let ⟨o, om, oe⟩ := Seq.exists_of_mem_map h
rcases o with - | a
· injection oe
injection oe with h'
exact ⟨a, om, h'⟩
@[simp]
theorem ofList_nil : ofList [] = (nil : WSeq α) :=
rfl
@[simp]
theorem ofList_cons (a : α) (l) : ofList (a::l) = cons a (ofList l) :=
show Seq.map some (Seq.ofList (a::l)) = Seq.cons (some a) (Seq.map some (Seq.ofList l)) by simp
@[simp]
theorem toList'_nil (l : List α) :
Computation.corec (fun ⟨l, s⟩ =>
match Seq.destruct s with
| none => Sum.inl l.reverse
| some (none, s') => Sum.inr (l, s')
| some (some a, s') => Sum.inr (a::l, s')) (l, nil) = Computation.pure l.reverse :=
destruct_eq_pure rfl
@[simp]
theorem toList'_cons (l : List α) (s : WSeq α) (a : α) :
Computation.corec (fun ⟨l, s⟩ =>
match Seq.destruct s with
| none => Sum.inl l.reverse
| some (none, s') => Sum.inr (l, s')
| some (some a, s') => Sum.inr (a::l, s')) (l, cons a s) =
(Computation.corec (fun ⟨l, s⟩ =>
match Seq.destruct s with
| none => Sum.inl l.reverse
| some (none, s') => Sum.inr (l, s')
| some (some a, s') => Sum.inr (a::l, s')) (a::l, s)).think :=
destruct_eq_think <| by simp [cons]
@[simp]
theorem toList'_think (l : List α) (s : WSeq α) :
Computation.corec (fun ⟨l, s⟩ =>
match Seq.destruct s with
| none => Sum.inl l.reverse
| some (none, s') => Sum.inr (l, s')
| some (some a, s') => Sum.inr (a::l, s')) (l, think s) =
(Computation.corec (fun ⟨l, s⟩ =>
match Seq.destruct s with
| none => Sum.inl l.reverse
| some (none, s') => Sum.inr (l, s')
| some (some a, s') => Sum.inr (a::l, s')) (l, s)).think :=
destruct_eq_think <| by simp [think]
theorem toList'_map (l : List α) (s : WSeq α) :
Computation.corec (fun ⟨l, s⟩ =>
match Seq.destruct s with
| none => Sum.inl l.reverse
| some (none, s') => Sum.inr (l, s')
| some (some a, s') => Sum.inr (a :: l, s')) (l, s) = (l.reverse ++ ·) <$> toList s := by
refine
Computation.eq_of_bisim
(fun c1 c2 =>
∃ (l' : List α) (s : WSeq α),
c1 = Computation.corec (fun ⟨l, s⟩ =>
match Seq.destruct s with
| none => Sum.inl l.reverse
| some (none, s') => Sum.inr (l, s')
| some (some a, s') => Sum.inr (a::l, s')) (l' ++ l, s) ∧
c2 = Computation.map (l.reverse ++ ·) (Computation.corec (fun ⟨l, s⟩ =>
match Seq.destruct s with
| none => Sum.inl l.reverse
| some (none, s') => Sum.inr (l, s')
| some (some a, s') => Sum.inr (a::l, s')) (l', s)))
?_ ⟨[], s, rfl, rfl⟩
intro s1 s2 h; rcases h with ⟨l', s, h⟩; rw [h.left, h.right]
induction s using WSeq.recOn <;> simp [nil, cons, think]
case cons a s => refine ⟨a :: l', s, ?_, ?_⟩ <;> simp
case think s => refine ⟨l', s, ?_, ?_⟩ <;> simp
@[simp]
theorem toList_cons (a : α) (s) : toList (cons a s) = (List.cons a <$> toList s).think :=
destruct_eq_think <| by
unfold toList
simp only [toList'_cons, Computation.destruct_think, Sum.inr.injEq]
rw [toList'_map]
simp only [List.reverse_cons, List.reverse_nil, List.nil_append, List.singleton_append]
rfl
@[simp]
theorem toList_nil : toList (nil : WSeq α) = Computation.pure [] :=
destruct_eq_pure rfl
theorem toList_ofList (l : List α) : l ∈ toList (ofList l) := by
induction l with
| nil => simp
| cons a l IH => simpa [ret_mem] using think_mem (Computation.mem_map _ IH)
@[simp]
theorem destruct_ofSeq (s : Seq α) :
destruct (ofSeq s) = Computation.pure (s.head.map fun a => (a, ofSeq s.tail)) :=
destruct_eq_pure <| by
simp only [destruct, Seq.destruct, Option.map_eq_map, ofSeq, Computation.corec_eq, rmap,
Seq.head]
rw [show Seq.get? (some <$> s) 0 = some <$> Seq.get? s 0 by apply Seq.map_get?]
rcases Seq.get? s 0 with - | a
· rfl
dsimp only [(· <$> ·)]
simp
@[simp]
theorem head_ofSeq (s : Seq α) : head (ofSeq s) = Computation.pure s.head := by
simp only [head, Option.map_eq_map, destruct_ofSeq, Computation.map_pure, Option.map_map]
cases Seq.head s <;> rfl
@[simp]
theorem tail_ofSeq (s : Seq α) : tail (ofSeq s) = ofSeq s.tail := by
simp only [tail, destruct_ofSeq, map_pure', flatten_pure]
induction s using Seq.recOn <;> simp only [ofSeq, Seq.tail_nil, Seq.head_nil,
Option.map_none, Seq.tail_cons, Seq.head_cons, Option.map_some]
· rfl
@[simp]
theorem dropn_ofSeq (s : Seq α) : ∀ n, drop (ofSeq s) n = ofSeq (s.drop n)
| 0 => rfl
| n + 1 => by
simp only [drop, Seq.drop]
rw [dropn_ofSeq s n, tail_ofSeq]
theorem get?_ofSeq (s : Seq α) (n) : get? (ofSeq s) n = Computation.pure (Seq.get? s n) := by
dsimp [get?]; rw [dropn_ofSeq, head_ofSeq, Seq.head_dropn]
@[simp]
theorem map_nil (f : α → β) : map f nil = nil :=
rfl
@[simp]
theorem map_cons (f : α → β) (a s) : map f (cons a s) = cons (f a) (map f s) :=
Seq.map_cons _ _ _
@[simp]
theorem map_think (f : α → β) (s) : map f (think s) = think (map f s) :=
Seq.map_cons _ _ _
@[simp]
theorem map_id (s : WSeq α) : map id s = s := by simp [map]
@[simp]
theorem map_ret (f : α → β) (a) : map f (ret a) = ret (f a) := by simp [ret]
@[simp]
theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) :=
Seq.map_append _ _ _
theorem map_comp (f : α → β) (g : β → γ) (s : WSeq α) : map (g ∘ f) s = map g (map f s) := by
dsimp [map]; rw [← Seq.map_comp]
apply congr_fun; apply congr_arg
ext ⟨⟩ <;> rfl
theorem mem_map (f : α → β) {a : α} {s : WSeq α} : a ∈ s → f a ∈ map f s :=
Seq.mem_map (Option.map f)
-- The converse is not true without additional assumptions
theorem exists_of_mem_join {a : α} : ∀ {S : WSeq (WSeq α)}, a ∈ join S → ∃ s, s ∈ S ∧ a ∈ s := by
suffices
∀ ss : WSeq α,
a ∈ ss → ∀ s S, append s (join S) = ss → a ∈ append s (join S) → a ∈ s ∨ ∃ s, s ∈ S ∧ a ∈ s
from fun S h => (this _ h nil S (by simp) (by simp [h])).resolve_left (notMem_nil _)
intro ss h; apply mem_rec_on h <;> [intro b ss o; intro ss IH] <;> intro s S
· induction s using WSeq.recOn <;>
[induction S using WSeq.recOn; skip; skip] <;>
intro ej m <;> simp at ej <;> have := congr_arg Seq.destruct ej <;>
simp at this; cases this
case cons.intro b' s =>
substs b' ss
simp? at m ⊢ says simp only [cons_append, mem_cons_iff] at m ⊢
rcases o with e | IH
· simp [e]
rcases m with e | m
· simp [e]
exact Or.imp_left Or.inr (IH _ _ rfl m)
· induction s using WSeq.recOn <;>
[induction S using WSeq.recOn; skip; skip] <;>
intro ej m <;> simp at ej <;> have := congr_arg Seq.destruct ej <;> simp at this <;>
subst ss
case cons s S =>
apply Or.inr
simp only [join_cons, nil_append, mem_think, mem_cons_iff, exists_eq_or_imp] at m ⊢
exact IH s S rfl m
case think S =>
apply Or.inr
replace m : a ∈ S.join := by simpa using m
rcases (IH nil S (by simp) (by simp [m])).resolve_left (notMem_nil _) with ⟨s, sS, as⟩
exact ⟨s, by simp [sS], as⟩
· simp only [think_append, mem_think] at m IH ⊢
apply IH _ _ rfl m
theorem exists_of_mem_bind {s : WSeq α} {f : α → WSeq β} {b} (h : b ∈ bind s f) :
∃ a ∈ s, b ∈ f a :=
let ⟨t, tm, bt⟩ := exists_of_mem_join h
let ⟨a, as, e⟩ := exists_of_mem_map tm
⟨a, as, by rwa [e]⟩
theorem destruct_map (f : α → β) (s : WSeq α) :
destruct (map f s) = Computation.map (Option.map (Prod.map f (map f))) (destruct s) := by
apply
Computation.eq_of_bisim fun c1 c2 =>
∃ s,
c1 = destruct (map f s) ∧
c2 = Computation.map (Option.map (Prod.map f (map f))) (destruct s)
· intro c1 c2 h
obtain ⟨s, h⟩ := h
rw [h.left, h.right]
induction s using WSeq.recOn <;> simp
case think s => exact ⟨s, rfl, rfl⟩
· exact ⟨s, rfl, rfl⟩
/-- auxiliary definition of `destruct_append` over weak sequences -/
@[simp]
def destruct_append.aux (t : WSeq α) : Option (α × WSeq α) → Computation (Option (α × WSeq α))
| none => destruct t
| some (a, s) => Computation.pure (some (a, append s t))
theorem destruct_append (s t : WSeq α) :
destruct (append s t) = (destruct s).bind (destruct_append.aux t) := by
apply
Computation.eq_of_bisim
(fun c1 c2 =>
∃ s t, c1 = destruct (append s t) ∧ c2 = (destruct s).bind (destruct_append.aux t))
_ ⟨s, t, rfl, rfl⟩
intro c1 c2 h; rcases h with ⟨s, t, h⟩; rw [h.left, h.right]
induction s using WSeq.recOn <;> simp
case nil =>
induction t using WSeq.recOn <;> simp
case think t => refine ⟨nil, t, ?_, ?_⟩ <;> simp
case think s => exact ⟨s, t, rfl, rfl⟩
/-- auxiliary definition of `destruct_join` over weak sequences -/
@[simp]
def destruct_join.aux : Option (WSeq α × WSeq (WSeq α)) → Computation (Option (α × WSeq α))
| none => Computation.pure none
| some (s, S) => (destruct (append s (join S))).think
theorem destruct_join (S : WSeq (WSeq α)) :
destruct (join S) = (destruct S).bind destruct_join.aux := by
apply
Computation.eq_of_bisim
(fun c1 c2 =>
c1 = c2 ∨ ∃ S, c1 = destruct (join S) ∧ c2 = (destruct S).bind destruct_join.aux)
_ (Or.inr ⟨S, rfl, rfl⟩)
intro c1 c2 h
exact
match c1, c2, h with
| c, _, Or.inl <| rfl => by cases c.destruct <;> simp
| _, _, Or.inr ⟨S, rfl, rfl⟩ => by
induction S using WSeq.recOn <;> simp
case think S => refine Or.inr ⟨S, rfl, rfl⟩
@[simp]
theorem map_join (f : α → β) (S) : map f (join S) = join (map (map f) S) := by
apply
Seq.eq_of_bisim fun s1 s2 =>
∃ s S, s1 = append s (map f (join S)) ∧ s2 = append s (join (map (map f) S))
· intro s1 s2 h
exact
match s1, s2, h with
| _, _, ⟨s, S, rfl, rfl⟩ => by
induction s using WSeq.recOn <;> simp
· induction S using WSeq.recOn <;> simp
case cons s S => exact ⟨map f s, S, rfl, rfl⟩
case think S => refine ⟨nil, S, ?_, ?_⟩ <;> simp
· exact ⟨_, _, rfl, rfl⟩
· exact ⟨_, _, rfl, rfl⟩
· refine ⟨nil, S, ?_, ?_⟩ <;> simp
end WSeq
end Stream' |
.lake/packages/mathlib/Mathlib/Data/WSeq/Relation.lean | import Mathlib.Data.WSeq.Basic
import Mathlib.Logic.Relation
/-!
# Relations between and equivalence of weak sequences
This file defines a relation between weak sequences as a relation between their `some` elements,
ignoring computation time (`none` elements). Equivalence is then defined in the obvious way.
## Main definitions
* `Stream'.WSeq.LiftRelO`: Lift a relation to a relation over weak sequences.
* `Stream'.WSeq.LiftRel`: Two sequences are `LiftRel R`-related if their corresponding `some`
elements are `R`-related.
* `Stream'.WSeq.Equiv`: Two sequences are equivalent if they are `LiftRel (· = ·)`-related.
-/
universe u v w
namespace Stream'.WSeq
variable {α : Type u} {β : Type v} {γ : Type w}
open Function
/-- lift a relation to a relation over weak sequences -/
@[simp]
def LiftRelO (R : α → β → Prop) (C : WSeq α → WSeq β → Prop) :
Option (α × WSeq α) → Option (β × WSeq β) → Prop
| none, none => True
| some (a, s), some (b, t) => R a b ∧ C s t
| _, _ => False
attribute [nolint simpNF] LiftRelO.eq_3
theorem LiftRelO.imp {R S : α → β → Prop} {C D : WSeq α → WSeq β → Prop} (H1 : ∀ a b, R a b → S a b)
(H2 : ∀ s t, C s t → D s t) : ∀ {o p}, LiftRelO R C o p → LiftRelO S D o p
| none, none, _ => trivial
| some (_, _), some (_, _), h => And.imp (H1 _ _) (H2 _ _) h
| none, some _, h => False.elim h
| some (_, _), none, h => False.elim h
theorem LiftRelO.imp_right (R : α → β → Prop) {C D : WSeq α → WSeq β → Prop}
(H : ∀ s t, C s t → D s t) {o p} : LiftRelO R C o p → LiftRelO R D o p :=
LiftRelO.imp (fun _ _ => id) H
theorem LiftRelO.swap (R : α → β → Prop) (C) :
swap (LiftRelO R C) = LiftRelO (swap R) (swap C) := by
funext x y
rcases x with ⟨⟩ | ⟨hx, jx⟩ <;> rcases y with ⟨⟩ | ⟨hy, jy⟩ <;> rfl
/-- Definition of bisimilarity for weak sequences -/
@[simp]
def BisimO (R : WSeq α → WSeq α → Prop) : Option (α × WSeq α) → Option (α × WSeq α) → Prop :=
LiftRelO (· = ·) R
theorem BisimO.imp {R S : WSeq α → WSeq α → Prop} (H : ∀ s t, R s t → S s t) {o p} :
BisimO R o p → BisimO S o p :=
LiftRelO.imp_right _ H
/-- Two weak sequences are `LiftRel R` related if they are either both empty,
or they are both nonempty and the heads are `R` related and the tails are
`LiftRel R` related. (This is a coinductive definition.) -/
def LiftRel (R : α → β → Prop) (s : WSeq α) (t : WSeq β) : Prop :=
∃ C : WSeq α → WSeq β → Prop,
C s t ∧ ∀ {s t}, C s t → Computation.LiftRel (LiftRelO R C) (destruct s) (destruct t)
theorem liftRel_destruct {R : α → β → Prop} {s : WSeq α} {t : WSeq β} :
LiftRel R s t → Computation.LiftRel (LiftRelO R (LiftRel R)) (destruct s) (destruct t)
| ⟨R, h1, h2⟩ => by
refine Computation.LiftRel.imp ?_ _ _ (h2 h1)
apply LiftRelO.imp_right
exact fun s' t' h' => ⟨R, h', @h2⟩
theorem liftRel_destruct_iff {R : α → β → Prop} {s : WSeq α} {t : WSeq β} :
LiftRel R s t ↔ Computation.LiftRel (LiftRelO R (LiftRel R)) (destruct s) (destruct t) :=
⟨liftRel_destruct, fun h =>
⟨fun s t =>
LiftRel R s t ∨ Computation.LiftRel (LiftRelO R (LiftRel R)) (destruct s) (destruct t),
Or.inr h, fun {s t} h => by
have h : Computation.LiftRel (LiftRelO R (LiftRel R)) (destruct s) (destruct t) := by
obtain h | h := h
· exact liftRel_destruct h
· assumption
apply Computation.LiftRel.imp _ _ _ h
intro a b
apply LiftRelO.imp_right
intro s t
apply Or.inl⟩⟩
theorem LiftRel.swap_lem {R : α → β → Prop} {s1 s2} (h : LiftRel R s1 s2) :
LiftRel (swap R) s2 s1 := by
refine ⟨swap (LiftRel R), h, fun {s t} (h : LiftRel R t s) => ?_⟩
rw [← LiftRelO.swap, Computation.LiftRel.swap]
apply liftRel_destruct h
theorem LiftRel.swap (R : α → β → Prop) : swap (LiftRel R) = LiftRel (swap R) :=
funext fun _ => funext fun _ => propext ⟨LiftRel.swap_lem, LiftRel.swap_lem⟩
theorem LiftRel.refl (R : α → α → Prop) (H : Reflexive R) : Reflexive (LiftRel R) := fun s => by
refine ⟨(· = ·), rfl, fun {s t} (h : s = t) => ?_⟩
rw [← h]
apply Computation.LiftRel.refl
intro a
rcases a with - | a
· simp
· cases a
simp only [LiftRelO, and_true]
apply H
theorem LiftRel.symm (R : α → α → Prop) (H : Symmetric R) : Symmetric (LiftRel R) :=
fun s1 s2 (h : Function.swap (LiftRel R) s2 s1) => by rwa [LiftRel.swap, H.swap_eq] at h
theorem LiftRel.trans (R : α → α → Prop) (H : Transitive R) : Transitive (LiftRel R) :=
fun s t u h1 h2 => by
refine ⟨fun s u => ∃ t, LiftRel R s t ∧ LiftRel R t u, ⟨t, h1, h2⟩, fun {s u} h => ?_⟩
rcases h with ⟨t, h1, h2⟩
have h1 := liftRel_destruct h1
have h2 := liftRel_destruct h2
refine
Computation.liftRel_def.2
⟨(Computation.terminates_of_liftRel h1).trans (Computation.terminates_of_liftRel h2),
fun {a c} ha hc => ?_⟩
rcases h1.left ha with ⟨b, hb, t1⟩
have t2 := Computation.rel_of_liftRel h2 hb hc
obtain - | a := a <;> obtain - | c := c
· trivial
· cases b
· cases t2
· cases t1
· cases a
rcases b with - | b
· cases t1
· cases b
cases t2
· obtain ⟨a, s⟩ := a
rcases b with - | b
· cases t1
obtain ⟨b, t⟩ := b
obtain ⟨c, u⟩ := c
obtain ⟨ab, st⟩ := t1
obtain ⟨bc, tu⟩ := t2
exact ⟨H ab bc, t, st, tu⟩
theorem LiftRel.equiv (R : α → α → Prop) : Equivalence R → Equivalence (LiftRel R)
| ⟨refl, symm, trans⟩ => ⟨LiftRel.refl R refl, @(LiftRel.symm R @symm), @(LiftRel.trans R @trans)⟩
/-- If two sequences are equivalent, then they have the same values and
the same computational behavior (i.e. if one loops forever then so does
the other), although they may differ in the number of `think`s needed to
arrive at the answer. -/
def Equiv : WSeq α → WSeq α → Prop :=
LiftRel (· = ·)
@[inherit_doc] infixl:50 " ~ʷ " => Equiv
@[refl]
theorem Equiv.refl : ∀ s : WSeq α, s ~ʷ s :=
LiftRel.refl (· = ·) Eq.refl
@[symm]
theorem Equiv.symm : ∀ {s t : WSeq α}, s ~ʷ t → t ~ʷ s :=
@(LiftRel.symm (· = ·) (@Eq.symm _))
@[trans]
theorem Equiv.trans : ∀ {s t u : WSeq α}, s ~ʷ t → t ~ʷ u → s ~ʷ u :=
@(LiftRel.trans (· = ·) (@Eq.trans _))
theorem Equiv.equivalence : Equivalence (@Equiv α) :=
⟨@Equiv.refl _, @Equiv.symm _, @Equiv.trans _⟩
theorem destruct_congr {s t : WSeq α} :
s ~ʷ t → Computation.LiftRel (BisimO (· ~ʷ ·)) (destruct s) (destruct t) :=
liftRel_destruct
theorem destruct_congr_iff {s t : WSeq α} :
s ~ʷ t ↔ Computation.LiftRel (BisimO (· ~ʷ ·)) (destruct s) (destruct t) :=
liftRel_destruct_iff
open Computation
theorem liftRel_dropn_destruct {R : α → β → Prop} {s t} (H : LiftRel R s t) :
∀ n, Computation.LiftRel (LiftRelO R (LiftRel R)) (destruct (drop s n)) (destruct (drop t n))
| 0 => liftRel_destruct H
| n + 1 => by
simp only [drop, destruct_tail]
apply liftRel_bind
· apply liftRel_dropn_destruct H n
exact fun {a b} o =>
match a, b, o with
| none, none, _ => by simp
| some (a, s), some (b, t), ⟨_, h2⟩ => by simpa [tail.aux] using liftRel_destruct h2
theorem exists_of_liftRel_left {R : α → β → Prop} {s t} (H : LiftRel R s t) {a} (h : a ∈ s) :
∃ b, b ∈ t ∧ R a b := by
let ⟨n, h⟩ := exists_get?_of_mem h
let ⟨some (_, s'), sd, rfl⟩ := Computation.exists_of_mem_map h
let ⟨some (b, t'), td, ⟨ab, _⟩⟩ := (liftRel_dropn_destruct H n).left sd
exact ⟨b, get?_mem (Computation.mem_map (Prod.fst.{v, v} <$> ·) td), ab⟩
theorem exists_of_liftRel_right {R : α → β → Prop} {s t} (H : LiftRel R s t) {b} (h : b ∈ t) :
∃ a, a ∈ s ∧ R a b := by rw [← LiftRel.swap] at H; exact exists_of_liftRel_left H h
@[simp]
theorem liftRel_nil (R : α → β → Prop) : LiftRel R nil nil := by
simp [liftRel_destruct_iff]
@[simp]
theorem liftRel_cons (R : α → β → Prop) (a b s t) :
LiftRel R (cons a s) (cons b t) ↔ R a b ∧ LiftRel R s t := by
simp [liftRel_destruct_iff]
@[simp]
theorem liftRel_think_left (R : α → β → Prop) (s t) : LiftRel R (think s) t ↔ LiftRel R s t := by
rw [liftRel_destruct_iff, liftRel_destruct_iff]; simp
@[simp]
theorem liftRel_think_right (R : α → β → Prop) (s t) : LiftRel R s (think t) ↔ LiftRel R s t := by
rw [liftRel_destruct_iff, liftRel_destruct_iff]; simp
theorem cons_congr {s t : WSeq α} (a : α) (h : s ~ʷ t) : cons a s ~ʷ cons a t := by
unfold Equiv; simpa using h
theorem think_equiv (s : WSeq α) : think s ~ʷ s := by unfold Equiv; simpa using Equiv.refl _
theorem think_congr {s t : WSeq α} (h : s ~ʷ t) : think s ~ʷ think t := by
unfold Equiv; simpa using h
theorem head_congr : ∀ {s t : WSeq α}, s ~ʷ t → head s ~ head t := by
suffices ∀ {s t : WSeq α}, s ~ʷ t → ∀ {o}, o ∈ head s → o ∈ head t from fun s t h o =>
⟨this h, this h.symm⟩
intro s t h o ho
rcases @Computation.exists_of_mem_map _ _ _ _ (destruct s) ho with ⟨ds, dsm, dse⟩
rw [← dse]
obtain ⟨l, r⟩ := destruct_congr h
rcases l dsm with ⟨dt, dtm, dst⟩
rcases ds with - | a <;> rcases dt with - | b
· apply Computation.mem_map _ dtm
· cases b
cases dst
· cases a
cases dst
· obtain ⟨a, s'⟩ := a
obtain ⟨b, t'⟩ := b
rw [dst.left]
exact @Computation.mem_map _ _ (@Functor.map _ _ (α × WSeq α) _ Prod.fst)
(some (b, t')) (destruct t) dtm
theorem flatten_equiv {c : Computation (WSeq α)} {s} (h : s ∈ c) : flatten c ~ʷ s := by
apply Computation.memRecOn h
· simp [Equiv.refl]
· intro s'
apply Equiv.trans
simp [think_equiv]
theorem liftRel_flatten {R : α → β → Prop} {c1 : Computation (WSeq α)} {c2 : Computation (WSeq β)}
(h : c1.LiftRel (LiftRel R) c2) : LiftRel R (flatten c1) (flatten c2) :=
let S s t := ∃ c1 c2, s = flatten c1 ∧ t = flatten c2 ∧ Computation.LiftRel (LiftRel R) c1 c2
⟨S, ⟨c1, c2, rfl, rfl, h⟩, fun {s t} h =>
match s, t, h with
| _, _, ⟨c1, c2, rfl, rfl, h⟩ => by
simp only [destruct_flatten]; apply liftRel_bind _ _ h
intro a b ab; apply Computation.LiftRel.imp _ _ _ (liftRel_destruct ab)
intro a b; apply LiftRelO.imp_right
intro s t h; refine ⟨Computation.pure s, Computation.pure t, ?_, ?_, ?_⟩ <;> simp [h]⟩
theorem flatten_congr {c1 c2 : Computation (WSeq α)} :
Computation.LiftRel Equiv c1 c2 → flatten c1 ~ʷ flatten c2 :=
liftRel_flatten
theorem tail_congr {s t : WSeq α} (h : s ~ʷ t) : tail s ~ʷ tail t := by
apply flatten_congr
dsimp only [(· <$> ·)]; rw [← Computation.bind_pure, ← Computation.bind_pure]
apply liftRel_bind _ _ (destruct_congr h)
intro a b h; simp only [comp_apply, liftRel_pure]
rcases a with - | a <;> rcases b with - | b
· trivial
· cases h
· cases a
cases h
· obtain ⟨a, s'⟩ := a
obtain ⟨b, t'⟩ := b
exact h.right
theorem dropn_congr {s t : WSeq α} (h : s ~ʷ t) (n) : drop s n ~ʷ drop t n := by
induction n <;> simp [*, tail_congr, drop]
theorem get?_congr {s t : WSeq α} (h : s ~ʷ t) (n) : get? s n ~ get? t n :=
head_congr (dropn_congr h _)
theorem mem_congr {s t : WSeq α} (h : s ~ʷ t) (a) : a ∈ s ↔ a ∈ t :=
suffices ∀ {s t : WSeq α}, s ~ʷ t → a ∈ s → a ∈ t from ⟨this h, this h.symm⟩
fun {_ _} h as =>
let ⟨_, hn⟩ := exists_get?_of_mem as
get?_mem ((get?_congr h _ _).1 hn)
theorem Equiv.ext {s t : WSeq α} (h : ∀ n, get? s n ~ get? t n) : s ~ʷ t :=
⟨fun s t => ∀ n, get? s n ~ get? t n, h, fun {s t} h => by
refine liftRel_def.2 ⟨?_, ?_⟩
· rw [← head_terminates_iff, ← head_terminates_iff]
exact terminates_congr (h 0)
· intro a b ma mb
rcases a with - | a <;> rcases b with - | b
· trivial
· injection mem_unique (Computation.mem_map _ ma) ((h 0 _).2 (Computation.mem_map _ mb))
· injection mem_unique (Computation.mem_map _ ma) ((h 0 _).2 (Computation.mem_map _ mb))
· obtain ⟨a, s'⟩ := a
obtain ⟨b, t'⟩ := b
injection mem_unique (Computation.mem_map _ ma) ((h 0 _).2 (Computation.mem_map _ mb)) with
ab
refine ⟨ab, fun n => ?_⟩
refine
(get?_congr (flatten_equiv (Computation.mem_map _ ma)) n).symm.trans
((?_ : get? (tail s) n ~ get? (tail t) n).trans
(get?_congr (flatten_equiv (Computation.mem_map _ mb)) n))
rw [get?_tail, get?_tail]
apply h⟩
theorem liftRel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : WSeq α} {s2 : WSeq β}
{f1 : α → γ} {f2 : β → δ} (h1 : LiftRel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b)) :
LiftRel S (map f1 s1) (map f2 s2) :=
⟨fun s1 s2 => ∃ s t, s1 = map f1 s ∧ s2 = map f2 t ∧ LiftRel R s t, ⟨s1, s2, rfl, rfl, h1⟩,
fun {s1 s2} h =>
match s1, s2, h with
| _, _, ⟨s, t, rfl, rfl, h⟩ => by
simp only [exists_and_left, destruct_map]
apply Computation.liftRel_map _ _ (liftRel_destruct h)
intro o p h
rcases o with - | a <;> rcases p with - | b
· simp
· cases b; cases h
· cases a; cases h
· obtain ⟨a, s⟩ := a; obtain ⟨b, t⟩ := b
obtain ⟨r, h⟩ := h
exact ⟨h2 r, s, rfl, t, rfl, h⟩⟩
theorem map_congr (f : α → β) {s t : WSeq α} (h : s ~ʷ t) : map f s ~ʷ map f t :=
liftRel_map _ _ h fun {_ _} => congr_arg _
theorem liftRel_append (R : α → β → Prop) {s1 s2 : WSeq α} {t1 t2 : WSeq β} (h1 : LiftRel R s1 t1)
(h2 : LiftRel R s2 t2) : LiftRel R (append s1 s2) (append t1 t2) :=
⟨fun s t => LiftRel R s t ∨ ∃ s1 t1, s = append s1 s2 ∧ t = append t1 t2 ∧ LiftRel R s1 t1,
Or.inr ⟨s1, t1, rfl, rfl, h1⟩, fun {s t} h =>
match s, t, h with
| s, t, Or.inl h => by
apply Computation.LiftRel.imp _ _ _ (liftRel_destruct h)
intro a b; apply LiftRelO.imp_right
intro s t; apply Or.inl
| _, _, Or.inr ⟨s1, t1, rfl, rfl, h⟩ => by
simp only [exists_and_left, destruct_append]
apply Computation.liftRel_bind _ _ (liftRel_destruct h)
intro o p h
rcases o with - | a <;> rcases p with - | b
· simp only [destruct_append.aux]
apply Computation.LiftRel.imp _ _ _ (liftRel_destruct h2)
intro a b
apply LiftRelO.imp_right
intro s t
apply Or.inl
· cases b; cases h
· cases a; cases h
· obtain ⟨a, s⟩ := a; obtain ⟨b, t⟩ := b
obtain ⟨r, h⟩ := h
simpa using ⟨r, Or.inr ⟨s, rfl, t, rfl, h⟩⟩⟩
theorem liftRel_join.lem (R : α → β → Prop) {S T} {U : WSeq α → WSeq β → Prop}
(ST : LiftRel (LiftRel R) S T)
(HU :
∀ s1 s2,
(∃ s t S T,
s1 = append s (join S) ∧
s2 = append t (join T) ∧ LiftRel R s t ∧ LiftRel (LiftRel R) S T) →
U s1 s2)
{a} (ma : a ∈ destruct (join S)) : ∃ b, b ∈ destruct (join T) ∧ LiftRelO R U a b := by
obtain ⟨n, h⟩ := exists_results_of_mem ma; clear ma; revert S T ST a
induction n using Nat.strongRecOn with | _ n IH
intro S T ST a ra; simp only [destruct_join] at ra
exact
let ⟨o, m, k, rs1, rs2, en⟩ := of_results_bind ra
let ⟨p, mT, rop⟩ := Computation.exists_of_liftRel_left (liftRel_destruct ST) rs1.mem
match o, p, rop, rs1, rs2, mT with
| none, none, _, _, rs2, mT => by
simp only [destruct_join]
exact ⟨none, mem_bind mT (ret_mem _), by rw [eq_of_pure_mem rs2.mem]; trivial⟩
| some (s, S'), some (t, T'), ⟨st, ST'⟩, _, rs2, mT => by
simp? [destruct_append] at rs2 says simp only [destruct_join.aux, destruct_append] at rs2
exact
let ⟨k1, rs3, ek⟩ := of_results_think rs2
let ⟨o', m1, n1, rs4, rs5, ek1⟩ := of_results_bind rs3
let ⟨p', mt, rop'⟩ := Computation.exists_of_liftRel_left (liftRel_destruct st) rs4.mem
match o', p', rop', rs4, rs5, mt with
| none, none, _, _, rs5', mt => by
have : n1 < n := by
rw [en, ek, ek1]
apply lt_of_lt_of_le _ (Nat.le_add_right _ _)
apply Nat.lt_succ_of_le (Nat.le_add_right _ _)
let ⟨ob, mb, rob⟩ := IH _ this ST' rs5'
refine ⟨ob, ?_, rob⟩
· simp +unfoldPartialApp only [destruct_join, destruct_join.aux]
apply mem_bind mT
simp only [destruct_append]
apply think_mem
apply mem_bind mt
exact mb
| some (a, s'), some (b, t'), ⟨ab, st'⟩, _, rs5, mt => by
simp only [destruct_append.aux] at rs5
refine ⟨some (b, append t' (join T')), ?_, ?_⟩
· simp +unfoldPartialApp only [destruct_join, destruct_join.aux]
apply mem_bind mT
simp only [destruct_append]
apply think_mem
apply mem_bind mt
apply ret_mem
rw [eq_of_pure_mem rs5.mem]
exact ⟨ab, HU _ _ ⟨s', t', S', T', rfl, rfl, st', ST'⟩⟩
theorem liftRel_join (R : α → β → Prop) {S : WSeq (WSeq α)} {T : WSeq (WSeq β)}
(h : LiftRel (LiftRel R) S T) : LiftRel R (join S) (join T) :=
⟨fun s1 s2 =>
∃ s t S T,
s1 = append s (join S) ∧ s2 = append t (join T) ∧ LiftRel R s t ∧ LiftRel (LiftRel R) S T,
⟨nil, nil, S, T, by simp, by simp, by simp, h⟩, fun {s1 s2} ⟨s, t, S, T, h1, h2, st, ST⟩ => by
rw [h1, h2]; rw [destruct_append, destruct_append]
apply Computation.liftRel_bind _ _ (liftRel_destruct st)
exact fun {o p} h =>
match o, p, h with
| some (a, s), some (b, t), ⟨h1, h2⟩ => by
simpa using ⟨h1, s, t, S, rfl, T, rfl, h2, ST⟩
| none, none, _ => by
-- We do not `dsimp` with `LiftRelO` since `liftRel_join.lem` uses `LiftRelO`.
dsimp only [destruct_append.aux, Computation.LiftRel]; constructor
· intro
apply liftRel_join.lem _ ST fun _ _ => id
· intro b mb
rw [← LiftRelO.swap]
apply liftRel_join.lem (swap R)
· rw [← LiftRel.swap R, ← LiftRel.swap]
apply ST
· rw [← LiftRel.swap R, ← LiftRel.swap (LiftRel R)]
exact fun s1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩ => ⟨t, s, T, S, h2, h1, st, ST⟩
· exact mb⟩
theorem join_congr {S T : WSeq (WSeq α)} (h : LiftRel Equiv S T) : join S ~ʷ join T :=
liftRel_join _ h
theorem liftRel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : WSeq α} {s2 : WSeq β}
{f1 : α → WSeq γ} {f2 : β → WSeq δ} (h1 : LiftRel R s1 s2)
(h2 : ∀ {a b}, R a b → LiftRel S (f1 a) (f2 b)) : LiftRel S (bind s1 f1) (bind s2 f2) :=
liftRel_join _ (liftRel_map _ _ h1 @h2)
theorem bind_congr {s1 s2 : WSeq α} {f1 f2 : α → WSeq β} (h1 : s1 ~ʷ s2) (h2 : ∀ a, f1 a ~ʷ f2 a) :
bind s1 f1 ~ʷ bind s2 f2 :=
liftRel_bind _ _ h1 fun {a b} h => by rw [h]; apply h2
@[simp]
theorem join_ret (s : WSeq α) : join (ret s) ~ʷ s := by simpa [ret] using think_equiv _
@[simp]
theorem join_map_ret (s : WSeq α) : join (map ret s) ~ʷ s := by
refine ⟨fun s1 s2 => join (map ret s2) = s1, rfl, ?_⟩
intro s' s h; rw [← h]
apply liftRel_rec fun c1 c2 => ∃ s, c1 = destruct (join (map ret s)) ∧ c2 = destruct s
· exact fun {c1 c2} h =>
match c1, c2, h with
| _, _, ⟨s, rfl, rfl⟩ => by
clear h
have (s : WSeq α) : ∃ s' : WSeq α,
(map ret s).join.destruct = (map ret s').join.destruct ∧ destruct s = s'.destruct :=
⟨s, rfl, rfl⟩
induction s using WSeq.recOn <;> simp [ret, this]
· exact ⟨s, rfl, rfl⟩
@[simp]
theorem join_append (S T : WSeq (WSeq α)) : join (append S T) ~ʷ append (join S) (join T) := by
refine
⟨fun s1 s2 =>
∃ s S T, s1 = append s (join (append S T)) ∧ s2 = append s (append (join S) (join T)),
⟨nil, S, T, by simp, by simp⟩, ?_⟩
intro s1 s2 h
apply
liftRel_rec
(fun c1 c2 =>
∃ (s : WSeq α) (S T : _),
c1 = destruct (append s (join (append S T))) ∧
c2 = destruct (append s (append (join S) (join T))))
_ _ _
(let ⟨s, S, T, h1, h2⟩ := h
⟨s, S, T, congr_arg destruct h1, congr_arg destruct h2⟩)
rintro c1 c2 ⟨s, S, T, rfl, rfl⟩
induction s using WSeq.recOn with
| nil =>
induction S using WSeq.recOn with
| nil =>
simp only [nil_append, join_nil]
induction T using WSeq.recOn with
| nil => simp
| cons s T =>
simp only [join_cons, destruct_think, Computation.destruct_think, liftRelAux_inr_inr]
refine ⟨s, nil, T, ?_, ?_⟩ <;> simp
| think T =>
simp only [join_think, destruct_think, Computation.destruct_think, liftRelAux_inr_inr]
refine ⟨nil, nil, T, ?_, ?_⟩ <;> simp
| cons s S => simpa using ⟨s, S, T, rfl, rfl⟩
| think S => refine ⟨nil, S, T, ?_, ?_⟩ <;> simp
| cons a s => simpa using ⟨s, S, T, rfl, rfl⟩
| think s => simpa using ⟨s, S, T, rfl, rfl⟩
@[simp]
theorem bind_ret (f : α → β) (s) : bind s (ret ∘ f) ~ʷ map f s := by
dsimp [bind]
rw [map_comp]
apply join_map_ret
@[simp]
theorem ret_bind (a : α) (f : α → WSeq β) : bind (ret a) f ~ʷ f a := by simp [bind]
@[simp]
theorem join_join (SS : WSeq (WSeq (WSeq α))) : join (join SS) ~ʷ join (map join SS) := by
refine
⟨fun s1 s2 =>
∃ s S SS,
s1 = append s (join (append S (join SS))) ∧
s2 = append s (append (join S) (join (map join SS))),
⟨nil, nil, SS, by simp, by simp⟩, ?_⟩
intro s1 s2 h
apply
liftRel_rec
(fun c1 c2 =>
∃ s S SS,
c1 = destruct (append s (join (append S (join SS)))) ∧
c2 = destruct (append s (append (join S) (join (map join SS)))))
_ (destruct s1) (destruct s2)
(let ⟨s, S, SS, h1, h2⟩ := h
⟨s, S, SS, by simp [h1], by simp [h2]⟩)
intro c1 c2 h
exact
match c1, c2, h with
| _, _, ⟨s, S, SS, rfl, rfl⟩ => by
clear h
induction s using WSeq.recOn with
| nil =>
induction S using WSeq.recOn with
| nil =>
simp only [nil_append, join_nil]
induction SS using WSeq.recOn with
| nil => simp
| cons S SS => refine ⟨nil, S, SS, ?_, ?_⟩ <;> simp
| think SS => refine ⟨nil, nil, SS, ?_, ?_⟩ <;> simp
| cons s S => simpa using ⟨s, S, SS, rfl, rfl⟩
| think S => refine ⟨nil, S, SS, ?_, ?_⟩ <;> simp
| cons a s => simpa using ⟨s, S, SS, rfl, rfl⟩
| think s => simpa using ⟨s, S, SS, rfl, rfl⟩
@[simp]
theorem bind_assoc_comp (s : WSeq α) (f : α → WSeq β) (g : β → WSeq γ) :
bind (bind s f) g ~ʷ bind s ((fun y : WSeq β => bind y g) ∘ f) := by
simp only [bind, map_join]
rw [← map_comp f (map g), ← Function.comp_def, comp_assoc, map_comp (map g ∘ f) join s]
exact join_join (map (map g ∘ f) s)
@[simp]
theorem bind_assoc (s : WSeq α) (f : α → WSeq β) (g : β → WSeq γ) :
bind (bind s f) g ~ʷ bind s fun x : α => bind (f x) g := by
exact bind_assoc_comp s f g
end Stream'.WSeq |
.lake/packages/mathlib/Mathlib/Data/WSeq/Defs.lean | import Batteries.Data.DList.Basic
import Mathlib.Data.WSeq.Basic
/-!
# Miscellaneous definitions concerning weak sequences
These definitions, as well as those in `Mathlib/Data/WSeq/Productive.lean`, are not needed for the
development of `Mathlib/Data/Seq/Parallel.lean`.
-/
universe u v w
namespace Stream'.WSeq
variable {α : Type u} {β : Type v} {γ : Type w}
open Function
/-- Get the length of `s` (if it is finite and completes in finite time). -/
def length (s : WSeq α) : Computation ℕ :=
@Computation.corec ℕ (ℕ × WSeq α)
(fun ⟨n, s⟩ =>
match Seq.destruct s with
| none => Sum.inl n
| some (none, s') => Sum.inr (n, s')
| some (some _, s') => Sum.inr (n + 1, s'))
(0, s)
/-- A weak sequence is finite if `toList s` terminates. Equivalently,
it is a finite number of `think` and `cons` applied to `nil`. -/
class IsFinite (s : WSeq α) : Prop where
out : (toList s).Terminates
instance toList_terminates (s : WSeq α) [h : IsFinite s] : (toList s).Terminates :=
h.out
/-- Get the list corresponding to a finite weak sequence. -/
def get (s : WSeq α) [IsFinite s] : List α :=
(toList s).get
/-- Replace the `n`th element of `s` with `a`. -/
def updateNth (s : WSeq α) (n : ℕ) (a : α) : WSeq α :=
@Seq.corec (Option α) (ℕ × WSeq α)
(fun ⟨n, s⟩ =>
match Seq.destruct s, n with
| none, _ => none
| some (none, s'), n => some (none, n, s')
| some (some a', s'), 0 => some (some a', 0, s')
| some (some _, s'), 1 => some (some a, 0, s')
| some (some a', s'), n + 2 => some (some a', n + 1, s'))
(n + 1, s)
/-- Remove the `n`th element of `s`. -/
def removeNth (s : WSeq α) (n : ℕ) : WSeq α :=
@Seq.corec (Option α) (ℕ × WSeq α)
(fun ⟨n, s⟩ =>
match Seq.destruct s, n with
| none, _ => none
| some (none, s'), n => some (none, n, s')
| some (some a', s'), 0 => some (some a', 0, s')
| some (some _, s'), 1 => some (none, 0, s')
| some (some a', s'), n + 2 => some (some a', n + 1, s'))
(n + 1, s)
/-- Map the elements of `s` over `f`, removing any values that yield `none`. -/
def filterMap (f : α → Option β) : WSeq α → WSeq β :=
Seq.corec fun s =>
match Seq.destruct s with
| none => none
| some (none, s') => some (none, s')
| some (some a, s') => some (f a, s')
/-- Select the elements of `s` that satisfy `p`. -/
def filter (p : α → Prop) [DecidablePred p] : WSeq α → WSeq α :=
filterMap fun a => if p a then some a else none
-- example of infinite list manipulations
/-- Get the first element of `s` satisfying `p`. -/
def find (p : α → Prop) [DecidablePred p] (s : WSeq α) : Computation (Option α) :=
head <| filter p s
/-- Zip a function over two weak sequences -/
def zipWith (f : α → β → γ) (s1 : WSeq α) (s2 : WSeq β) : WSeq γ :=
@Seq.corec (Option γ) (WSeq α × WSeq β)
(fun ⟨s1, s2⟩ =>
match Seq.destruct s1, Seq.destruct s2 with
| some (none, s1'), some (none, s2') => some (none, s1', s2')
| some (some _, _), some (none, s2') => some (none, s1, s2')
| some (none, s1'), some (some _, _) => some (none, s1', s2)
| some (some a1, s1'), some (some a2, s2') => some (some (f a1 a2), s1', s2')
| _, _ => none)
(s1, s2)
/-- Zip two weak sequences into a single sequence of pairs -/
def zip : WSeq α → WSeq β → WSeq (α × β) :=
zipWith Prod.mk
/-- Get the list of indexes of elements of `s` satisfying `p` -/
def findIndexes (p : α → Prop) [DecidablePred p] (s : WSeq α) : WSeq ℕ :=
(zip s (Stream'.nats : WSeq ℕ)).filterMap fun ⟨a, n⟩ => if p a then some n else none
/-- Get the index of the first element of `s` satisfying `p` -/
def findIndex (p : α → Prop) [DecidablePred p] (s : WSeq α) : Computation ℕ :=
(fun o => Option.getD o 0) <$> head (findIndexes p s)
/-- Get the index of the first occurrence of `a` in `s` -/
def indexOf [DecidableEq α] (a : α) : WSeq α → Computation ℕ :=
findIndex (Eq a)
/-- Get the indexes of occurrences of `a` in `s` -/
def indexesOf [DecidableEq α] (a : α) : WSeq α → WSeq ℕ :=
findIndexes (Eq a)
/-- `union s1 s2` is a weak sequence which interleaves `s1` and `s2` in
some order (nondeterministically). -/
def union (s1 s2 : WSeq α) : WSeq α :=
@Seq.corec (Option α) (WSeq α × WSeq α)
(fun ⟨s1, s2⟩ =>
match Seq.destruct s1, Seq.destruct s2 with
| none, none => none
| some (a1, s1'), none => some (a1, s1', nil)
| none, some (a2, s2') => some (a2, nil, s2')
| some (none, s1'), some (none, s2') => some (none, s1', s2')
| some (some a1, s1'), some (none, s2') => some (some a1, s1', s2')
| some (none, s1'), some (some a2, s2') => some (some a2, s1', s2')
| some (some a1, s1'), some (some a2, s2') => some (some a1, cons a2 s1', s2'))
(s1, s2)
/-- Returns `true` if `s` is `nil` and `false` if `s` has an element -/
def isEmpty (s : WSeq α) : Computation Bool :=
Computation.map Option.isNone <| head s
/-- Calculate one step of computation -/
def compute (s : WSeq α) : WSeq α :=
match Seq.destruct s with
| some (none, s') => s'
| _ => s
/-- Get the first `n` elements of a weak sequence -/
def take (s : WSeq α) (n : ℕ) : WSeq α :=
@Seq.corec (Option α) (ℕ × WSeq α)
(fun ⟨n, s⟩ =>
match n, Seq.destruct s with
| 0, _ => none
| _ + 1, none => none
| m + 1, some (none, s') => some (none, m + 1, s')
| m + 1, some (some a, s') => some (some a, m, s'))
(n, s)
/-- Split the sequence at position `n` into a finite initial segment
and the weak sequence tail -/
def splitAt (s : WSeq α) (n : ℕ) : Computation (List α × WSeq α) :=
@Computation.corec (List α × WSeq α) (ℕ × List α × WSeq α)
(fun ⟨n, l, s⟩ =>
match n, Seq.destruct s with
| 0, _ => Sum.inl (l.reverse, s)
| _ + 1, none => Sum.inl (l.reverse, s)
| _ + 1, some (none, s') => Sum.inr (n, l, s')
| m + 1, some (some a, s') => Sum.inr (m, a::l, s'))
(n, [], s)
/-- Returns `true` if any element of `s` satisfies `p` -/
def any (s : WSeq α) (p : α → Bool) : Computation Bool :=
Computation.corec
(fun s : WSeq α =>
match Seq.destruct s with
| none => Sum.inl false
| some (none, s') => Sum.inr s'
| some (some a, s') => if p a then Sum.inl true else Sum.inr s')
s
/-- Returns `true` if every element of `s` satisfies `p` -/
def all (s : WSeq α) (p : α → Bool) : Computation Bool :=
Computation.corec
(fun s : WSeq α =>
match Seq.destruct s with
| none => Sum.inl true
| some (none, s') => Sum.inr s'
| some (some a, s') => if p a then Sum.inr s' else Sum.inl false)
s
/-- Apply a function to the elements of the sequence to produce a sequence
of partial results. (There is no `scanr` because this would require
working from the end of the sequence, which may not exist.) -/
def scanl (f : α → β → α) (a : α) (s : WSeq β) : WSeq α :=
cons a <|
@Seq.corec (Option α) (α × WSeq β)
(fun ⟨a, s⟩ =>
match Seq.destruct s with
| none => none
| some (none, s') => some (none, a, s')
| some (some b, s') =>
let a' := f a b
some (some a', a', s'))
(a, s)
/-- Get the weak sequence of initial segments of the input sequence -/
def inits (s : WSeq α) : WSeq (List α) :=
cons [] <|
@Seq.corec (Option (List α)) (Batteries.DList α × WSeq α)
(fun ⟨l, s⟩ =>
match Seq.destruct s with
| none => none
| some (none, s') => some (none, l, s')
| some (some a, s') =>
let l' := l.push a
some (some l'.toList, l', s'))
(Batteries.DList.empty, s)
/-- Like take, but does not wait for a result. Calculates `n` steps of
computation and returns the sequence computed so far -/
def collect (s : WSeq α) (n : ℕ) : List α :=
(Seq.take n s).filterMap id
theorem length_eq_map (s : WSeq α) : length s = Computation.map List.length (toList s) := by
refine
Computation.eq_of_bisim
(fun c1 c2 =>
∃ (l : List α) (s : WSeq α),
c1 = Computation.corec (fun ⟨n, s⟩ =>
match Seq.destruct s with
| none => Sum.inl n
| some (none, s') => Sum.inr (n, s')
| some (some _, s') => Sum.inr (n + 1, s')) (l.length, s) ∧
c2 = Computation.map List.length (Computation.corec (fun ⟨l, s⟩ =>
match Seq.destruct s with
| none => Sum.inl l.reverse
| some (none, s') => Sum.inr (l, s')
| some (some a, s') => Sum.inr (a::l, s')) (l, s)))
?_ ⟨[], s, rfl, rfl⟩
intro s1 s2 h; rcases h with ⟨l, s, h⟩; rw [h.left, h.right]
induction s using WSeq.recOn with
| nil => simp [nil]
| cons a s => simpa using ⟨a::l, s, by simp, by simp⟩
| think s => simpa using ⟨l, s, by simp, by simp⟩
end Stream'.WSeq |
.lake/packages/mathlib/Mathlib/Data/WSeq/Productive.lean | import Mathlib.Data.WSeq.Relation
/-!
# Productive weak sequences
This file defines the property of a weak sequence being productive as never stalling – the next
output always comes after a finite time. Given a productive weak sequence, a regular sequence
(`Seq`) can be derived from it using `toSeq`.
-/
universe u
namespace Stream'.WSeq
variable {α : Type u}
open Function
/-- A weak sequence is *productive* if it never stalls forever - there are
always a finite number of `think`s between `cons` constructors.
The sequence itself is allowed to be infinite though. -/
class Productive (s : WSeq α) : Prop where
get?_terminates : ∀ n, (get? s n).Terminates
theorem productive_iff (s : WSeq α) : Productive s ↔ ∀ n, (get? s n).Terminates :=
⟨fun h => h.1, fun h => ⟨h⟩⟩
instance get?_terminates (s : WSeq α) [h : Productive s] : ∀ n, (get? s n).Terminates :=
h.get?_terminates
instance head_terminates (s : WSeq α) [Productive s] : (head s).Terminates :=
s.get?_terminates 0
instance productive_tail (s : WSeq α) [Productive s] : Productive (tail s) :=
⟨fun n => by rw [get?_tail]; infer_instance⟩
instance productive_dropn (s : WSeq α) [Productive s] (n) : Productive (drop s n) :=
⟨fun m => by rw [← get?_add]; infer_instance⟩
open Computation
instance productive_ofSeq (s : Seq α) : Productive (ofSeq s) :=
⟨fun n => by rw [get?_ofSeq]; infer_instance⟩
theorem productive_congr {s t : WSeq α} (h : s ~ʷ t) : Productive s ↔ Productive t := by
simp only [productive_iff]; exact forall_congr' fun n => terminates_congr <| get?_congr h _
/-- Given a productive weak sequence, we can collapse all the `think`s to
produce a sequence. -/
def toSeq (s : WSeq α) [Productive s] : Seq α :=
⟨fun n => (get? s n).get,
fun {n} h => by
cases e : Computation.get (get? s (n + 1))
· assumption
have := Computation.mem_of_get_eq _ e
simp only [get?] at this h
obtain ⟨a', h'⟩ := head_some_of_head_tail_some this
have := mem_unique h' (@Computation.mem_of_get_eq _ _ _ _ h)
contradiction⟩
theorem toSeq_ofSeq (s : Seq α) : toSeq (ofSeq s) = s := by
apply Subtype.eq; funext n
dsimp [toSeq]; apply get_eq_of_mem
rw [get?_ofSeq]; apply ret_mem
end Stream'.WSeq |
.lake/packages/mathlib/Mathlib/Data/PFunctor/Multivariate/Basic.lean | import Mathlib.Control.Functor.Multivariate
import Mathlib.Data.PFunctor.Univariate.Basic
/-!
# Multivariate polynomial functors.
Multivariate polynomial functors are used for defining M-types and W-types.
They map a type vector `α` to the type `Σ a : A, B a ⟹ α`, with `A : Type` and
`B : A → TypeVec n`. They interact well with Lean's inductive definitions because
they guarantee that occurrences of `α` are positive.
-/
universe u v
open MvFunctor
/-- multivariate polynomial functors
-/
@[pp_with_univ]
structure MvPFunctor (n : ℕ) where
/-- The head type -/
A : Type u
/-- The child family of types -/
B : A → TypeVec.{u} n
namespace MvPFunctor
open MvFunctor (LiftP LiftR)
variable {n m : ℕ} (P : MvPFunctor.{u} n)
/-- Applying `P` to an object of `Type` -/
@[coe]
def Obj (α : TypeVec.{u} n) : Type u :=
Σ a : P.A, P.B a ⟹ α
instance : CoeFun (MvPFunctor.{u} n) (fun _ => TypeVec.{u} n → Type u) where
coe := Obj
/-- Applying `P` to a morphism of `Type` -/
def map {α β : TypeVec n} (f : α ⟹ β) : P α → P β := fun ⟨a, g⟩ => ⟨a, TypeVec.comp f g⟩
instance : Inhabited (MvPFunctor n) :=
⟨⟨default, default⟩⟩
instance Obj.inhabited {α : TypeVec n} [Inhabited P.A] [∀ i, Inhabited (α i)] :
Inhabited (P α) :=
⟨⟨default, fun _ _ => default⟩⟩
instance : MvFunctor.{u} P.Obj :=
⟨@MvPFunctor.map n P⟩
theorem map_eq {α β : TypeVec n} (g : α ⟹ β) (a : P.A) (f : P.B a ⟹ α) :
@MvFunctor.map _ P.Obj _ _ _ g ⟨a, f⟩ = ⟨a, g ⊚ f⟩ :=
rfl
theorem id_map {α : TypeVec n} : ∀ x : P α, TypeVec.id <$$> x = x
| ⟨_, _⟩ => rfl
theorem comp_map {α β γ : TypeVec n} (f : α ⟹ β) (g : β ⟹ γ) :
∀ x : P α, (g ⊚ f) <$$> x = g <$$> f <$$> x
| ⟨_, _⟩ => rfl
instance : LawfulMvFunctor.{u} P.Obj where
id_map := @id_map _ P
comp_map := @comp_map _ P
/-- Constant functor where the input object does not affect the output -/
def const (n : ℕ) (A : Type u) : MvPFunctor n :=
{ A
B := fun _ _ => PEmpty }
section Const
variable (n) {A : Type u} {α β : TypeVec.{u} n}
/-- Constructor for the constant functor -/
def const.mk (x : A) {α} : const n A α :=
⟨x, fun _ a => PEmpty.elim a⟩
variable {n}
/-- Destructor for the constant functor -/
def const.get (x : const n A α) : A :=
x.1
@[simp]
theorem const.get_map (f : α ⟹ β) (x : const n A α) : const.get (f <$$> x) = const.get x := by
cases x
rfl
@[simp]
theorem const.get_mk (x : A) : const.get (const.mk n x : const n A α) = x := rfl
@[simp]
theorem const.mk_get (x : const n A α) : const.mk n (const.get x) = x := by
cases x
dsimp [const.get, const.mk]
congr with (_⟨⟩)
end Const
/-- Functor composition on polynomial functors -/
def comp (P : MvPFunctor.{u} n) (Q : Fin2 n → MvPFunctor.{u} m) : MvPFunctor m where
A := Σ a₂ : P.1, ∀ i, P.2 a₂ i → (Q i).1
B a i := Σ (j : _) (b : P.2 a.1 j), (Q j).2 (a.snd j b) i
variable {P} {Q : Fin2 n → MvPFunctor.{u} m} {α β : TypeVec.{u} m}
/-- Constructor for functor composition -/
def comp.mk (x : P (fun i => Q i α)) : comp P Q α :=
⟨⟨x.1, fun _ a => (x.2 _ a).1⟩, fun i a => (x.snd a.fst a.snd.fst).snd i a.snd.snd⟩
/-- Destructor for functor composition -/
def comp.get (x : comp P Q α) : P (fun i => Q i α) :=
⟨x.1.1, fun i a => ⟨x.fst.snd i a, fun (j : Fin2 m) (b : (Q i).B _ j) => x.snd j ⟨i, ⟨a, b⟩⟩⟩⟩
theorem comp.get_map (f : α ⟹ β) (x : comp P Q α) :
comp.get (f <$$> x) = (fun i (x : Q i α) => f <$$> x) <$$> comp.get x := by
rfl
@[simp]
theorem comp.get_mk (x : P (fun i => Q i α)) : comp.get (comp.mk x) = x := by
rfl
@[simp]
theorem comp.mk_get (x : comp P Q α) : comp.mk (comp.get x) = x := by
rfl
/-
lifting predicates and relations
-/
theorem liftP_iff {α : TypeVec n} (p : ∀ ⦃i⦄, α i → Prop) (x : P α) :
LiftP p x ↔ ∃ a f, x = ⟨a, f⟩ ∧ ∀ i j, p (f i j) := by
constructor
· rintro ⟨y, hy⟩
rcases h : y with ⟨a, f⟩
refine ⟨a, fun i j => (f i j).val, ?_, fun i j => (f i j).property⟩
rw [← hy, h, map_eq]
rfl
rintro ⟨a, f, xeq, pf⟩
use ⟨a, fun i j => ⟨f i j, pf i j⟩⟩
rw [xeq]; rfl
theorem liftP_iff' {α : TypeVec n} (p : ∀ ⦃i⦄, α i → Prop) (a : P.A) (f : P.B a ⟹ α) :
@LiftP.{u} _ P.Obj _ α p ⟨a, f⟩ ↔ ∀ i x, p (f i x) := by
simp only [liftP_iff]; constructor
· rintro ⟨_, _, ⟨⟩, _⟩
assumption
· intro
repeat' first |constructor|assumption
theorem liftR_iff {α : TypeVec n} (r : ∀ ⦃i⦄, α i → α i → Prop) (x y : P α) :
LiftR @r x y ↔ ∃ a f₀ f₁, x = ⟨a, f₀⟩ ∧ y = ⟨a, f₁⟩ ∧ ∀ i j, r (f₀ i j) (f₁ i j) := by
constructor
· rintro ⟨u, xeq, yeq⟩
rcases h : u with ⟨a, f⟩
use a, fun i j => (f i j).val.fst, fun i j => (f i j).val.snd
constructor
· rw [← xeq, h]
rfl
constructor
· rw [← yeq, h]
rfl
intro i j
exact (f i j).property
rintro ⟨a, f₀, f₁, xeq, yeq, h⟩
use ⟨a, fun i j => ⟨(f₀ i j, f₁ i j), h i j⟩⟩
dsimp; constructor
· rw [xeq]
rfl
rw [yeq]; rfl
open Set
theorem supp_eq {α : TypeVec n} (a : P.A) (f : P.B a ⟹ α) (i) :
@supp.{u} _ P.Obj _ α (⟨a, f⟩ : P α) i = f i '' univ := by
ext x; simp only [supp, image_univ, mem_range, mem_setOf_eq]
constructor <;> intro h
· apply @h fun i x => ∃ y : P.B a i, f i y = x
rw [liftP_iff']
intros
exact ⟨_, rfl⟩
· simp only [liftP_iff']
cases h
subst x
tauto
end MvPFunctor
/-
Decomposing an n+1-ary pfunctor.
-/
namespace MvPFunctor
open TypeVec
variable {n : ℕ} (P : MvPFunctor.{u} (n + 1))
/-- Split polynomial functor, get an n-ary functor
from an `n+1`-ary functor -/
def drop : MvPFunctor n where
A := P.A
B a := (P.B a).drop
/-- Split polynomial functor, get a univariate functor
from an `n+1`-ary functor -/
def last : PFunctor where
A := P.A
B a := (P.B a).last
/-- append arrows of a polynomial functor application -/
abbrev appendContents {α : TypeVec n} {β : Type*} {a : P.A} (f' : P.drop.B a ⟹ α)
(f : P.last.B a → β) : P.B a ⟹ (α ::: β) :=
splitFun f' f
end MvPFunctor |
.lake/packages/mathlib/Mathlib/Data/PFunctor/Multivariate/W.lean | import Mathlib.Data.PFunctor.Multivariate.Basic
/-!
# The W construction as a multivariate polynomial functor.
W types are well-founded tree-like structures. They are defined
as the least fixpoint of a polynomial functor.
## Main definitions
* `W_mk` - constructor
* `W_dest` - destructor
* `W_rec` - recursor: basis for defining functions by structural recursion on `P.W α`
* `W_rec_eq` - defining equation for `W_rec`
* `W_ind` - induction principle for `P.W α`
## Implementation notes
Three views of M-types:
* `wp`: polynomial functor
* `W`: data type inductively defined by a triple:
shape of the root, data in the root and children of the root
* `W`: least fixed point of a polynomial functor
Specifically, we define the polynomial functor `wp` as:
* A := a tree-like structure without information in the nodes
* B := given the tree-like structure `t`, `B t` is a valid path
(specified inductively by `W_path`) from the root of `t` to any given node.
As a result `wp α` is made of a dataless tree and a function from
its valid paths to values of `α`
## Reference
* Jeremy Avigad, Mario M. Carneiro and Simon Hudon.
[*Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019]
-/
universe u v
namespace MvPFunctor
open TypeVec
open MvFunctor
variable {n : ℕ} (P : MvPFunctor.{u} (n + 1))
/-- A path from the root of a tree to one of its node -/
inductive WPath : P.last.W → Fin2 n → Type u
| root (a : P.A) (f : P.last.B a → P.last.W) (i : Fin2 n) (c : P.drop.B a i) : WPath ⟨a, f⟩ i
| child (a : P.A) (f : P.last.B a → P.last.W) (i : Fin2 n) (j : P.last.B a)
(c : WPath (f j) i) : WPath ⟨a, f⟩ i
instance WPath.inhabited (x : P.last.W) {i} [I : Inhabited (P.drop.B x.head i)] :
Inhabited (WPath P x i) :=
⟨match x, I with
| ⟨a, f⟩, I => WPath.root a f i (@default _ I)⟩
/-- Specialized destructor on `WPath` -/
def wPathCasesOn {α : TypeVec n} {a : P.A} {f : P.last.B a → P.last.W} (g' : P.drop.B a ⟹ α)
(g : ∀ j : P.last.B a, P.WPath (f j) ⟹ α) : P.WPath ⟨a, f⟩ ⟹ α := by
intro i x
match x with
| WPath.root _ _ i c => exact g' i c
| WPath.child _ _ i j c => exact g j i c
/-- Specialized destructor on `WPath` -/
def wPathDestLeft {α : TypeVec n} {a : P.A} {f : P.last.B a → P.last.W}
(h : P.WPath ⟨a, f⟩ ⟹ α) : P.drop.B a ⟹ α := fun i c => h i (WPath.root a f i c)
/-- Specialized destructor on `WPath` -/
def wPathDestRight {α : TypeVec n} {a : P.A} {f : P.last.B a → P.last.W}
(h : P.WPath ⟨a, f⟩ ⟹ α) : ∀ j : P.last.B a, P.WPath (f j) ⟹ α := fun j i c =>
h i (WPath.child a f i j c)
theorem wPathDestLeft_wPathCasesOn {α : TypeVec n} {a : P.A} {f : P.last.B a → P.last.W}
(g' : P.drop.B a ⟹ α) (g : ∀ j : P.last.B a, P.WPath (f j) ⟹ α) :
P.wPathDestLeft (P.wPathCasesOn g' g) = g' := rfl
theorem wPathDestRight_wPathCasesOn {α : TypeVec n} {a : P.A} {f : P.last.B a → P.last.W}
(g' : P.drop.B a ⟹ α) (g : ∀ j : P.last.B a, P.WPath (f j) ⟹ α) :
P.wPathDestRight (P.wPathCasesOn g' g) = g := rfl
theorem wPathCasesOn_eta {α : TypeVec n} {a : P.A} {f : P.last.B a → P.last.W}
(h : P.WPath ⟨a, f⟩ ⟹ α) : P.wPathCasesOn (P.wPathDestLeft h) (P.wPathDestRight h) = h := by
ext i x; cases x <;> rfl
theorem comp_wPathCasesOn {α β : TypeVec n} (h : α ⟹ β) {a : P.A} {f : P.last.B a → P.last.W}
(g' : P.drop.B a ⟹ α) (g : ∀ j : P.last.B a, P.WPath (f j) ⟹ α) :
h ⊚ P.wPathCasesOn g' g = P.wPathCasesOn (h ⊚ g') fun i => h ⊚ g i := by
ext i x; cases x <;> rfl
/-- Polynomial functor for the W-type of `P`. `A` is a data-less well-founded
tree whereas, for a given `a : A`, `B a` is a valid path in tree `a` so
that `Wp.obj α` is made of a tree and a function from its valid paths to
the values it contains -/
def wp : MvPFunctor n where
A := P.last.W
B := P.WPath
/-- W-type of `P` -/
def W (α : TypeVec n) : Type _ :=
P.wp α
instance mvfunctorW : MvFunctor P.W := by delta MvPFunctor.W; infer_instance
/-!
First, describe operations on `W` as a polynomial functor.
-/
/-- Constructor for `wp` -/
def wpMk {α : TypeVec n} (a : P.A) (f : P.last.B a → P.last.W) (f' : P.WPath ⟨a, f⟩ ⟹ α) :
P.W α :=
⟨⟨a, f⟩, f'⟩
def wpRec {α : TypeVec n} {C : Type*}
(g : ∀ (a : P.A) (f : P.last.B a → P.last.W), P.WPath ⟨a, f⟩ ⟹ α → (P.last.B a → C) → C) :
∀ (x : P.last.W) (_ : P.WPath x ⟹ α), C
| ⟨a, f⟩, f' => g a f f' fun i => wpRec g (f i) (P.wPathDestRight f' i)
theorem wpRec_eq {α : TypeVec n} {C : Type*}
(g : ∀ (a : P.A) (f : P.last.B a → P.last.W), P.WPath ⟨a, f⟩ ⟹ α → (P.last.B a → C) → C)
(a : P.A) (f : P.last.B a → P.last.W) (f' : P.WPath ⟨a, f⟩ ⟹ α) :
P.wpRec g ⟨a, f⟩ f' = g a f f' fun i => P.wpRec g (f i) (P.wPathDestRight f' i) := rfl
-- Note: we could replace Prop by Type* and obtain a dependent recursor
theorem wp_ind {α : TypeVec n} {C : ∀ x : P.last.W, P.WPath x ⟹ α → Prop}
(ih : ∀ (a : P.A) (f : P.last.B a → P.last.W) (f' : P.WPath ⟨a, f⟩ ⟹ α),
(∀ i : P.last.B a, C (f i) (P.wPathDestRight f' i)) → C ⟨a, f⟩ f') :
∀ (x : P.last.W) (f' : P.WPath x ⟹ α), C x f'
| ⟨a, f⟩, f' => ih a f f' fun _i => wp_ind ih _ _
/-!
Now think of W as defined inductively by the data ⟨a, f', f⟩ where
- `a : P.A` is the shape of the top node
- `f' : P.drop.B a ⟹ α` is the contents of the top node
- `f : P.last.B a → P.last.W` are the subtrees
-/
/-- Constructor for `W` -/
def wMk {α : TypeVec n} (a : P.A) (f' : P.drop.B a ⟹ α) (f : P.last.B a → P.W α) : P.W α :=
let g : P.last.B a → P.last.W := fun i => (f i).fst
let g' : P.WPath ⟨a, g⟩ ⟹ α := P.wPathCasesOn f' fun i => (f i).snd
⟨⟨a, g⟩, g'⟩
/-- Recursor for `W` -/
def wRec {α : TypeVec n} {C : Type*}
(g : ∀ a : P.A, P.drop.B a ⟹ α → (P.last.B a → P.W α) → (P.last.B a → C) → C) : P.W α → C
| ⟨a, f'⟩ =>
let g' (a : P.A) (f : P.last.B a → P.last.W) (h : P.WPath ⟨a, f⟩ ⟹ α)
(h' : P.last.B a → C) : C :=
g a (P.wPathDestLeft h) (fun i => ⟨f i, P.wPathDestRight h i⟩) h'
P.wpRec g' a f'
/-- Defining equation for the recursor of `W` -/
theorem wRec_eq {α : TypeVec n} {C : Type*}
(g : ∀ a : P.A, P.drop.B a ⟹ α → (P.last.B a → P.W α) → (P.last.B a → C) → C) (a : P.A)
(f' : P.drop.B a ⟹ α) (f : P.last.B a → P.W α) :
P.wRec g (P.wMk a f' f) = g a f' f fun i => P.wRec g (f i) := rfl
/-- Induction principle for `W` -/
theorem w_ind {α : TypeVec n} {C : P.W α → Prop}
(ih : ∀ (a : P.A) (f' : P.drop.B a ⟹ α) (f : P.last.B a → P.W α),
(∀ i, C (f i)) → C (P.wMk a f' f)) :
∀ x, C x := by
intro x; obtain ⟨a, f⟩ := x
apply @wp_ind n P α fun a f => C ⟨a, f⟩
intro a f f' ih'
dsimp [wMk] at ih
let ih'' := ih a (P.wPathDestLeft f') fun i => ⟨f i, P.wPathDestRight f' i⟩
dsimp at ih''; rw [wPathCasesOn_eta] at ih''
apply ih''
apply ih'
theorem w_cases {α : TypeVec n} {C : P.W α → Prop}
(ih : ∀ (a : P.A) (f' : P.drop.B a ⟹ α) (f : P.last.B a → P.W α), C (P.wMk a f' f)) :
∀ x, C x := P.w_ind fun a f' f _ih' => ih a f' f
/-- W-types are functorial -/
def wMap {α β : TypeVec n} (g : α ⟹ β) : P.W α → P.W β := fun x => g <$$> x
theorem wMk_eq {α : TypeVec n} (a : P.A) (f : P.last.B a → P.last.W) (g' : P.drop.B a ⟹ α)
(g : ∀ j : P.last.B a, P.WPath (f j) ⟹ α) :
(P.wMk a g' fun i => ⟨f i, g i⟩) = ⟨⟨a, f⟩, P.wPathCasesOn g' g⟩ := rfl
theorem w_map_wMk {α β : TypeVec n} (g : α ⟹ β) (a : P.A) (f' : P.drop.B a ⟹ α)
(f : P.last.B a → P.W α) : g <$$> P.wMk a f' f = P.wMk a (g ⊚ f') fun i => g <$$> f i := by
change _ = P.wMk a (g ⊚ f') (MvFunctor.map g ∘ f)
have : MvFunctor.map g ∘ f = fun i => ⟨(f i).fst, g ⊚ (f i).snd⟩ := by
ext i : 1
dsimp [Function.comp_def]
cases f i
rfl
rw [this]
have : f = fun i => ⟨(f i).fst, (f i).snd⟩ := by
ext1 x
cases f x
rfl
rw [this]
dsimp
rw [wMk_eq, wMk_eq]
have h := MvPFunctor.map_eq P.wp g
rw [h, comp_wPathCasesOn]
-- TODO: this technical theorem is used in one place in constructing the initial algebra.
-- Can it be avoided?
/-- Constructor of a value of `P.obj (α ::: β)` from components.
Useful to avoid complicated type annotation -/
abbrev objAppend1 {α : TypeVec n} {β : Type u} (a : P.A) (f' : P.drop.B a ⟹ α)
(f : P.last.B a → β) : P (α ::: β) :=
⟨a, splitFun f' f⟩
theorem map_objAppend1 {α γ : TypeVec n} (g : α ⟹ γ) (a : P.A) (f' : P.drop.B a ⟹ α)
(f : P.last.B a → P.W α) :
appendFun g (P.wMap g) <$$> P.objAppend1 a f' f =
P.objAppend1 a (g ⊚ f') fun x => P.wMap g (f x) := by
rw [objAppend1, objAppend1, map_eq, appendFun, ← splitFun_comp]; rfl
/-!
Yet another view of the W type: as a fixed point for a multivariate polynomial functor.
These are needed to use the W-construction to construct a fixed point of a qpf, since
the qpf axioms are expressed in terms of `map` on `P`.
-/
/-- Constructor for the W-type of `P` -/
def wMk' {α : TypeVec n} : P (α ::: P.W α) → P.W α
| ⟨a, f⟩ => P.wMk a (dropFun f) (lastFun f)
/-- Destructor for the W-type of `P` -/
def wDest' {α : TypeVec.{u} n} : P.W α → P (α.append1 (P.W α)) :=
P.wRec fun a f' f _ => ⟨a, splitFun f' f⟩
theorem wDest'_wMk {α : TypeVec n} (a : P.A) (f' : P.drop.B a ⟹ α) (f : P.last.B a → P.W α) :
P.wDest' (P.wMk a f' f) = ⟨a, splitFun f' f⟩ := by rw [wDest', wRec_eq]
theorem wDest'_wMk' {α : TypeVec n} (x : P (α.append1 (P.W α))) : P.wDest' (P.wMk' x) = x := by
obtain ⟨a, f⟩ := x; rw [wMk', wDest'_wMk, split_dropFun_lastFun]
end MvPFunctor |
.lake/packages/mathlib/Mathlib/Data/PFunctor/Multivariate/M.lean | import Mathlib.Data.PFunctor.Multivariate.Basic
import Mathlib.Data.PFunctor.Univariate.M
/-!
# The M construction as a multivariate polynomial functor.
M types are potentially infinite tree-like structures. They are defined
as the greatest fixpoint of a polynomial functor.
## Main definitions
* `M.mk` - constructor
* `M.dest` - destructor
* `M.corec` - corecursor: useful for formulating infinite, productive computations
* `M.bisim` - bisimulation: proof technique to show the equality of infinite objects
## Implementation notes
Dual view of M-types:
* `mp`: polynomial functor
* `M`: greatest fixed point of a polynomial functor
Specifically, we define the polynomial functor `mp` as:
* A := a possibly infinite tree-like structure without information in the nodes
* B := given the tree-like structure `t`, `B t` is a valid path
from the root of `t` to any given node.
As a result `mp α` is made of a dataless tree and a function from
its valid paths to values of `α`
The difference with the polynomial functor of an initial algebra is
that `A` is a possibly infinite tree.
## Reference
* Jeremy Avigad, Mario M. Carneiro and Simon Hudon.
[*Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019]
-/
universe u v
open MvFunctor
namespace MvPFunctor
open TypeVec
variable {n : ℕ} (P : MvPFunctor.{u} (n + 1))
/-- A path from the root of a tree to one of its node -/
inductive M.Path : P.last.M → Fin2 n → Type u
| root (x : P.last.M)
(a : P.A)
(f : P.last.B a → P.last.M)
(h : PFunctor.M.dest x = ⟨a, f⟩)
(i : Fin2 n)
(c : P.drop.B a i) : M.Path x i
| child (x : P.last.M)
(a : P.A)
(f : P.last.B a → P.last.M)
(h : PFunctor.M.dest x = ⟨a, f⟩)
(j : P.last.B a)
(i : Fin2 n)
(c : M.Path (f j) i) : M.Path x i
instance M.Path.inhabited (x : P.last.M) {i} [Inhabited (P.drop.B x.head i)] :
Inhabited (M.Path P x i) :=
let a := PFunctor.M.head x
let f := PFunctor.M.children x
⟨M.Path.root _ a f
(PFunctor.M.casesOn' x
(r := fun _ => PFunctor.M.dest x = ⟨a, f⟩)
<| by
intros; simp [a]; rfl)
_ default⟩
/-- Polynomial functor of the M-type of `P`. `A` is a data-less
possibly infinite tree whereas, for a given `a : A`, `B a` is a valid
path in tree `a` so that `mp α` is made of a tree and a function
from its valid paths to the values it contains -/
def mp : MvPFunctor n where
A := P.last.M
B := M.Path P
/-- `n`-ary M-type for `P` -/
def M (α : TypeVec n) : Type _ :=
P.mp α
instance mvfunctorM : MvFunctor P.M := by delta M; infer_instance
instance inhabitedM {α : TypeVec _} [I : Inhabited P.A] [∀ i : Fin2 n, Inhabited (α i)] :
Inhabited (P.M α) :=
@Obj.inhabited _ (mp P) _ (@PFunctor.M.inhabited P.last I) _
/-- construct through corecursion the shape of an M-type
without its contents -/
def M.corecShape {β : Type v} (g₀ : β → P.A) (g₂ : ∀ b : β, P.last.B (g₀ b) → β) :
β → P.last.M :=
PFunctor.M.corec fun b => ⟨g₀ b, g₂ b⟩
/-- Proof of type equality as an arrow -/
def castDropB {a a' : P.A} (h : a = a') : P.drop.B a ⟹ P.drop.B a' := fun _i b => Eq.recOn h b
/-- Proof of type equality as a function -/
def castLastB {a a' : P.A} (h : a = a') : P.last.B a → P.last.B a' := fun b => Eq.recOn h b
/-- Using corecursion, construct the contents of an M-type -/
def M.corecContents {α : TypeVec.{u} n}
{β : Type v}
(g₀ : β → P.A)
(g₁ : ∀ b : β, P.drop.B (g₀ b) ⟹ α)
(g₂ : ∀ b : β, P.last.B (g₀ b) → β)
(x : _)
(b : β)
(h : x = M.corecShape P g₀ g₂ b) :
M.Path P x ⟹ α
| _, M.Path.root x a f h' i c =>
have : a = g₀ b := by
rw [h, M.corecShape, PFunctor.M.dest_corec] at h'
cases h'
rfl
g₁ b i (P.castDropB this i c)
| _, M.Path.child x a f h' j i c =>
have h₀ : a = g₀ b := by
rw [h, M.corecShape, PFunctor.M.dest_corec] at h'
cases h'
rfl
have h₁ : f j = M.corecShape P g₀ g₂ (g₂ b (castLastB P h₀ j)) := by
rw [h, M.corecShape, PFunctor.M.dest_corec] at h'
cases h'
rfl
M.corecContents g₀ g₁ g₂ (f j) (g₂ b (P.castLastB h₀ j)) h₁ i c
/-- Corecursor for M-type of `P` -/
def M.corec' {α : TypeVec n} {β : Type v} (g₀ : β → P.A) (g₁ : ∀ b : β, P.drop.B (g₀ b) ⟹ α)
(g₂ : ∀ b : β, P.last.B (g₀ b) → β) : β → P.M α := fun b =>
⟨M.corecShape P g₀ g₂ b, M.corecContents P g₀ g₁ g₂ _ _ rfl⟩
/-- Corecursor for M-type of `P` -/
def M.corec {α : TypeVec n} {β : Type u} (g : β → P (α.append1 β)) : β → P.M α :=
M.corec' P (fun b => (g b).fst) (fun b => dropFun (g b).snd) fun b => lastFun (g b).snd
/-- Implementation of destructor for M-type of `P` -/
def M.pathDestLeft {α : TypeVec n} {x : P.last.M} {a : P.A} {f : P.last.B a → P.last.M}
(h : PFunctor.M.dest x = ⟨a, f⟩) (f' : M.Path P x ⟹ α) : P.drop.B a ⟹ α := fun i c =>
f' i (M.Path.root x a f h i c)
/-- Implementation of destructor for M-type of `P` -/
def M.pathDestRight {α : TypeVec n} {x : P.last.M} {a : P.A} {f : P.last.B a → P.last.M}
(h : PFunctor.M.dest x = ⟨a, f⟩) (f' : M.Path P x ⟹ α) :
∀ j : P.last.B a, M.Path P (f j) ⟹ α := fun j i c => f' i (M.Path.child x a f h j i c)
/-- Destructor for M-type of `P` -/
def M.dest' {α : TypeVec n} {x : P.last.M} {a : P.A} {f : P.last.B a → P.last.M}
(h : PFunctor.M.dest x = ⟨a, f⟩) (f' : M.Path P x ⟹ α) : P (α.append1 (P.M α)) :=
⟨a, splitFun (M.pathDestLeft P h f') fun x => ⟨f x, M.pathDestRight P h f' x⟩⟩
/-- Destructor for M-types -/
def M.dest {α : TypeVec n} (x : P.M α) : P (α ::: P.M α) :=
M.dest' P (Sigma.eta <| PFunctor.M.dest x.fst).symm x.snd
/-- Constructor for M-types -/
def M.mk {α : TypeVec n} : P (α.append1 (P.M α)) → P.M α :=
M.corec _ fun i => appendFun id (M.dest P) <$$> i
theorem M.dest'_eq_dest' {α : TypeVec n} {x : P.last.M} {a₁ : P.A}
{f₁ : P.last.B a₁ → P.last.M} (h₁ : PFunctor.M.dest x = ⟨a₁, f₁⟩) {a₂ : P.A}
{f₂ : P.last.B a₂ → P.last.M} (h₂ : PFunctor.M.dest x = ⟨a₂, f₂⟩) (f' : M.Path P x ⟹ α) :
M.dest' P h₁ f' = M.dest' P h₂ f' := by cases h₁.symm.trans h₂; rfl
theorem M.dest_eq_dest' {α : TypeVec n} {x : P.last.M} {a : P.A}
{f : P.last.B a → P.last.M} (h : PFunctor.M.dest x = ⟨a, f⟩) (f' : M.Path P x ⟹ α) :
M.dest P ⟨x, f'⟩ = M.dest' P h f' :=
M.dest'_eq_dest' _ _ _ _
theorem M.dest_corec' {α : TypeVec.{u} n} {β : Type v} (g₀ : β → P.A)
(g₁ : ∀ b : β, P.drop.B (g₀ b) ⟹ α) (g₂ : ∀ b : β, P.last.B (g₀ b) → β) (x : β) :
M.dest P (M.corec' P g₀ g₁ g₂ x) = ⟨g₀ x, splitFun (g₁ x) (M.corec' P g₀ g₁ g₂ ∘ g₂ x)⟩ :=
rfl
theorem M.dest_corec {α : TypeVec n} {β : Type u} (g : β → P (α.append1 β)) (x : β) :
M.dest P (M.corec P g x) = appendFun id (M.corec P g) <$$> g x := by
trans
· apply M.dest_corec'
obtain ⟨a, f⟩ := g x; dsimp
rw [MvPFunctor.map_eq]; congr
conv_rhs => rw [← split_dropFun_lastFun f, appendFun_comp_splitFun]
rfl
theorem M.bisim_lemma {α : TypeVec n} {a₁ : (mp P).A} {f₁ : (mp P).B a₁ ⟹ α} {a' : P.A}
{f' : (P.B a').drop ⟹ α} {f₁' : (P.B a').last → M P α}
(e₁ : M.dest P ⟨a₁, f₁⟩ = ⟨a', splitFun f' f₁'⟩) :
∃ (g₁' : _)(e₁' : PFunctor.M.dest a₁ = ⟨a', g₁'⟩),
f' = M.pathDestLeft P e₁' f₁ ∧
f₁' = fun x : (last P).B a' => ⟨g₁' x, M.pathDestRight P e₁' f₁ x⟩ := by
generalize ef : @splitFun n _ (append1 α (M P α)) f' f₁' = ff at e₁
let he₁' := PFunctor.M.dest a₁
rcases e₁' : he₁' with ⟨a₁', g₁'⟩
rw [M.dest_eq_dest' _ e₁'] at e₁
cases e₁; exact ⟨_, e₁', splitFun_inj ef⟩
theorem M.bisim {α : TypeVec n} (R : P.M α → P.M α → Prop)
(h :
∀ x y,
R x y →
∃ a f f₁ f₂,
M.dest P x = ⟨a, splitFun f f₁⟩ ∧
M.dest P y = ⟨a, splitFun f f₂⟩ ∧ ∀ i, R (f₁ i) (f₂ i))
(x y) (r : R x y) : x = y := by
obtain ⟨a₁, f₁⟩ := x
obtain ⟨a₂, f₂⟩ := y
dsimp [mp] at *
have : a₁ = a₂ := by
refine
PFunctor.M.bisim (fun a₁ a₂ => ∃ x y, R x y ∧ x.1 = a₁ ∧ y.1 = a₂) ?_ _ _
⟨⟨a₁, f₁⟩, ⟨a₂, f₂⟩, r, rfl, rfl⟩
rintro _ _ ⟨⟨a₁, f₁⟩, ⟨a₂, f₂⟩, r, rfl, rfl⟩
rcases h _ _ r with ⟨a', f', f₁', f₂', e₁, e₂, h'⟩
rcases M.bisim_lemma P e₁ with ⟨g₁', e₁', rfl, rfl⟩
rcases M.bisim_lemma P e₂ with ⟨g₂', e₂', _, rfl⟩
rw [e₁', e₂']
exact ⟨_, _, _, rfl, rfl, fun b => ⟨_, _, h' b, rfl, rfl⟩⟩
subst this
congr with (i p)
induction p with (
obtain ⟨a', f', f₁', f₂', e₁, e₂, h''⟩ := h _ _ r
obtain ⟨g₁', e₁', rfl, rfl⟩ := M.bisim_lemma P e₁
obtain ⟨g₂', e₂', e₃, rfl⟩ := M.bisim_lemma P e₂
cases h'.symm.trans e₁'
cases h'.symm.trans e₂')
| root x a f h' i c =>
exact congr_fun (congr_fun e₃ i) c
| child x a f h' i c p IH =>
exact IH _ _ (h'' _)
theorem M.bisim₀ {α : TypeVec n} (R : P.M α → P.M α → Prop) (h₀ : Equivalence R)
(h : ∀ x y, R x y → (id ::: Quot.mk R) <$$> M.dest _ x = (id ::: Quot.mk R) <$$> M.dest _ y)
(x y) (r : R x y) : x = y := by
apply M.bisim P R _ _ _ r
clear r x y
introv Hr
specialize h _ _ Hr
clear Hr
revert h
rcases M.dest P x with ⟨ax, fx⟩
rcases M.dest P y with ⟨ay, fy⟩
intro h
rw [map_eq, map_eq] at h
injection h with h₀ h₁
subst ay
simp only [heq_eq_eq] at h₁
have Hdrop : dropFun fx = dropFun fy := by
replace h₁ := congr_arg dropFun h₁
simpa using h₁
exists ax, dropFun fx, lastFun fx, lastFun fy
rw [split_dropFun_lastFun, Hdrop, split_dropFun_lastFun]
simp only [true_and]
intro i
replace h₁ := congr_fun (congr_fun h₁ Fin2.fz) i
simp only [TypeVec.comp, appendFun, splitFun] at h₁
replace h₁ := Quot.eqvGen_exact h₁
rw [h₀.eqvGen_iff] at h₁
exact h₁
theorem M.bisim' {α : TypeVec n} (R : P.M α → P.M α → Prop)
(h : ∀ x y, R x y → (id ::: Quot.mk R) <$$> M.dest _ x = (id ::: Quot.mk R) <$$> M.dest _ y)
(x y) (r : R x y) : x = y := by
have := M.bisim₀ P (Relation.EqvGen R) ?_ ?_
· solve_by_elim [Relation.EqvGen.rel]
· apply Relation.EqvGen.is_equivalence
· clear r x y
introv Hr
have : ∀ x y, R x y → Relation.EqvGen R x y := @Relation.EqvGen.rel _ R
induction Hr
· rw [← Quot.factor_mk_eq R (Relation.EqvGen R) this]
rwa [appendFun_comp_id, ← MvFunctor.map_map, ← MvFunctor.map_map, h]
all_goals simp_all
theorem M.dest_map {α β : TypeVec n} (g : α ⟹ β) (x : P.M α) :
M.dest P (g <$$> x) = (appendFun g fun x => g <$$> x) <$$> M.dest P x := by
obtain ⟨a, f⟩ := x
rw [map_eq]
conv =>
rhs
rw [M.dest, M.dest', map_eq, appendFun_comp_splitFun]
rfl
theorem M.map_dest {α β : TypeVec n} (g : (α ::: P.M α) ⟹ (β ::: P.M β)) (x : P.M α)
(h : ∀ x : P.M α, lastFun g x = (dropFun g <$$> x : P.M β)) :
g <$$> M.dest P x = M.dest P (dropFun g <$$> x) := by
rw [M.dest_map]; congr
apply eq_of_drop_last_eq (by simp)
simp only [lastFun_appendFun]
ext1; apply h
end MvPFunctor |
.lake/packages/mathlib/Mathlib/Data/PFunctor/Univariate/Basic.lean | import Mathlib.Data.W.Basic
/-!
# Polynomial Functors
This file defines polynomial functors and the W-type construction as a polynomial functor.
(For the M-type construction, see `Mathlib/Data/PFunctor/Univariate/M.lean`.)
-/
universe u v uA uB uA₁ uB₁ uA₂ uB₂ v₁ v₂ v₃
/-- A polynomial functor `P` is given by a type `A` and a family `B` of types over `A`. `P` maps
any type `α` to a new type `P α`, which is defined as the sigma type `Σ x, P.B x → α`.
An element of `P α` is a pair `⟨a, f⟩`, where `a` is an element of a type `A` and
`f : B a → α`. Think of `a` as the shape of the object and `f` as an index to the relevant
elements of `α`.
-/
-- Note: `nolint checkUnivs` should not apply here, we really do want two separate universe levels
@[pp_with_univ, nolint checkUnivs]
structure PFunctor where
/-- The head type -/
A : Type uA
/-- The child family of types -/
B : A → Type uB
namespace PFunctor
instance : Inhabited PFunctor :=
⟨⟨default, default⟩⟩
variable (P : PFunctor.{uA, uB}) {α : Type v₁} {β : Type v₂} {γ : Type v₃}
/-- Applying `P` to an object of `Type` -/
@[coe]
def Obj (α : Type v) : Type (max v uA uB) :=
Σ x : P.A, P.B x → α
instance : CoeFun PFunctor.{uA, uB} (fun _ => Type v → Type (max v uA uB)) where
coe := Obj
/-- Applying `P` to a morphism of `Type` -/
def map (f : α → β) : P α → P β :=
fun ⟨a, g⟩ => ⟨a, f ∘ g⟩
instance Obj.inhabited [Inhabited P.A] [Inhabited α] : Inhabited (P α) :=
⟨⟨default, default⟩⟩
instance : Functor P.Obj where map := @map P
/-- We prefer `PFunctor.map` to `Functor.map` because it is universe-polymorphic. -/
@[simp]
theorem map_eq_map {α β : Type v} (f : α → β) (x : P α) : f <$> x = P.map f x :=
rfl
@[simp]
protected theorem map_eq (f : α → β) (a : P.A) (g : P.B a → α) :
P.map f ⟨a, g⟩ = ⟨a, f ∘ g⟩ :=
rfl
@[simp]
protected theorem id_map : ∀ x : P α, P.map id x = x := fun ⟨_, _⟩ => rfl
@[simp]
protected theorem map_map (f : α → β) (g : β → γ) :
∀ x : P α, P.map g (P.map f x) = P.map (g ∘ f) x := fun ⟨_, _⟩ => rfl
instance : LawfulFunctor (Obj.{v} P) where
map_const := rfl
id_map x := P.id_map x
comp_map f g x := P.map_map f g x |>.symm
/-- Re-export existing definition of W-types and adapt it to a packaged definition of polynomial
functor. -/
def W : Type (max uA uB) :=
WType P.B
/- Inhabitants of W types is awkward to encode as an instance assumption because there needs to be a
value `a : P.A` such that `P.B a` is empty to yield a finite tree. -/
variable {P}
/-- The root element of a W tree -/
def W.head : W P → P.A
| ⟨a, _f⟩ => a
/-- The children of the root of a W tree -/
def W.children : ∀ x : W P, P.B (W.head x) → W P
| ⟨_a, f⟩ => f
/-- The destructor for W-types -/
def W.dest : W P → P (W P)
| ⟨a, f⟩ => ⟨a, f⟩
/-- The constructor for W-types -/
def W.mk : P (W P) → W P
| ⟨a, f⟩ => ⟨a, f⟩
@[simp]
theorem W.dest_mk (p : P (W P)) : W.dest (W.mk p) = p := by cases p; rfl
@[simp]
theorem W.mk_dest (p : W P) : W.mk (W.dest p) = p := by cases p; rfl
variable (P)
/-- `Idx` identifies a location inside the application of a polynomial functor. For `F : PFunctor`,
`x : F α` and `i : F.Idx`, `i` can designate one part of `x` or is invalid, if `i.1 ≠ x.1`. -/
def Idx : Type (max uA uB) :=
Σ x : P.A, P.B x
instance Idx.inhabited [Inhabited P.A] [Inhabited (P.B default)] : Inhabited P.Idx :=
⟨⟨default, default⟩⟩
variable {P}
/-- `x.iget i` takes the component of `x` designated by `i` if any is or returns a default value -/
def Obj.iget [DecidableEq P.A] {α} [Inhabited α] (x : P α) (i : P.Idx) : α :=
if h : i.1 = x.1 then x.2 (cast (congr_arg _ h) i.2) else default
@[simp]
theorem fst_map (x : P α) (f : α → β) : (P.map f x).1 = x.1 := by cases x; rfl
@[simp]
theorem iget_map [DecidableEq P.A] [Inhabited α] [Inhabited β] (x : P α)
(f : α → β) (i : P.Idx) (h : i.1 = x.1) : (P.map f x).iget i = f (x.iget i) := by
simp only [Obj.iget, fst_map, *, dif_pos]
cases x
rfl
end PFunctor
/-
Composition of polynomial functors.
-/
namespace PFunctor
/-- Composition for polynomial functors -/
def comp (P₂ : PFunctor.{uA₂, uB₂}) (P₁ : PFunctor.{uA₁, uB₁}) :
PFunctor.{max uA₁ uA₂ uB₂, max uB₁ uB₂} :=
⟨Σ a₂ : P₂.1, P₂.2 a₂ → P₁.1, fun a₂a₁ => Σ u : P₂.2 a₂a₁.1, P₁.2 (a₂a₁.2 u)⟩
/-- Constructor for composition -/
def comp.mk (P₂ : PFunctor.{uA₂, uB₂}) (P₁ : PFunctor.{uA₁, uB₁}) {α : Type v} (x : P₂ (P₁ α)) :
comp P₂ P₁ α :=
⟨⟨x.1, Sigma.fst ∘ x.2⟩, fun a₂a₁ => (x.2 a₂a₁.1).2 a₂a₁.2⟩
/-- Destructor for composition -/
def comp.get (P₂ : PFunctor.{uA₂, uB₂}) (P₁ : PFunctor.{uA₁, uB₁}) {α : Type v} (x : comp P₂ P₁ α) :
P₂ (P₁ α) :=
⟨x.1.1, fun a₂ => ⟨x.1.2 a₂, fun a₁ => x.2 ⟨a₂, a₁⟩⟩⟩
end PFunctor
/-
Lifting predicates and relations.
-/
namespace PFunctor
variable {P : PFunctor.{uA, uB}}
open Functor
theorem liftp_iff {α : Type u} (p : α → Prop) (x : P α) :
Liftp p x ↔ ∃ a f, x = ⟨a, f⟩ ∧ ∀ i, p (f i) := by
constructor
· rintro ⟨y, hy⟩
rcases h : y with ⟨a, f⟩
refine ⟨a, fun i => (f i).val, ?_, fun i => (f i).property⟩
rw [← hy, h, map_eq_map, PFunctor.map_eq]
congr
rintro ⟨a, f, xeq, pf⟩
use ⟨a, fun i => ⟨f i, pf i⟩⟩
rw [xeq]; rfl
theorem liftp_iff' {α : Type u} (p : α → Prop) (a : P.A) (f : P.B a → α) :
@Liftp.{u} P.Obj _ α p ⟨a, f⟩ ↔ ∀ i, p (f i) := by
simp only [liftp_iff]; constructor <;> intro h
· rcases h with ⟨a', f', heq, h'⟩
cases heq
assumption
repeat' first |constructor|assumption
theorem liftr_iff {α : Type u} (r : α → α → Prop) (x y : P α) :
Liftr r x y ↔ ∃ a f₀ f₁, x = ⟨a, f₀⟩ ∧ y = ⟨a, f₁⟩ ∧ ∀ i, r (f₀ i) (f₁ i) := by
constructor
· rintro ⟨u, xeq, yeq⟩
rcases h : u with ⟨a, f⟩
use a, fun i => (f i).val.fst, fun i => (f i).val.snd
constructor
· rw [← xeq, h]
rfl
constructor
· rw [← yeq, h]
rfl
intro i
exact (f i).property
rintro ⟨a, f₀, f₁, xeq, yeq, h⟩
use ⟨a, fun i => ⟨(f₀ i, f₁ i), h i⟩⟩
constructor
· rw [xeq]
rfl
rw [yeq]; rfl
open Set
theorem supp_eq {α : Type u} (a : P.A) (f : P.B a → α) :
@supp.{u} P.Obj _ α (⟨a, f⟩ : P α) = f '' univ := by
ext x; simp only [supp, image_univ, mem_range, mem_setOf_eq]
constructor <;> intro h
· apply @h fun x => ∃ y : P.B a, f y = x
rw [liftp_iff']
intro
exact ⟨_, rfl⟩
· simp only [liftp_iff']
cases h
subst x
tauto
end PFunctor |
.lake/packages/mathlib/Mathlib/Data/PFunctor/Univariate/M.lean | import Mathlib.Data.PFunctor.Univariate.Basic
/-!
# M-types
M types are potentially infinite tree-like structures. They are defined
as the greatest fixpoint of a polynomial functor.
-/
universe u uA uB v w
open Nat Function
open List
variable (F : PFunctor.{uA, uB})
namespace PFunctor
namespace Approx
/-- `CofixA F n` is an `n` level approximation of an M-type -/
inductive CofixA : ℕ → Type (max uA uB)
| continue : CofixA 0
| intro {n} : ∀ a, (F.B a → CofixA n) → CofixA (succ n)
/-- default inhabitant of `CofixA` -/
protected def CofixA.default [Inhabited F.A] : ∀ n, CofixA F n
| 0 => CofixA.continue
| succ n => CofixA.intro default fun _ => CofixA.default n
instance [Inhabited F.A] {n} : Inhabited (CofixA F n) :=
⟨CofixA.default F n⟩
theorem cofixA_eq_zero : ∀ x y : CofixA F 0, x = y
| CofixA.continue, CofixA.continue => rfl
variable {F}
/-- The label of the root of the tree for a non-trivial
approximation of the cofix of a pfunctor.
-/
def head' : ∀ {n}, CofixA F (succ n) → F.A
| _, CofixA.intro i _ => i
/-- for a non-trivial approximation, return all the subtrees of the root -/
def children' : ∀ {n} (x : CofixA F (succ n)), F.B (head' x) → CofixA F n
| _, CofixA.intro _ f => f
theorem approx_eta {n : ℕ} (x : CofixA F (n + 1)) : x = CofixA.intro (head' x) (children' x) := by
cases x; rfl
/-- Relation between two approximations of the cofix of a pfunctor
that state they both contain the same data until one of them is truncated -/
inductive Agree : ∀ {n : ℕ}, CofixA F n → CofixA F (n + 1) → Prop
| continu (x : CofixA F 0) (y : CofixA F 1) : Agree x y
| intro {n} {a} (x : F.B a → CofixA F n) (x' : F.B a → CofixA F (n + 1)) :
(∀ i : F.B a, Agree (x i) (x' i)) → Agree (CofixA.intro a x) (CofixA.intro a x')
/-- Given an infinite series of approximations `approx`,
`AllAgree approx` states that they are all consistent with each other.
-/
def AllAgree (x : ∀ n, CofixA F n) :=
∀ n, Agree (x n) (x (succ n))
@[simp]
theorem agree_trivial {x : CofixA F 0} {y : CofixA F 1} : Agree x y := by constructor
theorem agree_children {n : ℕ} (x : CofixA F (succ n)) (y : CofixA F (succ n + 1)) {i j}
(h₀ : i ≍ j) (h₁ : Agree x y) : Agree (children' x i) (children' y j) := by
obtain - | ⟨_, _, hagree⟩ := h₁; cases h₀
apply hagree
/-- `truncate a` turns `a` into a more limited approximation -/
def truncate : ∀ {n : ℕ}, CofixA F (n + 1) → CofixA F n
| 0, CofixA.intro _ _ => CofixA.continue
| succ _, CofixA.intro i f => CofixA.intro i <| truncate ∘ f
theorem truncate_eq_of_agree {n : ℕ} (x : CofixA F n) (y : CofixA F (succ n)) (h : Agree x y) :
truncate y = x := by
induction n with
| zero =>
cases x
cases y
rfl
| succ n n_ih =>
cases h with | intro f y h₁ =>
simp only [truncate, Function.comp_def]
congr with y
exact n_ih _ _ (h₁ y)
variable {X : Type w}
variable (f : X → F X)
/-- `sCorec f i n` creates an approximation of height `n`
of the final coalgebra of `f` -/
def sCorec : X → ∀ n, CofixA F n
| _, 0 => CofixA.continue
| j, succ _ => CofixA.intro (f j).1 fun i => sCorec ((f j).2 i) _
theorem P_corec (i : X) (n : ℕ) : Agree (sCorec f i n) (sCorec f i (succ n)) := by
induction n generalizing i with
| zero => constructor
| succ n n_ih => exact .intro _ _ fun _ => n_ih _
/-- `Path F` provides indices to access internal nodes in `Corec F` -/
def Path (F : PFunctor.{uA, uB}) :=
List F.Idx
instance Path.inhabited : Inhabited (Path F) :=
⟨[]⟩
instance CofixA.instSubsingleton : Subsingleton (CofixA F 0) :=
⟨by rintro ⟨⟩ ⟨⟩; rfl⟩
theorem head_succ' (n m : ℕ) (x : ∀ n, CofixA F n) (Hconsistent : AllAgree x) :
head' (x (succ n)) = head' (x (succ m)) := by
suffices ∀ n, head' (x (succ n)) = head' (x 1) by simp [this]
clear m n
intro n
rcases h₀ : x (succ n) with - | ⟨_, f₀⟩
cases h₁ : x 1
dsimp only [head']
induction n with
| zero =>
rw [h₁] at h₀
cases h₀
trivial
| succ n n_ih =>
have H := Hconsistent (succ n)
cases h₂ : x (succ n)
rw [h₀, h₂] at H
apply n_ih (truncate ∘ f₀)
rw [h₂]
obtain - | ⟨_, _, hagree⟩ := H
congr
funext j
dsimp only [comp_apply]
rw [truncate_eq_of_agree]
apply hagree
end Approx
open Approx
/-- Internal definition for `M`. It is needed to avoid name clashes
between `M.mk` and `M.casesOn` and the declarations generated for
the structure -/
structure MIntl where
/-- An `n`-th level approximation, for each depth `n` -/
approx : ∀ n, CofixA F n
/-- Each approximation agrees with the next -/
consistent : AllAgree approx
/-- For polynomial functor `F`, `M F` is its final coalgebra -/
def M :=
MIntl F
theorem M.default_consistent [Inhabited F.A] : ∀ n, Agree (default : CofixA F n) default
| 0 => Agree.continu _ _
| succ n => Agree.intro _ _ fun _ => M.default_consistent n
instance M.inhabited [Inhabited F.A] : Inhabited (M F) :=
⟨{ approx := default
consistent := M.default_consistent _ }⟩
instance MIntl.inhabited [Inhabited F.A] : Inhabited (MIntl F) :=
show Inhabited (M F) by infer_instance
namespace M
theorem ext' (x y : M F) (H : ∀ i : ℕ, x.approx i = y.approx i) : x = y := by
cases x
cases y
congr with n
apply H
variable {X : Type*}
variable (f : X → F X)
variable {F}
/-- Corecursor for the M-type defined by `F`. -/
protected def corec (i : X) : M F where
approx := sCorec f i
consistent := P_corec _ _
/-- given a tree generated by `F`, `head` gives us the first piece of data
it contains -/
def head (x : M F) :=
head' (x.1 1)
/-- return all the subtrees of the root of a tree `x : M F` -/
def children (x : M F) (i : F.B (head x)) : M F :=
have H := fun n : ℕ => @head_succ' _ n 0 x.1 x.2
{ approx := fun n => children' (x.1 _) (cast (congr_arg _ <| by simp only [head, H]) i)
consistent := by
intro n
have P' := x.2 (succ n)
apply agree_children _ _ _ P'
trans i
· apply cast_heq
symm
apply cast_heq }
/-- select a subtree using an `i : F.Idx` or return an arbitrary tree if
`i` designates no subtree of `x` -/
def ichildren [Inhabited (M F)] [DecidableEq F.A] (i : F.Idx) (x : M F) : M F :=
if H' : i.1 = head x then children x (cast (congr_arg _ <| by simp only [head, H']) i.2)
else default
theorem head_succ (n m : ℕ) (x : M F) : head' (x.approx (succ n)) = head' (x.approx (succ m)) :=
head_succ' n m _ x.consistent
theorem head_eq_head' : ∀ (x : M F) (n : ℕ), head x = head' (x.approx <| n + 1)
| ⟨_, h⟩, _ => head_succ' _ _ _ h
theorem head'_eq_head : ∀ (x : M F) (n : ℕ), head' (x.approx <| n + 1) = head x
| ⟨_, h⟩, _ => head_succ' _ _ _ h
theorem truncate_approx (x : M F) (n : ℕ) : truncate (x.approx <| n + 1) = x.approx n :=
truncate_eq_of_agree _ _ (x.consistent _)
/-- unfold an M-type -/
def dest : M F → F (M F)
| x => ⟨head x, fun i => children x i⟩
namespace Approx
/-- generates the approximations needed for `M.mk` -/
protected def sMk (x : F (M F)) : ∀ n, CofixA F n
| 0 => CofixA.continue
| succ n => CofixA.intro x.1 fun i => (x.2 i).approx n
protected theorem P_mk (x : F (M F)) : AllAgree (Approx.sMk x)
| 0 => by constructor
| succ n => by
constructor
introv
apply (x.2 i).consistent
end Approx
/-- constructor for M-types -/
protected def mk (x : F (M F)) : M F where
approx := Approx.sMk x
consistent := Approx.P_mk x
/-- `Agree' n` relates two trees of type `M F` that
are the same up to depth `n` -/
inductive Agree' : ℕ → M F → M F → Prop
| trivial (x y : M F) : Agree' 0 x y
| step {n : ℕ} {a} (x y : F.B a → M F) {x' y'} :
x' = M.mk ⟨a, x⟩ → y' = M.mk ⟨a, y⟩ → (∀ i, Agree' n (x i) (y i)) → Agree' (succ n) x' y'
@[simp]
theorem dest_mk (x : F (M F)) : dest (M.mk x) = x := rfl
@[simp]
theorem mk_dest (x : M F) : M.mk (dest x) = x := by
apply ext'
intro n
dsimp only [M.mk]
induction n with
| zero => apply @Subsingleton.elim _ CofixA.instSubsingleton
| succ n => ?_
dsimp only [Approx.sMk, dest, head]
rcases h : x.approx (succ n) with - | ⟨hd, ch⟩
have h' : hd = head' (x.approx 1) := by
rw [← head_succ' n, h, head']
apply x.consistent
revert ch
rw [h']
intro ch h
congr
ext a
dsimp only [children]
generalize hh : cast _ a = a''
rw [cast_eq_iff_heq] at hh
revert a''
rw [h]
intro _ hh
cases hh
rfl
theorem mk_inj {x y : F (M F)} (h : M.mk x = M.mk y) : x = y := by rw [← dest_mk x, h, dest_mk]
/-- destructor for M-types -/
protected def cases {r : M F → Sort w} (f : ∀ x : F (M F), r (M.mk x)) (x : M F) : r x :=
suffices r (M.mk (dest x)) by
rw [← mk_dest x]
exact this
f _
/-- destructor for M-types -/
protected def casesOn {r : M F → Sort w} (x : M F) (f : ∀ x : F (M F), r (M.mk x)) : r x :=
M.cases f x
/-- destructor for M-types, similar to `casesOn` but also
gives access directly to the root and subtrees on an M-type -/
protected def casesOn' {r : M F → Sort w} (x : M F) (f : ∀ a f, r (M.mk ⟨a, f⟩)) : r x :=
M.casesOn x (fun ⟨a, g⟩ => f a g)
theorem approx_mk (a : F.A) (f : F.B a → M F) (i : ℕ) :
(M.mk ⟨a, f⟩).approx (succ i) = CofixA.intro a fun j => (f j).approx i :=
rfl
@[simp]
theorem agree'_refl {n : ℕ} (x : M F) : Agree' n x x := by
induction n generalizing x with | zero => ?_ | succ _ n_ih => ?_ <;>
induction x using PFunctor.M.casesOn' <;> constructor <;> try rfl
intro; apply n_ih
theorem agree_iff_agree' {n : ℕ} (x y : M F) :
Agree (x.approx n) (y.approx <| n + 1) ↔ Agree' n x y := by
constructor <;> intro h
· induction n generalizing x y with
| zero => constructor
| succ _ n_ih =>
induction x using PFunctor.M.casesOn'
induction y using PFunctor.M.casesOn'
simp only [approx_mk] at h
obtain - | ⟨_, _, hagree⟩ := h
constructor <;> try rfl
intro i
apply n_ih
apply hagree
· induction n generalizing x y with
| zero => constructor
| succ _ n_ih =>
obtain - | @⟨_, a, x', y'⟩ := h
induction x using PFunctor.M.casesOn' with | _ x_a x_f
induction y using PFunctor.M.casesOn' with | _ y_a y_f
simp only [approx_mk]
have h_a_1 := mk_inj ‹M.mk ⟨x_a, x_f⟩ = M.mk ⟨a, x'⟩›
cases h_a_1
replace h_a_2 := mk_inj ‹M.mk ⟨y_a, y_f⟩ = M.mk ⟨a, y'⟩›
cases h_a_2
constructor
intro i
apply n_ih
simp [*]
@[simp]
theorem cases_mk {r : M F → Sort*} (x : F (M F)) (f : ∀ x : F (M F), r (M.mk x)) :
PFunctor.M.cases f (M.mk x) = f x := rfl
@[simp]
theorem casesOn_mk {r : M F → Sort*} (x : F (M F)) (f : ∀ x : F (M F), r (M.mk x)) :
PFunctor.M.casesOn (M.mk x) f = f x :=
cases_mk x f
@[simp]
theorem casesOn_mk' {r : M F → Sort*} {a} (x : F.B a → M F)
(f : ∀ (a) (f : F.B a → M F), r (M.mk ⟨a, f⟩)) :
PFunctor.M.casesOn' (M.mk ⟨a, x⟩) f = f a x :=
@cases_mk F r ⟨a, x⟩ (fun ⟨a, g⟩ => f a g)
/-- `IsPath p x` tells us if `p` is a valid path through `x` -/
inductive IsPath : Path F → M F → Prop
| nil (x : M F) : IsPath [] x
| cons (xs : Path F) {a} (x : M F) (f : F.B a → M F) (i : F.B a) :
x = M.mk ⟨a, f⟩ → IsPath xs (f i) → IsPath (⟨a, i⟩ :: xs) x
theorem isPath_cons {xs : Path F} {a a'} {f : F.B a → M F} {i : F.B a'} :
IsPath (⟨a', i⟩ :: xs) (M.mk ⟨a, f⟩) → a = a' := by
generalize h : M.mk ⟨a, f⟩ = x
rintro (_ | ⟨_, _, _, _, rfl, _⟩)
cases mk_inj h
rfl
theorem isPath_cons' {xs : Path F} {a} {f : F.B a → M F} {i : F.B a} :
IsPath (⟨a, i⟩ :: xs) (M.mk ⟨a, f⟩) → IsPath xs (f i) := by
generalize h : M.mk ⟨a, f⟩ = x
rintro (_ | ⟨_, _, _, _, rfl, hp⟩)
cases mk_inj h
exact hp
/-- follow a path through a value of `M F` and return the subtree
found at the end of the path if it is a valid path for that value and
return a default tree -/
def isubtree [DecidableEq F.A] [Inhabited (M F)] : Path F → M F → M F
| [], x => x
| ⟨a, i⟩ :: ps, x =>
PFunctor.M.casesOn' (r := fun _ => M F) x (fun a' f =>
if h : a = a' then
isubtree ps (f <| cast (by rw [h]) i)
else
default (α := M F)
)
/-- similar to `isubtree` but returns the data at the end of the path instead
of the whole subtree -/
def iselect [DecidableEq F.A] [Inhabited (M F)] (ps : Path F) : M F → F.A := fun x : M F =>
head <| isubtree ps x
theorem iselect_eq_default [DecidableEq F.A] [Inhabited (M F)] (ps : Path F) (x : M F)
(h : ¬IsPath ps x) : iselect ps x = head default := by
induction ps generalizing x with
| nil =>
exfalso
apply h
constructor
| cons ps_hd ps_tail ps_ih =>
obtain ⟨a, i⟩ := ps_hd
induction x using PFunctor.M.casesOn' with | _ x_a x_f
simp only [iselect, isubtree] at ps_ih ⊢
by_cases h'' : a = x_a
· subst x_a
simp only [dif_pos, casesOn_mk']
rw [ps_ih]
intro h'
apply h
constructor <;> try rfl
apply h'
· simp [*]
@[simp]
theorem head_mk (x : F (M F)) : head (M.mk x) = x.1 :=
Eq.symm <|
calc
x.1 = (dest (M.mk x)).1 := by rw [dest_mk]
_ = head (M.mk x) := rfl
theorem children_mk {a} (x : F.B a → M F) (i : F.B (head (M.mk ⟨a, x⟩))) :
children (M.mk ⟨a, x⟩) i = x (cast (by rw [head_mk]) i) := by apply ext'; intro n; rfl
@[simp]
theorem ichildren_mk [DecidableEq F.A] [Inhabited (M F)] (x : F (M F)) (i : F.Idx) :
ichildren i (M.mk x) = x.iget i := by
dsimp only [ichildren, PFunctor.Obj.iget]
congr with h
@[simp]
theorem isubtree_cons [DecidableEq F.A] [Inhabited (M F)] (ps : Path F) {a} (f : F.B a → M F)
{i : F.B a} : isubtree (⟨_, i⟩ :: ps) (M.mk ⟨a, f⟩) = isubtree ps (f i) := by
simp only [isubtree, dif_pos, isubtree, M.casesOn_mk']; rfl
@[simp]
theorem iselect_nil [DecidableEq F.A] [Inhabited (M F)] {a} (f : F.B a → M F) :
iselect nil (M.mk ⟨a, f⟩) = a := rfl
@[simp]
theorem iselect_cons [DecidableEq F.A] [Inhabited (M F)] (ps : Path F) {a} (f : F.B a → M F) {i} :
iselect (⟨a, i⟩ :: ps) (M.mk ⟨a, f⟩) = iselect ps (f i) := by simp only [iselect, isubtree_cons]
theorem corec_def {X} (f : X → F X) (x₀ : X) : M.corec f x₀ = M.mk (F.map (M.corec f) (f x₀)) := by
dsimp only [M.corec, M.mk]
congr with n
rcases n with - | n
· dsimp only [sCorec, Approx.sMk]
· dsimp only [sCorec, Approx.sMk]
cases f x₀
dsimp only [PFunctor.map]
congr
theorem ext_aux [Inhabited (M F)] [DecidableEq F.A] {n : ℕ} (x y z : M F) (hx : Agree' n z x)
(hy : Agree' n z y) (hrec : ∀ ps : Path F, n = ps.length → iselect ps x = iselect ps y) :
x.approx (n + 1) = y.approx (n + 1) := by
induction n generalizing x y z with
| zero =>
specialize hrec [] rfl
induction x using PFunctor.M.casesOn'
induction y using PFunctor.M.casesOn'
simp only [iselect_nil] at hrec
subst hrec
simp only [approx_mk, heq_iff_eq, CofixA.intro.injEq,
eq_iff_true_of_subsingleton, and_self]
| succ n n_ih =>
cases hx
cases hy
induction x using PFunctor.M.casesOn'
induction y using PFunctor.M.casesOn'
subst z
iterate 3 (have := mk_inj ‹_›; cases this)
rename_i n_ih a f₃ f₂ hAgree₂ _ _ h₂ _ _ f₁ h₁ hAgree₁ clr
simp only [approx_mk]
have := mk_inj h₁
cases this; clear h₁
have := mk_inj h₂
cases this; clear h₂
congr
ext i
apply n_ih
· solve_by_elim
· solve_by_elim
introv h
specialize hrec (⟨_, i⟩ :: ps) (congr_arg _ h)
simp only [iselect_cons] at hrec
exact hrec
theorem ext [Inhabited (M F)] [DecidableEq F.A] (x y : M F)
(H : ∀ ps : Path F, iselect ps x = iselect ps y) :
x = y := by
apply ext'; intro i
induction i with
| zero => subsingleton
| succ i i_ih =>
apply ext_aux x y x
· rw [← agree_iff_agree']
apply x.consistent
· rw [← agree_iff_agree', i_ih]
apply y.consistent
introv H'
dsimp only [iselect] at H
cases H'
apply H ps
section Bisim
variable (R : M F → M F → Prop)
local infixl:50 " ~ " => R
/-- Bisimulation is the standard proof technique for equality between
infinite tree-like structures -/
structure IsBisimulation : Prop where
/-- The head of the trees are equal -/
head : ∀ {a a'} {f f'}, M.mk ⟨a, f⟩ ~ M.mk ⟨a', f'⟩ → a = a'
/-- The tails are equal -/
tail : ∀ {a} {f f' : F.B a → M F}, M.mk ⟨a, f⟩ ~ M.mk ⟨a, f'⟩ → ∀ i : F.B a, f i ~ f' i
theorem nth_of_bisim [Inhabited (M F)] [DecidableEq F.A]
(bisim : IsBisimulation R) (s₁ s₂) (ps : Path F) :
(R s₁ s₂) →
IsPath ps s₁ ∨ IsPath ps s₂ →
iselect ps s₁ = iselect ps s₂ ∧
∃ (a : _) (f f' : F.B a → M F),
isubtree ps s₁ = M.mk ⟨a, f⟩ ∧
isubtree ps s₂ = M.mk ⟨a, f'⟩ ∧ ∀ i : F.B a, f i ~ f' i := by
intro h₀ hh
induction s₁ using PFunctor.M.casesOn' with | _ a f
induction s₂ using PFunctor.M.casesOn' with | _ a' f'
obtain rfl : a = a' := bisim.head h₀
induction ps generalizing a f f' with
| nil =>
exists rfl, a, f, f', rfl, rfl
apply bisim.tail h₀
| cons i ps ps_ih => ?_
obtain ⟨a', i⟩ := i
obtain rfl : a = a' := by rcases hh with hh|hh <;> cases isPath_cons hh <;> rfl
dsimp only [iselect] at ps_ih ⊢
have h₁ := bisim.tail h₀ i
induction h : f i using PFunctor.M.casesOn' with | _ a₀ f₀
induction h' : f' i using PFunctor.M.casesOn' with | _ a₁ f₁
simp only [h, h', isubtree_cons] at ps_ih ⊢
rw [h, h'] at h₁
obtain rfl : a₀ = a₁ := bisim.head h₁
apply ps_ih _ _ _ h₁
rw [← h, ← h']
apply Or.imp isPath_cons' isPath_cons' hh
theorem eq_of_bisim [Nonempty (M F)] (bisim : IsBisimulation R) : ∀ s₁ s₂, R s₁ s₂ → s₁ = s₂ := by
inhabit M F
classical
introv Hr; apply ext
introv
by_cases h : IsPath ps s₁ ∨ IsPath ps s₂
· have H := nth_of_bisim R bisim _ _ ps Hr h
exact H.left
· rw [not_or] at h
obtain ⟨h₀, h₁⟩ := h
simp only [iselect_eq_default, *, not_false_iff]
end Bisim
universe u' v'
/-- corecursor for `M F` with swapped arguments -/
def corecOn {X : Type*} (x₀ : X) (f : X → F X) : M F :=
M.corec f x₀
variable {P : PFunctor.{uA, uB}} {α : Type*}
theorem dest_corec (g : α → P α) (x : α) : M.dest (M.corec g x) = P.map (M.corec g) (g x) := by
rw [corec_def, dest_mk]
theorem bisim (R : M P → M P → Prop)
(h : ∀ x y, R x y → ∃ a f f', M.dest x = ⟨a, f⟩ ∧ M.dest y = ⟨a, f'⟩ ∧ ∀ i, R (f i) (f' i)) :
∀ x y, R x y → x = y := by
introv h'
haveI := Inhabited.mk x.head
apply eq_of_bisim R _ _ _ h'; clear h' x y
constructor <;> introv ih <;> rcases h _ _ ih with ⟨a'', g, g', h₀, h₁, h₂⟩ <;> clear h
· replace h₀ := congr_arg Sigma.fst h₀
replace h₁ := congr_arg Sigma.fst h₁
simp only [dest_mk] at h₀ h₁
rw [h₀, h₁]
· simp only [dest_mk] at h₀ h₁
cases h₀
cases h₁
apply h₂
theorem bisim' {α : Type*} (Q : α → Prop) (u v : α → M P)
(h : ∀ x, Q x → ∃ a f f',
M.dest (u x) = ⟨a, f⟩
∧ M.dest (v x) = ⟨a, f'⟩
∧ ∀ i, ∃ x', Q x' ∧ f i = u x' ∧ f' i = v x') :
∀ x, Q x → u x = v x := fun x Qx =>
let R := fun w z : M P => ∃ x', Q x' ∧ w = u x' ∧ z = v x'
@M.bisim P R
(fun _ _ ⟨x', Qx', xeq, yeq⟩ =>
let ⟨a, f, f', ux'eq, vx'eq, h'⟩ := h x' Qx'
⟨a, f, f', xeq.symm ▸ ux'eq, yeq.symm ▸ vx'eq, h'⟩)
_ _ ⟨x, Qx, rfl, rfl⟩
-- for the record, show M_bisim follows from _bisim'
theorem bisim_equiv (R : M P → M P → Prop)
(h : ∀ x y, R x y → ∃ a f f', M.dest x = ⟨a, f⟩ ∧ M.dest y = ⟨a, f'⟩ ∧ ∀ i, R (f i) (f' i)) :
∀ x y, R x y → x = y := fun x y Rxy =>
let Q : M P × M P → Prop := fun p => R p.fst p.snd
bisim' Q Prod.fst Prod.snd
(fun p Qp =>
let ⟨a, f, f', hx, hy, h'⟩ := h p.fst p.snd Qp
⟨a, f, f', hx, hy, fun i => ⟨⟨f i, f' i⟩, h' i, rfl, rfl⟩⟩)
⟨x, y⟩ Rxy
theorem corec_unique (g : α → P α) (f : α → M P) (hyp : ∀ x, M.dest (f x) = P.map f (g x)) :
f = M.corec g := by
ext x
apply bisim' (fun _ => True) _ _ _ _ trivial
clear x
intro x _
rcases gxeq : g x with ⟨a, f'⟩
have h₀ : M.dest (f x) = ⟨a, f ∘ f'⟩ := by rw [hyp, gxeq, PFunctor.map_eq]
have h₁ : M.dest (M.corec g x) = ⟨a, M.corec g ∘ f'⟩ := by rw [dest_corec, gxeq, PFunctor.map_eq]
refine ⟨_, _, _, h₀, h₁, ?_⟩
intro i
exact ⟨f' i, trivial, rfl, rfl⟩
/-- corecursor where the state of the computation can be sent downstream
in the form of a recursive call -/
def corec₁ {α : Type u} (F : ∀ X, (α → X) → α → P X) : α → M P :=
M.corec (F _ id)
/-- corecursor where it is possible to return a fully formed value at any point
of the computation -/
def corec' {α : Type u} (F : ∀ {X : Type (max u uA uB)}, (α → X) → α → M P ⊕ P X) (x : α) : M P :=
corec₁
(fun _ rec (a : M P ⊕ α) =>
let y := Sum.bind a (F (rec ∘ Sum.inr))
match y with
| Sum.inr y => y
| Sum.inl y => P.map (rec ∘ Sum.inl) (M.dest y))
(@Sum.inr (M P) _ x)
end M
end PFunctor |
.lake/packages/mathlib/Mathlib/Data/Array/Extract.lean | import Mathlib.Init
/-!
# Lemmas about `Array.extract`
Some useful lemmas about Array.extract
-/
universe u
variable {α : Type u} {i : Nat}
namespace Array
@[simp]
theorem extract_eq_nil_of_start_eq_end {a : Array α} :
a.extract i i = #[] := by
refine extract_empty_of_stop_le_start ?h
exact Nat.le_refl i
/--
This is a stronger version of `Array.extract_append_left`,
and should be upstreamed to replace that.
-/
theorem extract_append_left' {a b : Array α} {i j : Nat} (h : j ≤ a.size) :
(a ++ b).extract i j = a.extract i j := by
simp [h]
/--
This is a stronger version of `Array.extract_append_right`,
and should be upstreamed to replace that.
-/
theorem extract_append_right' {a b : Array α} {i j : Nat} (h : a.size ≤ i) :
(a ++ b).extract i j = b.extract (i - a.size) (j - a.size) := by
apply ext
· rw [size_extract, size_extract, size_append]
omega
· intro k hi h2
rw [getElem_extract, getElem_extract,
getElem_append_right (by cutsat)]
congr
cutsat
theorem extract_eq_of_size_le_end {l p : Nat} {a : Array α} (h : a.size ≤ l) :
a.extract p l = a.extract p a.size := by
simp only [extract, Nat.min_eq_right h, Nat.sub_eq, Nat.min_self]
end Array |
.lake/packages/mathlib/Mathlib/Data/Array/Defs.lean | import Mathlib.Init
/-!
## Definitions on Arrays
This file contains various definitions on `Array`. It does not contain
proofs about these definitions, those are contained in other files in `Mathlib/Data/Array.lean`.
-/
namespace Array
universe u
variable {α : Type u}
/-- Permute the array using a sequence of indices defining a cyclic permutation.
If the list of indices `l = [i₁, i₂, ..., iₙ]` are all distinct then
`(cyclicPermute! a l)[iₖ₊₁] = a[iₖ]` and `(cyclicPermute! a l)[i₀] = a[iₙ]` -/
def cyclicPermute! [Inhabited α] : Array α → List Nat → Array α
| a, [] => a
| a, i :: is => cyclicPermuteAux a is a[i]! i
where cyclicPermuteAux : Array α → List Nat → α → Nat → Array α
| a, [], x, i0 => a.set! i0 x
| a, i :: is, x, i0 =>
let (y, a) := a.swapAt! i x
cyclicPermuteAux a is y i0
/-- Permute the array using a list of cycles. -/
def permute! [Inhabited α] (a : Array α) (ls : List (List Nat)) : Array α :=
ls.foldl (init := a) (·.cyclicPermute! ·)
end Array |
.lake/packages/mathlib/Mathlib/Data/ZMod/QuotientRing.lean | import Mathlib.RingTheory.Ideal.Quotient.Operations
import Mathlib.RingTheory.Int.Basic
import Mathlib.RingTheory.ZMod
import Mathlib.Data.Nat.Factorization.Basic
/-!
# `ZMod n` and quotient groups / rings
This file relates `ZMod n` to the quotient ring `ℤ ⧸ Ideal.span {(n : ℤ)}`.
## Main definitions
- `ZMod.quotient_span_nat_equiv_zmod` and `ZMod.quotientSpanEquivZMod `:
`ZMod n` is the ring quotient of `ℤ` by `n ℤ : Ideal.span {n}`
(where `n : ℕ` and `n : ℤ` respectively)
## Tags
zmod, quotient ring, ideal quotient
-/
open QuotientAddGroup Set ZMod
variable (n : ℕ) {A R : Type*} [AddGroup A] [Ring R]
namespace Int
/-- `ℤ` modulo the ideal generated by `n : ℕ` is `ZMod n`. -/
def quotientSpanNatEquivZMod : ℤ ⧸ Ideal.span {(n : ℤ)} ≃+* ZMod n :=
(Ideal.quotEquivOfEq (ZMod.ker_intCastRingHom _)).symm.trans <|
RingHom.quotientKerEquivOfRightInverse <|
show Function.RightInverse ZMod.cast (Int.castRingHom (ZMod n)) from intCast_zmod_cast
/-- `ℤ` modulo the ideal generated by `a : ℤ` is `ZMod a.natAbs`. -/
def quotientSpanEquivZMod (a : ℤ) : ℤ ⧸ Ideal.span ({a} : Set ℤ) ≃+* ZMod a.natAbs :=
(Ideal.quotEquivOfEq (span_natAbs a)).symm.trans (quotientSpanNatEquivZMod a.natAbs)
@[simp]
theorem quotientSpanNatEquivZMod_comp_Quotient_mk (n : ℕ) :
(Int.quotientSpanNatEquivZMod n : _ →+* _).comp (Ideal.Quotient.mk (Ideal.span {(n : ℤ)})) =
Int.castRingHom (ZMod n) := rfl
@[simp]
theorem quotientSpanNatEquivZMod_comp_castRingHom (n : ℕ) :
((Int.quotientSpanNatEquivZMod n).symm : _ →+* _).comp (Int.castRingHom (ZMod n)) =
Ideal.Quotient.mk (Ideal.span {(n : ℤ)}) := by ext; simp
@[simp]
theorem quotientSpanEquivZMod_comp_Quotient_mk (n : ℤ) :
(Int.quotientSpanEquivZMod n : _ →+* _).comp (Ideal.Quotient.mk (Ideal.span {(n : ℤ)})) =
Int.castRingHom (ZMod n.natAbs) := rfl
@[simp]
theorem quotientSpanEquivZMod_comp_castRingHom (n : ℤ) :
((Int.quotientSpanEquivZMod n).symm : _ →+* _).comp (Int.castRingHom (ZMod n.natAbs)) =
Ideal.Quotient.mk (Ideal.span {(n : ℤ)}) := by ext; simp
end Int
noncomputable section ChineseRemainder
open Ideal
open scoped Function in -- required for scoped `on` notation
/-- The **Chinese remainder theorem**, elementary version for `ZMod`. See also
`Mathlib/Data/ZMod/Basic.lean` for versions involving only two numbers. -/
def ZMod.prodEquivPi {ι : Type*} [Fintype ι] (a : ι → ℕ)
(coprime : Pairwise (Nat.Coprime on a)) : ZMod (∏ i, a i) ≃+* Π i, ZMod (a i) :=
have : Pairwise fun i j => IsCoprime (span {(a i : ℤ)}) (span {(a j : ℤ)}) :=
fun _i _j h ↦ (isCoprime_span_singleton_iff _ _).mpr ((coprime h).cast (R := ℤ))
Int.quotientSpanNatEquivZMod _ |>.symm.trans <|
quotEquivOfEq (iInf_span_singleton_natCast (R := ℤ) coprime) |>.symm.trans <|
quotientInfRingEquivPiQuotient _ this |>.trans <|
RingEquiv.piCongrRight fun i ↦ Int.quotientSpanNatEquivZMod (a i)
/-- The **Chinese remainder theorem**, version for `ZMod n`. -/
def ZMod.equivPi (hn : n ≠ 0) :
ZMod n ≃+* Π (p : n.primeFactors), ZMod (p ^ (n.factorization p)) :=
(ringEquivCongr <| Nat.prod_pow_primeFactors_factorization hn).trans
<| prodEquivPi (fun (p : n.primeFactors) ↦ (p : ℕ) ^ (n.factorization p))
n.pairwise_coprime_pow_primeFactors_factorization
end ChineseRemainder |
.lake/packages/mathlib/Mathlib/Data/ZMod/Aut.lean | import Mathlib.Algebra.Ring.AddAut
import Mathlib.Data.ZMod.Basic
/-!
# Automorphism Group of `ZMod`.
-/
assert_not_exists Field TwoSidedIdeal
namespace ZMod
variable (n : ℕ)
/-- The automorphism group of `ZMod n` is isomorphic to the group of units of `ZMod n`. -/
@[simps]
def AddAutEquivUnits : AddAut (ZMod n) ≃* (ZMod n)ˣ :=
have h (f : AddAut (ZMod n)) (x : ZMod n) : f 1 * x = f x := by
rw [mul_comm, ← x.intCast_zmod_cast, ← zsmul_eq_mul, ← map_zsmul, zsmul_one]
{ toFun := fun f ↦ Units.mkOfMulEqOne (f 1) (f⁻¹ 1) ((h f _).trans (f.inv_apply_self _ _))
invFun := AddAut.mulLeft
left_inv := fun f ↦ by simp [DFunLike.ext_iff, Units.smul_def, h]
right_inv := fun x ↦ by simp [Units.ext_iff, Units.smul_def]
map_mul' := fun f g ↦ by simp [Units.ext_iff, h] }
end ZMod |
.lake/packages/mathlib/Mathlib/Data/ZMod/IntUnitsPower.lean | import Mathlib.Algebra.GroupWithZero.Divisibility
import Mathlib.Data.Int.Order.Units
import Mathlib.Data.ZMod.Basic
/-!
# The power operator on `ℤˣ` by `ZMod 2`, `ℕ`, and `ℤ`
See also the related `negOnePow`.
## TODO
* Generalize this to `Pow G (Zmod n)` where `orderOf g = n`.
## Implementation notes
In future, we could consider a `LawfulPower M R` typeclass; but we can save ourselves a lot of work
by using `Module R (Additive M)` in its place, especially since this already has instances for
`R = ℕ` and `R = ℤ`.
-/
assert_not_exists Ideal TwoSidedIdeal
instance : SMul (ZMod 2) (Additive ℤˣ) where
smul z au := .ofMul <| au.toMul ^ z.val
lemma ZMod.smul_units_def (z : ZMod 2) (au : Additive ℤˣ) :
z • au = z.val • au := rfl
lemma ZMod.natCast_smul_units (n : ℕ) (au : Additive ℤˣ) : (n : ZMod 2) • au = n • au :=
(Int.units_pow_eq_pow_mod_two au n).symm
/-- This is an indirect way of saying that `ℤˣ` has a power operation by `ZMod 2`. -/
instance : Module (ZMod 2) (Additive ℤˣ) where
smul z au := .ofMul <| au.toMul ^ z.val
one_smul _ := Additive.toMul.injective <| pow_one _
mul_smul z₁ z₂ au := Additive.toMul.injective <| by
dsimp only [ZMod.smul_units_def, toMul_nsmul]
rw [← pow_mul, ZMod.val_mul, ← Int.units_pow_eq_pow_mod_two, mul_comm]
smul_zero _ := Additive.toMul.injective <| one_pow _
smul_add _ _ _ := Additive.toMul.injective <| mul_pow _ _ _
add_smul z₁ z₂ au := Additive.toMul.injective <| by
dsimp only [ZMod.smul_units_def, toMul_nsmul, toMul_add]
rw [← pow_add, ZMod.val_add, ← Int.units_pow_eq_pow_mod_two]
zero_smul au := Additive.toMul.injective <| pow_zero au.toMul
section CommSemiring
variable {R : Type*} [CommSemiring R] [Module R (Additive ℤˣ)]
/-- There is a canonical power operation on `ℤˣ` by `R` if `Additive ℤˣ` is an `R`-module.
In lemma names, this operations is called `uzpow` to match `zpow`.
Notably this is satisfied by `R ∈ {ℕ, ℤ, ZMod 2}`. -/
instance Int.instUnitsPow : Pow ℤˣ R where
pow u r := (r • Additive.ofMul u).toMul
-- The above instances form no typeclass diamonds with the standard power operators
-- but we will need `reducible_and_instances` which currently fails https://github.com/leanprover-community/mathlib4/issues/10906
example : Int.instUnitsPow = Monoid.toNatPow := rfl
example : Int.instUnitsPow = DivInvMonoid.toZPow := rfl
@[simp] lemma ofMul_uzpow (u : ℤˣ) (r : R) : Additive.ofMul (u ^ r) = r • Additive.ofMul u := rfl
@[simp] lemma toMul_uzpow (u : Additive ℤˣ) (r : R) : (r • u).toMul = u.toMul ^ r := rfl
@[norm_cast] lemma uzpow_natCast (u : ℤˣ) (n : ℕ) : u ^ (n : R) = u ^ n := by
change ((n : R) • Additive.ofMul u).toMul = _
rw [Nat.cast_smul_eq_nsmul, toMul_nsmul, toMul_ofMul]
lemma uzpow_coe_nat (s : ℤˣ) (n : ℕ) [n.AtLeastTwo] :
s ^ (ofNat(n) : R) = s ^ (ofNat(n) : ℕ) :=
uzpow_natCast _ _
@[simp] lemma one_uzpow (x : R) : (1 : ℤˣ) ^ x = 1 :=
Additive.ofMul.injective <| smul_zero _
lemma mul_uzpow (s₁ s₂ : ℤˣ) (x : R) : (s₁ * s₂) ^ x = s₁ ^ x * s₂ ^ x :=
Additive.ofMul.injective <| smul_add x (Additive.ofMul s₁) (Additive.ofMul s₂)
@[simp] lemma uzpow_zero (s : ℤˣ) : (s ^ (0 : R) : ℤˣ) = (1 : ℤˣ) :=
Additive.ofMul.injective <| zero_smul R (Additive.ofMul s)
@[simp] lemma uzpow_one (s : ℤˣ) : (s ^ (1 : R) : ℤˣ) = s :=
Additive.ofMul.injective <| one_smul R (Additive.ofMul s)
lemma uzpow_mul (s : ℤˣ) (x y : R) : s ^ (x * y) = (s ^ x) ^ y :=
Additive.ofMul.injective <| mul_comm x y ▸ mul_smul y x (Additive.ofMul s)
lemma uzpow_add (s : ℤˣ) (x y : R) : s ^ (x + y) = s ^ x * s ^ y :=
Additive.ofMul.injective <| add_smul x y (Additive.ofMul s)
end CommSemiring
section CommRing
variable {R : Type*} [CommRing R] [Module R (Additive ℤˣ)]
lemma uzpow_sub (s : ℤˣ) (x y : R) : s ^ (x - y) = s ^ x / s ^ y :=
Additive.ofMul.injective <| sub_smul x y (Additive.ofMul s)
lemma uzpow_neg (s : ℤˣ) (x : R) : s ^ (-x) = (s ^ x)⁻¹ :=
Additive.ofMul.injective <| neg_smul x (Additive.ofMul s)
@[norm_cast] lemma uzpow_intCast (u : ℤˣ) (z : ℤ) : u ^ (z : R) = u ^ z := by
change ((z : R) • Additive.ofMul u).toMul = _
rw [Int.cast_smul_eq_zsmul, toMul_zsmul, toMul_ofMul]
end CommRing |
.lake/packages/mathlib/Mathlib/Data/ZMod/ValMinAbs.lean | import Mathlib.Data.ZMod.Basic
import Mathlib.Tactic.Linarith
/-!
# Absolute value in `ZMod n`
-/
namespace ZMod
variable {n : ℕ} {a b : ZMod n}
/-- Returns the integer in the same equivalence class as `x` that is closest to `0`.
The result will be in the interval `(-n/2, n/2]`. -/
def valMinAbs : ∀ {n : ℕ}, ZMod n → ℤ
| 0, x => x
| n@(_ + 1), x => if x.val ≤ n / 2 then x.val else (x.val : ℤ) - n
@[simp] lemma valMinAbs_def_zero (x : ZMod 0) : valMinAbs x = x := rfl
lemma valMinAbs_def_pos : ∀ {n : ℕ} [NeZero n] (x : ZMod n),
valMinAbs x = if x.val ≤ n / 2 then (x.val : ℤ) else x.val - n
| 0, _, x => by cases NeZero.ne 0 rfl
| n + 1, _, x => rfl
@[simp, norm_cast]
lemma coe_valMinAbs : ∀ {n : ℕ} (x : ZMod n), (x.valMinAbs : ZMod n) = x
| 0, _ => Int.cast_id
| k@(n + 1), x => by
rw [valMinAbs_def_pos]
split_ifs
· rw [Int.cast_natCast, natCast_zmod_val]
· rw [Int.cast_sub, Int.cast_natCast, natCast_zmod_val, Int.cast_natCast, natCast_self,
sub_zero]
lemma injective_valMinAbs : (valMinAbs : ZMod n → ℤ).Injective :=
Function.injective_iff_hasLeftInverse.2 ⟨_, coe_valMinAbs⟩
@[simp]
theorem valMinAbs_inj : a.valMinAbs = b.valMinAbs ↔ a = b :=
ZMod.injective_valMinAbs.eq_iff
lemma valMinAbs_nonneg_iff [NeZero n] (x : ZMod n) : 0 ≤ x.valMinAbs ↔ x.val ≤ n / 2 := by
rw [valMinAbs_def_pos]; split_ifs with h
· exact iff_of_true (Nat.cast_nonneg _) h
· exact iff_of_false (sub_lt_zero.2 <| Int.ofNat_lt.2 x.val_lt).not_ge h
lemma valMinAbs_mul_two_eq_iff (a : ZMod n) : a.valMinAbs * 2 = n ↔ 2 * a.val = n := by
rcases n with - | n
· simp
by_cases h : a.val ≤ n.succ / 2
· dsimp [valMinAbs]
rw [if_pos h, ← Int.natCast_inj, Nat.cast_mul, Nat.cast_two, mul_comm, Int.natCast_add,
Nat.cast_one]
apply iff_of_false _ (mt _ h)
· intro he
rw [← a.valMinAbs_nonneg_iff, ← mul_nonneg_iff_left_nonneg_of_pos, he] at h
exacts [h (Nat.cast_nonneg _), zero_lt_two]
· rw [mul_comm]
exact fun h => (Nat.le_div_iff_mul_le zero_lt_two).2 h.le
lemma valMinAbs_mem_Ioc [NeZero n] (x : ZMod n) : x.valMinAbs * 2 ∈ Set.Ioc (-n : ℤ) n := by
simp_rw [valMinAbs_def_pos, Nat.le_div_two_iff_mul_two_le]; split_ifs with h
· refine ⟨(neg_lt_zero.2 <| mod_cast NeZero.pos n).trans_le (mul_nonneg ?_ ?_), h⟩
exacts [Nat.cast_nonneg _, zero_le_two]
· refine ⟨?_, le_trans (mul_nonpos_of_nonpos_of_nonneg ?_ zero_le_two) <| Nat.cast_nonneg _⟩
· linarith only [h]
· rw [sub_nonpos, Int.ofNat_le]
exact x.val_lt.le
lemma valMinAbs_spec [NeZero n] (x : ZMod n) (y : ℤ) :
x.valMinAbs = y ↔ x = y ∧ y * 2 ∈ Set.Ioc (-n : ℤ) n where
mp := by rintro rfl; exact ⟨x.coe_valMinAbs.symm, x.valMinAbs_mem_Ioc⟩
mpr h := by
rw [← sub_eq_zero]
apply @Int.eq_zero_of_abs_lt_dvd n
· rw [← intCast_zmod_eq_zero_iff_dvd, Int.cast_sub, coe_valMinAbs, h.1, sub_self]
rw [← mul_lt_mul_iff_left₀ (@zero_lt_two ℤ _ _ _ _ _)]
nth_rw 1 [← abs_eq_self.2 (@zero_le_two ℤ _ _ _ _)]
rw [← abs_mul, sub_mul, abs_lt]
constructor <;> linarith only [x.valMinAbs_mem_Ioc.1, x.valMinAbs_mem_Ioc.2, h.2.1, h.2.2]
lemma natAbs_valMinAbs_le [NeZero n] (x : ZMod n) : x.valMinAbs.natAbs ≤ n / 2 := by
rw [Nat.le_div_two_iff_mul_two_le]
rcases x.valMinAbs.natAbs_eq with h | h
· rw [← h]
exact x.valMinAbs_mem_Ioc.2
· rw [← neg_le_neg_iff, ← neg_mul, ← h]
exact x.valMinAbs_mem_Ioc.1.le
theorem eq_neg_of_valMinAbs_eq_neg_valMinAbs (h : a.valMinAbs = -b.valMinAbs) : a = -b := by
rcases eq_zero_or_neZero n with rfl | hn <;> simp_all [valMinAbs_spec]
@[simp]
lemma valMinAbs_zero : ∀ n, (0 : ZMod n).valMinAbs = 0
| 0 => by simp only [valMinAbs_def_zero]
| n + 1 => by simp only [valMinAbs_def_pos, if_true, Int.ofNat_zero, zero_le, val_zero]
@[simp]
lemma valMinAbs_eq_zero (x : ZMod n) : x.valMinAbs = 0 ↔ x = 0 :=
injective_valMinAbs.eq_iff' <| valMinAbs_zero _
lemma natCast_natAbs_valMinAbs [NeZero n] (a : ZMod n) :
(a.valMinAbs.natAbs : ZMod n) = if a.val ≤ (n : ℕ) / 2 then a else -a := by
have : (a.val : ℤ) - n ≤ 0 := by
rw [sub_nonpos, Int.ofNat_le]
exact a.val_le
rw [valMinAbs_def_pos]
split_ifs
· rw [Int.natAbs_natCast, natCast_zmod_val]
· rw [← Int.cast_natCast, Int.ofNat_natAbs_of_nonpos this, Int.cast_neg, Int.cast_sub,
Int.cast_natCast, Int.cast_natCast, natCast_self, sub_zero, natCast_zmod_val]
lemma valMinAbs_neg_of_ne_half (ha : 2 * a.val ≠ n) : (-a).valMinAbs = -a.valMinAbs := by
rcases eq_zero_or_neZero n with h | h
· subst h
rfl
refine (valMinAbs_spec _ _).2 ⟨?_, ?_, ?_⟩
· rw [Int.cast_neg, coe_valMinAbs]
· rw [neg_mul, neg_lt_neg_iff]
exact a.valMinAbs_mem_Ioc.2.lt_of_ne (mt a.valMinAbs_mul_two_eq_iff.1 ha)
· linarith only [a.valMinAbs_mem_Ioc.1]
@[simp]
lemma natAbs_valMinAbs_neg (a : ZMod n) : (-a).valMinAbs.natAbs = a.valMinAbs.natAbs := by
by_cases h2a : 2 * a.val = n
· rw [a.neg_eq_self_iff.2 (Or.inr h2a)]
· rw [valMinAbs_neg_of_ne_half h2a, Int.natAbs_neg]
theorem natAbs_valMinAbs_eq_natAbs_valMinAbs :
a.valMinAbs.natAbs = b.valMinAbs.natAbs ↔ a = b ∨ a = -b := by
constructor
· rw [Int.natAbs_eq_natAbs_iff, valMinAbs_inj]
exact Or.imp_right eq_neg_of_valMinAbs_eq_neg_valMinAbs
· rintro (rfl | rfl)
· rfl
· rw [natAbs_valMinAbs_neg]
theorem abs_valMinAbs_eq_abs_valMinAbs :
|a.valMinAbs| = |b.valMinAbs| ↔ a = b ∨ a = -b := by
rw [← natAbs_valMinAbs_eq_natAbs_valMinAbs, Int.abs_eq_natAbs, Int.abs_eq_natAbs]
norm_cast
lemma val_eq_ite_valMinAbs [NeZero n] (a : ZMod n) :
(a.val : ℤ) = a.valMinAbs + if a.val ≤ n / 2 then 0 else n := by
rw [valMinAbs_def_pos]
split_ifs <;> simp [add_zero, sub_add_cancel]
lemma prime_ne_zero (p q : ℕ) [hp : Fact p.Prime] [hq : Fact q.Prime] (hpq : p ≠ q) :
(q : ZMod p) ≠ 0 := by
rwa [← Nat.cast_zero, Ne, natCast_eq_natCast_iff, Nat.modEq_zero_iff_dvd,
← hp.1.coprime_iff_not_dvd, Nat.coprime_primes hp.1 hq.1]
variable {n a : ℕ}
lemma valMinAbs_natAbs_eq_min [hpos : NeZero n] (a : ZMod n) :
a.valMinAbs.natAbs = min a.val (n - a.val) := by
rw [valMinAbs_def_pos]
have := a.val_lt
omega
lemma valMinAbs_natCast_of_le_half (ha : a ≤ n / 2) : (a : ZMod n).valMinAbs = a := by
cases n
· simp
· simp [valMinAbs_def_pos, val_natCast, Nat.mod_eq_of_lt (ha.trans_lt <| Nat.div_lt_self' _ 0),
ha]
lemma valMinAbs_natCast_of_half_lt (ha : n / 2 < a) (ha' : a < n) :
(a : ZMod n).valMinAbs = a - n := by
cases n
· cases not_lt_bot ha'
· simp [valMinAbs_def_pos, val_natCast, Nat.mod_eq_of_lt ha', ha.not_ge]
@[simp]
lemma valMinAbs_natCast_eq_self [NeZero n] : (a : ZMod n).valMinAbs = a ↔ a ≤ n / 2 := by
refine ⟨fun ha => ?_, valMinAbs_natCast_of_le_half⟩
rw [← Int.natAbs_natCast a, ← ha]
exact natAbs_valMinAbs_le (n := n) a
lemma natAbs_valMinAbs_add_le (a b : ZMod n) :
(a + b).valMinAbs.natAbs ≤ (a.valMinAbs + b.valMinAbs).natAbs := by
rcases n with - | n
· rfl
apply natAbs_min_of_le_div_two n.succ
· simp_rw [Int.cast_add, coe_valMinAbs]
· apply natAbs_valMinAbs_le
end ZMod |
.lake/packages/mathlib/Mathlib/Data/ZMod/Basic.lean | import Mathlib.Algebra.CharP.Basic
import Mathlib.Algebra.Ring.Prod
import Mathlib.Data.Fintype.Units
import Mathlib.GroupTheory.GroupAction.SubMulAction
import Mathlib.GroupTheory.OrderOfElement
import Mathlib.Tactic.FinCases
/-!
# Integers mod `n`
Definition of the integers mod n, and the field structure on the integers mod p.
## Definitions
* `ZMod n`, which is for integers modulo a nat `n : ℕ`
* `val a` is defined as a natural number:
- for `a : ZMod 0` it is the absolute value of `a`
- for `a : ZMod n` with `0 < n` it is the least natural number in the equivalence class
* A coercion `cast` is defined from `ZMod n` into any ring.
This is a ring hom if the ring has characteristic dividing `n`
-/
assert_not_exists Field Submodule TwoSidedIdeal
open Function ZMod
namespace ZMod
instance : IsDomain (ZMod 0) := inferInstanceAs (IsDomain ℤ)
/-- For non-zero `n : ℕ`, the ring `Fin n` is equivalent to `ZMod n`. -/
def finEquiv : ∀ (n : ℕ) [NeZero n], Fin n ≃+* ZMod n
| 0, h => (h.ne _ rfl).elim
| _ + 1, _ => .refl _
instance charZero : CharZero (ZMod 0) := inferInstanceAs (CharZero ℤ)
/-- `val a` is a natural number defined as:
- for `a : ZMod 0` it is the absolute value of `a`
- for `a : ZMod n` with `0 < n` it is the least natural number in the equivalence class
See `ZMod.valMinAbs` for a variant that takes values in the integers.
-/
def val : ∀ {n : ℕ}, ZMod n → ℕ
| 0 => Int.natAbs
| n + 1 => ((↑) : Fin (n + 1) → ℕ)
theorem val_lt {n : ℕ} [NeZero n] (a : ZMod n) : a.val < n := by
cases n
· cases NeZero.ne 0 rfl
exact Fin.is_lt a
theorem val_le {n : ℕ} [NeZero n] (a : ZMod n) : a.val ≤ n :=
a.val_lt.le
@[simp]
theorem val_zero : ∀ {n}, (0 : ZMod n).val = 0
| 0 => rfl
| _ + 1 => rfl
@[simp]
theorem val_one' : (1 : ZMod 0).val = 1 :=
rfl
@[simp]
theorem val_neg' {n : ZMod 0} : (-n).val = n.val :=
Int.natAbs_neg n
@[simp]
theorem val_mul' {m n : ZMod 0} : (m * n).val = m.val * n.val :=
Int.natAbs_mul m n
@[simp]
theorem val_natCast (n a : ℕ) : (a : ZMod n).val = a % n := by
cases n
· rw [Nat.mod_zero]
exact Int.natAbs_natCast a
· apply Fin.val_natCast
lemma val_natCast_of_lt {n a : ℕ} (h : a < n) : (a : ZMod n).val = a := by
rwa [val_natCast, Nat.mod_eq_of_lt]
lemma val_ofNat (n a : ℕ) [a.AtLeastTwo] : (ofNat(a) : ZMod n).val = ofNat(a) % n := val_natCast ..
lemma val_ofNat_of_lt {n a : ℕ} [a.AtLeastTwo] (han : a < n) : (ofNat(a) : ZMod n).val = ofNat(a) :=
val_natCast_of_lt han
theorem val_unit' {n : ZMod 0} : IsUnit n ↔ n.val = 1 := by
simp only [val]
rw [Int.isUnit_iff, Int.natAbs_eq_iff, Nat.cast_one]
lemma eq_one_of_isUnit_natCast {n : ℕ} (h : IsUnit (n : ZMod 0)) : n = 1 := by
rw [← Nat.mod_zero n, ← val_natCast, val_unit'.mp h]
instance charP (n : ℕ) : CharP (ZMod n) n where
cast_eq_zero_iff := by
intro k
rcases n with - | n
· simp [zero_dvd_iff]
· exact Fin.natCast_eq_zero
-- Verify that `grind` can see that `ZMod n` has characteristic `n`.
example (n : ℕ) : Lean.Grind.IsCharP (ZMod n) n := inferInstance
@[simp]
theorem addOrderOf_one (n : ℕ) : addOrderOf (1 : ZMod n) = n :=
CharP.eq _ (CharP.addOrderOf_one _) (ZMod.charP n)
/-- This lemma works in the case in which `ZMod n` is not infinite, i.e. `n ≠ 0`. The version
where `a ≠ 0` is `addOrderOf_coe'`. -/
@[simp]
theorem addOrderOf_coe (a : ℕ) {n : ℕ} (n0 : n ≠ 0) : addOrderOf (a : ZMod n) = n / n.gcd a := by
rcases a with - | a
· simp only [Nat.cast_zero, addOrderOf_zero, Nat.gcd_zero_right,
Nat.pos_of_ne_zero n0, Nat.div_self]
rw [← Nat.smul_one_eq_cast, addOrderOf_nsmul' _ a.succ_ne_zero, ZMod.addOrderOf_one]
/-- This lemma works in the case in which `a ≠ 0`. The version where
`ZMod n` is not infinite, i.e. `n ≠ 0`, is `addOrderOf_coe`. -/
@[simp]
theorem addOrderOf_coe' {a : ℕ} (n : ℕ) (a0 : a ≠ 0) : addOrderOf (a : ZMod n) = n / n.gcd a := by
rw [← Nat.smul_one_eq_cast, addOrderOf_nsmul' _ a0, ZMod.addOrderOf_one]
/-- We have that `ringChar (ZMod n) = n`. -/
theorem ringChar_zmod_n (n : ℕ) : ringChar (ZMod n) = n := by
rw [ringChar.eq_iff]
exact ZMod.charP n
theorem natCast_self (n : ℕ) : (n : ZMod n) = 0 :=
CharP.cast_eq_zero (ZMod n) n
@[simp]
theorem natCast_self' (n : ℕ) : (n + 1 : ZMod (n + 1)) = 0 := by
rw [← Nat.cast_add_one, natCast_self (n + 1)]
lemma natCast_pow_eq_zero_of_le (p : ℕ) {m n : ℕ} (h : n ≤ m) :
(p ^ m : ZMod (p ^ n)) = 0 := by
obtain ⟨q, rfl⟩ := Nat.exists_eq_add_of_le h
rw [pow_add, ← Nat.cast_pow]
simp
section UniversalProperty
variable {n : ℕ} {R : Type*}
section
variable [AddGroupWithOne R]
/-- Cast an integer modulo `n` to another semiring.
This function is a morphism if the characteristic of `R` divides `n`.
See `ZMod.castHom` for a bundled version. -/
def cast : ∀ {n : ℕ}, ZMod n → R
| 0 => Int.cast
| _ + 1 => fun i => i.val
@[simp]
theorem cast_zero : (cast (0 : ZMod n) : R) = 0 := by
delta ZMod.cast
cases n
· exact Int.cast_zero
· simp
theorem cast_eq_val [NeZero n] (a : ZMod n) : (cast a : R) = a.val := by
cases n
· cases NeZero.ne 0 rfl
rfl
variable {S : Type*} [AddGroupWithOne S]
@[simp]
theorem _root_.Prod.fst_zmod_cast (a : ZMod n) : (cast a : R × S).fst = cast a := by
cases n
· rfl
· simp [ZMod.cast]
@[simp]
theorem _root_.Prod.snd_zmod_cast (a : ZMod n) : (cast a : R × S).snd = cast a := by
cases n
· rfl
· simp [ZMod.cast]
end
/-- So-named because the coercion is `Nat.cast` into `ZMod`. For `Nat.cast` into an arbitrary ring,
see `ZMod.natCast_val`. -/
theorem natCast_zmod_val {n : ℕ} [NeZero n] (a : ZMod n) : (a.val : ZMod n) = a := by
cases n
· cases NeZero.ne 0 rfl
· apply Fin.cast_val_eq_self
theorem natCast_rightInverse [NeZero n] : Function.RightInverse val ((↑) : ℕ → ZMod n) :=
natCast_zmod_val
theorem natCast_zmod_surjective [NeZero n] : Function.Surjective ((↑) : ℕ → ZMod n) :=
natCast_rightInverse.surjective
/-- So-named because the outer coercion is `Int.cast` into `ZMod`. For `Int.cast` into an arbitrary
ring, see `ZMod.intCast_cast`. -/
@[norm_cast]
theorem intCast_zmod_cast (a : ZMod n) : ((cast a : ℤ) : ZMod n) = a := by
cases n
· simp [ZMod.cast, ZMod]
· dsimp [ZMod.cast]
rw [Int.cast_natCast, natCast_zmod_val]
theorem intCast_rightInverse : Function.RightInverse (cast : ZMod n → ℤ) ((↑) : ℤ → ZMod n) :=
intCast_zmod_cast
theorem intCast_surjective : Function.Surjective ((↑) : ℤ → ZMod n) :=
intCast_rightInverse.surjective
lemma «forall» {P : ZMod n → Prop} : (∀ x, P x) ↔ ∀ x : ℤ, P x := intCast_surjective.forall
lemma «exists» {P : ZMod n → Prop} : (∃ x, P x) ↔ ∃ x : ℤ, P x := intCast_surjective.exists
theorem cast_id : ∀ (n) (i : ZMod n), (ZMod.cast i : ZMod n) = i
| 0, _ => Int.cast_id
| _ + 1, i => natCast_zmod_val i
@[simp]
theorem cast_id' : (ZMod.cast : ZMod n → ZMod n) = id :=
funext (cast_id n)
variable (R) [Ring R]
/-- The coercions are respectively `Nat.cast` and `ZMod.cast`. -/
@[simp]
theorem natCast_comp_val [NeZero n] : ((↑) : ℕ → R) ∘ (val : ZMod n → ℕ) = cast := by
cases n
· cases NeZero.ne 0 rfl
rfl
/-- The coercions are respectively `Int.cast`, `ZMod.cast`, and `ZMod.cast`. -/
@[simp]
theorem intCast_comp_cast : ((↑) : ℤ → R) ∘ (cast : ZMod n → ℤ) = cast := by
cases n
· exact congr_arg (Int.cast ∘ ·) ZMod.cast_id'
· ext
simp [ZMod, ZMod.cast]
variable {R}
@[simp]
theorem natCast_val [NeZero n] (i : ZMod n) : (i.val : R) = cast i :=
congr_fun (natCast_comp_val R) i
@[simp]
theorem intCast_cast (i : ZMod n) : ((cast i : ℤ) : R) = cast i :=
congr_fun (intCast_comp_cast R) i
theorem cast_add_eq_ite {n : ℕ} (a b : ZMod n) :
(cast (a + b) : ℤ) =
if (n : ℤ) ≤ cast a + cast b then (cast a + cast b - n : ℤ) else cast a + cast b := by
rcases n with - | n
· simp; rfl
change Fin (n + 1) at a b
change ((((a + b) : Fin (n + 1)) : ℕ) : ℤ) = if ((n + 1 : ℕ) : ℤ) ≤ (a : ℕ) + b then _ else _
simp only [Fin.val_add_eq_ite, Int.natCast_succ]
norm_cast
split_ifs with h
· rw [Nat.cast_sub h]
congr
· rfl
section CharDvd
/-! If the characteristic of `R` divides `n`, then `cast` is a homomorphism. -/
variable {m : ℕ} [CharP R m]
@[simp]
theorem cast_one (h : m ∣ n) : (cast (1 : ZMod n) : R) = 1 := by
rcases n with - | n
· exact Int.cast_one
change ((1 % (n + 1) : ℕ) : R) = 1
cases n
· rw [Nat.dvd_one] at h
subst m
subsingleton [CharP.CharOne.subsingleton]
rw [Nat.mod_eq_of_lt]
· exact Nat.cast_one
exact Nat.lt_of_sub_eq_succ rfl
@[simp]
theorem cast_add (h : m ∣ n) (a b : ZMod n) : (cast (a + b : ZMod n) : R) = cast a + cast b := by
cases n
· apply Int.cast_add
symm
dsimp [ZMod, ZMod.cast, ZMod.val]
rw [← Nat.cast_add, Fin.val_add, ← sub_eq_zero, ← Nat.cast_sub (Nat.mod_le _ _),
@CharP.cast_eq_zero_iff R _ m]
exact h.trans (Nat.dvd_sub_mod _)
@[simp]
theorem cast_mul (h : m ∣ n) (a b : ZMod n) : (cast (a * b : ZMod n) : R) = cast a * cast b := by
cases n
· apply Int.cast_mul
symm
dsimp [ZMod, ZMod.cast, ZMod.val]
rw [← Nat.cast_mul, Fin.val_mul, ← sub_eq_zero, ← Nat.cast_sub (Nat.mod_le _ _),
@CharP.cast_eq_zero_iff R _ m]
exact h.trans (Nat.dvd_sub_mod _)
/-- The canonical ring homomorphism from `ZMod n` to a ring of characteristic dividing `n`.
See also `ZMod.lift` for a generalized version working in `AddGroup`s.
-/
def castHom (h : m ∣ n) (R : Type*) [Ring R] [CharP R m] : ZMod n →+* R where
toFun := cast
map_zero' := cast_zero
map_one' := cast_one h
map_add' := cast_add h
map_mul' := cast_mul h
@[simp]
theorem castHom_apply {h : m ∣ n} (i : ZMod n) : castHom h R i = cast i :=
rfl
@[simp]
theorem cast_sub (h : m ∣ n) (a b : ZMod n) : (cast (a - b : ZMod n) : R) = cast a - cast b :=
(castHom h R).map_sub a b
@[simp]
theorem cast_neg (h : m ∣ n) (a : ZMod n) : (cast (-a : ZMod n) : R) = -(cast a) :=
(castHom h R).map_neg a
@[simp]
theorem cast_pow (h : m ∣ n) (a : ZMod n) (k : ℕ) : (cast (a ^ k : ZMod n) : R) = (cast a) ^ k :=
(castHom h R).map_pow a k
@[simp, norm_cast]
theorem cast_natCast (h : m ∣ n) (k : ℕ) : (cast (k : ZMod n) : R) = k :=
map_natCast (castHom h R) k
@[simp, norm_cast]
theorem cast_intCast (h : m ∣ n) (k : ℤ) : (cast (k : ZMod n) : R) = k :=
map_intCast (castHom h R) k
theorem castHom_surjective (h : m ∣ n) : Function.Surjective (castHom h (ZMod m)) :=
fun a ↦ by obtain ⟨a, rfl⟩ := intCast_surjective a; exact ⟨a, map_intCast ..⟩
end CharDvd
section CharEq
/-! Some specialised simp lemmas which apply when `R` has characteristic `n`. -/
variable [CharP R n]
theorem cast_one' : (cast (1 : ZMod n) : R) = 1 := by simp
theorem cast_add' (a b : ZMod n) : (cast (a + b : ZMod n) : R) = cast a + cast b := by simp
theorem cast_mul' (a b : ZMod n) : (cast (a * b : ZMod n) : R) = cast a * cast b := by simp
theorem cast_sub' (a b : ZMod n) : (cast (a - b : ZMod n) : R) = cast a - cast b := by simp
theorem cast_pow' (a : ZMod n) (k : ℕ) : (cast (a ^ k : ZMod n) : R) = (cast a : R) ^ k := by simp
@[norm_cast]
theorem cast_natCast' (k : ℕ) : (cast (k : ZMod n) : R) = k := by simp
@[norm_cast]
theorem cast_intCast' (k : ℤ) : (cast (k : ZMod n) : R) = k := by simp
variable (R)
theorem castHom_injective : Function.Injective (ZMod.castHom (dvd_refl n) R) := by
rw [injective_iff_map_eq_zero]
intro x
obtain ⟨k, rfl⟩ := ZMod.intCast_surjective x
rw [map_intCast, CharP.intCast_eq_zero_iff R n, CharP.intCast_eq_zero_iff (ZMod n) n]
exact id
theorem castHom_bijective [Fintype R] (h : Fintype.card R = n) :
Function.Bijective (ZMod.castHom (dvd_refl n) R) := by
haveI : NeZero n :=
⟨by
intro hn
rw [hn] at h
exact (Fintype.card_eq_zero_iff.mp h).elim' 0⟩
rw [Fintype.bijective_iff_injective_and_card, ZMod.card, h, eq_self_iff_true, and_true]
apply ZMod.castHom_injective
/-- The unique ring isomorphism between `ZMod n` and a ring `R`
of characteristic `n` and cardinality `n`. -/
noncomputable def ringEquiv [Fintype R] (h : Fintype.card R = n) : ZMod n ≃+* R :=
RingEquiv.ofBijective _ (ZMod.castHom_bijective R h)
/-- The unique ring isomorphism between `ZMod p` and a ring `R` of cardinality a prime `p`.
If you need any property of this isomorphism, first of all use `ringEquivOfPrime_eq_ringEquiv`
below (after `have : CharP R p := ...`) and deduce it by the results about `ZMod.ringEquiv`. -/
noncomputable def ringEquivOfPrime [Fintype R] {p : ℕ} (hp : p.Prime) (hR : Fintype.card R = p) :
ZMod p ≃+* R :=
have : Nontrivial R := Fintype.one_lt_card_iff_nontrivial.1 (hR ▸ hp.one_lt)
-- The following line exists as `charP_of_card_eq_prime` in
-- `Mathlib/Algebra/CharP/CharAndCard.lean`.
have : CharP R p := (CharP.charP_iff_prime_eq_zero hp).2 (hR ▸ Nat.cast_card_eq_zero R)
ZMod.ringEquiv R hR
@[simp]
lemma ringEquivOfPrime_eq_ringEquiv [Fintype R] {p : ℕ} [CharP R p] (hp : p.Prime)
(hR : Fintype.card R = p) : ringEquivOfPrime R hp hR = ringEquiv R hR := rfl
/-- The identity between `ZMod m` and `ZMod n` when `m = n`, as a ring isomorphism. -/
def ringEquivCongr {m n : ℕ} (h : m = n) : ZMod m ≃+* ZMod n := by
rcases m with - | m <;> rcases n with - | n
· exact RingEquiv.refl _
· exfalso
exact n.succ_ne_zero h.symm
· exfalso
exact m.succ_ne_zero h
· exact
{ finCongr h with
map_mul' := fun a b => by
dsimp [ZMod]
ext
rw [Fin.coe_cast, Fin.coe_mul, Fin.coe_mul, Fin.coe_cast, Fin.coe_cast, ← h]
map_add' := fun a b => by
dsimp [ZMod]
ext
rw [Fin.coe_cast, Fin.val_add, Fin.val_add, Fin.coe_cast, Fin.coe_cast, ← h] }
@[simp] lemma ringEquivCongr_refl (a : ℕ) : ringEquivCongr (rfl : a = a) = .refl _ := by
cases a <;> rfl
lemma ringEquivCongr_refl_apply {a : ℕ} (x : ZMod a) : ringEquivCongr rfl x = x := by
rw [ringEquivCongr_refl]
rfl
lemma ringEquivCongr_symm {a b : ℕ} (hab : a = b) :
(ringEquivCongr hab).symm = ringEquivCongr hab.symm := by
subst hab
cases a <;> rfl
lemma ringEquivCongr_trans {a b c : ℕ} (hab : a = b) (hbc : b = c) :
(ringEquivCongr hab).trans (ringEquivCongr hbc) = ringEquivCongr (hab.trans hbc) := by
subst hab hbc
cases a <;> rfl
lemma ringEquivCongr_ringEquivCongr_apply {a b c : ℕ} (hab : a = b) (hbc : b = c) (x : ZMod a) :
ringEquivCongr hbc (ringEquivCongr hab x) = ringEquivCongr (hab.trans hbc) x := by
rw [← ringEquivCongr_trans hab hbc]
rfl
lemma ringEquivCongr_val {a b : ℕ} (h : a = b) (x : ZMod a) :
ZMod.val ((ZMod.ringEquivCongr h) x) = ZMod.val x := by
subst h
cases a <;> rfl
lemma ringEquivCongr_intCast {a b : ℕ} (h : a = b) (z : ℤ) :
ZMod.ringEquivCongr h z = z := map_intCast (ringEquivCongr h) z
end CharEq
end UniversalProperty
variable {m n : ℕ}
@[simp]
theorem val_eq_zero : ∀ {n : ℕ} (a : ZMod n), a.val = 0 ↔ a = 0
| 0, _ => Int.natAbs_eq_zero
| n + 1, a => by
rw [Fin.ext_iff]
exact Iff.rfl
theorem intCast_eq_intCast_iff (a b : ℤ) (c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a ≡ b [ZMOD c] :=
CharP.intCast_eq_intCast (ZMod c) c
theorem intCast_eq_intCast_iff' (a b : ℤ) (c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a % c = b % c :=
ZMod.intCast_eq_intCast_iff a b c
theorem val_intCast {n : ℕ} (a : ℤ) [NeZero n] : ↑(a : ZMod n).val = a % n := by
have hle : (0 : ℤ) ≤ ↑(a : ZMod n).val := Int.natCast_nonneg _
have hlt : ↑(a : ZMod n).val < (n : ℤ) := Int.ofNat_lt.mpr (ZMod.val_lt a)
refine (Int.emod_eq_of_lt hle hlt).symm.trans ?_
rw [← ZMod.intCast_eq_intCast_iff', Int.cast_natCast, ZMod.natCast_val, ZMod.cast_id]
theorem natCast_eq_natCast_iff (a b c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a ≡ b [MOD c] := by
simpa [Int.natCast_modEq_iff] using ZMod.intCast_eq_intCast_iff a b c
theorem natCast_eq_natCast_iff' (a b c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a % c = b % c :=
ZMod.natCast_eq_natCast_iff a b c
theorem intCast_zmod_eq_zero_iff_dvd (a : ℤ) (b : ℕ) : (a : ZMod b) = 0 ↔ (b : ℤ) ∣ a := by
rw [← Int.cast_zero, ZMod.intCast_eq_intCast_iff, Int.modEq_zero_iff_dvd]
theorem intCast_eq_intCast_iff_dvd_sub (a b : ℤ) (c : ℕ) : (a : ZMod c) = ↑b ↔ ↑c ∣ b - a := by
rw [ZMod.intCast_eq_intCast_iff, Int.modEq_iff_dvd]
theorem natCast_eq_zero_iff (a b : ℕ) : (a : ZMod b) = 0 ↔ b ∣ a := by
rw [← Nat.cast_zero, ZMod.natCast_eq_natCast_iff, Nat.modEq_zero_iff_dvd]
@[deprecated (since := "2025-06-30")] alias natCast_zmod_eq_zero_iff_dvd := natCast_eq_zero_iff
theorem coe_intCast (a : ℤ) : cast (a : ZMod n) = a % n := by
cases n
· rw [Int.ofNat_zero, Int.emod_zero, Int.cast_id]; rfl
· rw [← val_intCast, val]; rfl
lemma intCast_cast_add (x y : ZMod n) : (cast (x + y) : ℤ) = (cast x + cast y) % n := by
rw [← ZMod.coe_intCast, Int.cast_add, ZMod.intCast_zmod_cast, ZMod.intCast_zmod_cast]
lemma intCast_cast_mul (x y : ZMod n) : (cast (x * y) : ℤ) = cast x * cast y % n := by
rw [← ZMod.coe_intCast, Int.cast_mul, ZMod.intCast_zmod_cast, ZMod.intCast_zmod_cast]
lemma intCast_cast_sub (x y : ZMod n) : (cast (x - y) : ℤ) = (cast x - cast y) % n := by
rw [← ZMod.coe_intCast, Int.cast_sub, ZMod.intCast_zmod_cast, ZMod.intCast_zmod_cast]
lemma intCast_cast_neg (x : ZMod n) : (cast (-x) : ℤ) = -cast x % n := by
rw [← ZMod.coe_intCast, Int.cast_neg, ZMod.intCast_zmod_cast]
@[simp]
theorem val_neg_one (n : ℕ) : (-1 : ZMod n.succ).val = n := by
dsimp [val, Fin.coe_neg]
cases n
· simp
· dsimp [ZMod, ZMod.cast]
rw [Fin.coe_neg_one]
/-- `-1 : ZMod n` lifts to `n - 1 : R`. This avoids the characteristic assumption in `cast_neg`. -/
theorem cast_neg_one {R : Type*} [Ring R] (n : ℕ) : cast (-1 : ZMod n) = (n - 1 : R) := by
rcases n with - | n
· dsimp [ZMod, ZMod.cast]; simp
· rw [← natCast_val, val_neg_one, Nat.cast_succ, add_sub_cancel_right]
theorem cast_sub_one {R : Type*} [Ring R] {n : ℕ} (k : ZMod n) :
(cast (k - 1 : ZMod n) : R) = (if k = 0 then (n : R) else cast k) - 1 := by
split_ifs with hk
· rw [hk, zero_sub, ZMod.cast_neg_one]
· cases n
· dsimp [ZMod, ZMod.cast]
rw [Int.cast_sub, Int.cast_one]
· dsimp [ZMod, ZMod.cast, ZMod.val]
rw [Fin.coe_sub_one, if_neg]
· rw [Nat.cast_sub, Nat.cast_one]
rwa [Fin.ext_iff, Fin.val_zero, ← Ne, ← Nat.one_le_iff_ne_zero] at hk
· exact hk
theorem natCast_eq_iff (p : ℕ) (n : ℕ) (z : ZMod p) [NeZero p] :
↑n = z ↔ ∃ k, n = z.val + p * k := by
constructor
· rintro rfl
refine ⟨n / p, ?_⟩
rw [val_natCast, Nat.mod_add_div]
· rintro ⟨k, rfl⟩
rw [Nat.cast_add, natCast_zmod_val, Nat.cast_mul, natCast_self, zero_mul,
add_zero]
theorem intCast_eq_iff (p : ℕ) (n : ℤ) (z : ZMod p) [NeZero p] :
↑n = z ↔ ∃ k, n = z.val + p * k := by
constructor
· rintro rfl
refine ⟨n / p, ?_⟩
rw [val_intCast, Int.emod_add_mul_ediv]
· rintro ⟨k, rfl⟩
rw [Int.cast_add, Int.cast_mul, Int.cast_natCast, Int.cast_natCast, natCast_val,
ZMod.natCast_self, zero_mul, add_zero, cast_id]
@[push_cast, simp]
theorem intCast_mod (a : ℤ) (b : ℕ) : ((a % b : ℤ) : ZMod b) = (a : ZMod b) := by
rw [ZMod.intCast_eq_intCast_iff]
apply Int.mod_modEq
theorem ker_intCastAddHom (n : ℕ) :
(Int.castAddHom (ZMod n)).ker = AddSubgroup.zmultiples (n : ℤ) := by
ext
rw [Int.mem_zmultiples_iff, AddMonoidHom.mem_ker, Int.coe_castAddHom,
intCast_zmod_eq_zero_iff_dvd]
theorem cast_injective_of_le {m n : ℕ} [nzm : NeZero m] (h : m ≤ n) :
Function.Injective (@cast (ZMod n) _ m) := by
cases m with
| zero => cases nzm; simp_all
| succ m =>
rintro ⟨x, hx⟩ ⟨y, hy⟩ f
simp only [cast, val, natCast_eq_natCast_iff',
Nat.mod_eq_of_lt (hx.trans_le h), Nat.mod_eq_of_lt (hy.trans_le h)] at f
apply Fin.ext
exact f
theorem cast_zmod_eq_zero_iff_of_le {m n : ℕ} [NeZero m] (h : m ≤ n) (a : ZMod m) :
(cast a : ZMod n) = 0 ↔ a = 0 := by
rw [← ZMod.cast_zero (n := m)]
exact Injective.eq_iff' (cast_injective_of_le h) rfl
@[simp]
theorem natCast_toNat (p : ℕ) : ∀ {z : ℤ} (_h : 0 ≤ z), (z.toNat : ZMod p) = z
| (n : ℕ), _h => by simp only [Int.cast_natCast, Int.toNat_natCast]
| Int.negSucc n, h => by simp at h
theorem val_injective (n : ℕ) [NeZero n] : Function.Injective (val : ZMod n → ℕ) := by
cases n
· cases NeZero.ne 0 rfl
intro a b h
dsimp [ZMod]
ext
exact h
theorem val_one_eq_one_mod (n : ℕ) : (1 : ZMod n).val = 1 % n := by
rw [← Nat.cast_one, val_natCast]
theorem val_two_eq_two_mod (n : ℕ) : (2 : ZMod n).val = 2 % n := by
rw [← Nat.cast_two, val_natCast]
theorem val_one (n : ℕ) [Fact (1 < n)] : (1 : ZMod n).val = 1 := by
rw [val_one_eq_one_mod]
exact Nat.mod_eq_of_lt Fact.out
lemma val_one'' : ∀ {n}, n ≠ 1 → (1 : ZMod n).val = 1
| 0, _ => rfl
| 1, hn => by cases hn rfl
| n + 2, _ =>
haveI : Fact (1 < n + 2) := ⟨by simp⟩
ZMod.val_one _
theorem val_add {n : ℕ} [NeZero n] (a b : ZMod n) : (a + b).val = (a.val + b.val) % n := by
cases n
· cases NeZero.ne 0 rfl
· apply Fin.val_add
theorem val_add_of_lt {n : ℕ} {a b : ZMod n} (h : a.val + b.val < n) :
(a + b).val = a.val + b.val := by
have : NeZero n := by constructor; rintro rfl; simp at h
rw [ZMod.val_add, Nat.mod_eq_of_lt h]
theorem val_add_val_of_le {n : ℕ} [NeZero n] {a b : ZMod n} (h : n ≤ a.val + b.val) :
a.val + b.val = (a + b).val + n := by
rw [val_add, Nat.add_mod_add_of_le_add_mod, Nat.mod_eq_of_lt (val_lt _),
Nat.mod_eq_of_lt (val_lt _)]
rwa [Nat.mod_eq_of_lt (val_lt _), Nat.mod_eq_of_lt (val_lt _)]
theorem val_add_of_le {n : ℕ} [NeZero n] {a b : ZMod n} (h : n ≤ a.val + b.val) :
(a + b).val = a.val + b.val - n := by
rw [val_add_val_of_le h]
exact eq_tsub_of_add_eq rfl
theorem val_add_le {n : ℕ} (a b : ZMod n) : (a + b).val ≤ a.val + b.val := by
cases n
· simpa [ZMod.val] using Int.natAbs_add_le _ _
· simpa [ZMod.val_add] using Nat.mod_le _ _
theorem val_mul {n : ℕ} (a b : ZMod n) : (a * b).val = a.val * b.val % n := by
cases n
· rw [Nat.mod_zero]
apply Int.natAbs_mul
· apply Fin.val_mul
theorem val_mul_le {n : ℕ} (a b : ZMod n) : (a * b).val ≤ a.val * b.val := by
rw [val_mul]
apply Nat.mod_le
theorem val_mul_of_lt {n : ℕ} {a b : ZMod n} (h : a.val * b.val < n) :
(a * b).val = a.val * b.val := by
rw [val_mul]
apply Nat.mod_eq_of_lt h
theorem val_mul_iff_lt {n : ℕ} [NeZero n] (a b : ZMod n) :
(a * b).val = a.val * b.val ↔ a.val * b.val < n := by
constructor <;> intro h
· rw [← h]; apply ZMod.val_lt
· apply ZMod.val_mul_of_lt h
instance nontrivial (n : ℕ) [Fact (1 < n)] : Nontrivial (ZMod n) :=
⟨⟨0, 1, fun h =>
zero_ne_one <|
calc
0 = (0 : ZMod n).val := by rw [val_zero]
_ = (1 : ZMod n).val := congr_arg ZMod.val h
_ = 1 := val_one n
⟩⟩
instance nontrivial' : Nontrivial (ZMod 0) := by
delta ZMod; infer_instance
lemma one_eq_zero_iff {n : ℕ} : (1 : ZMod n) = 0 ↔ n = 1 := by
rw [← Nat.cast_one, natCast_eq_zero_iff, Nat.dvd_one]
/-- The inversion on `ZMod n`.
It is setup in such a way that `a * a⁻¹` is equal to `gcd a.val n`.
In particular, if `a` is coprime to `n`, and hence a unit, `a * a⁻¹ = 1`. -/
def inv : ∀ n : ℕ, ZMod n → ZMod n
| 0, i => Int.sign i
| n + 1, i => Nat.gcdA i.val (n + 1)
instance (n : ℕ) : Inv (ZMod n) :=
⟨inv n⟩
theorem inv_zero : ∀ n : ℕ, (0 : ZMod n)⁻¹ = 0
| 0 => Int.sign_zero
| n + 1 =>
show (Nat.gcdA _ (n + 1) : ZMod (n + 1)) = 0 by
rw [val_zero]
unfold Nat.gcdA Nat.xgcd Nat.xgcdAux
rfl
theorem mul_inv_eq_gcd {n : ℕ} (a : ZMod n) : a * a⁻¹ = Nat.gcd a.val n := by
rcases n with - | n
· dsimp [ZMod] at a ⊢
calc
_ = a * Int.sign a := rfl
_ = a.natAbs := by rw [Int.mul_sign_self]
_ = a.natAbs.gcd 0 := by rw [Nat.gcd_zero_right]
· calc
a * a⁻¹ = a * a⁻¹ + n.succ * Nat.gcdB (val a) n.succ := by
rw [natCast_self, zero_mul, add_zero]
_ = ↑(↑a.val * Nat.gcdA (val a) n.succ + n.succ * Nat.gcdB (val a) n.succ) := by
push_cast
rw [natCast_zmod_val]
rfl
_ = Nat.gcd a.val n.succ := by rw [← Nat.gcd_eq_gcd_ab a.val n.succ]; rfl
@[simp] protected lemma inv_one (n : ℕ) : (1⁻¹ : ZMod n) = 1 := by
obtain rfl | hn := eq_or_ne n 1
· exact Subsingleton.elim _ _
· simpa [ZMod.val_one'' hn] using mul_inv_eq_gcd (1 : ZMod n)
@[simp]
theorem natCast_mod (a : ℕ) (n : ℕ) : ((a % n : ℕ) : ZMod n) = a :=
(CharP.cast_eq_mod (ZMod n) n a).symm
@[deprecated natCast_eq_natCast_iff (since := "2025-08-12")]
theorem eq_iff_modEq_nat (n : ℕ) {a b : ℕ} : (a : ZMod n) = b ↔ a ≡ b [MOD n] :=
natCast_eq_natCast_iff a b n
theorem intCast_eq_zero_iff_even {n : ℤ} : (n : ZMod 2) = 0 ↔ Even n :=
(CharP.intCast_eq_zero_iff (ZMod 2) 2 n).trans even_iff_two_dvd.symm
alias ⟨_, _root_.Even.intCast_zmod_two⟩ := intCast_eq_zero_iff_even
theorem natCast_eq_zero_iff_even {n : ℕ} : (n : ZMod 2) = 0 ↔ Even n :=
mod_cast intCast_eq_zero_iff_even (n := n)
@[deprecated (since := "2025-08-25")]
alias eq_zero_iff_even := natCast_eq_zero_iff_even
alias ⟨_, _root_.Even.natCast_zmod_two⟩ := natCast_eq_zero_iff_even
theorem intCast_eq_one_iff_odd {n : ℤ} : (n : ZMod 2) = 1 ↔ Odd n := by
rw [← Int.cast_one, ZMod.intCast_eq_intCast_iff, Int.odd_iff, Int.ModEq]
simp
alias ⟨_, _root_.Odd.intCast_zmod_two⟩ := intCast_eq_one_iff_odd
theorem natCast_eq_one_iff_odd {n : ℕ} : (n : ZMod 2) = 1 ↔ Odd n :=
mod_cast intCast_eq_one_iff_odd (n := n)
@[deprecated (since := "2025-08-25")]
alias eq_one_iff_odd := natCast_eq_one_iff_odd
alias ⟨_, _root_.Odd.natCast_zmod_two⟩ := natCast_eq_one_iff_odd
theorem natCast_ne_zero_iff_odd {n : ℕ} : (n : ZMod 2) ≠ 0 ↔ Odd n := by
simp [natCast_eq_zero_iff_even]
@[deprecated (since := "2025-08-25")]
alias ne_zero_iff_odd := natCast_ne_zero_iff_odd
theorem coe_mul_inv_eq_one {n : ℕ} (x : ℕ) (h : Nat.Coprime x n) :
((x : ZMod n) * (x : ZMod n)⁻¹) = 1 := by
rw [Nat.Coprime, Nat.gcd_comm, Nat.gcd_rec] at h
rw [mul_inv_eq_gcd, val_natCast, h, Nat.cast_one]
lemma mul_val_inv (hmn : m.Coprime n) : (m * (m⁻¹ : ZMod n).val : ZMod n) = 1 := by
obtain rfl | hn := eq_or_ne n 0
· simp [m.coprime_zero_right.1 hmn]
haveI : NeZero n := ⟨hn⟩
rw [ZMod.natCast_zmod_val, ZMod.coe_mul_inv_eq_one _ hmn]
lemma val_inv_mul (hmn : m.Coprime n) : ((m⁻¹ : ZMod n).val * m : ZMod n) = 1 := by
rw [mul_comm, mul_val_inv hmn]
/-- `unitOfCoprime` makes an element of `(ZMod n)ˣ` given
a natural number `x` and a proof that `x` is coprime to `n` -/
def unitOfCoprime {n : ℕ} (x : ℕ) (h : Nat.Coprime x n) : (ZMod n)ˣ :=
⟨x, x⁻¹, coe_mul_inv_eq_one x h, by rw [mul_comm, coe_mul_inv_eq_one x h]⟩
@[simp]
theorem coe_unitOfCoprime {n : ℕ} (x : ℕ) (h : Nat.Coprime x n) :
(unitOfCoprime x h : ZMod n) = x :=
rfl
theorem val_coe_unit_coprime {n : ℕ} (u : (ZMod n)ˣ) : Nat.Coprime (u : ZMod n).val n := by
rcases n with - | n
· rcases Int.units_eq_one_or u with (rfl | rfl) <;> simp
apply Nat.coprime_of_mul_modEq_one ((u⁻¹ : Units (ZMod (n + 1))) : ZMod (n + 1)).val
have := Units.ext_iff.1 (mul_inv_cancel u)
rw [Units.val_one] at this
rw [← natCast_eq_natCast_iff, Nat.cast_one, ← this]; clear this
rw [← natCast_zmod_val ((u * u⁻¹ : Units (ZMod (n + 1))) : ZMod (n + 1))]
rw [Units.val_mul, val_mul, natCast_mod]
lemma isUnit_iff_coprime (m n : ℕ) : IsUnit (m : ZMod n) ↔ m.Coprime n := by
refine ⟨fun H ↦ ?_, fun H ↦ (unitOfCoprime m H).isUnit⟩
have H' := val_coe_unit_coprime H.unit
rw [IsUnit.unit_spec, val_natCast, Nat.coprime_iff_gcd_eq_one] at H'
rw [Nat.coprime_iff_gcd_eq_one, Nat.gcd_comm, ← H']
exact Nat.gcd_rec n m
lemma isUnit_prime_iff_not_dvd {n p : ℕ} (hp : p.Prime) : IsUnit (p : ZMod n) ↔ ¬p ∣ n := by
rw [isUnit_iff_coprime, Nat.Prime.coprime_iff_not_dvd hp]
lemma isUnit_prime_of_not_dvd {n p : ℕ} (hp : p.Prime) (h : ¬ p ∣ n) : IsUnit (p : ZMod n) :=
(isUnit_prime_iff_not_dvd hp).mpr h
@[simp]
theorem inv_coe_unit {n : ℕ} (u : (ZMod n)ˣ) : (u : ZMod n)⁻¹ = (u⁻¹ : (ZMod n)ˣ) := by
have := congr_arg ((↑) : ℕ → ZMod n) (val_coe_unit_coprime u)
rw [← mul_inv_eq_gcd, Nat.cast_one] at this
let u' : (ZMod n)ˣ := ⟨u, (u : ZMod n)⁻¹, this, by rwa [mul_comm]⟩
have h : u = u' := by
apply Units.ext
rfl
rw [h]
rfl
theorem mul_inv_of_unit {n : ℕ} (a : ZMod n) (h : IsUnit a) : a * a⁻¹ = 1 := by
rcases h with ⟨u, rfl⟩
rw [inv_coe_unit, u.mul_inv]
theorem inv_mul_of_unit {n : ℕ} (a : ZMod n) (h : IsUnit a) : a⁻¹ * a = 1 := by
rw [mul_comm, mul_inv_of_unit a h]
-- TODO: If we changed `⁻¹` so that `ZMod n` is always a `DivisionMonoid`,
-- then we could use the general lemma `inv_eq_of_mul_eq_one`
protected theorem inv_eq_of_mul_eq_one (n : ℕ) (a b : ZMod n) (h : a * b = 1) : a⁻¹ = b :=
left_inv_eq_right_inv (inv_mul_of_unit a ⟨⟨a, b, h, mul_comm a b ▸ h⟩, rfl⟩) h
@[simp]
theorem inv_neg_one (n : ℕ) : (-1 : ZMod n)⁻¹ = -1 :=
ZMod.inv_eq_of_mul_eq_one n (-1) (-1) (by simp)
lemma inv_mul_eq_one_of_isUnit {n : ℕ} {a : ZMod n} (ha : IsUnit a) (b : ZMod n) :
a⁻¹ * b = 1 ↔ a = b := by
-- ideally, this would be `ha.inv_mul_eq_one`, but `ZMod n` is not a `DivisionMonoid`...
-- (see the "TODO" above)
refine ⟨fun H ↦ ?_, fun H ↦ H ▸ a.inv_mul_of_unit ha⟩
apply_fun (a * ·) at H
rwa [← mul_assoc, a.mul_inv_of_unit ha, one_mul, mul_one, eq_comm] at H
-- TODO: this equivalence is true for `ZMod 0 = ℤ`, but needs to use different functions.
/-- Equivalence between the units of `ZMod n` and
the subtype of terms `x : ZMod n` for which `x.val` is coprime to `n` -/
def unitsEquivCoprime {n : ℕ} [NeZero n] : (ZMod n)ˣ ≃ { x : ZMod n // Nat.Coprime x.val n } where
toFun x := ⟨x, val_coe_unit_coprime x⟩
invFun x := unitOfCoprime x.1.val x.2
left_inv := fun ⟨_, _, _, _⟩ => Units.ext (natCast_zmod_val _)
right_inv := fun ⟨_, _⟩ => by simp
/-- The **Chinese remainder theorem**. For a pair of coprime natural numbers, `m` and `n`,
the rings `ZMod (m * n)` and `ZMod m × ZMod n` are isomorphic.
See `Ideal.quotientInfRingEquivPiQuotient` for the Chinese remainder theorem for ideals in any
ring.
-/
def chineseRemainder {m n : ℕ} (h : m.Coprime n) : ZMod (m * n) ≃+* ZMod m × ZMod n :=
let to_fun : ZMod (m * n) → ZMod m × ZMod n :=
ZMod.castHom (show m.lcm n ∣ m * n by simp [Nat.lcm_dvd_iff]) (ZMod m × ZMod n)
let inv_fun : ZMod m × ZMod n → ZMod (m * n) := fun x =>
if m * n = 0 then
if m = 1 then cast (RingHom.snd _ (ZMod n) x) else cast (RingHom.fst (ZMod m) _ x)
else Nat.chineseRemainder h x.1.val x.2.val
have inv : Function.LeftInverse inv_fun to_fun ∧ Function.RightInverse inv_fun to_fun :=
if hmn0 : m * n = 0 then by
rcases h.eq_of_mul_eq_zero hmn0 with (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩)
· constructor
· intro x; rfl
· rintro ⟨x, y⟩
fin_cases y
simp [to_fun, inv_fun, castHom, Prod.ext_iff, eq_iff_true_of_subsingleton]
· constructor
· intro x; rfl
· rintro ⟨x, y⟩
fin_cases x
simp [to_fun, inv_fun, castHom, Prod.ext_iff, eq_iff_true_of_subsingleton]
else by
haveI : NeZero (m * n) := ⟨hmn0⟩
haveI : NeZero m := ⟨left_ne_zero_of_mul hmn0⟩
haveI : NeZero n := ⟨right_ne_zero_of_mul hmn0⟩
have left_inv : Function.LeftInverse inv_fun to_fun := by
intro x
dsimp only [to_fun, inv_fun, ZMod.castHom_apply]
conv_rhs => rw [← ZMod.natCast_zmod_val x]
rw [if_neg hmn0, ZMod.natCast_eq_natCast_iff, ← Nat.modEq_and_modEq_iff_modEq_mul h,
Prod.fst_zmod_cast, Prod.snd_zmod_cast]
refine
⟨(Nat.chineseRemainder h (cast x : ZMod m).val (cast x : ZMod n).val).2.left.trans ?_,
(Nat.chineseRemainder h (cast x : ZMod m).val (cast x : ZMod n).val).2.right.trans ?_⟩
· rw [← ZMod.natCast_eq_natCast_iff, ZMod.natCast_zmod_val, ZMod.natCast_val]
· rw [← ZMod.natCast_eq_natCast_iff, ZMod.natCast_zmod_val, ZMod.natCast_val]
exact ⟨left_inv, left_inv.rightInverse_of_card_le (by simp)⟩
{ toFun := to_fun,
invFun := inv_fun,
map_mul' := RingHom.map_mul _
map_add' := RingHom.map_add _
left_inv := inv.1
right_inv := inv.2 }
lemma subsingleton_iff {n : ℕ} : Subsingleton (ZMod n) ↔ n = 1 := by
constructor
· obtain (_ | _ | n) := n
· simpa [ZMod] using not_subsingleton _
· simp [ZMod]
· simpa [ZMod] using not_subsingleton _
· rintro rfl
infer_instance
lemma nontrivial_iff {n : ℕ} : Nontrivial (ZMod n) ↔ n ≠ 1 := by
rw [← not_subsingleton_iff_nontrivial, subsingleton_iff]
-- todo: this can be made a `Unique` instance.
instance subsingleton_units : Subsingleton (ZMod 2)ˣ :=
⟨by decide⟩
@[simp]
theorem add_self_eq_zero_iff_eq_zero {n : ℕ} (hn : Odd n) {a : ZMod n} :
a + a = 0 ↔ a = 0 := by
rw [Nat.odd_iff, ← Nat.two_dvd_ne_zero, ← Nat.prime_two.coprime_iff_not_dvd] at hn
rw [← mul_two, ← @Nat.cast_two (ZMod n), ← ZMod.coe_unitOfCoprime 2 hn, Units.mul_left_eq_zero]
theorem ne_neg_self {n : ℕ} (hn : Odd n) {a : ZMod n} (ha : a ≠ 0) : a ≠ -a := by
rwa [Ne, eq_neg_iff_add_eq_zero, add_self_eq_zero_iff_eq_zero hn]
theorem neg_one_ne_one {n : ℕ} [Fact (2 < n)] : (-1 : ZMod n) ≠ 1 :=
CharP.neg_one_ne_one (ZMod n) n
@[simp]
theorem neg_eq_self_mod_two (a : ZMod 2) : -a = a := by
fin_cases a <;> apply Fin.ext <;> simp; rfl
@[simp]
theorem intCast_abs_mod_two (a : ℤ) : (↑|a| : ZMod 2) = a := by
cases le_total a 0 <;> simp [abs_of_nonneg, abs_of_nonpos, *]
theorem natAbs_mod_two (a : ℤ) : (a.natAbs : ZMod 2) = a := by
simp
theorem val_ne_zero {n : ℕ} (a : ZMod n) : a.val ≠ 0 ↔ a ≠ 0 :=
(val_eq_zero a).not
@[simp]
theorem val_pos {n : ℕ} {a : ZMod n} : 0 < a.val ↔ a ≠ 0 := by
simp [pos_iff_ne_zero]
theorem val_eq_one : ∀ {n : ℕ} (_ : 1 < n) (a : ZMod n), a.val = 1 ↔ a = 1
| 0, hn, _
| 1, hn, _ => by simp at hn
| n + 2, _, _ => by simp only [val, ZMod, Fin.ext_iff, Fin.val_one]
theorem neg_eq_self_iff {n : ℕ} (a : ZMod n) : -a = a ↔ a = 0 ∨ 2 * a.val = n := by
rw [neg_eq_iff_add_eq_zero, ← two_mul]
cases n
· rw [@mul_eq_zero ℤ, @mul_eq_zero ℕ, val_eq_zero]
exact
⟨fun h => h.elim (by simp) Or.inl, fun h =>
Or.inr (h.elim id fun h => h.elim (by simp) id)⟩
conv_lhs =>
rw [← a.natCast_zmod_val, ← Nat.cast_two, ← Nat.cast_mul, natCast_eq_zero_iff]
constructor
· rintro ⟨m, he⟩
rcases m with - | m
· rw [mul_zero, mul_eq_zero] at he
rcases he with (⟨⟨⟩⟩ | he)
exact Or.inl (a.val_eq_zero.1 he)
cases m
· right
rwa [show 0 + 1 = 1 from rfl, mul_one] at he
refine (a.val_lt.not_ge <| Nat.le_of_mul_le_mul_left ?_ zero_lt_two).elim
rw [he, mul_comm]
apply Nat.mul_le_mul_left
simp
· rintro (rfl | h)
· rw [val_zero, mul_zero]
apply dvd_zero
· rw [h]
theorem val_cast_of_lt {n : ℕ} {a : ℕ} (h : a < n) : (a : ZMod n).val = a := by
rw [val_natCast, Nat.mod_eq_of_lt h]
theorem val_cast_zmod_lt {m : ℕ} [NeZero m] (n : ℕ) [NeZero n] (a : ZMod m) :
(a.cast : ZMod n).val < m := by
rcases m with (⟨⟩|⟨m⟩); · cases NeZero.ne 0 rfl
by_cases! h : m < n
· rcases n with (⟨⟩|⟨n⟩); · simp at h
rw [← natCast_val, val_cast_of_lt]
· apply a.val_lt
apply lt_of_le_of_lt (Nat.le_of_lt_succ (ZMod.val_lt a)) h
· apply lt_of_lt_of_le (ZMod.val_lt _) (le_trans h (Nat.le_succ m))
theorem neg_val' {n : ℕ} [NeZero n] (a : ZMod n) : (-a).val = (n - a.val) % n :=
calc
(-a).val = val (-a) % n := by rw [Nat.mod_eq_of_lt (-a).val_lt]
_ = (n - val a) % n :=
Nat.ModEq.add_right_cancel' (val a)
(by
rw [Nat.ModEq, ← val_add, neg_add_cancel, tsub_add_cancel_of_le a.val_le, Nat.mod_self,
val_zero])
theorem neg_val {n : ℕ} [NeZero n] (a : ZMod n) : (-a).val = if a = 0 then 0 else n - a.val := by
rw [neg_val']
by_cases h : a = 0; · rw [if_pos h, h, val_zero, tsub_zero, Nat.mod_self]
rw [if_neg h]
apply Nat.mod_eq_of_lt
apply Nat.sub_lt (NeZero.pos n)
contrapose! h
rwa [Nat.le_zero, val_eq_zero] at h
theorem val_neg_of_ne_zero {n : ℕ} [nz : NeZero n] (a : ZMod n) [na : NeZero a] :
(- a).val = n - a.val := by simp_all [neg_val a, na.out]
theorem val_sub {n : ℕ} [NeZero n] {a b : ZMod n} (h : b.val ≤ a.val) :
(a - b).val = a.val - b.val := by
by_cases hb : b = 0
· cases hb; simp
· have : NeZero b := ⟨hb⟩
rw [sub_eq_add_neg, val_add, val_neg_of_ne_zero, ← Nat.add_sub_assoc (le_of_lt (val_lt _)),
add_comm, Nat.add_sub_assoc h, Nat.add_mod_left]
apply Nat.mod_eq_of_lt (tsub_lt_of_lt (val_lt _))
theorem val_cast_eq_val_of_lt {m n : ℕ} [nzm : NeZero m] {a : ZMod m}
(h : a.val < n) : (a.cast : ZMod n).val = a.val := by
have nzn : NeZero n := by constructor; rintro rfl; simp at h
cases m with
| zero => cases nzm; simp_all
| succ m =>
cases n with
| zero => cases nzn; simp_all
| succ n => exact Fin.val_cast_of_lt h
theorem cast_cast_zmod_of_le {m n : ℕ} [hm : NeZero m] (h : m ≤ n) (a : ZMod m) :
(cast (cast a : ZMod n) : ZMod m) = a := by
have : NeZero n := ⟨((Nat.zero_lt_of_ne_zero hm.out).trans_le h).ne'⟩
rw [cast_eq_val, val_cast_eq_val_of_lt (a.val_lt.trans_le h), natCast_zmod_val]
theorem val_pow {m n : ℕ} {a : ZMod n} [ilt : Fact (1 < n)] (h : a.val ^ m < n) :
(a ^ m).val = a.val ^ m := by
induction m with
| zero => simp [ZMod.val_one]
| succ m ih =>
have : a.val ^ m < n := by
obtain rfl | ha := eq_or_ne a 0
· by_cases hm : m = 0
· cases hm; simp [ilt.out]
· simp only [val_zero, ne_eq, hm, not_false_eq_true, zero_pow, Nat.zero_lt_of_lt h]
· exact lt_of_le_of_lt
(Nat.pow_le_pow_right (by rwa [gt_iff_lt, ZMod.val_pos]) (Nat.le_succ m)) h
rw [pow_succ, ZMod.val_mul, ih this, ← pow_succ, Nat.mod_eq_of_lt h]
theorem val_pow_le {m n : ℕ} [Fact (1 < n)] {a : ZMod n} : (a ^ m).val ≤ a.val ^ m := by
induction m with
| zero => simp [ZMod.val_one]
| succ m ih =>
rw [pow_succ, pow_succ]
apply le_trans (ZMod.val_mul_le _ _)
apply Nat.mul_le_mul_right _ ih
theorem natAbs_min_of_le_div_two (n : ℕ) (x y : ℤ) (he : (x : ZMod n) = y) (hl : x.natAbs ≤ n / 2) :
x.natAbs ≤ y.natAbs := by
rw [intCast_eq_intCast_iff_dvd_sub] at he
obtain ⟨m, he⟩ := he
rw [sub_eq_iff_eq_add] at he
subst he
obtain rfl | hm := eq_or_ne m 0
· rw [mul_zero, zero_add]
apply hl.trans
rw [← add_le_add_iff_right x.natAbs]
refine le_trans (le_trans ((add_le_add_iff_left _).2 hl) ?_) (Int.natAbs_sub_le _ _)
rw [add_sub_cancel_right, Int.natAbs_mul, Int.natAbs_natCast]
refine le_trans ?_ (Nat.le_mul_of_pos_right _ <| Int.natAbs_pos.2 hm)
rw [← mul_two]; apply Nat.div_mul_le_self
end ZMod
theorem RingHom.ext_zmod {n : ℕ} {R : Type*} [NonAssocSemiring R] (f g : ZMod n →+* R) : f = g := by
ext a
obtain ⟨k, rfl⟩ := ZMod.intCast_surjective a
let φ : ℤ →+* R := f.comp (Int.castRingHom (ZMod n))
let ψ : ℤ →+* R := g.comp (Int.castRingHom (ZMod n))
change φ k = ψ k
rw [φ.ext_int ψ]
namespace ZMod
variable {n : ℕ} {R : Type*}
instance subsingleton_ringHom [Semiring R] : Subsingleton (ZMod n →+* R) :=
⟨RingHom.ext_zmod⟩
instance subsingleton_ringEquiv [Semiring R] : Subsingleton (ZMod n ≃+* R) :=
⟨fun f g => by
rw [RingEquiv.coe_ringHom_inj_iff]
apply RingHom.ext_zmod _ _⟩
@[simp]
theorem ringHom_map_cast [NonAssocRing R] (f : R →+* ZMod n) (k : ZMod n) : f (cast k) = k := by
cases n
· dsimp [ZMod, ZMod.cast] at f k ⊢; simp
· dsimp [ZMod.cast]
rw [map_natCast, natCast_zmod_val]
/-- Any ring homomorphism into `ZMod n` has a right inverse. -/
theorem ringHom_rightInverse [NonAssocRing R] (f : R →+* ZMod n) :
Function.RightInverse (cast : ZMod n → R) f :=
ringHom_map_cast f
/-- Any ring homomorphism into `ZMod n` is surjective. -/
theorem ringHom_surjective [NonAssocRing R] (f : R →+* ZMod n) : Function.Surjective f :=
(ringHom_rightInverse f).surjective
@[simp]
lemma castHom_self : ZMod.castHom dvd_rfl (ZMod n) = RingHom.id (ZMod n) :=
Subsingleton.elim _ _
@[simp]
lemma castHom_comp {m d : ℕ} (hm : n ∣ m) (hd : m ∣ d) :
(castHom hm (ZMod n)).comp (castHom hd (ZMod m)) = castHom (dvd_trans hm hd) (ZMod n) :=
RingHom.ext_zmod _ _
section lift
variable (n) {A : Type*} [AddGroup A]
/-- The map from `ZMod n` induced by `f : ℤ →+ A` that maps `n` to `0`. -/
def lift : { f : ℤ →+ A // f n = 0 } ≃ (ZMod n →+ A) :=
(Equiv.subtypeEquivRight <| by
intro f
rw [ker_intCastAddHom]
constructor
· rintro hf _ ⟨x, rfl⟩
simp only [f.map_zsmul, zsmul_zero, f.mem_ker, hf]
· intro h
exact h (AddSubgroup.mem_zmultiples _)).trans <|
(Int.castAddHom (ZMod n)).liftOfRightInverse cast intCast_zmod_cast
variable (f : { f : ℤ →+ A // f n = 0 })
@[simp]
theorem lift_coe (x : ℤ) : lift n f (x : ZMod n) = f.val x :=
AddMonoidHom.liftOfRightInverse_comp_apply _ _ (fun _ => intCast_zmod_cast _) _ _
theorem lift_castAddHom (x : ℤ) : lift n f (Int.castAddHom (ZMod n) x) = f.1 x :=
AddMonoidHom.liftOfRightInverse_comp_apply _ _ (fun _ => intCast_zmod_cast _) _ _
@[simp]
theorem lift_comp_coe : ZMod.lift n f ∘ ((↑) : ℤ → _) = f :=
funext <| lift_coe _ _
@[simp]
theorem lift_comp_castAddHom : (ZMod.lift n f).comp (Int.castAddHom (ZMod n)) = f :=
AddMonoidHom.ext <| lift_castAddHom _ _
lemma lift_injective {f : {f : ℤ →+ A // f n = 0}} :
Injective (lift n f) ↔ ∀ m, f.1 m = 0 → (m : ZMod n) = 0 := by
simp only [← AddMonoidHom.ker_eq_bot_iff, eq_bot_iff, SetLike.le_def,
ZMod.intCast_surjective.forall, ZMod.lift_coe, AddMonoidHom.mem_ker, AddSubgroup.mem_bot]
end lift
end ZMod
/-!
### Groups of bounded torsion
For `G` a group and `n` a natural number, `G` having torsion dividing `n`
(`∀ x : G, n • x = 0`) can be derived from `Module R G` where `R` has characteristic dividing `n`.
It is however painful to have the API for such groups `G` stated in this generality, as `R` does not
appear anywhere in the lemmas' return type. Instead of writing the API in terms of a general `R`, we
therefore specialise to the canonical ring of order `n`, namely `ZMod n`.
This spelling `Module (ZMod n) G` has the extra advantage of providing the canonical action by
`ZMod n`. It is however Type-valued, so we might want to acquire a Prop-valued version in the
future.
-/
section Module
variable {n : ℕ} {S G : Type*} [AddCommGroup G] [SetLike S G] [AddSubgroupClass S G] {K : S} {x : G}
section general
variable [Module (ZMod n) G] {x : G}
lemma zmod_smul_mem (hx : x ∈ K) : ∀ a : ZMod n, a • x ∈ K := by
simpa [ZMod.forall, Int.cast_smul_eq_zsmul] using zsmul_mem hx
/-- This cannot be made an instance because of the `[Module (ZMod n) G]` argument and the fact that
`n` only appears in the second argument of `SMulMemClass`, which is an `OutParam`. -/
lemma smulMemClass : SMulMemClass S (ZMod n) G where smul_mem _ _ {_x} hx := zmod_smul_mem hx _
namespace AddSubgroupClass
instance instZModSMul : SMul (ZMod n) K where smul a x := ⟨a • x, zmod_smul_mem x.2 _⟩
@[simp, norm_cast] lemma coe_zmod_smul (a : ZMod n) (x : K) : ↑(a • x) = (a • x : G) := rfl
instance instZModModule : Module (ZMod n) K := fast_instance%
Subtype.coe_injective.module _ (AddSubmonoidClass.subtype K) coe_zmod_smul
end AddSubgroupClass
variable (n)
lemma ZModModule.char_nsmul_eq_zero (x : G) : n • x = 0 := by
simp [← Nat.cast_smul_eq_nsmul (ZMod n)]
variable (G) in
lemma ZModModule.char_ne_one [Nontrivial G] : n ≠ 1 := by
rintro rfl
obtain ⟨x, hx⟩ := exists_ne (0 : G)
exact hx <| by simpa using char_nsmul_eq_zero 1 x
variable (G) in
lemma ZModModule.two_le_char [NeZero n] [Nontrivial G] : 2 ≤ n := by
have := NeZero.ne n
have := char_ne_one n G
cutsat
lemma ZModModule.periodicPts_add_left [NeZero n] (x : G) : periodicPts (x + ·) = .univ :=
Set.eq_univ_of_forall fun y ↦ ⟨n, NeZero.pos n, by
simpa [char_nsmul_eq_zero, IsPeriodicPt] using isFixedPt_id _⟩
end general
section two
variable [Module (ZMod 2) G]
lemma ZModModule.add_self (x : G) : x + x = 0 := by
simpa [two_nsmul] using char_nsmul_eq_zero 2 x
lemma ZModModule.neg_eq_self (x : G) : -x = x := by simp [add_self, eq_comm, ← sub_eq_zero]
lemma ZModModule.sub_eq_add (x y : G) : x - y = x + y := by simp [neg_eq_self, sub_eq_add_neg]
lemma ZModModule.add_add_add_cancel (x y z : G) : (x + y) + (y + z) = x + z := by
simpa [sub_eq_add] using sub_add_sub_cancel x y z
end two
end Module
section Group
variable {α : Type*} [Group α] {n : ℕ}
@[to_additive (attr := simp) nsmul_zmod_val_inv_nsmul]
lemma pow_zmod_val_inv_pow (hn : (Nat.card α).gcd n = 1) (a : α) :
(a ^ (n⁻¹ : ZMod (Nat.card α)).val) ^ n = a := by
replace hn : (Nat.card α).Coprime n := hn
rw [← pow_mul', ← pow_mod_natCard, ← ZMod.val_natCast, Nat.cast_mul, ZMod.mul_val_inv hn.symm,
ZMod.val_one_eq_one_mod, pow_mod_natCard, pow_one]
@[to_additive (attr := simp) zmod_val_inv_nsmul_nsmul]
lemma pow_pow_zmod_val_inv (hn : (Nat.card α).gcd n = 1) (a : α) :
(a ^ n) ^ (n⁻¹ : ZMod (Nat.card α)).val = a := by rw [pow_right_comm, pow_zmod_val_inv_pow hn]
end Group
open ZMod
/-- The range of `(m * · + k)` on natural numbers is the set of elements `≥ k` in the
residue class of `k` mod `m`. -/
lemma Nat.range_mul_add (m k : ℕ) :
Set.range (fun n : ℕ ↦ m * n + k) = {n : ℕ | (n : ZMod m) = k ∧ k ≤ n} := by
ext n
simp only [Set.mem_range, Set.mem_setOf_eq]
conv => enter [1, 1, y]; rw [add_comm, eq_comm]
refine ⟨fun ⟨a, ha⟩ ↦ ⟨?_, le_iff_exists_add.mpr ⟨_, ha⟩⟩, fun ⟨H₁, H₂⟩ ↦ ?_⟩
· simpa using congr_arg ((↑) : ℕ → ZMod m) ha
· obtain ⟨a, ha⟩ := le_iff_exists_add.mp H₂
simp only [ha, Nat.cast_add, add_eq_left, ZMod.natCast_eq_zero_iff] at H₁
obtain ⟨b, rfl⟩ := H₁
exact ⟨b, ha⟩
/-- Equivalence between `ℕ` and `ZMod N × ℕ`, sending `n` to `(n mod N, n / N)`. -/
def Nat.residueClassesEquiv (N : ℕ) [NeZero N] : ℕ ≃ ZMod N × ℕ where
toFun n := (↑n, n / N)
invFun p := p.1.val + N * p.2
left_inv n := by simpa only [val_natCast] using mod_add_div n N
right_inv p := by
ext1
· simp only [add_comm p.1.val, cast_add, cast_mul, natCast_self, zero_mul, natCast_val,
cast_id', id_eq, zero_add]
· simp only [add_comm p.1.val, mul_add_div (NeZero.pos _),
(Nat.div_eq_zero_iff).2 <| .inr p.1.val_lt, add_zero] |
.lake/packages/mathlib/Mathlib/Data/ZMod/Defs.lean | import Mathlib.Algebra.Group.Fin.Basic
import Mathlib.Algebra.NeZero
import Mathlib.Algebra.Ring.Int.Defs
import Mathlib.Algebra.Ring.GrindInstances
import Mathlib.Data.Nat.ModEq
import Mathlib.Data.Fintype.EquivFin
/-!
# Definition of `ZMod n` + basic results.
This file provides the basic details of `ZMod n`, including its commutative ring structure.
## Implementation details
This used to be inlined into `Data.ZMod.Basic`. This file imports `CharP.Lemmas`, which is an
issue; all `CharP` instances create an `Algebra (ZMod p) R` instance; however, this instance may
not be definitionally equal to other `Algebra` instances (for example, `GaloisField` also has an
`Algebra` instance as it is defined as a `SplittingField`). The way to fix this is to use the
forgetful inheritance pattern, and make `CharP` carry the data of what the `smul` should be (so
for example, the `smul` on the `GaloisField` `CharP` instance should be equal to the `smul` from
its `SplittingField` structure); there is only one possible `ZMod p` algebra for any `p`, so this
is not an issue mathematically. For this to be possible, however, we need `CharP.Lemmas` to be
able to import some part of `ZMod`.
-/
namespace Fin
/-!
## Ring structure on `Fin n`
We define a commutative ring structure on `Fin n`.
Afterwards, when we define `ZMod n` in terms of `Fin n`, we use these definitions
to register the ring structure on `ZMod n` as type class instance.
-/
open Nat.ModEq Int
open scoped Fin.IntCast Fin.NatCast
@[simp] theorem val_intCast {n : Nat} [NeZero n] (x : Int) :
(x : Fin n).val = (x % n).toNat := by
rw [Fin.intCast_def']
split <;> rename_i h
· simp [Int.emod_natAbs_of_nonneg h]
· simp only [Fin.val_neg, Fin.natCast_eq_zero, Fin.val_natCast]
split <;> rename_i h
· rw [← Int.natCast_dvd] at h
rw [Int.emod_eq_zero_of_dvd h, Int.toNat_zero]
· rw [Int.emod_natAbs_of_neg (by cutsat) (NeZero.ne n),
if_neg (by rwa [← Int.natCast_dvd] at h)]
have : x % n < n := Int.emod_lt_of_pos x (by have := NeZero.ne n; cutsat)
cutsat
/-- Multiplicative commutative semigroup structure on `Fin n`. -/
instance instCommSemigroup (n : ℕ) : CommSemigroup (Fin n) :=
{ inferInstanceAs (Mul (Fin n)) with
mul_assoc := fun ⟨a, _⟩ ⟨b, _⟩ ⟨c, _⟩ =>
Fin.eq_of_val_eq <|
calc
a * b % n * c ≡ a * b * c [MOD n] := (Nat.mod_modEq _ _).mul_right _
_ ≡ a * (b * c) [MOD n] := by rw [mul_assoc]
_ ≡ a * (b * c % n) [MOD n] := (Nat.mod_modEq _ _).symm.mul_left _
mul_comm := Fin.mul_comm }
private theorem left_distrib_aux (n : ℕ) : ∀ a b c : Fin n, a * (b + c) = a * b + a * c :=
fun ⟨a, _⟩ ⟨b, _⟩ ⟨c, _⟩ =>
Fin.eq_of_val_eq <|
calc
a * ((b + c) % n) ≡ a * (b + c) [MOD n] := (Nat.mod_modEq _ _).mul_left _
_ ≡ a * b + a * c [MOD n] := by rw [mul_add]
_ ≡ a * b % n + a * c % n [MOD n] := (Nat.mod_modEq _ _).symm.add (Nat.mod_modEq _ _).symm
/-- Distributive structure on `Fin n`. -/
instance instDistrib (n : ℕ) : Distrib (Fin n) :=
{ Fin.addCommSemigroup n, Fin.instCommSemigroup n with
left_distrib := left_distrib_aux n
right_distrib := fun a b c => by
rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm] }
instance instNonUnitalCommRing (n : ℕ) [NeZero n] : NonUnitalCommRing (Fin n) where
__ := Fin.addCommGroup n
__ := Fin.instCommSemigroup n
__ := Fin.instDistrib n
zero_mul := Fin.zero_mul
mul_zero := Fin.mul_zero
instance instCommMonoid (n : ℕ) [NeZero n] : CommMonoid (Fin n) where
one_mul := Fin.one_mul
mul_one := Fin.mul_one
/-- Note this is more general than `Fin.instCommRing` as it applies (vacuously) to `Fin 0` too. -/
instance instHasDistribNeg (n : ℕ) : HasDistribNeg (Fin n) where
toInvolutiveNeg := Fin.instInvolutiveNeg n
mul_neg := Nat.casesOn n finZeroElim fun _i => mul_neg
neg_mul := Nat.casesOn n finZeroElim fun _i => neg_mul
/--
Commutative ring structure on `Fin n`.
This is not a global instance, but can introduced locally using `open Fin.CommRing in ...`.
This is not an instance because the `binop%` elaborator assumes that
there are no non-trivial coercion loops,
but this instance would introduce a coercion from `Nat` to `Fin n` and back.
Non-trivial loops lead to undesirable and counterintuitive elaboration behavior.
For example, for `x : Fin k` and `n : Nat`,
it causes `x < n` to be elaborated as `x < ↑n` rather than `↑x < n`,
silently introducing wraparound arithmetic.
-/
def instCommRing (n : ℕ) [NeZero n] : CommRing (Fin n) where
__ := Fin.instAddMonoidWithOne n
__ := Fin.addCommGroup n
__ := Fin.instCommSemigroup n
__ := Fin.instNonUnitalCommRing n
__ := Fin.instCommMonoid n
intCast n := Fin.intCast n
namespace CommRing
attribute [scoped instance] Fin.instCommRing
end CommRing
instance (n : ℕ) [NeZero n] : NeZero (1 : Fin (n + 1)) :=
open Fin.CommRing in inferInstance
end Fin
/-- The integers modulo `n : ℕ`. -/
@[to_additive_dont_translate]
def ZMod : ℕ → Type
| 0 => ℤ
| n + 1 => Fin (n + 1)
instance ZMod.decidableEq : ∀ n : ℕ, DecidableEq (ZMod n)
| 0 => inferInstanceAs (DecidableEq ℤ)
| n + 1 => inferInstanceAs (DecidableEq (Fin (n + 1)))
instance ZMod.repr : ∀ n : ℕ, Repr (ZMod n)
| 0 => by dsimp [ZMod]; infer_instance
| n + 1 => by dsimp [ZMod]; infer_instance
namespace ZMod
instance instUnique : Unique (ZMod 1) := Fin.instUnique
instance fintype : ∀ (n : ℕ) [NeZero n], Fintype (ZMod n)
| 0, h => (h.ne _ rfl).elim
| n + 1, _ => Fin.fintype (n + 1)
instance infinite : Infinite (ZMod 0) :=
Int.infinite
@[simp]
theorem card (n : ℕ) [Fintype (ZMod n)] : Fintype.card (ZMod n) = n := by
cases n with
| zero => exact (not_finite (ZMod 0)).elim
| succ n => convert Fintype.card_fin (n + 1) using 2
open Fin.CommRing in
/- We define each field by cases, to ensure that the eta-expanded `ZMod.commRing` is defeq to the
original, this helps avoid diamonds with instances coming from classes extending `CommRing` such as
field. -/
instance commRing (n : ℕ) : CommRing (ZMod n) where
add := Nat.casesOn n (@Add.add Int _) fun n => @Add.add (Fin n.succ) _
add_assoc := Nat.casesOn n (@add_assoc Int _) fun n => @add_assoc (Fin n.succ) _
zero := Nat.casesOn n (0 : Int) fun n => (0 : Fin n.succ)
zero_add := Nat.casesOn n (@zero_add Int _) fun n => @zero_add (Fin n.succ) _
add_zero := Nat.casesOn n (@add_zero Int _) fun n => @add_zero (Fin n.succ) _
neg := Nat.casesOn n (@Neg.neg Int _) fun n => @Neg.neg (Fin n.succ) _
sub := Nat.casesOn n (@Sub.sub Int _) fun n => @Sub.sub (Fin n.succ) _
sub_eq_add_neg := Nat.casesOn n (@sub_eq_add_neg Int _) fun n => @sub_eq_add_neg (Fin n.succ) _
zsmul := Nat.casesOn n
(inferInstanceAs (CommRing ℤ)).zsmul fun n => (inferInstanceAs (CommRing (Fin n.succ))).zsmul
zsmul_zero' := Nat.casesOn n
(inferInstanceAs (CommRing ℤ)).zsmul_zero'
fun n => (inferInstanceAs (CommRing (Fin n.succ))).zsmul_zero'
zsmul_succ' := Nat.casesOn n
(inferInstanceAs (CommRing ℤ)).zsmul_succ'
fun n => (inferInstanceAs (CommRing (Fin n.succ))).zsmul_succ'
zsmul_neg' := Nat.casesOn n
(inferInstanceAs (CommRing ℤ)).zsmul_neg'
fun n => (inferInstanceAs (CommRing (Fin n.succ))).zsmul_neg'
nsmul := Nat.casesOn n
(inferInstanceAs (CommRing ℤ)).nsmul fun n => (inferInstanceAs (CommRing (Fin n.succ))).nsmul
nsmul_zero := Nat.casesOn n
(inferInstanceAs (CommRing ℤ)).nsmul_zero
fun n => (inferInstanceAs (CommRing (Fin n.succ))).nsmul_zero
nsmul_succ := Nat.casesOn n
(inferInstanceAs (CommRing ℤ)).nsmul_succ
fun n => (inferInstanceAs (CommRing (Fin n.succ))).nsmul_succ
neg_add_cancel := Nat.casesOn n (@neg_add_cancel Int _) fun n => @neg_add_cancel (Fin n.succ) _
add_comm := Nat.casesOn n (@add_comm Int _) fun n => @add_comm (Fin n.succ) _
mul := Nat.casesOn n (@Mul.mul Int _) fun n => @Mul.mul (Fin n.succ) _
mul_assoc := Nat.casesOn n (@mul_assoc Int _) fun n => @mul_assoc (Fin n.succ) _
one := Nat.casesOn n (1 : Int) fun n => (1 : Fin n.succ)
one_mul := Nat.casesOn n (@one_mul Int _) fun n => @one_mul (Fin n.succ) _
mul_one := Nat.casesOn n (@mul_one Int _) fun n => @mul_one (Fin n.succ) _
natCast := Nat.casesOn n ((↑) : ℕ → ℤ) fun n => ((↑) : ℕ → Fin n.succ)
natCast_zero := Nat.casesOn n (@Nat.cast_zero Int _) fun n => @Nat.cast_zero (Fin n.succ) _
natCast_succ := Nat.casesOn n (@Nat.cast_succ Int _) fun n => @Nat.cast_succ (Fin n.succ) _
intCast := Nat.casesOn n ((↑) : ℤ → ℤ) fun n => ((↑) : ℤ → Fin n.succ)
intCast_ofNat := Nat.casesOn n (@Int.cast_natCast Int _) fun n => @Int.cast_natCast (Fin n.succ) _
intCast_negSucc :=
Nat.casesOn n (@Int.cast_negSucc Int _) fun n => @Int.cast_negSucc (Fin n.succ) _
left_distrib := Nat.casesOn n (@left_distrib Int _ _ _) fun n => @left_distrib (Fin n.succ) _ _ _
right_distrib :=
Nat.casesOn n (@right_distrib Int _ _ _) fun n => @right_distrib (Fin n.succ) _ _ _
mul_comm := Nat.casesOn n (@mul_comm Int _) fun n => @mul_comm (Fin n.succ) _
zero_mul := Nat.casesOn n (@zero_mul Int _) fun n => @zero_mul (Fin n.succ) _
mul_zero := Nat.casesOn n (@mul_zero Int _) fun n => @mul_zero (Fin n.succ) _
npow := Nat.casesOn n
(inferInstanceAs (CommRing ℤ)).npow fun n => (inferInstanceAs (CommRing (Fin n.succ))).npow
npow_zero := Nat.casesOn n
(inferInstanceAs (CommRing ℤ)).npow_zero
fun n => (inferInstanceAs (CommRing (Fin n.succ))).npow_zero
npow_succ := Nat.casesOn n
(inferInstanceAs (CommRing ℤ)).npow_succ
fun n => (inferInstanceAs (CommRing (Fin n.succ))).npow_succ
instance inhabited (n : ℕ) : Inhabited (ZMod n) :=
⟨0⟩
-- Verify that we can use `ZMod n` in `grind`.
example (n : ℕ) : Lean.Grind.CommRing (ZMod n) := inferInstance
end ZMod |
.lake/packages/mathlib/Mathlib/Data/ZMod/Coprime.lean | import Mathlib.Algebra.EuclideanDomain.Int
import Mathlib.Data.Nat.Prime.Int
import Mathlib.Data.ZMod.Basic
import Mathlib.RingTheory.Int.Basic
import Mathlib.RingTheory.PrincipalIdealDomain
/-!
# Coprimality and vanishing
We show that for prime `p`, the image of an integer `a` in `ZMod p` vanishes if and only if
`a` and `p` are not coprime.
-/
assert_not_exists TwoSidedIdeal
namespace ZMod
theorem coe_int_isUnit_iff_isCoprime (n : ℤ) (m : ℕ) :
IsUnit (n : ZMod m) ↔ IsCoprime (m : ℤ) n := by
rw [Int.isCoprime_iff_nat_coprime, Nat.coprime_comm, ← isUnit_iff_coprime, Associated.isUnit_iff]
simpa only [eq_intCast, Int.cast_natCast] using (Int.associated_natAbs _).map (Int.castRingHom _)
/-- If `p` is a prime and `a` is an integer, then `a : ZMod p` is zero if and only if
`gcd a p ≠ 1`. -/
theorem eq_zero_iff_gcd_ne_one {a : ℤ} {p : ℕ} [pp : Fact p.Prime] :
(a : ZMod p) = 0 ↔ a.gcd p ≠ 1 := by
rw [Ne, Int.gcd_comm, ← Int.isCoprime_iff_gcd_eq_one,
(Nat.prime_iff_prime_int.1 pp.1).coprime_iff_not_dvd, Classical.not_not,
intCast_zmod_eq_zero_iff_dvd]
/-- If an integer `a` and a prime `p` satisfy `gcd a p = 1`, then `a : ZMod p` is nonzero. -/
theorem ne_zero_of_gcd_eq_one {a : ℤ} {p : ℕ} (pp : p.Prime) (h : a.gcd p = 1) : (a : ZMod p) ≠ 0 :=
mt (@eq_zero_iff_gcd_ne_one a p ⟨pp⟩).mp (Classical.not_not.mpr h)
/-- If an integer `a` and a prime `p` satisfy `gcd a p ≠ 1`, then `a : ZMod p` is zero. -/
theorem eq_zero_of_gcd_ne_one {a : ℤ} {p : ℕ} (pp : p.Prime) (h : a.gcd p ≠ 1) : (a : ZMod p) = 0 :=
(@eq_zero_iff_gcd_ne_one a p ⟨pp⟩).mpr h
end ZMod |
.lake/packages/mathlib/Mathlib/Data/ZMod/Factorial.lean | import Mathlib.Data.Nat.Factorial.BigOperators
import Mathlib.Data.ZMod.Basic
/-!
# Facts about factorials in ZMod
We collect facts about factorials in context of modular arithmetic.
## Main statements
* `ZMod.cast_descFactorial`: For natural numbers `n` and `p`, where `n` is less than or equal to `p`
the descending factorial of `(p - 1)` taken `n` times modulo `p` equals `(-1) ^ n * n!`.
## See also
For the prime case and involving `factorial` rather than `descFactorial`, see Wilson's theorem:
* Nat.prime_iff_fac_equiv_neg_one
-/
assert_not_exists TwoSidedIdeal
open Finset Nat
namespace ZMod
theorem cast_descFactorial {n p : ℕ} (h : n ≤ p) :
(descFactorial (p - 1) n : ZMod p) = (-1) ^ n * n ! := by
rw [descFactorial_eq_prod_range, factorial_eq_prod_range_add_one]
simp only [cast_prod]
nth_rw 2 [← card_range n]
rw [pow_card_mul_prod]
refine prod_congr rfl ?_
intro x hx
rw [← tsub_add_eq_tsub_tsub_swap,
Nat.cast_sub <| Nat.le_trans (Nat.add_one_le_iff.mpr (List.mem_range.mp hx)) h,
CharP.cast_eq_zero, zero_sub, cast_succ, neg_add_rev, mul_add, neg_mul, one_mul,
mul_one, add_comm]
end ZMod |
.lake/packages/mathlib/Mathlib/Data/ZMod/Units.lean | import Mathlib.Algebra.BigOperators.Associated
import Mathlib.Data.ZMod.Basic
import Mathlib.RingTheory.Coprime.Lemmas
/-!
# Lemmas about units in `ZMod`.
-/
assert_not_exists TwoSidedIdeal
namespace ZMod
variable {n m : ℕ}
/-- `unitsMap` is a group homomorphism that maps units of `ZMod m` to units of `ZMod n` when `n`
divides `m`. -/
def unitsMap (hm : n ∣ m) : (ZMod m)ˣ →* (ZMod n)ˣ := Units.map (castHom hm (ZMod n))
lemma unitsMap_def (hm : n ∣ m) : unitsMap hm = Units.map (castHom hm (ZMod n)) := rfl
lemma unitsMap_comp {d : ℕ} (hm : n ∣ m) (hd : m ∣ d) :
(unitsMap hm).comp (unitsMap hd) = unitsMap (dvd_trans hm hd) := by
simp only [unitsMap_def]
rw [← Units.map_comp]
exact congr_arg Units.map <| congr_arg RingHom.toMonoidHom <| castHom_comp hm hd
@[simp]
lemma unitsMap_self (n : ℕ) : unitsMap (dvd_refl n) = MonoidHom.id _ := by
simp [unitsMap, castHom_self]
/-- `unitsMap_val` shows that coercing from `(ZMod m)ˣ` to `ZMod n` gives the same result
when going via `(ZMod n)ˣ` and `ZMod m`. -/
lemma unitsMap_val (h : n ∣ m) (a : (ZMod m)ˣ) :
↑(unitsMap h a) = ((a : ZMod m).cast : ZMod n) := rfl
lemma isUnit_cast_of_dvd (hm : n ∣ m) (a : Units (ZMod m)) : IsUnit (cast (a : ZMod m) : ZMod n) :=
Units.isUnit (unitsMap hm a)
theorem unitsMap_surjective [hm : NeZero m] (h : n ∣ m) :
Function.Surjective (unitsMap h) := by
suffices ∀ x : ℕ, x.Coprime n → ∃ k : ℕ, (x + k * n).Coprime m by
intro x
have ⟨k, hk⟩ := this x.val.val (val_coe_unit_coprime x)
refine ⟨unitOfCoprime _ hk, Units.ext ?_⟩
have : NeZero n := ⟨fun hn ↦ hm.out (eq_zero_of_zero_dvd (hn ▸ h))⟩
simp [unitsMap_def, - castHom_apply]
intro x hx
let ps : Finset ℕ := {p ∈ m.primeFactors | ¬p ∣ x}
use ps.prod id
apply Nat.coprime_of_dvd
intro p pp hp hpn
by_cases hpx : p ∣ x
· have h := Nat.dvd_sub hp hpx
rw [add_comm, Nat.add_sub_cancel] at h
rcases pp.dvd_mul.mp h with h | h
· have ⟨q, hq, hq'⟩ := (pp.prime.dvd_finset_prod_iff id).mp h
rw [Finset.mem_filter, Nat.mem_primeFactors,
← (Nat.prime_dvd_prime_iff_eq pp hq.1.1).mp hq'] at hq
exact hq.2 hpx
· exact Nat.Prime.not_coprime_iff_dvd.mpr ⟨p, pp, hpx, h⟩ hx
· have pps : p ∈ ps := Finset.mem_filter.mpr ⟨Nat.mem_primeFactors.mpr ⟨pp, hpn, hm.out⟩, hpx⟩
have h := Nat.dvd_sub hp ((Finset.dvd_prod_of_mem id pps).mul_right n)
rw [Nat.add_sub_cancel] at h
contradiction
-- This needs `Nat.primeFactors`, so cannot go into `Mathlib/Data/ZMod/Basic.lean`.
open Nat in
lemma not_isUnit_of_mem_primeFactors {n p : ℕ} (h : p ∈ n.primeFactors) :
¬ IsUnit (p : ZMod n) := by
rw [isUnit_iff_coprime]
exact (Prime.dvd_iff_not_coprime <| prime_of_mem_primeFactors h).mp <| dvd_of_mem_primeFactors h
/-- Any element of `ZMod N` has the form `u * d` where `u` is a unit and `d` is a divisor of `N`. -/
lemma eq_unit_mul_divisor {N : ℕ} (a : ZMod N) :
∃ d : ℕ, d ∣ N ∧ ∃ (u : ZMod N), IsUnit u ∧ a = u * d := by
rcases eq_or_ne N 0 with rfl | hN
-- Silly special case : N = 0. Of no mathematical interest, but true, so let's prove it.
· change ℤ at a
rcases eq_or_ne a 0 with rfl | ha
· refine ⟨0, dvd_zero _, 1, isUnit_one, by rw [Nat.cast_zero, mul_zero]⟩
refine ⟨a.natAbs, dvd_zero _, Int.sign a, ?_, (Int.sign_mul_natAbs a).symm⟩
rcases lt_or_gt_of_ne ha with h | h
· simp only [Int.sign_eq_neg_one_of_neg h, IsUnit.neg_iff, isUnit_one]
· simp only [Int.sign_eq_one_of_pos h, isUnit_one]
-- now the interesting case
have : NeZero N := ⟨hN⟩
-- Define `d` as the GCD of a lift of `a` and `N`.
let d := a.val.gcd N
have hd : d ≠ 0 := Nat.gcd_ne_zero_right hN
obtain ⟨a₀, (ha₀ : _ = d * _)⟩ := a.val.gcd_dvd_left N
obtain ⟨N₀, (hN₀ : _ = d * _)⟩ := a.val.gcd_dvd_right N
refine ⟨d, ⟨N₀, hN₀⟩, ?_⟩
-- Show `a` is a unit mod `N / d`.
have hu₀ : IsUnit (a₀ : ZMod N₀) := by
refine (isUnit_iff_coprime _ _).mpr (Nat.isCoprime_iff_coprime.mp ?_)
obtain ⟨p, q, hpq⟩ : ∃ (p q : ℤ), d = a.val * p + N * q := ⟨_, _, Nat.gcd_eq_gcd_ab _ _⟩
rw [ha₀, hN₀, Nat.cast_mul, Nat.cast_mul, mul_assoc, mul_assoc, ← mul_add, eq_comm,
mul_comm _ p, mul_comm _ q] at hpq
exact ⟨p, q, Int.eq_one_of_mul_eq_self_right (Nat.cast_ne_zero.mpr hd) hpq⟩
-- Lift it arbitrarily to a unit mod `N`.
obtain ⟨u, hu⟩ := (unitsMap_surjective (⟨d, mul_comm d N₀ ▸ hN₀⟩ : N₀ ∣ N)) hu₀.unit
rw [unitsMap_def, ← Units.val_inj, Units.coe_map, IsUnit.unit_spec, MonoidHom.coe_coe] at hu
refine ⟨u.val, u.isUnit, ?_⟩
rw [← natCast_zmod_val a, ← natCast_zmod_val u.1, ha₀, ← Nat.cast_mul,
natCast_eq_natCast_iff, mul_comm _ d, Nat.ModEq]
simp only [hN₀, Nat.mul_mod_mul_left, Nat.mul_right_inj hd]
rw [← Nat.ModEq, ← natCast_eq_natCast_iff, ← hu, natCast_val, castHom_apply]
theorem coe_int_mul_inv_eq_one {n : ℕ} {x : ℤ} (h : IsCoprime x n) :
(x : ZMod n) * (x : ZMod n)⁻¹ = 1 := by
by_cases hn : n = 0
· simp only [hn, Nat.cast_zero, isCoprime_zero_right] at h
rcases Int.isUnit_eq_one_or h with h | h <;> simp [h]
haveI : NeZero n := ⟨hn⟩
rw [← natCast_zmod_val x]
apply coe_mul_inv_eq_one
rwa [Int.isCoprime_iff_gcd_eq_one, ← Int.gcd_emod, ← val_intCast] at h
theorem coe_int_inv_mul_eq_one {n : ℕ} {x : ℤ} (h : IsCoprime x n) :
(x : ZMod n)⁻¹ * (x : ZMod n) = 1 := by
rw [mul_comm, coe_int_mul_inv_eq_one h]
lemma coe_int_mul_val_inv {n : ℕ} [NeZero n] {m : ℤ} (h : IsCoprime m n) :
(m * (m⁻¹ : ZMod n).val : ZMod n) = 1 := by
rw [natCast_zmod_val, coe_int_mul_inv_eq_one h]
lemma coe_int_val_inv_mul {n : ℕ} [NeZero n] {m : ℤ} (h : IsCoprime m n) :
((m⁻¹ : ZMod n).val : ZMod n) * m = 1 := by
rw [mul_comm, coe_int_mul_val_inv h]
/-- The unit of `ZMod m` associated with an integer prime to `n`. -/
def unitOfIsCoprime {m : ℕ} (n : ℤ)
(h : IsCoprime n (m : ℤ)) : (ZMod m)ˣ where
val := n
inv := n⁻¹
val_inv := coe_int_mul_inv_eq_one h
inv_val := coe_int_inv_mul_eq_one h
@[simp]
theorem coe_unitOfIsCoprime {m : ℕ} (n : ℤ) (h : IsCoprime n ↑m) :
(unitOfIsCoprime n h : ZMod m) = n := rfl
theorem isUnit_inv {m : ℕ} {n : ℤ} (h : IsUnit (n : ZMod m)) :
IsUnit (n : ZMod m)⁻¹ := by
rw [isUnit_iff_exists]
exact ⟨n, inv_mul_of_unit _ h, mul_inv_of_unit _ h⟩
end ZMod |
.lake/packages/mathlib/Mathlib/Data/ZMod/QuotientGroup.lean | import Mathlib.Data.ZMod.Basic
/-!
# `ZMod n` and quotient groups / rings
This file relates `ZMod n` to the quotient group `ℤ / AddSubgroup.zmultiples (n : ℤ)`.
## Main definitions
- `ZMod.quotientZMultiplesNatEquivZMod` and `ZMod.quotientZMultiplesEquivZMod`:
`ZMod n` is the group quotient of `ℤ` by `n ℤ := AddSubgroup.zmultiples (n)`,
(where `n : ℕ` and `n : ℤ` respectively)
- `ZMod.lift n f` is the map from `ZMod n` induced by `f : ℤ →+ A` that maps `n` to `0`.
## Tags
zmod, quotient group
-/
assert_not_exists Ideal TwoSidedIdeal
open QuotientAddGroup Set ZMod
variable (n : ℕ) {A R : Type*} [AddGroup A] [Ring R]
namespace Int
/-- `ℤ` modulo multiples of `n : ℕ` is `ZMod n`. -/
def quotientZMultiplesNatEquivZMod : ℤ ⧸ AddSubgroup.zmultiples (n : ℤ) ≃+ ZMod n :=
(quotientAddEquivOfEq (ZMod.ker_intCastAddHom _)).symm.trans <|
quotientKerEquivOfRightInverse (Int.castAddHom (ZMod n)) cast intCast_zmod_cast
/-- `ℤ` modulo multiples of `a : ℤ` is `ZMod a.natAbs`. -/
def quotientZMultiplesEquivZMod (a : ℤ) : ℤ ⧸ AddSubgroup.zmultiples a ≃+ ZMod a.natAbs :=
(quotientAddEquivOfEq (zmultiples_natAbs a)).symm.trans (quotientZMultiplesNatEquivZMod a.natAbs)
@[simp]
lemma index_zmultiples (a : ℤ) : (AddSubgroup.zmultiples a).index = a.natAbs := by
rw [AddSubgroup.index, Nat.card_congr (quotientZMultiplesEquivZMod a).toEquiv, Nat.card_zmod]
end Int
namespace AddAction
open AddSubgroup AddMonoidHom AddEquiv Function
variable {α β : Type*} [AddGroup α] (a : α) [AddAction α β] (b : β)
/-- The quotient `(ℤ ∙ a) ⧸ (stabilizer b)` is cyclic of order `minimalPeriod (a +ᵥ ·) b`. -/
noncomputable def zmultiplesQuotientStabilizerEquiv :
zmultiples a ⧸ stabilizer (zmultiples a) b ≃+ ZMod (minimalPeriod (a +ᵥ ·) b) :=
(ofBijective
(map _ (stabilizer (zmultiples a) b) (zmultiplesHom (zmultiples a) ⟨a, mem_zmultiples a⟩)
(by
rw [zmultiples_le, mem_comap, mem_stabilizer_iff, zmultiplesHom_apply, natCast_zsmul]
simp_rw [← vadd_iterate]
exact isPeriodicPt_minimalPeriod (a +ᵥ ·) b))
⟨by
rw [← ker_eq_bot_iff, eq_bot_iff]
refine fun q => induction_on q fun n hn => ?_
rw [mem_bot, eq_zero_iff, Int.mem_zmultiples_iff, ←
zsmul_vadd_eq_iff_minimalPeriod_dvd]
exact (eq_zero_iff _).mp hn, fun q =>
induction_on q fun ⟨_, n, rfl⟩ => ⟨n, rfl⟩⟩).symm.trans
(Int.quotientZMultiplesNatEquivZMod (minimalPeriod (a +ᵥ ·) b))
theorem zmultiplesQuotientStabilizerEquiv_symm_apply (n : ZMod (minimalPeriod (a +ᵥ ·) b)) :
(zmultiplesQuotientStabilizerEquiv a b).symm n =
(cast n : ℤ) • (⟨a, mem_zmultiples a⟩ : zmultiples a) :=
rfl
end AddAction
namespace MulAction
open AddAction Subgroup AddSubgroup Function
variable {α β : Type*} [Group α] (a : α) [MulAction α β] (b : β)
/-- The quotient `(a ^ ℤ) ⧸ (stabilizer b)` is cyclic of order `minimalPeriod ((•) a) b`. -/
noncomputable def zpowersQuotientStabilizerEquiv :
zpowers a ⧸ stabilizer (zpowers a) b ≃* Multiplicative (ZMod (minimalPeriod (a • ·) b)) :=
letI f := zmultiplesQuotientStabilizerEquiv (Additive.ofMul a) b
AddEquiv.toMultiplicative f
theorem zpowersQuotientStabilizerEquiv_symm_apply (n : ZMod (minimalPeriod (a • ·) b)) :
(zpowersQuotientStabilizerEquiv a b).symm n = (⟨a, mem_zpowers a⟩ : zpowers a) ^ (cast n : ℤ) :=
rfl
/-- The orbit `(a ^ ℤ) • b` is a cycle of order `minimalPeriod ((•) a) b`. -/
noncomputable def orbitZPowersEquiv : orbit (zpowers a) b ≃ ZMod (minimalPeriod (a • ·) b) :=
(orbitEquivQuotientStabilizer _ b).trans (zpowersQuotientStabilizerEquiv a b).toEquiv
/-- The orbit `(ℤ • a) +ᵥ b` is a cycle of order `minimalPeriod (a +ᵥ ·) b`. -/
noncomputable def _root_.AddAction.orbitZMultiplesEquiv {α β : Type*} [AddGroup α] (a : α)
[AddAction α β] (b : β) :
AddAction.orbit (zmultiples a) b ≃ ZMod (minimalPeriod (a +ᵥ ·) b) :=
(AddAction.orbitEquivQuotientStabilizer (zmultiples a) b).trans
(zmultiplesQuotientStabilizerEquiv a b).toEquiv
attribute [to_additive existing] orbitZPowersEquiv
@[to_additive]
theorem orbitZPowersEquiv_symm_apply (k : ZMod (minimalPeriod (a • ·) b)) :
(orbitZPowersEquiv a b).symm k =
(⟨a, mem_zpowers a⟩ : zpowers a) ^ (cast k : ℤ) • ⟨b, mem_orbit_self b⟩ :=
rfl
theorem orbitZPowersEquiv_symm_apply' (k : ℤ) :
(orbitZPowersEquiv a b).symm k =
(⟨a, mem_zpowers a⟩ : zpowers a) ^ k • ⟨b, mem_orbit_self b⟩ := by
rw [orbitZPowersEquiv_symm_apply, ZMod.coe_intCast]
exact Subtype.ext (zpow_smul_mod_minimalPeriod _ _ k)
theorem _root_.AddAction.orbitZMultiplesEquiv_symm_apply' {α β : Type*} [AddGroup α] (a : α)
[AddAction α β] (b : β) (k : ℤ) :
(AddAction.orbitZMultiplesEquiv a b).symm k =
k • (⟨a, mem_zmultiples a⟩ : zmultiples a) +ᵥ ⟨b, AddAction.mem_orbit_self b⟩ := by
rw [AddAction.orbitZMultiplesEquiv_symm_apply, ZMod.coe_intCast]
-- Making `a` explicit turns this from ~190000 heartbeats to ~700.
exact Subtype.ext (zsmul_vadd_mod_minimalPeriod a _ k)
attribute [to_additive existing]
orbitZPowersEquiv_symm_apply'
@[to_additive]
theorem minimalPeriod_eq_card [Fintype (orbit (zpowers a) b)] :
minimalPeriod (a • ·) b = Fintype.card (orbit (zpowers a) b) := by
rw [← Fintype.ofEquiv_card (orbitZPowersEquiv a b), ZMod.card]
@[to_additive]
instance minimalPeriod_pos [Finite <| orbit (zpowers a) b] :
NeZero <| minimalPeriod (a • ·) b :=
⟨by
cases nonempty_fintype (orbit (zpowers a) b)
haveI : Nonempty (orbit (zpowers a) b) := (nonempty_orbit b).to_subtype
rw [minimalPeriod_eq_card]
exact Fintype.card_ne_zero⟩
end MulAction
section Group
open Subgroup
variable {α : Type*} [Group α] (a : α)
/-- See also `Fintype.card_zpowers`. -/
@[to_additive (attr := simp) /-- See also `Fintype.card_zmultiples`. -/]
theorem Nat.card_zpowers : Nat.card (zpowers a) = orderOf a := by
have := Nat.card_congr (MulAction.orbitZPowersEquiv a (1 : α))
rwa [Nat.card_zmod, orbit_subgroup_one_eq_self] at this
variable {a}
@[to_additive (attr := simp)]
lemma finite_zpowers : (zpowers a : Set α).Finite ↔ IsOfFinOrder a := by
simp only [← orderOf_pos_iff, ← Nat.card_zpowers, Nat.card_pos_iff, ← SetLike.coe_sort_coe,
nonempty_coe_sort, Nat.card_pos_iff, Set.finite_coe_iff, Subgroup.coe_nonempty, true_and]
@[to_additive (attr := simp)]
lemma infinite_zpowers : (zpowers a : Set α).Infinite ↔ ¬IsOfFinOrder a := finite_zpowers.not
@[to_additive]
protected alias ⟨_, IsOfFinOrder.finite_zpowers⟩ := finite_zpowers
end Group
namespace Subgroup
variable {G : Type*} [Group G] (H : Subgroup G) (g : G)
open Equiv Function MulAction
/-- Partition `G ⧸ H` into orbits of the action of `g : G`. -/
noncomputable def quotientEquivSigmaZMod :
G ⧸ H ≃ Σ q : orbitRel.Quotient (zpowers g) (G ⧸ H), ZMod (minimalPeriod (g • ·) q.out) :=
(selfEquivSigmaOrbits (zpowers g) (G ⧸ H)).trans
(sigmaCongrRight fun q => orbitZPowersEquiv g q.out)
lemma quotientEquivSigmaZMod_symm_apply (q : orbitRel.Quotient (zpowers g) (G ⧸ H))
(k : ZMod (minimalPeriod (g • ·) q.out)) :
(quotientEquivSigmaZMod H g).symm ⟨q, k⟩ = g ^ (cast k : ℤ) • q.out := rfl
lemma quotientEquivSigmaZMod_apply (q : orbitRel.Quotient (zpowers g) (G ⧸ H)) (k : ℤ) :
quotientEquivSigmaZMod H g (g ^ k • q.out) = ⟨q, k⟩ := by
rw [apply_eq_iff_eq_symm_apply, quotientEquivSigmaZMod_symm_apply, ZMod.coe_intCast,
zpow_smul_mod_minimalPeriod]
end Subgroup |
.lake/packages/mathlib/Mathlib/Data/NNReal/Star.lean | import Mathlib.Data.NNReal.Defs
import Mathlib.Data.Real.Star
/-!
# The non-negative real numbers are a `*`-ring, with the trivial `*`-structure
-/
assert_not_exists Finset
open scoped NNReal
instance : StarRing ℝ≥0 := starRingOfComm
instance : TrivialStar ℝ≥0 where
star_trivial _ := rfl
instance : StarModule ℝ≥0 ℝ where
star_smul := by simp only [star_trivial, forall_const]
instance {E : Type*} [AddCommMonoid E] [Star E] [Module ℝ E] [StarModule ℝ E] :
StarModule ℝ≥0 E where
star_smul _ := star_smul (_ : ℝ) |
.lake/packages/mathlib/Mathlib/Data/NNReal/Basic.lean | import Mathlib.Algebra.BigOperators.Expect
import Mathlib.Algebra.Order.BigOperators.Ring.Finset
import Mathlib.Algebra.Order.Field.Canonical
import Mathlib.Algebra.Order.Nonneg.Floor
import Mathlib.Data.Real.Pointwise
import Mathlib.Data.NNReal.Defs
import Mathlib.Order.ConditionallyCompleteLattice.Group
/-!
# Basic results on nonnegative real numbers
This file contains all results on `NNReal` that do not directly follow from its basic structure.
As a consequence, it is a bit of a random collection of results, and is a good target for cleanup.
## Notation
This file uses `ℝ≥0` as a localized notation for `NNReal`.
-/
assert_not_exists TrivialStar
open Function
open scoped BigOperators
namespace NNReal
noncomputable instance : FloorSemiring ℝ≥0 := Nonneg.floorSemiring
@[simp, norm_cast]
theorem coe_indicator {α} (s : Set α) (f : α → ℝ≥0) (a : α) :
((s.indicator f a : ℝ≥0) : ℝ) = s.indicator (fun x => ↑(f x)) a :=
(toRealHom : ℝ≥0 →+ ℝ).map_indicator _ _ _
@[norm_cast]
theorem coe_list_sum (l : List ℝ≥0) : ((l.sum : ℝ≥0) : ℝ) = (l.map (↑)).sum :=
map_list_sum toRealHom l
@[norm_cast]
theorem coe_list_prod (l : List ℝ≥0) : ((l.prod : ℝ≥0) : ℝ) = (l.map (↑)).prod :=
map_list_prod toRealHom l
@[norm_cast]
theorem coe_multiset_sum (s : Multiset ℝ≥0) : ((s.sum : ℝ≥0) : ℝ) = (s.map (↑)).sum :=
map_multiset_sum toRealHom s
@[norm_cast]
theorem coe_multiset_prod (s : Multiset ℝ≥0) : ((s.prod : ℝ≥0) : ℝ) = (s.map (↑)).prod :=
map_multiset_prod toRealHom s
variable {ι : Type*} {s : Finset ι} {f : ι → ℝ}
@[simp, norm_cast]
theorem coe_sum (s : Finset ι) (f : ι → ℝ≥0) : ∑ i ∈ s, f i = ∑ i ∈ s, (f i : ℝ) :=
map_sum toRealHom _ _
@[simp, norm_cast]
lemma coe_expect (s : Finset ι) (f : ι → ℝ≥0) : 𝔼 i ∈ s, f i = 𝔼 i ∈ s, (f i : ℝ) :=
map_expect toRealHom ..
theorem _root_.Real.toNNReal_sum_of_nonneg (hf : ∀ i ∈ s, 0 ≤ f i) :
Real.toNNReal (∑ a ∈ s, f a) = ∑ a ∈ s, Real.toNNReal (f a) := by
rw [← coe_inj, NNReal.coe_sum, Real.coe_toNNReal _ (Finset.sum_nonneg hf)]
exact Finset.sum_congr rfl fun x hxs => by rw [Real.coe_toNNReal _ (hf x hxs)]
@[simp, norm_cast]
theorem coe_prod (s : Finset ι) (f : ι → ℝ≥0) : ↑(∏ a ∈ s, f a) = ∏ a ∈ s, (f a : ℝ) :=
map_prod toRealHom _ _
theorem _root_.Real.toNNReal_prod_of_nonneg (hf : ∀ a, a ∈ s → 0 ≤ f a) :
Real.toNNReal (∏ a ∈ s, f a) = ∏ a ∈ s, Real.toNNReal (f a) := by
rw [← coe_inj, NNReal.coe_prod, Real.coe_toNNReal _ (Finset.prod_nonneg hf)]
exact Finset.prod_congr rfl fun x hxs => by rw [Real.coe_toNNReal _ (hf x hxs)]
theorem le_iInf_add_iInf {ι ι' : Sort*} [Nonempty ι] [Nonempty ι'] {f : ι → ℝ≥0} {g : ι' → ℝ≥0}
{a : ℝ≥0} (h : ∀ i j, a ≤ f i + g j) : a ≤ (⨅ i, f i) + ⨅ j, g j := by
rw [← NNReal.coe_le_coe, NNReal.coe_add, coe_iInf, coe_iInf]
exact le_ciInf_add_ciInf h
theorem mul_finset_sup {α} (r : ℝ≥0) (s : Finset α) (f : α → ℝ≥0) :
r * s.sup f = s.sup fun a => r * f a :=
Finset.comp_sup_eq_sup_comp _ (NNReal.mul_sup r) (mul_zero r)
theorem finset_sup_mul {α} (s : Finset α) (f : α → ℝ≥0) (r : ℝ≥0) :
s.sup f * r = s.sup fun a => f a * r :=
Finset.comp_sup_eq_sup_comp (· * r) (fun x y => NNReal.sup_mul x y r) (zero_mul r)
theorem finset_sup_div {α} {f : α → ℝ≥0} {s : Finset α} (r : ℝ≥0) :
s.sup f / r = s.sup fun a => f a / r := by simp only [div_eq_inv_mul, mul_finset_sup]
open Real
section Sub
/-!
### Lemmas about subtraction
In this section we provide a few lemmas about subtraction that do not fit well into any other
typeclass. For lemmas about subtraction and addition see lemmas about `OrderedSub` in the file
`Mathlib/Algebra/Order/Sub/Basic.lean`. See also `mul_tsub` and `tsub_mul`.
-/
theorem sub_div (a b c : ℝ≥0) : (a - b) / c = a / c - b / c :=
tsub_div _ _ _
end Sub
section Csupr
open Set
variable {ι : Sort*} {f : ι → ℝ≥0}
theorem iInf_mul (f : ι → ℝ≥0) (a : ℝ≥0) : iInf f * a = ⨅ i, f i * a := by
rw [← coe_inj, NNReal.coe_mul, coe_iInf, coe_iInf]
exact Real.iInf_mul_of_nonneg (NNReal.coe_nonneg _) _
theorem mul_iInf (f : ι → ℝ≥0) (a : ℝ≥0) : a * iInf f = ⨅ i, a * f i := by
simpa only [mul_comm] using iInf_mul f a
theorem mul_iSup (f : ι → ℝ≥0) (a : ℝ≥0) : (a * ⨆ i, f i) = ⨆ i, a * f i := by
rw [← coe_inj, NNReal.coe_mul, NNReal.coe_iSup, NNReal.coe_iSup]
exact Real.mul_iSup_of_nonneg (NNReal.coe_nonneg _) _
theorem iSup_mul (f : ι → ℝ≥0) (a : ℝ≥0) : (⨆ i, f i) * a = ⨆ i, f i * a := by
rw [mul_comm, mul_iSup]
simp_rw [mul_comm]
theorem iSup_div (f : ι → ℝ≥0) (a : ℝ≥0) : (⨆ i, f i) / a = ⨆ i, f i / a := by
simp only [div_eq_mul_inv, iSup_mul]
theorem mul_iSup_le {a : ℝ≥0} {g : ℝ≥0} {h : ι → ℝ≥0} (H : ∀ j, g * h j ≤ a) : g * iSup h ≤ a := by
rw [mul_iSup]
exact ciSup_le' H
theorem iSup_mul_le {a : ℝ≥0} {g : ι → ℝ≥0} {h : ℝ≥0} (H : ∀ i, g i * h ≤ a) : iSup g * h ≤ a := by
rw [iSup_mul]
exact ciSup_le' H
theorem iSup_mul_iSup_le {a : ℝ≥0} {g h : ι → ℝ≥0} (H : ∀ i j, g i * h j ≤ a) :
iSup g * iSup h ≤ a :=
iSup_mul_le fun _ => mul_iSup_le <| H _
variable [Nonempty ι]
theorem le_mul_iInf {a : ℝ≥0} {g : ℝ≥0} {h : ι → ℝ≥0} (H : ∀ j, a ≤ g * h j) : a ≤ g * iInf h := by
rw [mul_iInf]
exact le_ciInf H
theorem le_iInf_mul {a : ℝ≥0} {g : ι → ℝ≥0} {h : ℝ≥0} (H : ∀ i, a ≤ g i * h) : a ≤ iInf g * h := by
rw [iInf_mul]
exact le_ciInf H
theorem le_iInf_mul_iInf {a : ℝ≥0} {g h : ι → ℝ≥0} (H : ∀ i j, a ≤ g i * h j) :
a ≤ iInf g * iInf h :=
le_iInf_mul fun i => le_mul_iInf <| H i
end Csupr
end NNReal |
.lake/packages/mathlib/Mathlib/Data/NNReal/Defs.lean | import Mathlib.Algebra.Algebra.Defs
import Mathlib.Algebra.Order.Nonneg.Module
import Mathlib.Data.Real.Archimedean
/-!
# Nonnegative real numbers
In this file we define `NNReal` (notation: `ℝ≥0`) to be the type of non-negative real numbers,
a.k.a. the interval `[0, ∞)`. We also define the following operations and structures on `ℝ≥0`:
* the order on `ℝ≥0` is the restriction of the order on `ℝ`; these relations define a conditionally
complete linear order with a bottom element, `ConditionallyCompleteLinearOrderBot`;
* `a + b` and `a * b` are the restrictions of addition and multiplication of real numbers to `ℝ≥0`;
these operations together with `0 = ⟨0, _⟩` and `1 = ⟨1, _⟩` turn `ℝ≥0` into a conditionally
complete linear ordered archimedean commutative semifield; we have no typeclass for this in
`mathlib` yet, so we define the following instances instead:
- `LinearOrderedSemiring ℝ≥0`;
- `OrderedCommSemiring ℝ≥0`;
- `CanonicallyOrderedAdd ℝ≥0`;
- `LinearOrderedCommGroupWithZero ℝ≥0`;
- `CanonicallyLinearOrderedAddCommMonoid ℝ≥0`;
- `Archimedean ℝ≥0`;
- `ConditionallyCompleteLinearOrderBot ℝ≥0`.
These instances are derived from corresponding instances about the type `{x : α // 0 ≤ x}` in an
appropriate ordered field/ring/group/monoid `α`, see `Mathlib/Algebra/Order/Nonneg/Ring.lean`.
* `Real.toNNReal x` is defined as `⟨max x 0, _⟩`, i.e. `↑(Real.toNNReal x) = x` when `0 ≤ x` and
`↑(Real.toNNReal x) = 0` otherwise.
We also define an instance `CanLift ℝ ℝ≥0`. This instance can be used by the `lift` tactic to
replace `x : ℝ` and `hx : 0 ≤ x` in the proof context with `x : ℝ≥0` while replacing all occurrences
of `x` with `↑x`. This tactic also works for a function `f : α → ℝ` with a hypothesis
`hf : ∀ x, 0 ≤ f x`.
## Notation
This file defines `ℝ≥0` as a localized notation for `NNReal`.
-/
assert_not_exists TrivialStar
open Function
-- to ensure these instances are computable
/-- Nonnegative real numbers, denoted as `ℝ≥0` within the NNReal namespace -/
def NNReal := { r : ℝ // 0 ≤ r } deriving
Zero, One, Semiring, CommMonoidWithZero, CommSemiring,
PartialOrder, SemilatticeInf, SemilatticeSup, DistribLattice,
Nontrivial, Inhabited
namespace NNReal
@[inherit_doc] scoped notation "ℝ≥0" => NNReal
/-- Coercion `ℝ≥0 → ℝ`. -/
@[coe] def toReal : ℝ≥0 → ℝ := Subtype.val
instance : Coe ℝ≥0 ℝ := ⟨toReal⟩
instance : CanonicallyOrderedAdd ℝ≥0 := Nonneg.canonicallyOrderedAdd
instance : NoZeroDivisors ℝ≥0 := Nonneg.noZeroDivisors
instance instDenselyOrdered : DenselyOrdered ℝ≥0 := Nonneg.instDenselyOrdered
instance : OrderBot ℝ≥0 := Nonneg.orderBot
instance instArchimedean : Archimedean ℝ≥0 := Nonneg.instArchimedean
instance instMulArchimedean : MulArchimedean ℝ≥0 := Nonneg.instMulArchimedean
instance : Min ℝ≥0 := SemilatticeInf.toMin
instance : Max ℝ≥0 := SemilatticeSup.toMax
instance : Sub ℝ≥0 := Nonneg.sub
instance : OrderedSub ℝ≥0 := Nonneg.orderedSub
-- a computable copy of `Nonneg.instNNRatCast`
instance : NNRatCast ℝ≥0 where nnratCast r := ⟨r, r.cast_nonneg⟩
noncomputable instance : LinearOrder ℝ≥0 :=
Subtype.instLinearOrder _
noncomputable instance : Inv ℝ≥0 where
inv x := ⟨(x : ℝ)⁻¹, inv_nonneg.mpr x.2⟩
noncomputable instance : Div ℝ≥0 where
div x y := ⟨(x : ℝ) / (y : ℝ), div_nonneg x.2 y.2⟩
noncomputable instance : SMul ℚ≥0 ℝ≥0 where
smul x y := ⟨x • (y : ℝ), by rw [NNRat.smul_def]; exact mul_nonneg x.cast_nonneg y.2⟩
noncomputable instance zpow : Pow ℝ≥0 ℤ where
pow x n := ⟨(x : ℝ) ^ n, zpow_nonneg x.2 _⟩
/-- Redo the `Nonneg.semifield` instance, because this will get unfolded a lot,
and ends up inserting the non-reducible defeq `ℝ≥0 = { x // x ≥ 0 }` in places where
it needs to be reducible(-with-instances).
-/
noncomputable instance : Semifield ℝ≥0 := fast_instance%
Function.Injective.semifield toReal Subtype.val_injective
rfl rfl (fun _ _ => rfl) (fun _ _ => rfl) (fun _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl)
(fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) (fun _ => rfl) (fun _ => rfl)
instance : IsOrderedRing ℝ≥0 :=
Nonneg.isOrderedRing
instance : IsStrictOrderedRing ℝ≥0 :=
Nonneg.isStrictOrderedRing
noncomputable instance : LinearOrderedCommGroupWithZero ℝ≥0 :=
Nonneg.linearOrderedCommGroupWithZero
example {p q : ℝ≥0} (h1p : 0 < p) (h2p : p ≤ q) : q⁻¹ ≤ p⁻¹ := by
with_reducible_and_instances exact inv_anti₀ h1p h2p
-- Simp lemma to put back `n.val` into the normal form given by the coercion.
@[simp]
theorem val_eq_coe (n : ℝ≥0) : n.val = n :=
rfl
instance canLift : CanLift ℝ ℝ≥0 toReal fun r => 0 ≤ r :=
Subtype.canLift _
@[ext] protected theorem eq {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) → n = m :=
Subtype.eq
theorem ne_iff {x y : ℝ≥0} : (x : ℝ) ≠ (y : ℝ) ↔ x ≠ y :=
not_congr <| NNReal.eq_iff.symm
protected theorem «forall» {p : ℝ≥0 → Prop} :
(∀ x : ℝ≥0, p x) ↔ ∀ (x : ℝ) (hx : 0 ≤ x), p ⟨x, hx⟩ :=
Subtype.forall
protected theorem «exists» {p : ℝ≥0 → Prop} :
(∃ x : ℝ≥0, p x) ↔ ∃ (x : ℝ) (hx : 0 ≤ x), p ⟨x, hx⟩ :=
Subtype.exists
/-- Reinterpret a real number `r` as a non-negative real number. Returns `0` if `r < 0`. -/
def _root_.Real.toNNReal (r : ℝ) : ℝ≥0 :=
⟨max r 0, le_max_right _ _⟩
theorem _root_.Real.coe_toNNReal (r : ℝ) (hr : 0 ≤ r) : (Real.toNNReal r : ℝ) = r :=
max_eq_left hr
theorem _root_.Real.toNNReal_of_nonneg {r : ℝ} (hr : 0 ≤ r) : r.toNNReal = ⟨r, hr⟩ := by
simp_rw [Real.toNNReal, max_eq_left hr]
theorem _root_.Real.le_coe_toNNReal (r : ℝ) : r ≤ Real.toNNReal r :=
le_max_left r 0
@[bound] theorem coe_nonneg (r : ℝ≥0) : (0 : ℝ) ≤ r := r.2
@[simp, norm_cast] theorem coe_mk (a : ℝ) (ha) : toReal ⟨a, ha⟩ = a := rfl
example : Zero ℝ≥0 := by infer_instance
example : One ℝ≥0 := by infer_instance
example : Add ℝ≥0 := by infer_instance
example : Sub ℝ≥0 := by infer_instance
example : Mul ℝ≥0 := by infer_instance
noncomputable example : Inv ℝ≥0 := by infer_instance
noncomputable example : Div ℝ≥0 := by infer_instance
example : LE ℝ≥0 := by infer_instance
example : Bot ℝ≥0 := by infer_instance
example : Inhabited ℝ≥0 := by infer_instance
example : Nontrivial ℝ≥0 := by infer_instance
protected theorem coe_injective : Injective ((↑) : ℝ≥0 → ℝ) := Subtype.coe_injective
@[simp, norm_cast] lemma coe_inj {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) = r₂ ↔ r₁ = r₂ :=
NNReal.coe_injective.eq_iff
@[simp, norm_cast] lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl
@[simp] lemma mk_zero : (⟨0, le_rfl⟩ : ℝ≥0) = 0 := rfl
@[simp] lemma mk_one : (⟨1, zero_le_one⟩ : ℝ≥0) = 1 := rfl
@[simp, norm_cast]
protected theorem coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ :=
rfl
@[simp, norm_cast]
protected theorem coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ :=
rfl
@[simp, norm_cast]
protected theorem coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = (r : ℝ)⁻¹ :=
rfl
@[simp, norm_cast]
protected theorem coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = (r₁ : ℝ) / r₂ :=
rfl
protected theorem coe_two : ((2 : ℝ≥0) : ℝ) = 2 := rfl
@[simp, norm_cast]
protected theorem coe_sub {r₁ r₂ : ℝ≥0} (h : r₂ ≤ r₁) : ((r₁ - r₂ : ℝ≥0) : ℝ) = ↑r₁ - ↑r₂ :=
max_eq_left <| le_sub_comm.2 <| by simp [show (r₂ : ℝ) ≤ r₁ from h]
variable {r r₁ r₂ : ℝ≥0} {x y : ℝ}
@[simp, norm_cast] lemma coe_eq_zero : (r : ℝ) = 0 ↔ r = 0 := by rw [← coe_zero, coe_inj]
@[simp, norm_cast] lemma coe_eq_one : (r : ℝ) = 1 ↔ r = 1 := by rw [← coe_one, coe_inj]
@[norm_cast] lemma coe_ne_zero : (r : ℝ) ≠ 0 ↔ r ≠ 0 := coe_eq_zero.not
@[norm_cast] lemma coe_ne_one : (r : ℝ) ≠ 1 ↔ r ≠ 1 := coe_eq_one.not
example : CommSemiring ℝ≥0 := by infer_instance
/-- Coercion `ℝ≥0 → ℝ` as a `RingHom`.
TODO: what if we define `Coe ℝ≥0 ℝ` using this function? -/
def toRealHom : ℝ≥0 →+* ℝ where
toFun := (↑)
map_one' := NNReal.coe_one
map_mul' := NNReal.coe_mul
map_zero' := NNReal.coe_zero
map_add' := NNReal.coe_add
@[simp] theorem coe_toRealHom : ⇑toRealHom = toReal := rfl
section Actions
/-- A `MulAction` over `ℝ` restricts to a `MulAction` over `ℝ≥0`. -/
instance {M : Type*} [MulAction ℝ M] : MulAction ℝ≥0 M :=
MulAction.compHom M toRealHom.toMonoidHom
theorem smul_def {M : Type*} [MulAction ℝ M] (c : ℝ≥0) (x : M) : c • x = (c : ℝ) • x :=
rfl
instance {M N : Type*} [MulAction ℝ M] [MulAction ℝ N] [SMul M N] [IsScalarTower ℝ M N] :
IsScalarTower ℝ≥0 M N where smul_assoc r := smul_assoc (r : ℝ)
instance smulCommClass_left {M N : Type*} [MulAction ℝ N] [SMul M N] [SMulCommClass ℝ M N] :
SMulCommClass ℝ≥0 M N where smul_comm r := smul_comm (r : ℝ)
instance smulCommClass_right {M N : Type*} [MulAction ℝ N] [SMul M N] [SMulCommClass M ℝ N] :
SMulCommClass M ℝ≥0 N where smul_comm m r := smul_comm m (r : ℝ)
/-- A `DistribMulAction` over `ℝ` restricts to a `DistribMulAction` over `ℝ≥0`. -/
instance {M : Type*} [AddMonoid M] [DistribMulAction ℝ M] : DistribMulAction ℝ≥0 M :=
DistribMulAction.compHom M toRealHom.toMonoidHom
/-- A `Module` over `ℝ` restricts to a `Module` over `ℝ≥0`. -/
instance {M : Type*} [AddCommMonoid M] [Module ℝ M] : Module ℝ≥0 M :=
Module.compHom M toRealHom
/-- An `Algebra` over `ℝ` restricts to an `Algebra` over `ℝ≥0`. -/
instance {A : Type*} [Semiring A] [Algebra ℝ A] : Algebra ℝ≥0 A where
commutes' r x := by simp [Algebra.commutes]
smul_def' r x := by simp [← Algebra.smul_def (r : ℝ) x, smul_def]
algebraMap := (algebraMap ℝ A).comp (toRealHom : ℝ≥0 →+* ℝ)
-- verify that the above produces instances we might care about
example : Algebra ℝ≥0 ℝ := by infer_instance
example : DistribMulAction ℝ≥0ˣ ℝ := by infer_instance
end Actions
example : MonoidWithZero ℝ≥0 := by infer_instance
example : CommMonoidWithZero ℝ≥0 := by infer_instance
noncomputable example : CommGroupWithZero ℝ≥0 := by infer_instance
@[simp, norm_cast]
theorem coe_pow (r : ℝ≥0) (n : ℕ) : ((r ^ n : ℝ≥0) : ℝ) = (r : ℝ) ^ n := rfl
@[simp, norm_cast]
theorem coe_zpow (r : ℝ≥0) (n : ℤ) : ((r ^ n : ℝ≥0) : ℝ) = (r : ℝ) ^ n := rfl
variable {ι : Type*} {f : ι → ℝ}
@[simp, norm_cast] lemma coe_nsmul (r : ℝ≥0) (n : ℕ) : ↑(n • r) = n • (r : ℝ) := rfl
@[simp, norm_cast] lemma coe_nnqsmul (q : ℚ≥0) (x : ℝ≥0) : ↑(q • x) = (q • x : ℝ) := rfl
@[simp, norm_cast]
protected theorem coe_natCast (n : ℕ) : (↑(↑n : ℝ≥0) : ℝ) = n :=
map_natCast toRealHom n
@[simp, norm_cast]
protected theorem coe_ofNat (n : ℕ) [n.AtLeastTwo] : ((ofNat(n) : ℝ≥0) : ℝ) = ofNat(n) :=
rfl
@[simp, norm_cast]
protected theorem coe_ofScientific (m : ℕ) (s : Bool) (e : ℕ) :
↑(OfScientific.ofScientific m s e : ℝ≥0) = (OfScientific.ofScientific m s e : ℝ) :=
rfl
@[simp, norm_cast]
lemma algebraMap_eq_coe : (algebraMap ℝ≥0 ℝ : ℝ≥0 → ℝ) = (↑) := rfl
noncomputable example : LinearOrder ℝ≥0 := by infer_instance
@[simp, norm_cast] lemma coe_le_coe : (r₁ : ℝ) ≤ r₂ ↔ r₁ ≤ r₂ := Iff.rfl
@[simp, norm_cast] lemma coe_lt_coe : (r₁ : ℝ) < r₂ ↔ r₁ < r₂ := Iff.rfl
@[gcongr] private alias ⟨_, GCongr.coe_le_coe_of_le⟩ := coe_le_coe
@[gcongr, bound] private alias ⟨_, Bound.coe_lt_coe_of_lt⟩ := coe_lt_coe
@[simp, norm_cast] lemma coe_pos : (0 : ℝ) < r ↔ 0 < r := Iff.rfl
@[bound] private alias ⟨_, Bound.coe_pos_of_pos⟩ := coe_pos
@[simp, norm_cast] lemma one_le_coe : 1 ≤ (r : ℝ) ↔ 1 ≤ r := by rw [← coe_le_coe, coe_one]
@[simp, norm_cast] lemma one_lt_coe : 1 < (r : ℝ) ↔ 1 < r := by rw [← coe_lt_coe, coe_one]
@[simp, norm_cast] lemma coe_le_one : (r : ℝ) ≤ 1 ↔ r ≤ 1 := by rw [← coe_le_coe, coe_one]
@[simp, norm_cast] lemma coe_lt_one : (r : ℝ) < 1 ↔ r < 1 := by rw [← coe_lt_coe, coe_one]
@[mono] lemma coe_mono : Monotone ((↑) : ℝ≥0 → ℝ) := fun _ _ => NNReal.coe_le_coe.2
/-- Alias for the use of `gcongr` -/
@[gcongr] alias ⟨_, GCongr.toReal_le_toReal⟩ := coe_le_coe
protected theorem _root_.Real.toNNReal_monotone : Monotone Real.toNNReal := fun _ _ h =>
max_le_max_right _ h
@[gcongr]
protected theorem _root_.Real.toNNReal_mono {r₁ r₂ : ℝ} (h : r₁ ≤ r₂) : r₁.toNNReal ≤ r₂.toNNReal :=
Real.toNNReal_monotone h
@[simp]
theorem _root_.Real.toNNReal_coe {r : ℝ≥0} : Real.toNNReal r = r :=
NNReal.eq <| max_eq_left r.2
@[simp]
theorem mk_natCast (n : ℕ) : @Eq ℝ≥0 (⟨(n : ℝ), n.cast_nonneg⟩ : ℝ≥0) n :=
NNReal.eq (NNReal.coe_natCast n).symm
@[simp]
theorem _root_.Real.toNNReal_coe_nat (n : ℕ) : Real.toNNReal n = n :=
NNReal.eq <| by simp [Real.coe_toNNReal]
@[simp]
theorem _root_.Real.toNNReal_ofNat (n : ℕ) [n.AtLeastTwo] :
Real.toNNReal ofNat(n) = OfNat.ofNat n :=
Real.toNNReal_coe_nat n
/-- `Real.toNNReal` and `NNReal.toReal : ℝ≥0 → ℝ` form a Galois insertion. -/
def gi : GaloisInsertion Real.toNNReal (↑) :=
GaloisInsertion.monotoneIntro NNReal.coe_mono Real.toNNReal_monotone Real.le_coe_toNNReal
fun _ => Real.toNNReal_coe
-- note that anything involving the (decidability of the) linear order,
-- will be noncomputable, everything else should not be.
example : OrderBot ℝ≥0 := by infer_instance
example : PartialOrder ℝ≥0 := by infer_instance
example : AddCommMonoid ℝ≥0 := by infer_instance
example : IsOrderedAddMonoid ℝ≥0 := by infer_instance
example : DistribLattice ℝ≥0 := by infer_instance
example : SemilatticeInf ℝ≥0 := by infer_instance
example : SemilatticeSup ℝ≥0 := by infer_instance
example : Semiring ℝ≥0 := by infer_instance
example : CommMonoid ℝ≥0 := by infer_instance
example : IsOrderedMonoid ℝ≥0 := instLinearOrderedCommGroupWithZero.toIsOrderedMonoid
noncomputable example : LinearOrderedCommMonoidWithZero ℝ≥0 := by infer_instance
example : DenselyOrdered ℝ≥0 := by infer_instance
example : NoMaxOrder ℝ≥0 := by infer_instance
instance instPosSMulStrictMono {α} [Preorder α] [MulAction ℝ α] [PosSMulStrictMono ℝ α] :
PosSMulStrictMono ℝ≥0 α where
smul_lt_smul_of_pos_left _r hr _a₁ _a₂ ha := (smul_lt_smul_of_pos_left ha (coe_pos.2 hr) :)
instance instSMulPosStrictMono {α} [Zero α] [Preorder α] [MulAction ℝ α] [SMulPosStrictMono ℝ α] :
SMulPosStrictMono ℝ≥0 α where
smul_lt_smul_of_pos_right _a ha _r₁ _r₂ hr := (smul_lt_smul_of_pos_right (coe_lt_coe.2 hr) ha :)
/-- If `a` is a nonnegative real number, then the closed interval `[0, a]` in `ℝ` is order
isomorphic to the interval `Set.Iic a`. -/
-- TODO: if we use `@[simps!]` it will look through the `NNReal = Subtype _` definition,
-- but if we use `@[simps]` it will not look through the `Equiv.Set.sep` definition.
-- Turning `NNReal` into a structure may be the best way to go here.
-- @[simps!? apply_coe_coe]
def orderIsoIccZeroCoe (a : ℝ≥0) : Set.Icc (0 : ℝ) a ≃o Set.Iic a where
toEquiv := Equiv.Set.sep (Set.Ici 0) fun x : ℝ => x ≤ a
map_rel_iff' := Iff.rfl
@[simp]
theorem orderIsoIccZeroCoe_apply_coe_coe (a : ℝ≥0) (b : Set.Icc (0 : ℝ) a) :
(orderIsoIccZeroCoe a b : ℝ) = b :=
rfl
@[simp]
theorem orderIsoIccZeroCoe_symm_apply_coe (a : ℝ≥0) (b : Set.Iic a) :
((orderIsoIccZeroCoe a).symm b : ℝ) = b :=
rfl
-- note we need the `@` to make the `Membership.mem` have a sensible type
theorem coe_image {s : Set ℝ≥0} :
(↑) '' s = { x : ℝ | ∃ h : 0 ≤ x, @Membership.mem ℝ≥0 _ _ s ⟨x, h⟩ } :=
Subtype.coe_image
theorem bddAbove_coe {s : Set ℝ≥0} : BddAbove (((↑) : ℝ≥0 → ℝ) '' s) ↔ BddAbove s :=
Iff.intro
(fun ⟨b, hb⟩ =>
⟨Real.toNNReal b, fun ⟨y, _⟩ hys =>
show y ≤ max b 0 from le_max_of_le_left <| hb <| Set.mem_image_of_mem _ hys⟩)
fun ⟨b, hb⟩ => ⟨b, fun _ ⟨_, hx, eq⟩ => eq ▸ hb hx⟩
theorem bddBelow_coe (s : Set ℝ≥0) : BddBelow (((↑) : ℝ≥0 → ℝ) '' s) :=
⟨0, fun _ ⟨q, _, eq⟩ => eq ▸ q.2⟩
noncomputable instance : ConditionallyCompleteLinearOrderBot ℝ≥0 :=
Nonneg.conditionallyCompleteLinearOrderBot 0
@[norm_cast]
theorem coe_sSup (s : Set ℝ≥0) : (↑(sSup s) : ℝ) = sSup (((↑) : ℝ≥0 → ℝ) '' s) := by
rcases Set.eq_empty_or_nonempty s with rfl | hs
· simp
by_cases H : BddAbove s
· have A : sSup (Subtype.val '' s) ∈ Set.Ici 0 := by
apply Real.sSup_nonneg
rintro - ⟨y, -, rfl⟩
exact y.2
exact (@subset_sSup_of_within ℝ (Set.Ici (0 : ℝ)) _ _ (_) s hs H A).symm
· simp only [csSup_of_not_bddAbove H, csSup_empty, bot_eq_zero', NNReal.coe_zero]
apply (Real.sSup_of_not_bddAbove ?_).symm
contrapose! H
exact bddAbove_coe.1 H
@[simp, norm_cast]
theorem coe_iSup {ι : Sort*} (s : ι → ℝ≥0) : (↑(⨆ i, s i) : ℝ) = ⨆ i, ↑(s i) := by
rw [iSup, iSup, coe_sSup, ← Set.range_comp]; rfl
@[norm_cast]
theorem coe_sInf (s : Set ℝ≥0) : (↑(sInf s) : ℝ) = sInf (((↑) : ℝ≥0 → ℝ) '' s) := by
rcases Set.eq_empty_or_nonempty s with rfl | hs
· simp only [Set.image_empty, Real.sInf_empty, coe_eq_zero]
exact @subset_sInf_emptyset ℝ (Set.Ici (0 : ℝ)) _ _ (_)
have A : sInf (Subtype.val '' s) ∈ Set.Ici 0 := by
apply Real.sInf_nonneg
rintro - ⟨y, -, rfl⟩
exact y.2
exact (@subset_sInf_of_within ℝ (Set.Ici (0 : ℝ)) _ _ (_) s hs (OrderBot.bddBelow s) A).symm
@[simp]
theorem sInf_empty : sInf (∅ : Set ℝ≥0) = 0 := by
rw [← coe_eq_zero, coe_sInf, Set.image_empty, Real.sInf_empty]
@[norm_cast]
theorem coe_iInf {ι : Sort*} (s : ι → ℝ≥0) : (↑(⨅ i, s i) : ℝ) = ⨅ i, ↑(s i) := by
rw [iInf, iInf, coe_sInf, ← Set.range_comp]; rfl
-- Short-circuit instance search
instance addLeftMono : AddLeftMono ℝ≥0 := inferInstance
instance addLeftReflectLT : AddLeftReflectLT ℝ≥0 := inferInstance
instance mulLeftMono : MulLeftMono ℝ≥0 := inferInstance
theorem lt_iff_exists_rat_btwn (a b : ℝ≥0) :
a < b ↔ ∃ q : ℚ, 0 ≤ q ∧ a < Real.toNNReal q ∧ Real.toNNReal q < b :=
Iff.intro
(fun h : (↑a : ℝ) < (↑b : ℝ) =>
let ⟨q, haq, hqb⟩ := exists_rat_btwn h
have : 0 ≤ (q : ℝ) := le_trans a.2 <| le_of_lt haq
⟨q, Rat.cast_nonneg.1 this, by
simp [Real.coe_toNNReal _ this, NNReal.coe_lt_coe.symm, haq, hqb]⟩)
fun ⟨_, _, haq, hqb⟩ => lt_trans haq hqb
theorem bot_eq_zero : (⊥ : ℝ≥0) = 0 := rfl
theorem mul_sup (a b c : ℝ≥0) : a * (b ⊔ c) = a * b ⊔ a * c :=
mul_max_of_nonneg _ _ <| zero_le a
theorem sup_mul (a b c : ℝ≥0) : (a ⊔ b) * c = a * c ⊔ b * c :=
max_mul_of_nonneg _ _ <| zero_le c
@[simp, norm_cast]
theorem coe_max (x y : ℝ≥0) : ((max x y : ℝ≥0) : ℝ) = max (x : ℝ) (y : ℝ) :=
NNReal.coe_mono.map_max
@[simp, norm_cast]
theorem coe_min (x y : ℝ≥0) : ((min x y : ℝ≥0) : ℝ) = min (x : ℝ) (y : ℝ) :=
NNReal.coe_mono.map_min
@[simp]
theorem zero_le_coe {q : ℝ≥0} : 0 ≤ (q : ℝ) :=
q.2
instance instIsStrictOrderedModule {M : Type*} [AddCommMonoid M] [PartialOrder M]
[Module ℝ M] [IsStrictOrderedModule ℝ M] :
IsStrictOrderedModule ℝ≥0 M := Nonneg.instIsStrictOrderedModule
end NNReal
open NNReal
namespace Real
section ToNNReal
@[simp]
theorem coe_toNNReal' (r : ℝ) : (Real.toNNReal r : ℝ) = max r 0 :=
rfl
@[simp]
theorem toNNReal_zero : Real.toNNReal 0 = 0 := NNReal.eq <| coe_toNNReal _ le_rfl
@[simp]
theorem toNNReal_one : Real.toNNReal 1 = 1 := NNReal.eq <| coe_toNNReal _ zero_le_one
@[simp]
theorem toNNReal_pos {r : ℝ} : 0 < Real.toNNReal r ↔ 0 < r := by
simp [← NNReal.coe_lt_coe]
@[simp]
theorem toNNReal_eq_zero {r : ℝ} : Real.toNNReal r = 0 ↔ r ≤ 0 := by
simpa [-toNNReal_pos] using not_iff_not.2 (@toNNReal_pos r)
theorem toNNReal_of_nonpos {r : ℝ} : r ≤ 0 → Real.toNNReal r = 0 :=
toNNReal_eq_zero.2
lemma toNNReal_eq_iff_eq_coe {r : ℝ} {p : ℝ≥0} (hp : p ≠ 0) : r.toNNReal = p ↔ r = p :=
⟨fun h ↦ h ▸ (coe_toNNReal _ <| not_lt.1 fun hlt ↦ hp <| h ▸ toNNReal_of_nonpos hlt.le).symm,
fun h ↦ h.symm ▸ toNNReal_coe⟩
@[simp]
lemma toNNReal_eq_one {r : ℝ} : r.toNNReal = 1 ↔ r = 1 := toNNReal_eq_iff_eq_coe one_ne_zero
@[simp]
lemma toNNReal_eq_natCast {r : ℝ} {n : ℕ} (hn : n ≠ 0) : r.toNNReal = n ↔ r = n :=
mod_cast toNNReal_eq_iff_eq_coe <| Nat.cast_ne_zero.2 hn
@[simp]
lemma toNNReal_eq_ofNat {r : ℝ} {n : ℕ} [n.AtLeastTwo] :
r.toNNReal = ofNat(n) ↔ r = OfNat.ofNat n :=
toNNReal_eq_natCast (NeZero.ne n)
@[simp]
theorem toNNReal_le_toNNReal_iff {r p : ℝ} (hp : 0 ≤ p) :
toNNReal r ≤ toNNReal p ↔ r ≤ p := by simp [← NNReal.coe_le_coe, hp]
@[simp]
lemma toNNReal_le_one {r : ℝ} : r.toNNReal ≤ 1 ↔ r ≤ 1 := by
simpa using toNNReal_le_toNNReal_iff zero_le_one
@[simp]
lemma one_lt_toNNReal {r : ℝ} : 1 < r.toNNReal ↔ 1 < r := by
simpa only [not_le] using toNNReal_le_one.not
@[simp]
lemma toNNReal_le_natCast {r : ℝ} {n : ℕ} : r.toNNReal ≤ n ↔ r ≤ n := by
simpa using toNNReal_le_toNNReal_iff n.cast_nonneg
@[simp]
lemma natCast_lt_toNNReal {r : ℝ} {n : ℕ} : n < r.toNNReal ↔ n < r := by
simpa only [not_le] using toNNReal_le_natCast.not
@[simp]
lemma toNNReal_le_ofNat {r : ℝ} {n : ℕ} [n.AtLeastTwo] :
r.toNNReal ≤ ofNat(n) ↔ r ≤ n :=
toNNReal_le_natCast
@[simp]
lemma ofNat_lt_toNNReal {r : ℝ} {n : ℕ} [n.AtLeastTwo] :
ofNat(n) < r.toNNReal ↔ n < r :=
natCast_lt_toNNReal
@[simp]
theorem toNNReal_eq_toNNReal_iff {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) :
toNNReal r = toNNReal p ↔ r = p := by simp [← coe_inj, hr, hp]
@[simp]
theorem toNNReal_lt_toNNReal_iff' {r p : ℝ} : Real.toNNReal r < Real.toNNReal p ↔ r < p ∧ 0 < p :=
NNReal.coe_lt_coe.symm.trans max_lt_max_left_iff
theorem toNNReal_lt_toNNReal_iff {r p : ℝ} (h : 0 < p) :
Real.toNNReal r < Real.toNNReal p ↔ r < p :=
toNNReal_lt_toNNReal_iff'.trans (and_iff_left h)
theorem lt_of_toNNReal_lt {r p : ℝ} (h : r.toNNReal < p.toNNReal) : r < p :=
(Real.toNNReal_lt_toNNReal_iff <| Real.toNNReal_pos.1 (ne_bot_of_gt h).bot_lt).1 h
theorem toNNReal_lt_toNNReal_iff_of_nonneg {r p : ℝ} (hr : 0 ≤ r) :
Real.toNNReal r < Real.toNNReal p ↔ r < p :=
toNNReal_lt_toNNReal_iff'.trans ⟨And.left, fun h => ⟨h, lt_of_le_of_lt hr h⟩⟩
lemma toNNReal_le_toNNReal_iff' {r p : ℝ} : r.toNNReal ≤ p.toNNReal ↔ r ≤ p ∨ r ≤ 0 := by
simp_rw [← not_lt, toNNReal_lt_toNNReal_iff', not_and_or]
lemma toNNReal_le_toNNReal_iff_of_pos {r p : ℝ} (hr : 0 < r) : r.toNNReal ≤ p.toNNReal ↔ r ≤ p := by
simp [toNNReal_le_toNNReal_iff', hr.not_ge]
@[simp]
lemma one_le_toNNReal {r : ℝ} : 1 ≤ r.toNNReal ↔ 1 ≤ r := by
simpa using toNNReal_le_toNNReal_iff_of_pos one_pos
@[simp]
lemma toNNReal_lt_one {r : ℝ} : r.toNNReal < 1 ↔ r < 1 := by simp only [← not_le, one_le_toNNReal]
@[simp]
lemma natCastle_toNNReal' {n : ℕ} {r : ℝ} : ↑n ≤ r.toNNReal ↔ n ≤ r ∨ n = 0 := by
simpa [n.cast_nonneg.ge_iff_eq'] using toNNReal_le_toNNReal_iff' (r := n)
@[simp]
lemma toNNReal_lt_natCast' {n : ℕ} {r : ℝ} : r.toNNReal < n ↔ r < n ∧ n ≠ 0 := by
simpa [pos_iff_ne_zero] using toNNReal_lt_toNNReal_iff' (r := r) (p := n)
lemma natCast_le_toNNReal {n : ℕ} {r : ℝ} (hn : n ≠ 0) : ↑n ≤ r.toNNReal ↔ n ≤ r := by simp [hn]
lemma toNNReal_lt_natCast {r : ℝ} {n : ℕ} (hn : n ≠ 0) : r.toNNReal < n ↔ r < n := by simp [hn]
@[simp]
lemma toNNReal_lt_ofNat {r : ℝ} {n : ℕ} [n.AtLeastTwo] :
r.toNNReal < ofNat(n) ↔ r < OfNat.ofNat n :=
toNNReal_lt_natCast (NeZero.ne n)
@[simp]
lemma ofNat_le_toNNReal {n : ℕ} {r : ℝ} [n.AtLeastTwo] :
ofNat(n) ≤ r.toNNReal ↔ OfNat.ofNat n ≤ r :=
natCast_le_toNNReal (NeZero.ne n)
@[simp]
theorem toNNReal_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) :
Real.toNNReal (r + p) = Real.toNNReal r + Real.toNNReal p :=
NNReal.eq <| by simp [hr, hp, add_nonneg]
theorem toNNReal_add_toNNReal {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) :
Real.toNNReal r + Real.toNNReal p = Real.toNNReal (r + p) :=
(Real.toNNReal_add hr hp).symm
theorem toNNReal_le_toNNReal {r p : ℝ} (h : r ≤ p) : Real.toNNReal r ≤ Real.toNNReal p :=
Real.toNNReal_mono h
theorem toNNReal_add_le {r p : ℝ} : Real.toNNReal (r + p) ≤ Real.toNNReal r + Real.toNNReal p :=
NNReal.coe_le_coe.1 <| max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) NNReal.zero_le_coe
theorem toNNReal_le_iff_le_coe {r : ℝ} {p : ℝ≥0} : toNNReal r ≤ p ↔ r ≤ ↑p :=
NNReal.gi.gc r p
theorem le_toNNReal_iff_coe_le {r : ℝ≥0} {p : ℝ} (hp : 0 ≤ p) : r ≤ Real.toNNReal p ↔ ↑r ≤ p := by
rw [← NNReal.coe_le_coe, Real.coe_toNNReal p hp]
theorem le_toNNReal_iff_coe_le' {r : ℝ≥0} {p : ℝ} (hr : 0 < r) : r ≤ Real.toNNReal p ↔ ↑r ≤ p :=
(le_or_gt 0 p).elim le_toNNReal_iff_coe_le fun hp => by
simp only [(hp.trans_le r.coe_nonneg).not_ge, toNNReal_eq_zero.2 hp.le, hr.not_ge]
theorem toNNReal_lt_iff_lt_coe {r : ℝ} {p : ℝ≥0} (ha : 0 ≤ r) : Real.toNNReal r < p ↔ r < ↑p := by
rw [← NNReal.coe_lt_coe, Real.coe_toNNReal r ha]
theorem lt_toNNReal_iff_coe_lt {r : ℝ≥0} {p : ℝ} : r < Real.toNNReal p ↔ ↑r < p :=
lt_iff_lt_of_le_iff_le toNNReal_le_iff_le_coe
theorem toNNReal_pow {x : ℝ} (hx : 0 ≤ x) (n : ℕ) : (x ^ n).toNNReal = x.toNNReal ^ n := by
rw [← coe_inj, NNReal.coe_pow, Real.coe_toNNReal _ (pow_nonneg hx _),
Real.coe_toNNReal x hx]
theorem toNNReal_zpow {x : ℝ} (hx : 0 ≤ x) (n : ℤ) : (x ^ n).toNNReal = x.toNNReal ^ n := by
rw [← coe_inj, NNReal.coe_zpow, Real.coe_toNNReal _ (zpow_nonneg hx _), Real.coe_toNNReal x hx]
theorem toNNReal_mul {p q : ℝ} (hp : 0 ≤ p) :
Real.toNNReal (p * q) = Real.toNNReal p * Real.toNNReal q :=
NNReal.eq <| by simp [mul_max_of_nonneg, hp]
end ToNNReal
end Real
open Real
namespace NNReal
section Mul
theorem mul_eq_mul_left {a b c : ℝ≥0} (h : a ≠ 0) : a * b = a * c ↔ b = c := by
rw [mul_eq_mul_left_iff, or_iff_left h]
end Mul
section Pow
theorem pow_antitone_exp {a : ℝ≥0} (m n : ℕ) (mn : m ≤ n) (a1 : a ≤ 1) : a ^ n ≤ a ^ m :=
pow_le_pow_of_le_one (zero_le a) a1 mn
nonrec theorem exists_pow_lt_of_lt_one {a b : ℝ≥0} (ha : 0 < a) (hb : b < 1) :
∃ n : ℕ, b ^ n < a := by
simpa only [← coe_pow, NNReal.coe_lt_coe] using
exists_pow_lt_of_lt_one (NNReal.coe_pos.2 ha) (NNReal.coe_lt_coe.2 hb)
nonrec theorem exists_mem_Ico_zpow {x : ℝ≥0} {y : ℝ≥0} (hx : x ≠ 0) (hy : 1 < y) :
∃ n : ℤ, x ∈ Set.Ico (y ^ n) (y ^ (n + 1)) :=
exists_mem_Ico_zpow hx.bot_lt hy
nonrec theorem exists_mem_Ioc_zpow {x : ℝ≥0} {y : ℝ≥0} (hx : x ≠ 0) (hy : 1 < y) :
∃ n : ℤ, x ∈ Set.Ioc (y ^ n) (y ^ (n + 1)) :=
exists_mem_Ioc_zpow hx.bot_lt hy
end Pow
section Sub
/-!
### Lemmas about subtraction
In this section we provide a few lemmas about subtraction that do not fit well into any other
typeclass. For lemmas about subtraction and addition see lemmas about `OrderedSub` in the file
`Mathlib/Algebra/Order/Sub/Basic.lean`. See also `mul_tsub` and `tsub_mul`.
-/
theorem sub_def {r p : ℝ≥0} : r - p = Real.toNNReal (r - p) :=
rfl
theorem coe_sub_def {r p : ℝ≥0} : ↑(r - p) = max (r - p : ℝ) 0 :=
rfl
example : OrderedSub ℝ≥0 := by infer_instance
end Sub
section Inv
@[simp]
theorem inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p := by
rw [← mul_le_mul_iff_right₀ (pos_iff_ne_zero.2 h), mul_inv_cancel₀ h]
theorem inv_le_of_le_mul {r p : ℝ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p := by
by_cases r = 0 <;> simp [*, inv_le]
@[simp]
theorem le_inv_iff_mul_le {r p : ℝ≥0} (h : p ≠ 0) : r ≤ p⁻¹ ↔ r * p ≤ 1 := by
rw [← mul_le_mul_iff_right₀ (pos_iff_ne_zero.2 h), mul_inv_cancel₀ h, mul_comm]
@[simp]
theorem lt_inv_iff_mul_lt {r p : ℝ≥0} (h : p ≠ 0) : r < p⁻¹ ↔ r * p < 1 := by
rw [← mul_lt_mul_iff_right₀ (pos_iff_ne_zero.2 h), mul_inv_cancel₀ h, mul_comm]
theorem div_le_of_le_mul {a b c : ℝ≥0} (h : a ≤ b * c) : a / c ≤ b :=
if h0 : c = 0 then by simp [h0] else (div_le_iff₀ (pos_iff_ne_zero.2 h0)).2 h
theorem div_le_of_le_mul' {a b c : ℝ≥0} (h : a ≤ b * c) : a / b ≤ c :=
div_le_of_le_mul <| mul_comm b c ▸ h
theorem mul_lt_of_lt_div {a b r : ℝ≥0} (h : a < b / r) : a * r < b :=
(lt_div_iff₀ <| pos_iff_ne_zero.2 fun hr => False.elim <| by simp [hr] at h).1 h
theorem le_of_forall_lt_one_mul_le {x y : ℝ≥0} (h : ∀ a < 1, a * x ≤ y) : x ≤ y :=
le_of_forall_lt_imp_le_of_dense fun a ha => by
have hx : x ≠ 0 := pos_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha)
have hx' : x⁻¹ ≠ 0 := by rwa [Ne, inv_eq_zero]
have : a * x⁻¹ < 1 := by rwa [← lt_inv_iff_mul_lt hx', inv_inv]
have : a * x⁻¹ * x ≤ y := h _ this
rwa [mul_assoc, inv_mul_cancel₀ hx, mul_one] at this
nonrec theorem half_le_self (a : ℝ≥0) : a / 2 ≤ a :=
half_le_self bot_le
nonrec theorem half_lt_self {a : ℝ≥0} (h : a ≠ 0) : a / 2 < a :=
half_lt_self h.bot_lt
theorem div_lt_one_of_lt {a b : ℝ≥0} (h : a < b) : a / b < 1 := by
rwa [div_lt_iff₀ h.bot_lt, one_mul]
theorem _root_.Real.toNNReal_inv {x : ℝ} : Real.toNNReal x⁻¹ = (Real.toNNReal x)⁻¹ := by
rcases le_total 0 x with hx | hx
· nth_rw 1 [← Real.coe_toNNReal x hx]
rw [← NNReal.coe_inv, Real.toNNReal_coe]
· rw [toNNReal_eq_zero.mpr hx, inv_zero, toNNReal_eq_zero.mpr (inv_nonpos.mpr hx)]
theorem _root_.Real.toNNReal_div {x y : ℝ} (hx : 0 ≤ x) :
Real.toNNReal (x / y) = Real.toNNReal x / Real.toNNReal y := by
rw [div_eq_mul_inv, div_eq_mul_inv, ← Real.toNNReal_inv, ← Real.toNNReal_mul hx]
theorem _root_.Real.toNNReal_div' {x y : ℝ} (hy : 0 ≤ y) :
Real.toNNReal (x / y) = Real.toNNReal x / Real.toNNReal y := by
rw [div_eq_inv_mul, div_eq_inv_mul, Real.toNNReal_mul (inv_nonneg.2 hy), Real.toNNReal_inv]
theorem inv_lt_one_iff {x : ℝ≥0} (hx : x ≠ 0) : x⁻¹ < 1 ↔ 1 < x := by
rw [← one_div, div_lt_iff₀ hx.bot_lt, one_mul]
theorem inv_lt_inv {x y : ℝ≥0} (hx : x ≠ 0) (h : x < y) : y⁻¹ < x⁻¹ :=
inv_strictAnti₀ hx.bot_lt h
lemma exists_nat_pos_inv_lt {b : ℝ≥0} (hb : 0 < b) :
∃ (n : ℕ), 0 < n ∧ (n : ℝ≥0)⁻¹ < b :=
b.toReal.exists_nat_pos_inv_lt hb
end Inv
@[simp]
theorem abs_eq (x : ℝ≥0) : |(x : ℝ)| = x :=
abs_of_nonneg x.property
section Csupr
open Set
variable {ι : Sort*} {f : ι → ℝ≥0}
theorem le_toNNReal_of_coe_le {x : ℝ≥0} {y : ℝ} (h : ↑x ≤ y) : x ≤ y.toNNReal :=
(le_toNNReal_iff_coe_le <| x.2.trans h).2 h
nonrec theorem sSup_of_not_bddAbove {s : Set ℝ≥0} (hs : ¬BddAbove s) : SupSet.sSup s = 0 := by
grind [csSup_of_not_bddAbove, csSup_empty, bot_eq_zero']
theorem iSup_of_not_bddAbove (hf : ¬BddAbove (range f)) : ⨆ i, f i = 0 :=
sSup_of_not_bddAbove hf
theorem iSup_empty [IsEmpty ι] (f : ι → ℝ≥0) : ⨆ i, f i = 0 := ciSup_of_empty f
theorem iInf_empty [IsEmpty ι] (f : ι → ℝ≥0) : ⨅ i, f i = 0 := by
rw [_root_.iInf_of_isEmpty, sInf_empty]
@[simp] lemma iSup_eq_zero (hf : BddAbove (range f)) : ⨆ i, f i = 0 ↔ ∀ i, f i = 0 := by
cases isEmpty_or_nonempty ι
· simp
· simp [← bot_eq_zero', ← le_bot_iff, ciSup_le_iff hf]
@[simp]
theorem iInf_const_zero {α : Sort*} : ⨅ _ : α, (0 : ℝ≥0) = 0 := by
rw [← coe_inj, coe_iInf]
exact Real.iInf_const_zero
end Csupr
end NNReal
namespace Set
namespace OrdConnected
variable {s : Set ℝ} {t : Set ℝ≥0}
theorem preimage_coe_nnreal_real (h : s.OrdConnected) : ((↑) ⁻¹' s : Set ℝ≥0).OrdConnected :=
h.preimage_mono NNReal.coe_mono
theorem image_coe_nnreal_real (h : t.OrdConnected) : ((↑) '' t : Set ℝ).OrdConnected :=
⟨forall_mem_image.2 fun x hx =>
forall_mem_image.2 fun _y hy z hz => ⟨⟨z, x.2.trans hz.1⟩, h.out hx hy hz, rfl⟩⟩
-- TODO: does it generalize to a `GaloisInsertion`?
theorem image_real_toNNReal (h : s.OrdConnected) : (Real.toNNReal '' s).OrdConnected := by
refine ⟨forall_mem_image.2 fun x hx => forall_mem_image.2 fun y hy z hz => ?_⟩
rcases le_total y 0 with hy₀ | hy₀
· rw [mem_Icc, Real.toNNReal_of_nonpos hy₀, nonpos_iff_eq_zero] at hz
exact ⟨y, hy, (toNNReal_of_nonpos hy₀).trans hz.2.symm⟩
· lift y to ℝ≥0 using hy₀
rw [toNNReal_coe] at hz
exact ⟨z, h.out hx hy ⟨toNNReal_le_iff_le_coe.1 hz.1, hz.2⟩, toNNReal_coe⟩
theorem preimage_real_toNNReal (h : t.OrdConnected) : (Real.toNNReal ⁻¹' t).OrdConnected :=
h.preimage_mono Real.toNNReal_monotone
end OrdConnected
end Set
namespace Real
/-- The absolute value on `ℝ` as a map to `ℝ≥0`. -/
@[pp_nodot]
def nnabs : ℝ →*₀ ℝ≥0 where
toFun x := ⟨|x|, abs_nonneg x⟩
map_zero' := by ext; simp
map_one' := by ext; simp
map_mul' x y := by ext; simp [abs_mul]
@[norm_cast, simp]
theorem coe_nnabs (x : ℝ) : (nnabs x : ℝ) = |x| :=
rfl
@[simp]
theorem nnabs_of_nonneg {x : ℝ} (h : 0 ≤ x) : nnabs x = toNNReal x := by
ext
rw [coe_toNNReal x h, coe_nnabs, abs_of_nonneg h]
theorem nnabs_coe (x : ℝ≥0) : nnabs x = x := by simp
theorem coe_toNNReal_le (x : ℝ) : (toNNReal x : ℝ) ≤ |x| :=
max_le (le_abs_self _) (abs_nonneg _)
@[simp] lemma toNNReal_abs (x : ℝ) : |x|.toNNReal = nnabs x := NNReal.coe_injective <| by simp
theorem cast_natAbs_eq_nnabs_cast (n : ℤ) : (n.natAbs : ℝ≥0) = nnabs n := by
ext
rw [NNReal.coe_natCast, Nat.cast_natAbs, Real.coe_nnabs, Int.cast_abs]
/-- Every real number nonnegative or nonpositive, phrased using `ℝ≥0`. -/
lemma nnreal_dichotomy (r : ℝ) : ∃ x : ℝ≥0, r = x ∨ r = -x := by
obtain (hr | hr) : 0 ≤ r ∨ 0 ≤ -r := by simpa using le_total ..
all_goals
rw [← neg_neg r]
lift (_ : ℝ) to ℝ≥0 using hr with r
aesop
/-- Every real number is either zero, positive or negative, phrased using `ℝ≥0`. -/
lemma nnreal_trichotomy (r : ℝ) : r = 0 ∨ ∃ x : ℝ≥0, 0 < x ∧ (r = x ∨ r = -x) := by
obtain ⟨x, hx⟩ := nnreal_dichotomy r
rw [or_iff_not_imp_left]
aesop (add simp pos_iff_ne_zero)
/-- To prove a property holds for real numbers it suffices to show that it holds for `x : ℝ≥0`,
and if it holds for `x : ℝ≥0`, then it does also for `(-↑x : ℝ)`. -/
@[elab_as_elim]
lemma nnreal_induction_on {motive : ℝ → Prop} (nonneg : ∀ x : ℝ≥0, motive x)
(nonpos : ∀ x : ℝ≥0, motive x → motive (-x)) (r : ℝ) : motive r := by
obtain ⟨r, (rfl | rfl)⟩ := r.nnreal_dichotomy
all_goals simp_all
/-- A version of `nnreal_induction_on` which splits into three cases (zero, positive and negative)
instead of two. -/
@[elab_as_elim]
lemma nnreal_induction_on' {motive : ℝ → Prop} (zero : motive 0) (pos : ∀ x : ℝ≥0, 0 < x → motive x)
(neg : ∀ x : ℝ≥0, 0 < x → motive x → motive (-x)) (r : ℝ) : motive r := by
obtain rfl | ⟨r, hr, (rfl | rfl)⟩ := r.nnreal_trichotomy
all_goals simp_all
end Real
section StrictMono
variable {Γ₀ : Type*} [LinearOrderedCommGroupWithZero Γ₀]
/-- If `Γ₀ˣ` is nontrivial and `f : Γ₀ →*₀ ℝ≥0` is strictly monotone, then for any positive
`r : ℝ≥0`, there exists `d : Γ₀ˣ` with `f d < r`. -/
theorem NNReal.exists_lt_of_strictMono [h : Nontrivial Γ₀ˣ] {f : Γ₀ →*₀ ℝ≥0} (hf : StrictMono f)
{r : ℝ≥0} (hr : 0 < r) : ∃ d : Γ₀ˣ, f d < r := by
obtain ⟨g, hg1⟩ := (nontrivial_iff_exists_ne (1 : Γ₀ˣ)).mp h
set u : Γ₀ˣ := if g < 1 then g else g⁻¹ with hu
have hfu : f u < 1 := by
rw [hu]
split_ifs with hu1
· rw [← map_one f]; exact hf hu1
· have hfg0 : f g ≠ 0 :=
fun h0 ↦ (Units.ne_zero g) ((map_eq_zero f).mp h0)
have hg1' : 1 < g := lt_of_le_of_ne (not_lt.mp hu1) hg1.symm
rw [Units.val_inv_eq_inv_val, map_inv₀, inv_lt_one_iff hfg0, ← map_one f]
exact hf hg1'
obtain ⟨n, hn⟩ := exists_pow_lt_of_lt_one hr hfu
use u ^ n
rwa [Units.val_pow_eq_pow_val, map_pow]
/-- If `Γ₀ˣ` is nontrivial and `f : Γ₀ →*₀ ℝ≥0` is strictly monotone, then for any positive
real `r`, there exists `d : Γ₀ˣ` with `f d < r`. -/
theorem Real.exists_lt_of_strictMono [h : Nontrivial Γ₀ˣ] {f : Γ₀ →*₀ ℝ≥0} (hf : StrictMono f)
{r : ℝ} (hr : 0 < r) : ∃ d : Γ₀ˣ, (f d : ℝ) < r := by
set s : NNReal := ⟨r, le_of_lt hr⟩
have hs : 0 < s := hr
exact NNReal.exists_lt_of_strictMono hf hs
end StrictMono
/-- While not very useful, this instance uses the same representation as `Real.instRepr`. -/
unsafe instance : Repr ℝ≥0 where
reprPrec r _ := f!"({repr r.val}).toNNReal"
namespace Mathlib.Meta.Positivity
open Lean Meta Qq
private alias ⟨_, nnreal_coe_pos⟩ := coe_pos
/-- Extension for the `positivity` tactic: cast from `ℝ≥0` to `ℝ`. -/
@[positivity NNReal.toReal _]
def evalNNRealtoReal : PositivityExt where eval {u α} _zα _pα e := do
match u, α, e with
| 0, ~q(ℝ), ~q(NNReal.toReal $a) =>
let ra ← core q(inferInstance) q(inferInstance) a
assertInstancesCommute
match ra with
| .positive pa => pure (.positive q(nnreal_coe_pos $pa))
| _ => pure (.nonnegative q(NNReal.coe_nonneg $a))
| _, _, _ => throwError "not NNReal.toReal"
end Mathlib.Meta.Positivity |
.lake/packages/mathlib/Mathlib/Data/Finset/Sum.lean | import Mathlib.Data.Finset.Card
import Mathlib.Data.Finset.Fold
import Mathlib.Data.Multiset.Sum
/-!
# Disjoint sum of finsets
This file defines the disjoint sum of two finsets as `Finset (α ⊕ β)`. Beware not to confuse with
the `Finset.sum` operation which computes the additive sum.
## Main declarations
* `Finset.disjSum`: `s.disjSum t` is the disjoint sum of `s` and `t`.
* `Finset.toLeft`: Given a finset of elements `α ⊕ β`, extracts all the elements of the form `α`.
* `Finset.toRight`: Given a finset of elements `α ⊕ β`, extracts all the elements of the form `β`.
-/
open Function Multiset Sum
namespace Finset
variable {α β γ : Type*} (s : Finset α) (t : Finset β)
/-- Disjoint sum of finsets. -/
def disjSum : Finset (α ⊕ β) :=
⟨s.1.disjSum t.1, s.2.disjSum t.2⟩
@[simp]
theorem val_disjSum : (s.disjSum t).1 = s.1.disjSum t.1 :=
rfl
@[simp]
theorem empty_disjSum : (∅ : Finset α).disjSum t = t.map Embedding.inr :=
val_inj.1 <| Multiset.zero_disjSum _
@[simp]
theorem disjSum_empty : s.disjSum (∅ : Finset β) = s.map Embedding.inl :=
val_inj.1 <| Multiset.disjSum_zero _
@[simp]
theorem card_disjSum : (s.disjSum t).card = s.card + t.card :=
Multiset.card_disjSum _ _
theorem disjoint_map_inl_map_inr : Disjoint (s.map Embedding.inl) (t.map Embedding.inr) := by
simp_rw [disjoint_left, mem_map]
rintro x ⟨a, _, rfl⟩ ⟨b, _, ⟨⟩⟩
@[simp]
theorem map_inl_disjUnion_map_inr :
(s.map Embedding.inl).disjUnion (t.map Embedding.inr) (disjoint_map_inl_map_inr _ _) =
s.disjSum t :=
rfl
variable {s t} {s₁ s₂ : Finset α} {t₁ t₂ : Finset β} {a : α} {b : β} {x : α ⊕ β}
theorem mem_disjSum : x ∈ s.disjSum t ↔ (∃ a, a ∈ s ∧ inl a = x) ∨ ∃ b, b ∈ t ∧ inr b = x :=
Multiset.mem_disjSum
@[simp]
theorem inl_mem_disjSum : inl a ∈ s.disjSum t ↔ a ∈ s :=
Multiset.inl_mem_disjSum
@[simp]
theorem inr_mem_disjSum : inr b ∈ s.disjSum t ↔ b ∈ t :=
Multiset.inr_mem_disjSum
@[simp]
theorem disjSum_eq_empty : s.disjSum t = ∅ ↔ s = ∅ ∧ t = ∅ := by simp [Finset.ext_iff]
theorem disjSum_mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : s₁.disjSum t₁ ⊆ s₂.disjSum t₂ :=
val_le_iff.1 <| Multiset.disjSum_mono (val_le_iff.2 hs) (val_le_iff.2 ht)
theorem disjSum_mono_left (t : Finset β) : Monotone fun s : Finset α => s.disjSum t :=
fun _ _ hs => disjSum_mono hs Subset.rfl
theorem disjSum_mono_right (s : Finset α) : Monotone (s.disjSum : Finset β → Finset (α ⊕ β)) :=
fun _ _ => disjSum_mono Subset.rfl
theorem disjSum_ssubset_disjSum_of_ssubset_of_subset (hs : s₁ ⊂ s₂) (ht : t₁ ⊆ t₂) :
s₁.disjSum t₁ ⊂ s₂.disjSum t₂ :=
val_lt_iff.1 <| disjSum_lt_disjSum_of_lt_of_le (val_lt_iff.2 hs) (val_le_iff.2 ht)
theorem disjSum_ssubset_disjSum_of_subset_of_ssubset (hs : s₁ ⊆ s₂) (ht : t₁ ⊂ t₂) :
s₁.disjSum t₁ ⊂ s₂.disjSum t₂ :=
val_lt_iff.1 <| disjSum_lt_disjSum_of_le_of_lt (val_le_iff.2 hs) (val_lt_iff.2 ht)
theorem disjSum_strictMono_left (t : Finset β) : StrictMono fun s : Finset α => s.disjSum t :=
fun _ _ hs => disjSum_ssubset_disjSum_of_ssubset_of_subset hs Subset.rfl
theorem disjSum_strictMono_right (s : Finset α) :
StrictMono (s.disjSum : Finset β → Finset (α ⊕ β)) := fun _ _ =>
disjSum_ssubset_disjSum_of_subset_of_ssubset Subset.rfl
@[deprecated (since := "2025-06-11")]
alias disj_sum_strictMono_right := disjSum_strictMono_right
@[simp] lemma disjSum_inj {α β : Type*} {s₁ s₂ : Finset α} {t₁ t₂ : Finset β} :
s₁.disjSum t₁ = s₂.disjSum t₂ ↔ s₁ = s₂ ∧ t₁ = t₂ := by
simp [Finset.ext_iff]
lemma Injective2_disjSum {α β : Type*} : Function.Injective2 (@disjSum α β) :=
fun _ _ _ _ => by simp [Finset.ext_iff]
/--
Given a finset of elements `α ⊕ β`, extract all the elements of the form `α`. This
forms a quasi-inverse to `disjSum`, in that it recovers its left input.
See also `List.partitionMap`.
-/
def toLeft (u : Finset (α ⊕ β)) : Finset α :=
u.filterMap (Sum.elim some fun _ => none) (by clear x; aesop)
/--
Given a finset of elements `α ⊕ β`, extract all the elements of the form `β`. This
forms a quasi-inverse to `disjSum`, in that it recovers its right input.
See also `List.partitionMap`.
-/
def toRight (u : Finset (α ⊕ β)) : Finset β :=
u.filterMap (Sum.elim (fun _ => none) some) (by clear x; aesop)
variable {u v : Finset (α ⊕ β)} {a : α} {b : β}
@[simp] lemma mem_toLeft : a ∈ u.toLeft ↔ .inl a ∈ u := by simp [toLeft]
@[simp] lemma mem_toRight : b ∈ u.toRight ↔ .inr b ∈ u := by simp [toRight]
@[gcongr]
lemma toLeft_subset_toLeft : u ⊆ v → u.toLeft ⊆ v.toLeft :=
fun h _ => by simpa only [mem_toLeft] using @h _
@[gcongr]
lemma toRight_subset_toRight : u ⊆ v → u.toRight ⊆ v.toRight :=
fun h _ => by simpa only [mem_toRight] using @h _
lemma toLeft_monotone : Monotone (@toLeft α β) := fun _ _ => toLeft_subset_toLeft
lemma toRight_monotone : Monotone (@toRight α β) := fun _ _ => toRight_subset_toRight
lemma toLeft_disjSum_toRight : u.toLeft.disjSum u.toRight = u := by
ext (x | x) <;> simp
lemma card_toLeft_add_card_toRight : #u.toLeft + #u.toRight = #u := by
rw [← card_disjSum, toLeft_disjSum_toRight]
lemma card_toLeft_le : #u.toLeft ≤ #u :=
(Nat.le_add_right _ _).trans_eq card_toLeft_add_card_toRight
lemma card_toRight_le : #u.toRight ≤ #u :=
(Nat.le_add_left _ _).trans_eq card_toLeft_add_card_toRight
@[simp] lemma toLeft_disjSum : (s.disjSum t).toLeft = s := by ext x; simp
@[simp] lemma toRight_disjSum : (s.disjSum t).toRight = t := by ext x; simp
lemma disjSum_eq_iff : s.disjSum t = u ↔ s = u.toLeft ∧ t = u.toRight :=
⟨fun h => by simp [← h], fun h => by simp [h, toLeft_disjSum_toRight]⟩
lemma eq_disjSum_iff : u = s.disjSum t ↔ u.toLeft = s ∧ u.toRight = t :=
⟨fun h => by simp [h], fun h => by simp [← h, toLeft_disjSum_toRight]⟩
lemma disjSum_subset : s.disjSum t ⊆ u ↔ s ⊆ u.toLeft ∧ t ⊆ u.toRight := by simp [subset_iff]
lemma subset_disjSum : u ⊆ s.disjSum t ↔ u.toLeft ⊆ s ∧ u.toRight ⊆ t := by simp [subset_iff]
lemma subset_map_inl : u ⊆ s.map .inl ↔ u.toLeft ⊆ s ∧ u.toRight = ∅ := by
simp [← disjSum_empty, subset_disjSum]
lemma subset_map_inr : u ⊆ t.map .inr ↔ u.toLeft = ∅ ∧ u.toRight ⊆ t := by
simp [← empty_disjSum, subset_disjSum]
lemma map_inl_subset_iff_subset_toLeft : s.map .inl ⊆ u ↔ s ⊆ u.toLeft := by
simp [← disjSum_empty, disjSum_subset]
lemma map_inr_subset_iff_subset_toRight : t.map .inr ⊆ u ↔ t ⊆ u.toRight := by
simp [← empty_disjSum, disjSum_subset]
lemma gc_map_inl_toLeft : GaloisConnection (·.map (.inl : α ↪ α ⊕ β)) toLeft :=
fun _ _ ↦ map_inl_subset_iff_subset_toLeft
lemma gc_map_inr_toRight : GaloisConnection (·.map (.inr : β ↪ α ⊕ β)) toRight :=
fun _ _ ↦ map_inr_subset_iff_subset_toRight
@[simp] lemma toLeft_map_sumComm : (u.map (Equiv.sumComm _ _).toEmbedding).toLeft = u.toRight := by
ext x; simp
@[simp] lemma toRight_map_sumComm : (u.map (Equiv.sumComm _ _).toEmbedding).toRight = u.toLeft := by
ext x; simp
@[simp] lemma toLeft_cons_inl (ha) :
(cons (inl a) u ha).toLeft = cons a u.toLeft (by simpa) := by ext y; simp
@[simp] lemma toLeft_cons_inr (hb) :
(cons (inr b) u hb).toLeft = u.toLeft := by ext y; simp
@[simp] lemma toRight_cons_inl (ha) :
(cons (inl a) u ha).toRight = u.toRight := by ext y; simp
@[simp] lemma toRight_cons_inr (hb) :
(cons (inr b) u hb).toRight = cons b u.toRight (by simpa) := by ext y; simp
section
variable [DecidableEq α] [DecidableEq β]
lemma toLeft_image_swap : (u.image Sum.swap).toLeft = u.toRight := by
ext x; simp
lemma toRight_image_swap : (u.image Sum.swap).toRight = u.toLeft := by
ext x; simp
@[simp] lemma toLeft_insert_inl : (insert (inl a) u).toLeft = insert a u.toLeft := by ext y; simp
@[simp] lemma toLeft_insert_inr : (insert (inr b) u).toLeft = u.toLeft := by ext y; simp
@[simp] lemma toRight_insert_inl : (insert (inl a) u).toRight = u.toRight := by ext y; simp
@[simp] lemma toRight_insert_inr : (insert (inr b) u).toRight = insert b u.toRight := by ext y; simp
lemma toLeft_inter : (u ∩ v).toLeft = u.toLeft ∩ v.toLeft := by ext x; simp
lemma toRight_inter : (u ∩ v).toRight = u.toRight ∩ v.toRight := by ext x; simp
lemma toLeft_union : (u ∪ v).toLeft = u.toLeft ∪ v.toLeft := by ext x; simp
lemma toRight_union : (u ∪ v).toRight = u.toRight ∪ v.toRight := by ext x; simp
lemma toLeft_sdiff : (u \ v).toLeft = u.toLeft \ v.toLeft := by ext x; simp
lemma toRight_sdiff : (u \ v).toRight = u.toRight \ v.toRight := by ext x; simp
end
/-- Finsets on sum types are equivalent to pairs of finsets on each summand. -/
@[simps apply_fst apply_snd]
def sumEquiv {α β : Type*} : Finset (α ⊕ β) ≃o Finset α × Finset β where
toFun s := (s.toLeft, s.toRight)
invFun s := disjSum s.1 s.2
left_inv s := toLeft_disjSum_toRight
right_inv s := by simp
map_rel_iff' := by simp [← Finset.coe_subset, Set.subset_def]
@[simp]
lemma sumEquiv_symm_apply {α β : Type*} (s : Finset α × Finset β) :
sumEquiv.symm s = disjSum s.1 s.2 := rfl
theorem map_disjSum (f : α ⊕ β ↪ γ) :
(s.disjSum t).map f =
(s.map (.trans .inl f)).disjUnion (t.map (.trans .inr f)) (by
as_aux_lemma =>
simpa only [← map_map]
using (Finset.disjoint_map f).2 (disjoint_map_inl_map_inr _ _)) :=
val_injective <| Multiset.map_disjSum _
lemma fold_disjSum (s : Finset α) (t : Finset β) (f : α ⊕ β → γ) (b₁ b₂ : γ) (op : γ → γ → γ)
[Std.Commutative op] [Std.Associative op] :
(s.disjSum t).fold op (op b₁ b₂) f =
op (s.fold op b₁ (f <| .inl ·)) (t.fold op b₂ (f <| .inr ·)) := by
simp_rw [fold, disjSum, Multiset.map_disjSum, fold_add]
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Fin.lean | import Mathlib.Data.Finset.Card
import Mathlib.Data.Fin.Embedding
/-!
# Finsets in `Fin n`
A few constructions for Finsets in `Fin n`.
## Main declarations
* `Finset.attachFin`: Turns a Finset of naturals strictly less than `n` into a `Finset (Fin n)`.
-/
variable {n : ℕ}
namespace Finset
/-- Given a Finset `s` of `ℕ` contained in `{0,..., n-1}`, the corresponding Finset in `Fin n`
is `s.attachFin h` where `h` is a proof that all elements of `s` are less than `n`. -/
def attachFin (s : Finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : Finset (Fin n) :=
⟨s.1.pmap (fun a ha ↦ ⟨a, ha⟩) h, s.nodup.pmap fun _ _ _ _ ↦ Fin.val_eq_of_eq⟩
@[simp]
theorem mem_attachFin {s : Finset ℕ} (h : ∀ m ∈ s, m < n) {a : Fin n} :
a ∈ s.attachFin h ↔ (a : ℕ) ∈ s :=
⟨fun h ↦
let ⟨_, hb₁, hb₂⟩ := Multiset.mem_pmap.1 h
hb₂ ▸ hb₁,
fun h ↦ Multiset.mem_pmap.2 ⟨a, h, Fin.eta _ _⟩⟩
@[simp]
lemma coe_attachFin {s : Finset ℕ} (h : ∀ m ∈ s, m < n) :
(attachFin s h : Set (Fin n)) = Fin.val ⁻¹' s := by
ext; simp
@[simp]
theorem card_attachFin (s : Finset ℕ) (h : ∀ m ∈ s, m < n) :
(s.attachFin h).card = s.card :=
Multiset.card_pmap _ _ _
@[simp]
lemma image_val_attachFin {s : Finset ℕ} (h : ∀ m ∈ s, m < n) :
image Fin.val (s.attachFin h) = s := by
apply coe_injective
rw [coe_image, coe_attachFin, Set.image_preimage_eq_iff]
exact fun m hm ↦ ⟨⟨m, h m hm⟩, rfl⟩
@[simp]
lemma map_valEmbedding_attachFin {s : Finset ℕ} (h : ∀ m ∈ s, m < n) :
map Fin.valEmbedding (s.attachFin h) = s := by
simp [map_eq_image]
@[simp]
lemma attachFin_subset_attachFin_iff {s t : Finset ℕ} (hs : ∀ m ∈ s, m < n) (ht : ∀ m ∈ t, m < n) :
s.attachFin hs ⊆ t.attachFin ht ↔ s ⊆ t := by
simp [← map_subset_map (f := Fin.valEmbedding)]
@[mono, gcongr]
lemma attachFin_subset_attachFin {s t : Finset ℕ} (hst : s ⊆ t) (ht : ∀ m ∈ t, m < n) :
s.attachFin (fun m hm ↦ ht m (hst hm)) ⊆ t.attachFin ht := by simpa
@[simp]
lemma attachFin_ssubset_attachFin_iff {s t : Finset ℕ} (hs : ∀ m ∈ s, m < n) (ht : ∀ m ∈ t, m < n) :
s.attachFin hs ⊂ t.attachFin ht ↔ s ⊂ t := by
simp [← map_ssubset_map (f := Fin.valEmbedding)]
@[mono, gcongr]
lemma attachFin_ssubset_attachFin {s t : Finset ℕ} (hst : s ⊂ t) (ht : ∀ m ∈ t, m < n) :
s.attachFin (fun m hm ↦ ht m (hst.subset hm)) ⊂ t.attachFin ht := by simpa
set_option linter.deprecated false
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Card.lean | import Mathlib.Data.Finset.Basic
import Mathlib.Data.Finset.Image
import Mathlib.Data.Finset.Lattice.Lemmas
/-!
# Cardinality of a finite set
This defines the cardinality of a `Finset` and provides induction principles for finsets.
## Main declarations
* `Finset.card`: `#s : ℕ` returns the cardinality of `s : Finset α`.
### Induction principles
* `Finset.strongInduction`: Strong induction
* `Finset.strongInductionOn`
* `Finset.strongDownwardInduction`
* `Finset.strongDownwardInductionOn`
* `Finset.case_strong_induction_on`
* `Finset.Nonempty.strong_induction`
* `Finset.eraseInduction`
-/
assert_not_exists Monoid
open Function Multiset Nat
variable {α β R : Type*}
namespace Finset
variable {s t : Finset α} {a b : α}
/-- `s.card` is the number of elements of `s`, aka its cardinality.
The notation `#s` can be accessed in the `Finset` locale. -/
def card (s : Finset α) : ℕ :=
Multiset.card s.1
@[inherit_doc] scoped prefix:arg "#" => Finset.card
theorem card_def (s : Finset α) : #s = Multiset.card s.1 :=
rfl
@[simp] lemma card_val (s : Finset α) : Multiset.card s.1 = #s := rfl
@[simp]
theorem card_mk {m nodup} : #(⟨m, nodup⟩ : Finset α) = Multiset.card m :=
rfl
@[simp, grind =]
theorem card_empty : #(∅ : Finset α) = 0 :=
rfl
@[gcongr]
theorem card_le_card : s ⊆ t → #s ≤ #t :=
Multiset.card_le_card ∘ val_le_iff.mpr
-- This pattern is unreasonable to use generally, but it's convenient in this file.
-- (Note that we turn it on again later in this file.)
local grind_pattern card_le_card => #s, #t
@[mono]
theorem card_mono : Monotone (@card α) := by apply card_le_card
@[simp] lemma card_eq_zero : #s = 0 ↔ s = ∅ := Multiset.card_eq_zero.trans val_eq_zero
lemma card_ne_zero : #s ≠ 0 ↔ s.Nonempty := card_eq_zero.ne.trans nonempty_iff_ne_empty.symm
@[simp] lemma card_pos : 0 < #s ↔ s.Nonempty := Nat.pos_iff_ne_zero.trans card_ne_zero
@[simp] lemma one_le_card : 1 ≤ #s ↔ s.Nonempty := card_pos
alias ⟨_, Nonempty.card_pos⟩ := card_pos
alias ⟨_, Nonempty.card_ne_zero⟩ := card_ne_zero
theorem card_ne_zero_of_mem (h : a ∈ s) : #s ≠ 0 :=
(not_congr card_eq_zero).2 <| ne_empty_of_mem h
grind_pattern card_ne_zero_of_mem => a ∈ s, #s
@[simp, grind =]
theorem card_singleton (a : α) : #{a} = 1 :=
Multiset.card_singleton _
theorem card_singleton_inter [DecidableEq α] : #({a} ∩ s) ≤ 1 := by grind
@[simp, grind =]
theorem card_cons (h : a ∉ s) : #(s.cons a h) = #s + 1 :=
Multiset.card_cons _ _
section InsertErase
variable [DecidableEq α]
@[simp, grind =]
theorem card_insert_of_notMem (h : a ∉ s) : #(insert a s) = #s + 1 := by
grind [=_ cons_eq_insert]
@[deprecated (since := "2025-05-23")] alias card_insert_of_not_mem := card_insert_of_notMem
theorem card_insert_of_mem (h : a ∈ s) : #(insert a s) = #s := by rw [insert_eq_of_mem h]
theorem card_insert_le (a : α) (s : Finset α) : #(insert a s) ≤ #s + 1 := by grind
section
variable {a b c d e f : α}
theorem card_le_two : #{a, b} ≤ 2 := card_insert_le _ _
theorem card_le_three : #{a, b, c} ≤ 3 :=
(card_insert_le _ _).trans (Nat.succ_le_succ card_le_two)
theorem card_le_four : #{a, b, c, d} ≤ 4 :=
(card_insert_le _ _).trans (Nat.succ_le_succ card_le_three)
theorem card_le_five : #{a, b, c, d, e} ≤ 5 :=
(card_insert_le _ _).trans (Nat.succ_le_succ card_le_four)
theorem card_le_six : #{a, b, c, d, e, f} ≤ 6 :=
(card_insert_le _ _).trans (Nat.succ_le_succ card_le_five)
end
/-- If `a ∈ s` is known, see also `Finset.card_insert_of_mem` and `Finset.card_insert_of_notMem`.
-/
theorem card_insert_eq_ite : #(insert a s) = if a ∈ s then #s else #s + 1 := by grind
@[simp]
theorem card_pair_eq_one_or_two : #{a, b} = 1 ∨ #{a, b} = 2 := by grind
theorem card_pair (h : a ≠ b) : #{a, b} = 2 := by
simp [h]
/-- $\#(s \setminus \{a\}) = \#s - 1$ if $a \in s$. -/
@[simp, grind =]
theorem card_erase_of_mem : a ∈ s → #(s.erase a) = #s - 1 :=
Multiset.card_erase_of_mem
-- @[simp] -- removed because LHS is not in simp normal form
theorem card_erase_add_one : a ∈ s → #(s.erase a) + 1 = #s :=
Multiset.card_erase_add_one
theorem card_erase_lt_of_mem : a ∈ s → #(s.erase a) < #s :=
Multiset.card_erase_lt_of_mem
theorem card_erase_le : #(s.erase a) ≤ #s :=
Multiset.card_erase_le
theorem pred_card_le_card_erase : #s - 1 ≤ #(s.erase a) := by grind
/-- If `a ∈ s` is known, see also `Finset.card_erase_of_mem` and `Finset.erase_eq_of_notMem`. -/
theorem card_erase_eq_ite : #(s.erase a) = if a ∈ s then #s - 1 else #s :=
Multiset.card_erase_eq_ite
end InsertErase
@[simp, grind =]
theorem card_range (n : ℕ) : #(range n) = n :=
Multiset.card_range n
@[simp, grind =]
theorem card_attach : #s.attach = #s :=
Multiset.card_attach
end Finset
open scoped Finset
section ToMultiset
variable [DecidableEq α] (m : Multiset α) (l : List α)
theorem Multiset.card_toFinset : #m.toFinset = Multiset.card m.dedup :=
rfl
theorem Multiset.toFinset_card_le : #m.toFinset ≤ Multiset.card m :=
card_le_card <| dedup_le _
theorem Multiset.toFinset_card_of_nodup {m : Multiset α} (h : m.Nodup) :
#m.toFinset = Multiset.card m :=
congr_arg card <| Multiset.dedup_eq_self.mpr h
theorem Multiset.dedup_card_eq_card_iff_nodup {m : Multiset α} :
card m.dedup = card m ↔ m.Nodup :=
.trans ⟨fun h ↦ eq_of_le_of_card_le (dedup_le m) h.ge, congr_arg _⟩ dedup_eq_self
theorem Multiset.toFinset_card_eq_card_iff_nodup {m : Multiset α} :
#m.toFinset = card m ↔ m.Nodup := dedup_card_eq_card_iff_nodup
theorem List.card_toFinset : #l.toFinset = l.dedup.length :=
rfl
theorem List.toFinset_card_le : #l.toFinset ≤ l.length :=
Multiset.toFinset_card_le ⟦l⟧
theorem List.toFinset_card_of_nodup {l : List α} (h : l.Nodup) : #l.toFinset = l.length :=
Multiset.toFinset_card_of_nodup h
end ToMultiset
namespace Finset
variable {s t u : Finset α} {f : α → β} {n : ℕ}
@[simp, grind =]
theorem length_toList (s : Finset α) : s.toList.length = #s := by
rw [toList, ← Multiset.coe_card, Multiset.coe_toList, card_def]
theorem card_image_le [DecidableEq β] : #(s.image f) ≤ #s := by
simpa only [card_map] using (s.1.map f).toFinset_card_le
grind_pattern card_image_le => #(s.image f)
grind_pattern card_image_le => s.image f, #s
theorem card_image_of_injOn [DecidableEq β] (H : Set.InjOn f s) : #(s.image f) = #s := by
simp only [card, image_val_of_injOn H, card_map]
theorem injOn_of_card_image_eq [DecidableEq β] (H : #(s.image f) = #s) : Set.InjOn f s := by
rw [card_def, card_def, image, toFinset] at H
dsimp only at H
have : (s.1.map f).dedup = s.1.map f := by
refine Multiset.eq_of_le_of_card_le (Multiset.dedup_le _) ?_
simp only [H, Multiset.card_map, le_rfl]
rw [Multiset.dedup_eq_self] at this
exact inj_on_of_nodup_map this
theorem card_image_iff [DecidableEq β] : #(s.image f) = #s ↔ Set.InjOn f s :=
⟨injOn_of_card_image_eq, card_image_of_injOn⟩
grind_pattern card_image_iff => #(s.image f)
grind_pattern card_image_iff => s.image f, #s
theorem card_image_of_injective [DecidableEq β] (s : Finset α) (H : Injective f) :
#(s.image f) = #s :=
card_image_of_injOn fun _ _ _ _ h => H h
theorem fiber_card_ne_zero_iff_mem_image (s : Finset α) (f : α → β) [DecidableEq β] (y : β) :
#(s.filter fun x ↦ f x = y) ≠ 0 ↔ y ∈ s.image f := by
rw [← Nat.pos_iff_ne_zero, card_pos, fiber_nonempty_iff_mem_image]
lemma card_filter_le_iff (s : Finset α) (P : α → Prop) [DecidablePred P] (n : ℕ) :
#(s.filter P) ≤ n ↔ ∀ s' ⊆ s, n < #s' → ∃ a ∈ s', ¬ P a :=
(s.1.card_filter_le_iff P n).trans ⟨fun H s' hs' h ↦ H s'.1 (by simp_all) h,
fun H s' hs' h ↦ H ⟨s', nodup_of_le hs' s.2⟩ (fun _ hx ↦ Multiset.subset_of_le hs' hx) h⟩
@[simp, grind =]
theorem card_map (f : α ↪ β) : #(s.map f) = #s :=
Multiset.card_map _ _
@[simp, grind =]
theorem card_subtype (p : α → Prop) [DecidablePred p] (s : Finset α) :
#(s.subtype p) = #(s.filter p) := by simp [Finset.subtype]
theorem card_filter_le (s : Finset α) (p : α → Prop) [DecidablePred p] :
#(s.filter p) ≤ #s :=
card_le_card <| filter_subset _ _
grind_pattern card_filter_le => #(s.filter p)
grind_pattern card_filter_le => s.filter p, #s
theorem eq_of_subset_of_card_le {s t : Finset α} (h : s ⊆ t) (h₂ : #t ≤ #s) : s = t :=
eq_of_veq <| Multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂
theorem eq_iff_card_le_of_subset (hst : s ⊆ t) : #t ≤ #s ↔ s = t :=
⟨eq_of_subset_of_card_le hst, (ge_of_eq <| congr_arg _ ·)⟩
theorem eq_of_superset_of_card_ge (hst : s ⊆ t) (hts : #t ≤ #s) : t = s :=
(eq_of_subset_of_card_le hst hts).symm
theorem eq_iff_card_ge_of_superset (hst : s ⊆ t) : #t ≤ #s ↔ t = s :=
(eq_iff_card_le_of_subset hst).trans eq_comm
theorem subset_iff_eq_of_card_le (h : #t ≤ #s) : s ⊆ t ↔ s = t :=
⟨fun hst => eq_of_subset_of_card_le hst h, Eq.subset'⟩
theorem map_eq_of_subset {f : α ↪ α} (hs : s.map f ⊆ s) : s.map f = s :=
eq_of_subset_of_card_le hs (card_map _).ge
theorem card_filter_eq_iff {p : α → Prop} [DecidablePred p] :
#(s.filter p) = #s ↔ ∀ x ∈ s, p x := by
rw [← (card_filter_le s p).ge_iff_eq, eq_iff_card_le_of_subset (filter_subset p s),
filter_eq_self]
alias ⟨filter_card_eq, _⟩ := card_filter_eq_iff
theorem card_filter_eq_zero_iff {p : α → Prop} [DecidablePred p] :
#(s.filter p) = 0 ↔ ∀ x ∈ s, ¬ p x := by
rw [card_eq_zero, filter_eq_empty_iff]
@[gcongr]
nonrec lemma card_lt_card (h : s ⊂ t) : #s < #t := card_lt_card <| val_lt_iff.2 h
lemma card_strictMono : StrictMono (card : Finset α → ℕ) := fun _ _ ↦ card_lt_card
section bij
/--
See also `card_bij`.
TODO: consider deprecating, since this has been unused in mathlib for a long time and is just a
special case of `card_bij`.
-/
theorem card_eq_of_bijective (f : ∀ i, i < n → α) (hf : ∀ a ∈ s, ∃ i, ∃ h : i < n, f i h = a)
(hf' : ∀ i (h : i < n), f i h ∈ s)
(f_inj : ∀ i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : #s = n := by
classical
have : s = (range n).attach.image fun i => f i.1 (mem_range.1 i.2) := by
ext a
suffices _ : a ∈ s ↔ ∃ (i : _) (hi : i ∈ range n), f i (mem_range.1 hi) = a by
simpa only [mem_image, mem_attach, true_and, Subtype.exists]
constructor
· intro ha; obtain ⟨i, hi, rfl⟩ := hf a ha; use i, mem_range.2 hi
· rintro ⟨i, hi, rfl⟩; apply hf'
calc
#s = #((range n).attach.image fun i => f i.1 (mem_range.1 i.2)) := by rw [this]
_ = #(range n).attach := ?_
_ = #(range n) := card_attach
_ = n := card_range n
apply card_image_of_injective
intro ⟨i, hi⟩ ⟨j, hj⟩ eq
exact Subtype.eq <| f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq
variable {t : Finset β}
/-- Given a bijection from a finite set `s` to a finite set `t`, the cardinalities of `s` and `t`
are equal.
The difference with `Finset.card_bij'` is that the bijection is specified as a surjective injection,
rather than by an inverse function.
The difference with `Finset.card_nbij` is that the bijection is allowed to use membership of the
domain, rather than being a non-dependent function. -/
lemma card_bij (i : ∀ a ∈ s, β) (hi : ∀ a ha, i a ha ∈ t)
(i_inj : ∀ a₁ ha₁ a₂ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂)
(i_surj : ∀ b ∈ t, ∃ a ha, i a ha = b) : #s = #t := by
classical
calc
#s = #s.attach := card_attach.symm
_ = #(s.attach.image fun a ↦ i a.1 a.2) := Eq.symm ?_
_ = #t := ?_
· apply card_image_of_injective
intro ⟨_, _⟩ ⟨_, _⟩ h
simpa using i_inj _ _ _ _ h
· congr 1
ext b
constructor <;> intro h
· obtain ⟨_, _, rfl⟩ := mem_image.1 h; apply hi
· obtain ⟨a, ha, rfl⟩ := i_surj b h; exact mem_image.2 ⟨⟨a, ha⟩, by simp⟩
/-- Given a bijection from a finite set `s` to a finite set `t`, the cardinalities of `s` and `t`
are equal.
The difference with `Finset.card_bij` is that the bijection is specified with an inverse, rather
than as a surjective injection.
The difference with `Finset.card_nbij'` is that the bijection and its inverse are allowed to use
membership of the domains, rather than being non-dependent functions. -/
lemma card_bij' (i : ∀ a ∈ s, β) (j : ∀ a ∈ t, α) (hi : ∀ a ha, i a ha ∈ t)
(hj : ∀ a ha, j a ha ∈ s) (left_inv : ∀ a ha, j (i a ha) (hi a ha) = a)
(right_inv : ∀ a ha, i (j a ha) (hj a ha) = a) : #s = #t := by
refine card_bij i hi (fun a1 h1 a2 h2 eq ↦ ?_) (fun b hb ↦ ⟨_, hj b hb, right_inv b hb⟩)
rw [← left_inv a1 h1, ← left_inv a2 h2]
simp only [eq]
/-- Given a bijection from a finite set `s` to a finite set `t`, the cardinalities of `s` and `t`
are equal.
The difference with `Finset.card_nbij'` is that the bijection is specified as a surjective
injection, rather than by an inverse function.
The difference with `Finset.card_bij` is that the bijection is a non-dependent function, rather than
being allowed to use membership of the domain. -/
lemma card_nbij (i : α → β) (hi : Set.MapsTo i s t) (i_inj : (s : Set α).InjOn i)
(i_surj : (s : Set α).SurjOn i t) : #s = #t :=
card_bij (fun a _ ↦ i a) hi i_inj (by simpa using i_surj)
/-- Given a bijection from a finite set `s` to a finite set `t`, the cardinalities of `s` and `t`
are equal.
The difference with `Finset.card_nbij` is that the bijection is specified with an inverse, rather
than as a surjective injection.
The difference with `Finset.card_bij'` is that the bijection and its inverse are non-dependent
functions, rather than being allowed to use membership of the domains.
The difference with `Finset.card_equiv` is that bijectivity is only required to hold on the domains,
rather than on the entire types. -/
lemma card_nbij' (i : α → β) (j : β → α) (hi : Set.MapsTo i s t) (hj : Set.MapsTo j t s)
(left_inv : Set.LeftInvOn j i s) (right_inv : Set.RightInvOn j i t) : #s = #t :=
card_bij' (fun a _ ↦ i a) (fun b _ ↦ j b) hi hj left_inv right_inv
/-- Specialization of `Finset.card_nbij'` that automatically fills in most arguments.
See `Fintype.card_equiv` for the version where `s` and `t` are `univ`. -/
lemma card_equiv (e : α ≃ β) (hst : ∀ i, i ∈ s ↔ e i ∈ t) : #s = #t := by
refine card_nbij' e e.symm ?_ ?_ ?_ ?_ <;> simp [hst, Set.MapsTo, Set.LeftInvOn, Set.RightInvOn]
/-- Specialization of `Finset.card_nbij` that automatically fills in most arguments.
See `Fintype.card_bijective` for the version where `s` and `t` are `univ`. -/
lemma card_bijective (e : α → β) (he : e.Bijective) (hst : ∀ i, i ∈ s ↔ e i ∈ t) :
#s = #t := card_equiv (.ofBijective e he) hst
lemma _root_.Set.BijOn.finsetCard_eq (e : α → β) (he : Set.BijOn e s t) : #s = #t :=
card_nbij e he.mapsTo he.injOn he.surjOn
lemma card_le_card_of_injOn (f : α → β) (hf : Set.MapsTo f s t) (f_inj : (s : Set α).InjOn f) :
#s ≤ #t := by
classical
calc
#s = #(s.image f) := (card_image_of_injOn f_inj).symm
_ ≤ #t := card_le_card <| image_subset_iff.2 hf
lemma card_le_card_of_injective {f : s → t} (hf : f.Injective) : #s ≤ #t := by
rcases s.eq_empty_or_nonempty with rfl | ⟨a₀, ha₀⟩
· simp
· classical
let f' : α → β := fun a => f (if ha : a ∈ s then ⟨a, ha⟩ else ⟨a₀, ha₀⟩)
apply card_le_card_of_injOn f'
· aesop (add safe unfold Set.MapsTo)
· intro a₁ ha₁ a₂ ha₂ haa
rw [mem_coe] at ha₁ ha₂
simp only [f', ha₁, ha₂, ← Subtype.ext_iff] at haa
exact Subtype.ext_iff.mp (hf haa)
grind_pattern card_le_card_of_injective => f.Injective, #s
grind_pattern card_le_card_of_injective => f.Injective, #t
lemma card_le_card_of_surjOn (f : α → β) (hf : Set.SurjOn f s t) : #t ≤ #s := by
classical unfold Set.SurjOn at hf; exact (card_le_card (mod_cast hf)).trans card_image_le
/-- If there are more pigeons than pigeonholes, then there are two pigeons in the same pigeonhole.
See also `Set.exists_ne_map_eq_of_encard_lt_of_maps_to` and
`Set.exists_ne_map_eq_of_ncard_lt_of_maps_to`. -/
theorem exists_ne_map_eq_of_card_lt_of_maps_to (hc : #t < #s) {f : α → β}
(hf : Set.MapsTo f s t) : ∃ x ∈ s, ∃ y ∈ s, x ≠ y ∧ f x = f y := by
classical
by_contra! hz
refine hc.not_ge (card_le_card_of_injOn f hf ?_)
intro x hx y hy
contrapose
exact hz x hx y hy
/-- a special case of `Finset.exists_ne_map_eq_of_card_lt_of_maps_to` where `t` is `s.image f` -/
theorem exists_ne_map_eq_of_card_image_lt [DecidableEq β] {f : α → β} (hc : #(s.image f) < #s) :
∃ x ∈ s, ∃ y ∈ s, x ≠ y ∧ f x = f y :=
exists_ne_map_eq_of_card_lt_of_maps_to hc (coe_image (β := β) ▸ Set.mapsTo_image f s)
/-- a variant of `Finset.exists_ne_map_eq_of_card_image_lt` using `Set.InjOn` -/
theorem not_injOn_of_card_image_lt [DecidableEq β] {f : α → β} (hc : #(s.image f) < #s) :
¬ Set.InjOn f s :=
mt card_image_of_injOn hc.ne
/--
See also `Finset.card_le_card_of_injOn`, which is a more general version of this lemma.
TODO: consider deprecating, since this is just a special case of `Finset.card_le_card_of_injOn`.
-/
lemma le_card_of_inj_on_range (f : ℕ → α) (hf : ∀ i < n, f i ∈ s)
(f_inj : ∀ i < n, ∀ j < n, f i = f j → i = j) : n ≤ #s :=
calc
n = #(range n) := (card_range n).symm
_ ≤ #s := card_le_card_of_injOn f (by simpa [Set.MapsTo, mem_range] using hf) (by simpa)
/--
Given an injective map `f` from a finite set `s` to another finite set `t`, if `t` is no larger
than `s`, then `f` is surjective to `t` when restricted to `s`.
See `Finset.surj_on_of_inj_on_of_card_le` for the version where `f` is a dependent function.
-/
lemma surjOn_of_injOn_of_card_le (f : α → β) (hf : Set.MapsTo f s t) (hinj : Set.InjOn f s)
(hst : #t ≤ #s) : Set.SurjOn f s t := by
classical
suffices s.image f = t by simp [← this, Set.SurjOn]
have : s.image f ⊆ t := by aesop (add simp Finset.subset_iff)
exact eq_of_subset_of_card_le this (hst.trans_eq (card_image_of_injOn hinj).symm)
/--
Given an injective map `f` defined on a finite set `s` to another finite set `t`, if `t` is no
larger than `s`, then `f` is surjective to `t` when restricted to `s`.
See `Finset.surjOn_of_injOn_of_card_le` for the version where `f` is a non-dependent function.
-/
lemma surj_on_of_inj_on_of_card_le (f : ∀ a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t)
(hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : #t ≤ #s) :
∀ b ∈ t, ∃ a ha, b = f a ha := by
let f' : s → β := fun a ↦ f a a.2
have hinj' : Set.InjOn f' s.attach := fun x hx y hy hxy ↦ Subtype.ext (hinj _ _ x.2 y.2 hxy)
have hmapsto' : Set.MapsTo f' s.attach t := fun x hx ↦ hf _ _
intro b hb
obtain ⟨a, ha, rfl⟩ := surjOn_of_injOn_of_card_le _ hmapsto' hinj' (by rwa [card_attach]) hb
exact ⟨a, a.2, rfl⟩
/--
Given a surjective map `f` from a finite set `s` to another finite set `t`, if `s` is no larger
than `t`, then `f` is injective when restricted to `s`.
See `Finset.inj_on_of_surj_on_of_card_le` for the version where `f` is a dependent function.
-/
lemma injOn_of_surjOn_of_card_le (f : α → β) (hf : Set.MapsTo f s t) (hsurj : Set.SurjOn f s t)
(hst : #s ≤ #t) : Set.InjOn f s := by
classical
have : s.image f = t := Finset.coe_injective <| by simp [hsurj.image_eq_of_mapsTo hf]
have : #(s.image f) = #t := by rw [this]
have : #(s.image f) ≤ #s := card_image_le
rw [← card_image_iff]
cutsat
/--
Given a surjective map `f` defined on a finite set `s` to another finite set `t`, if `s` is no
larger than `t`, then `f` is injective when restricted to `s`.
See `Finset.injOn_of_surjOn_of_card_le` for the version where `f` is a non-dependent function.
-/
theorem inj_on_of_surj_on_of_card_le (f : ∀ a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t)
(hsurj : ∀ b ∈ t, ∃ a ha, f a ha = b) (hst : #s ≤ #t) ⦃a₁⦄ (ha₁ : a₁ ∈ s) ⦃a₂⦄
(ha₂ : a₂ ∈ s) (ha₁a₂ : f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ := by
let f' : s → β := fun a ↦ f a a.2
have hsurj' : Set.SurjOn f' s.attach t := fun x hx ↦ by simpa [f'] using hsurj x hx
have hinj' := injOn_of_surjOn_of_card_le f' (fun x hx ↦ hf _ _) hsurj' (by simpa)
exact congrArg Subtype.val (@hinj' ⟨a₁, ha₁⟩ (by simp) ⟨a₂, ha₂⟩ (by simp) ha₁a₂)
end bij
@[simp, grind =]
theorem card_disjUnion (s t : Finset α) (h) : #(s.disjUnion t h) = #s + #t :=
Multiset.card_add _ _
/-! ### Lattice structure -/
-- This pattern is unreasonable to use generally, but it's convenient in this file.
-- (Note that we've already turned it on earlier in this file, but need to redo it now.)
local grind_pattern card_le_card => #s, #t
section Lattice
variable [DecidableEq α]
theorem card_union_add_card_inter (s t : Finset α) :
#(s ∪ t) + #(s ∩ t) = #s + #t :=
Finset.induction_on t (by simp) (by grind)
grind_pattern card_union_add_card_inter => #(s ∪ t), s ∩ t
grind_pattern card_union_add_card_inter => s ∪ t, #(s ∩ t)
grind_pattern card_union_add_card_inter => #(s ∪ t), #s
grind_pattern card_union_add_card_inter => #(s ∪ t), #t
grind_pattern card_union_add_card_inter => #(s ∩ t), #s
grind_pattern card_union_add_card_inter => #(s ∩ t), #t
theorem card_inter_add_card_union (s t : Finset α) :
#(s ∩ t) + #(s ∪ t) = #s + #t := by grind
lemma card_union (s t : Finset α) : #(s ∪ t) = #s + #t - #(s ∩ t) := by grind
lemma card_inter (s t : Finset α) : #(s ∩ t) = #s + #t - #(s ∪ t) := by grind
theorem card_union_le (s t : Finset α) : #(s ∪ t) ≤ #s + #t := by grind
lemma card_union_eq_card_add_card : #(s ∪ t) = #s + #t ↔ Disjoint s t := by
rw [← card_union_add_card_inter]; simp [disjoint_iff_inter_eq_empty]
@[simp] alias ⟨_, card_union_of_disjoint⟩ := card_union_eq_card_add_card
@[grind =]
theorem card_sdiff_of_subset (h : s ⊆ t) : #(t \ s) = #t - #s := by
suffices #(t \ s) = #(t \ s ∪ s) - #s by rwa [sdiff_union_of_subset h] at this
rw [card_union_of_disjoint sdiff_disjoint, Nat.add_sub_cancel_right]
@[grind =]
theorem card_sdiff : #(t \ s) = #t - #(s ∩ t) := by
rw [← card_sdiff_of_subset] <;> grind
theorem card_sdiff_add_card_eq_card {s t : Finset α} (h : s ⊆ t) : #(t \ s) + #s = #t := by grind
theorem le_card_sdiff (s t : Finset α) : #t - #s ≤ #(t \ s) :=
calc
#t - #s ≤ #t - #(s ∩ t) := by grind
_ = #(t \ (s ∩ t)) := by grind
_ ≤ #(t \ s) := by grind
grind_pattern le_card_sdiff => #(t \ s), #t
grind_pattern le_card_sdiff => #(t \ s), #s
theorem card_le_card_sdiff_add_card : #s ≤ #(s \ t) + #t := by grind
theorem card_sdiff_add_card (s t : Finset α) : #(s \ t) + #t = #(s ∪ t) := by
rw [← card_union_of_disjoint sdiff_disjoint, sdiff_union_self_eq_union]
theorem sdiff_nonempty_of_card_lt_card (h : #s < #t) : (t \ s).Nonempty := by
rw [nonempty_iff_ne_empty, Ne, sdiff_eq_empty_iff_subset]
exact fun h' ↦ h.not_ge (card_le_card h')
omit [DecidableEq α] in
theorem exists_mem_notMem_of_card_lt_card (h : #s < #t) : ∃ e, e ∈ t ∧ e ∉ s := by
classical simpa [Finset.Nonempty] using sdiff_nonempty_of_card_lt_card h
@[deprecated (since := "2025-05-23")]
alias exists_mem_not_mem_of_card_lt_card := exists_mem_notMem_of_card_lt_card
@[simp]
lemma card_sdiff_add_card_inter (s t : Finset α) :
#(s \ t) + #(s ∩ t) = #s := by
rw [← card_union_of_disjoint (disjoint_sdiff_inter _ _), sdiff_union_inter]
grind_pattern card_sdiff_add_card_inter => #(s \ t), #(s ∩ t)
grind_pattern card_sdiff_add_card_inter => #(s \ t), #s
@[simp]
lemma card_inter_add_card_sdiff (s t : Finset α) :
#(s ∩ t) + #(s \ t) = #s := by grind
lemma card_sdiff_le_card_sdiff_iff : #(s \ t) ≤ #(t \ s) ↔ #s ≤ #t := by grind
lemma card_sdiff_lt_card_sdiff_iff : #(s \ t) < #(t \ s) ↔ #s < #t := by grind
lemma card_sdiff_eq_card_sdiff_iff : #(s \ t) = #(t \ s) ↔ #s = #t := by grind
alias ⟨_, card_sdiff_comm⟩ := card_sdiff_eq_card_sdiff_iff
/-- **Pigeonhole principle** for two finsets inside an ambient finset. -/
theorem inter_nonempty_of_card_lt_card_add_card (hts : t ⊆ s) (hus : u ⊆ s)
(hstu : #s < #t + #u) : (t ∩ u).Nonempty := by
contrapose! hstu
calc
_ = #(t ∪ u) := by simp [← card_union_add_card_inter, not_nonempty_iff_eq_empty.1 hstu]
_ ≤ #s := by gcongr; exact union_subset hts hus
end Lattice
theorem filter_card_add_filter_neg_card_eq_card
(p : α → Prop) [DecidablePred p] [∀ x, Decidable (¬p x)] :
#(s.filter p) + #(s.filter fun a ↦ ¬ p a) = #s := by
classical
rw [← card_union_of_disjoint (disjoint_filter_filter_neg _ _ _), filter_union_filter_neg_eq]
/-- Given a subset `s` of a set `t`, of sizes at most and at least `n` respectively, there exists a
set `u` of size `n` which is both a superset of `s` and a subset of `t`. -/
lemma exists_subsuperset_card_eq (hst : s ⊆ t) (hsn : #s ≤ n) (hnt : n ≤ #t) :
∃ u, s ⊆ u ∧ u ⊆ t ∧ #u = n := by
classical
refine Nat.decreasingInduction' ?_ hnt ⟨t, by simp [hst]⟩
intro k _ hnk ⟨u, hu₁, hu₂, hu₃⟩
obtain ⟨a, ha⟩ : (u \ s).Nonempty := by grind
exact ⟨u.erase a, by grind⟩
/-- We can shrink a set to any smaller size. -/
lemma exists_subset_card_eq (hns : n ≤ #s) : ∃ t ⊆ s, #t = n := by
simpa using exists_subsuperset_card_eq s.empty_subset (by simp) hns
theorem le_card_iff_exists_subset_card : n ≤ #s ↔ ∃ t ⊆ s, #t = n := by
refine ⟨fun h => ?_, fun ⟨t, hst, ht⟩ => ht ▸ card_le_card hst⟩
exact exists_subset_card_eq h
theorem exists_subset_or_subset_of_two_mul_lt_card [DecidableEq α] {X Y : Finset α} {n : ℕ}
(hXY : 2 * n < #(X ∪ Y)) : ∃ C : Finset α, n < #C ∧ (C ⊆ X ∨ C ⊆ Y) := by
have h₁ : #(X ∩ (Y \ X)) = 0 := Finset.card_eq_zero.mpr (by grind)
have h₂ : #(X ∪ Y) = #X + #(Y \ X) := by grind
obtain h | h : n < #X ∨ n < #(Y \ X) := by cutsat
· exact ⟨X, by grind⟩
· exact ⟨Y \ X, by grind⟩
/-! ### Explicit description of a finset from its card -/
theorem card_eq_one : #s = 1 ↔ ∃ a, s = {a} := by
cases s
simp only [Multiset.card_eq_one, Finset.card, ← val_inj, singleton_val]
theorem exists_eq_insert_iff [DecidableEq α] {s t : Finset α} :
(∃ a ∉ s, insert a s = t) ↔ s ⊆ t ∧ #s + 1 = #t := by
constructor
· grind
· rintro ⟨hst, h⟩
obtain ⟨a, ha⟩ : ∃ a, t \ s = {a} := card_eq_one.mp (by grind)
exact
⟨a, fun hs => (by grind : a ∉ {a}) <| mem_singleton_self _, by
rw [insert_eq, ← ha, sdiff_union_of_subset hst]⟩
theorem card_le_one : #s ≤ 1 ↔ ∀ a ∈ s, ∀ b ∈ s, a = b := by
obtain rfl | ⟨x, hx⟩ := s.eq_empty_or_nonempty
· simp
refine (Nat.succ_le_of_lt (card_pos.2 ⟨x, hx⟩)).ge_iff_eq'.trans (card_eq_one.trans ⟨?_, ?_⟩)
· grind
· exact fun h => ⟨x, by grind⟩
theorem card_le_one_iff : #s ≤ 1 ↔ ∀ {a b}, a ∈ s → b ∈ s → a = b := by
grind [card_le_one]
theorem card_le_one_iff_subsingleton_coe : #s ≤ 1 ↔ Subsingleton (s : Type _) :=
card_le_one.trans (s : Set α).subsingleton_coe.symm
theorem card_le_one_iff_subset_singleton [Nonempty α] : #s ≤ 1 ↔ ∃ x : α, s ⊆ {x} := by
refine ⟨fun H => ?_, ?_⟩
· obtain rfl | ⟨x, hx⟩ := s.eq_empty_or_nonempty
· exact ⟨Classical.arbitrary α, empty_subset _⟩
· exact ⟨x, fun y hy => by rw [card_le_one.1 H y hy x hx, mem_singleton]⟩
· rintro ⟨x, hx⟩
rw [← card_singleton x]
exact card_le_card hx
lemma exists_mem_ne (hs : 1 < #s) (a : α) : ∃ b ∈ s, b ≠ a := by
have : Nonempty α := ⟨a⟩
by_contra!
exact hs.not_ge (card_le_one_iff_subset_singleton.2 ⟨a, subset_singleton_iff'.2 this⟩)
/-- A `Finset` of a subsingleton type has cardinality at most one. -/
theorem card_le_one_of_subsingleton [Subsingleton α] (s : Finset α) : #s ≤ 1 :=
Finset.card_le_one_iff.2 fun {_ _ _ _} => Subsingleton.elim _ _
theorem one_lt_card : 1 < #s ↔ ∃ a ∈ s, ∃ b ∈ s, a ≠ b := by
rw [← not_iff_not]
push_neg
exact card_le_one
theorem one_lt_card_iff : 1 < #s ↔ ∃ a b, a ∈ s ∧ b ∈ s ∧ a ≠ b := by
rw [one_lt_card]
simp only [exists_and_left]
theorem one_lt_card_iff_nontrivial : 1 < #s ↔ s.Nontrivial := by
rw [← not_iff_not, not_lt, Finset.Nontrivial, ← Set.nontrivial_coe_sort,
not_nontrivial_iff_subsingleton, card_le_one_iff_subsingleton_coe, coe_sort_coe]
@[deprecated (since := "2025-08-14")] alias exists_ne_of_one_lt_card := exists_mem_ne
/-- If a Finset in a Pi type is nontrivial (has at least two elements), then
its projection to some factor is nontrivial, and the fibers of the projection
are proper subsets. -/
lemma exists_of_one_lt_card_pi {ι : Type*} {α : ι → Type*} [∀ i, DecidableEq (α i)]
{s : Finset (∀ i, α i)} (h : 1 < #s) :
∃ i, 1 < #(s.image (· i)) ∧ ∀ ai, s.filter (· i = ai) ⊂ s := by
simp_rw [one_lt_card_iff, Function.ne_iff] at h ⊢
obtain ⟨a1, a2, h1, h2, i, hne⟩ := h
refine ⟨i, ⟨_, _, mem_image_of_mem _ h1, mem_image_of_mem _ h2, hne⟩, fun ai => ?_⟩
rw [filter_ssubset]
obtain rfl | hne := eq_or_ne (a2 i) ai
exacts [⟨a1, h1, hne⟩, ⟨a2, h2, hne⟩]
theorem card_eq_succ_iff_cons :
#s = n + 1 ↔ ∃ a t, ∃ (h : a ∉ t), cons a t h = s ∧ #t = n :=
⟨cons_induction_on s (by simp) fun a s _ _ _ => ⟨a, s, by simp_all⟩,
fun ⟨a, t, _, hs, _⟩ => by simpa [← hs]⟩
section DecidableEq
variable [DecidableEq α]
theorem card_eq_succ : #s = n + 1 ↔ ∃ a t, a ∉ t ∧ insert a t = s ∧ #t = n :=
⟨fun h =>
let ⟨a, has⟩ := card_pos.mp (h.symm ▸ Nat.zero_lt_succ _ : 0 < #s)
⟨a, s.erase a, s.notMem_erase a, insert_erase has, by
simp only [h, card_erase_of_mem has, Nat.add_sub_cancel_right]⟩,
fun ⟨_, _, hat, s_eq, n_eq⟩ => s_eq ▸ n_eq ▸ card_insert_of_notMem hat⟩
theorem card_eq_two : #s = 2 ↔ ∃ x y, x ≠ y ∧ s = {x, y} := by
constructor
· rw [card_eq_succ]
grind [card_eq_one]
· grind
theorem card_eq_three : #s = 3 ↔ ∃ x y z, x ≠ y ∧ x ≠ z ∧ y ≠ z ∧ s = {x, y, z} := by
constructor
· rw [card_eq_succ]
grind [card_eq_two]
· grind
theorem card_eq_four : #s = 4 ↔
∃ x y z w, x ≠ y ∧ x ≠ z ∧ x ≠ w ∧ y ≠ z ∧ y ≠ w ∧ z ≠ w ∧ s = {x, y, z, w} := by
constructor
· rw [card_eq_succ]
grind [card_eq_three]
· grind
end DecidableEq
theorem two_lt_card_iff : 2 < #s ↔ ∃ a b c, a ∈ s ∧ b ∈ s ∧ c ∈ s ∧ a ≠ b ∧ a ≠ c ∧ b ≠ c := by
classical
simp_rw [lt_iff_add_one_le, le_card_iff_exists_subset_card, reduceAdd, card_eq_three,
← exists_and_left, exists_comm (α := Finset α)]
constructor
· rintro ⟨a, b, c, t, hsub, hab, hac, hbc, rfl⟩
exact ⟨a, b, c, by simp_all [insert_subset_iff]⟩
· rintro ⟨a, b, c, ha, hb, hc, hab, hac, hbc⟩
exact ⟨a, b, c, {a, b, c}, by simp_all [insert_subset_iff]⟩
theorem two_lt_card : 2 < #s ↔ ∃ a ∈ s, ∃ b ∈ s, ∃ c ∈ s, a ≠ b ∧ a ≠ c ∧ b ≠ c := by
simp_rw [two_lt_card_iff, exists_and_left]
theorem three_lt_card_iff : 3 < #s ↔
∃ a b c d, a ∈ s ∧ b ∈ s ∧ c ∈ s ∧ d ∈ s ∧
a ≠ b ∧ a ≠ c ∧ a ≠ d ∧ b ≠ c ∧ b ≠ d ∧ c ≠ d := by
classical
simp_rw [lt_iff_add_one_le, le_card_iff_exists_subset_card, reduceAdd, card_eq_four,
← exists_and_left, exists_comm (α := Finset α)]
constructor
· rintro ⟨a, b, c, d, t, hsub, hab, hac, had, hbc, hbd, hcd, rfl⟩
exact ⟨a, b, c, d, by simp_all [insert_subset_iff]⟩
· rintro ⟨a, b, c, d, ha, hb, hc, hd, hab, hac, had, hbc, hbd, hcd⟩
exact ⟨a, b, c, d, {a, b, c, d}, by simp_all [insert_subset_iff]⟩
theorem three_lt_card : 3 < #s ↔ ∃ a ∈ s, ∃ b ∈ s, ∃ c ∈ s, ∃ d ∈ s,
a ≠ b ∧ a ≠ c ∧ a ≠ d ∧ b ≠ c ∧ b ≠ d ∧ c ≠ d := by
simp_rw [three_lt_card_iff, exists_and_left]
/-! ### Inductions -/
/-- Suppose that, given objects defined on all strict subsets of any finset `s`, one knows how to
define an object on `s`. Then one can inductively define an object on all finsets, starting from
the empty set and iterating. This can be used either to define data, or to prove properties. -/
def strongInduction {p : Finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s) :
∀ s : Finset α, p s
| s =>
H s fun t h =>
have : #t < #s := card_lt_card h
strongInduction H t
termination_by s => #s
theorem strongInduction_eq {p : Finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s)
(s : Finset α) : strongInduction H s = H s fun t _ => strongInduction H t := by
rw [strongInduction]
/-- Analogue of `strongInduction` with order of arguments swapped. -/
@[elab_as_elim]
def strongInductionOn {p : Finset α → Sort*} (s : Finset α) :
(∀ s, (∀ t ⊂ s, p t) → p s) → p s := fun H => strongInduction H s
theorem strongInductionOn_eq {p : Finset α → Sort*} (s : Finset α)
(H : ∀ s, (∀ t ⊂ s, p t) → p s) :
s.strongInductionOn H = H s fun t _ => t.strongInductionOn H := by
dsimp only [strongInductionOn]
rw [strongInduction]
@[elab_as_elim]
theorem case_strong_induction_on [DecidableEq α] {p : Finset α → Prop} (s : Finset α) (h₀ : p ∅)
(h₁ : ∀ a s, a ∉ s → (∀ t ⊆ s, p t) → p (insert a s)) : p s :=
Finset.strongInductionOn s fun s =>
Finset.induction_on s (fun _ => h₀) fun a s n _ ih =>
(h₁ a s n) fun t ss => ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _)
/-- Suppose that, given objects defined on all nonempty strict subsets of any nontrivial finset `s`,
one knows how to define an object on `s`. Then one can inductively define an object on all finsets,
starting from singletons and iterating.
TODO: Currently this can only be used to prove properties.
Replace `Finset.Nonempty.exists_eq_singleton_or_nontrivial` with computational content
in order to let `p` be `Sort`-valued. -/
@[elab_as_elim]
protected lemma Nonempty.strong_induction {p : ∀ s, s.Nonempty → Prop}
(h₀ : ∀ a, p {a} (singleton_nonempty _))
(h₁ : ∀ ⦃s⦄ (hs : s.Nontrivial), (∀ t ht, t ⊂ s → p t ht) → p s hs.nonempty) :
∀ ⦃s : Finset α⦄ (hs), p s hs
| s, hs => by
obtain ⟨a, rfl⟩ | hs := hs.exists_eq_singleton_or_nontrivial
· exact h₀ _
· refine h₁ hs fun t ht hts ↦ ?_
have := card_lt_card hts
exact ht.strong_induction h₀ h₁
termination_by s => #s
/-- Suppose that, given that `p t` can be defined on all supersets of `s` of cardinality less than
`n`, one knows how to define `p s`. Then one can inductively define `p s` for all finsets `s` of
cardinality less than `n`, starting from finsets of card `n` and iterating. This
can be used either to define data, or to prove properties. -/
def strongDownwardInduction {p : Finset α → Sort*} {n : ℕ}
(H : ∀ t₁, (∀ {t₂ : Finset α}, #t₂ ≤ n → t₁ ⊂ t₂ → p t₂) → #t₁ ≤ n → p t₁) :
∀ s : Finset α, #s ≤ n → p s
| s =>
H s fun {t} ht h =>
have := Finset.card_lt_card h
have : n - #t < n - #s := by omega
strongDownwardInduction H t ht
termination_by s => n - #s
theorem strongDownwardInduction_eq {p : Finset α → Sort*}
(H : ∀ t₁, (∀ {t₂ : Finset α}, #t₂ ≤ n → t₁ ⊂ t₂ → p t₂) → #t₁ ≤ n → p t₁)
(s : Finset α) :
strongDownwardInduction H s = H s fun {t} ht _ => strongDownwardInduction H t ht := by
rw [strongDownwardInduction]
/-- Analogue of `strongDownwardInduction` with order of arguments swapped. -/
@[elab_as_elim]
def strongDownwardInductionOn {p : Finset α → Sort*} (s : Finset α)
(H : ∀ t₁, (∀ {t₂ : Finset α}, #t₂ ≤ n → t₁ ⊂ t₂ → p t₂) → #t₁ ≤ n → p t₁) :
#s ≤ n → p s :=
strongDownwardInduction H s
theorem strongDownwardInductionOn_eq {p : Finset α → Sort*} (s : Finset α)
(H : ∀ t₁, (∀ {t₂ : Finset α}, #t₂ ≤ n → t₁ ⊂ t₂ → p t₂) → #t₁ ≤ n → p t₁) :
s.strongDownwardInductionOn H = H s fun {t} ht _ => t.strongDownwardInductionOn H ht := by
dsimp only [strongDownwardInductionOn]
rw [strongDownwardInduction]
theorem lt_wf {α} : WellFounded (@LT.lt (Finset α) _) :=
have H : Subrelation (@LT.lt (Finset α) _) (InvImage (· < ·) card) := fun {_ _} hxy =>
card_lt_card hxy
Subrelation.wf H <| InvImage.wf _ <| (Nat.lt_wfRel).2
/--
To prove a proposition for an arbitrary `Finset α`,
it suffices to prove that for any `S : Finset α`, the following is true:
the property is true for S with any element `s` removed, then the property holds for `S`.
This is a weaker version of `Finset.strongInduction`.
But it can be more precise when the induction argument
only requires removing single elements at a time.
-/
theorem eraseInduction [DecidableEq α] {p : Finset α → Prop}
(H : (S : Finset α) → (∀ s ∈ S, p (S.erase s)) → p S) (S : Finset α) : p S :=
S.strongInduction fun S ih => H S fun _ hs => ih _ (erase_ssubset hs)
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/NoncommProd.lean | import Mathlib.Algebra.BigOperators.Group.Finset.Basic
import Mathlib.Algebra.Group.Commute.Hom
import Mathlib.Algebra.Group.Pi.Lemmas
import Mathlib.Data.Fintype.Basic
/-!
# Products (respectively, sums) over a finset or a multiset.
The regular `Finset.prod` and `Multiset.prod` require `[CommMonoid α]`.
Often, there are collections `s : Finset α` where `[Monoid α]` and we know,
in a dependent fashion, that for all the terms `∀ (x ∈ s) (y ∈ s), Commute x y`.
This allows to still have a well-defined product over `s`.
## Main definitions
- `Finset.noncommProd`, requiring a proof of commutativity of held terms
- `Multiset.noncommProd`, requiring a proof of commutativity of held terms
## Implementation details
While `List.prod` is defined via `List.foldl`, `noncommProd` is defined via
`Multiset.foldr` for neater proofs and definitions. By the commutativity assumption,
the two must be equal.
TODO: Tidy up this file by using the fact that the submonoid generated by commuting
elements is commutative and using the `Finset.prod` versions of lemmas to prove the `noncommProd`
version.
-/
variable {F ι α β γ : Type*} (f : α → β → β) (op : α → α → α)
namespace Multiset
/-- Fold of a `s : Multiset α` with `f : α → β → β`, given a proof that `LeftCommutative f`
on all elements `x ∈ s`. -/
def noncommFoldr (s : Multiset α)
(comm : { x | x ∈ s }.Pairwise fun x y => ∀ b, f x (f y b) = f y (f x b)) (b : β) : β :=
letI : LeftCommutative (α := { x // x ∈ s }) (f ∘ Subtype.val) :=
⟨fun ⟨_, hx⟩ ⟨_, hy⟩ =>
haveI : IsRefl α fun x y => ∀ b, f x (f y b) = f y (f x b) := ⟨fun _ _ => rfl⟩
comm.of_refl hx hy⟩
s.attach.foldr (f ∘ Subtype.val) b
@[simp]
theorem noncommFoldr_coe (l : List α) (comm) (b : β) :
noncommFoldr f (l : Multiset α) comm b = l.foldr f b := by
simp only [noncommFoldr, coe_foldr, coe_attach, List.attach, List.attachWith, Function.comp_def]
rw [← List.foldr_map]
simp [List.map_pmap]
@[simp]
theorem noncommFoldr_empty (h) (b : β) : noncommFoldr f (0 : Multiset α) h b = b :=
rfl
theorem noncommFoldr_cons (s : Multiset α) (a : α) (h h') (b : β) :
noncommFoldr f (a ::ₘ s) h b = f a (noncommFoldr f s h' b) := by
induction s using Quotient.inductionOn
simp
theorem noncommFoldr_eq_foldr (s : Multiset α) [h : LeftCommutative f] (b : β) :
noncommFoldr f s (fun x _ y _ _ => h.left_comm x y) b = foldr f b s := by
induction s using Quotient.inductionOn
simp
section assoc
variable [assoc : Std.Associative op]
/-- Fold of a `s : Multiset α` with an associative `op : α → α → α`, given a proofs that `op`
is commutative on all elements `x ∈ s`. -/
def noncommFold (s : Multiset α) (comm : { x | x ∈ s }.Pairwise fun x y => op x y = op y x) :
α → α :=
noncommFoldr op s fun x hx y hy h b => by rw [← assoc.assoc, comm hx hy h, assoc.assoc]
@[simp]
theorem noncommFold_coe (l : List α) (comm) (a : α) :
noncommFold op (l : Multiset α) comm a = l.foldr op a := by simp [noncommFold]
@[simp]
theorem noncommFold_empty (h) (a : α) : noncommFold op (0 : Multiset α) h a = a :=
rfl
theorem noncommFold_cons (s : Multiset α) (a : α) (h h') (x : α) :
noncommFold op (a ::ₘ s) h x = op a (noncommFold op s h' x) := by
induction s using Quotient.inductionOn
simp
theorem noncommFold_eq_fold (s : Multiset α) [Std.Commutative op] (a : α) :
noncommFold op s (fun x _ y _ _ => Std.Commutative.comm x y) a = fold op a s := by
induction s using Quotient.inductionOn
simp
end assoc
variable [Monoid α] [Monoid β]
/-- Product of a `s : Multiset α` with `[Monoid α]`, given a proof that `*` commutes
on all elements `x ∈ s`. -/
@[to_additive
/-- Sum of a `s : Multiset α` with `[AddMonoid α]`, given a proof that `+` commutes
on all elements `x ∈ s`. -/]
def noncommProd (s : Multiset α) (comm : { x | x ∈ s }.Pairwise Commute) : α :=
s.noncommFold (· * ·) comm 1
@[to_additive (attr := simp)]
theorem noncommProd_coe (l : List α) (comm) : noncommProd (l : Multiset α) comm = l.prod := by
rw [noncommProd]
simp only [noncommFold_coe]
induction l with
| nil => simp
| cons hd tl hl =>
rw [List.prod_cons, List.foldr, hl]
intro x hx y hy
exact comm (List.mem_cons_of_mem _ hx) (List.mem_cons_of_mem _ hy)
@[to_additive (attr := simp)]
theorem noncommProd_empty (h) : noncommProd (0 : Multiset α) h = 1 :=
rfl
@[to_additive (attr := simp)]
theorem noncommProd_cons (s : Multiset α) (a : α) (comm) :
noncommProd (a ::ₘ s) comm = a * noncommProd s (comm.mono fun _ => mem_cons_of_mem) := by
induction s using Quotient.inductionOn
simp
@[to_additive]
theorem noncommProd_cons' (s : Multiset α) (a : α) (comm) :
noncommProd (a ::ₘ s) comm = noncommProd s (comm.mono fun _ => mem_cons_of_mem) * a := by
induction s using Quotient.inductionOn with | _ s
simp only [quot_mk_to_coe, cons_coe, noncommProd_coe, List.prod_cons]
induction s with
| nil => simp
| cons hd tl IH =>
rw [List.prod_cons, mul_assoc, ← IH, ← mul_assoc, ← mul_assoc]
· congr 1
apply comm.of_refl <;> simp
· intro x hx y hy
simp only [quot_mk_to_coe, List.mem_cons, mem_coe, cons_coe] at hx hy
apply comm
· cases hx <;> simp [*]
· cases hy <;> simp [*]
@[to_additive]
theorem noncommProd_add (s t : Multiset α) (comm) :
noncommProd (s + t) comm =
noncommProd s (comm.mono <| subset_of_le <| s.le_add_right t) *
noncommProd t (comm.mono <| subset_of_le <| t.le_add_left s) := by
rcases s with ⟨⟩
rcases t with ⟨⟩
simp
@[to_additive]
lemma noncommProd_induction (s : Multiset α) (comm)
(p : α → Prop) (hom : ∀ a b, p a → p b → p (a * b)) (unit : p 1) (base : ∀ x ∈ s, p x) :
p (s.noncommProd comm) := by
induction s using Quotient.inductionOn with | _ l
simp only [quot_mk_to_coe, noncommProd_coe, mem_coe] at base ⊢
exact l.prod_induction p hom unit base
variable [FunLike F α β]
@[to_additive]
protected theorem map_noncommProd_aux [MulHomClass F α β] (s : Multiset α)
(comm : { x | x ∈ s }.Pairwise Commute) (f : F) : { x | x ∈ s.map f }.Pairwise Commute := by
simp only [Multiset.mem_map]
rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ _
exact (comm.of_refl hx hy).map f
@[to_additive]
theorem map_noncommProd [MonoidHomClass F α β] (s : Multiset α) (comm) (f : F) :
f (s.noncommProd comm) = (s.map f).noncommProd (Multiset.map_noncommProd_aux s comm f) := by
induction s using Quotient.inductionOn
simpa using map_list_prod f _
@[to_additive noncommSum_eq_card_nsmul]
theorem noncommProd_eq_pow_card (s : Multiset α) (comm) (m : α) (h : ∀ x ∈ s, x = m) :
s.noncommProd comm = m ^ Multiset.card s := by
induction s using Quotient.inductionOn
simp only [quot_mk_to_coe, noncommProd_coe, coe_card, mem_coe] at *
exact List.prod_eq_pow_card _ m h
@[to_additive]
theorem noncommProd_eq_prod {α : Type*} [CommMonoid α] (s : Multiset α) :
(noncommProd s fun _ _ _ _ _ => Commute.all _ _) = prod s := by
induction s using Quotient.inductionOn
simp
@[to_additive]
theorem noncommProd_commute (s : Multiset α) (comm) (y : α) (h : ∀ x ∈ s, Commute y x) :
Commute y (s.noncommProd comm) := by
induction s using Quotient.inductionOn
simp only [quot_mk_to_coe, noncommProd_coe]
exact Commute.list_prod_right _ _ h
theorem mul_noncommProd_erase [DecidableEq α] (s : Multiset α) {a : α} (h : a ∈ s) (comm)
(comm' := fun _ hx _ hy hxy ↦ comm (s.mem_of_mem_erase hx) (s.mem_of_mem_erase hy) hxy) :
a * (s.erase a).noncommProd comm' = s.noncommProd comm := by
induction s using Quotient.inductionOn with | _ l
simp only [quot_mk_to_coe, mem_coe, coe_erase, noncommProd_coe] at comm h ⊢
suffices ∀ x ∈ l, ∀ y ∈ l, x * y = y * x by rw [List.prod_erase_of_comm h this]
intro x hx y hy
rcases eq_or_ne x y with rfl | hxy
· rfl
exact comm hx hy hxy
theorem noncommProd_erase_mul [DecidableEq α] (s : Multiset α) {a : α} (h : a ∈ s) (comm)
(comm' := fun _ hx _ hy hxy ↦ comm (s.mem_of_mem_erase hx) (s.mem_of_mem_erase hy) hxy) :
(s.erase a).noncommProd comm' * a = s.noncommProd comm := by
suffices ∀ b ∈ erase s a, Commute a b by
rw [← (noncommProd_commute (s.erase a) comm' a this).eq, mul_noncommProd_erase s h comm comm']
intro b hb
rcases eq_or_ne a b with rfl | hab
· rfl
exact comm h (mem_of_mem_erase hb) hab
end Multiset
namespace Finset
variable [Monoid β] [Monoid γ]
open scoped Function -- required for scoped `on` notation
/-- Proof used in definition of `Finset.noncommProd` -/
@[to_additive]
theorem noncommProd_lemma (s : Finset α) (f : α → β)
(comm : (s : Set α).Pairwise (Commute on f)) :
Set.Pairwise { x | x ∈ Multiset.map f s.val } Commute := by
simp_rw [Multiset.mem_map]
rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ _
exact comm.of_refl ha hb
/-- Product of a `s : Finset α` mapped with `f : α → β` with `[Monoid β]`,
given a proof that `*` commutes on all elements `f x` for `x ∈ s`. -/
@[to_additive
/-- Sum of a `s : Finset α` mapped with `f : α → β` with `[AddMonoid β]`,
given a proof that `+` commutes on all elements `f x` for `x ∈ s`. -/]
def noncommProd (s : Finset α) (f : α → β)
(comm : (s : Set α).Pairwise (Commute on f)) : β :=
(s.1.map f).noncommProd <| noncommProd_lemma s f comm
@[to_additive]
lemma noncommProd_induction (s : Finset α) (f : α → β) (comm)
(p : β → Prop) (hom : ∀ a b, p a → p b → p (a * b)) (unit : p 1) (base : ∀ x ∈ s, p (f x)) :
p (s.noncommProd f comm) := by
refine Multiset.noncommProd_induction _ _ _ hom unit fun b hb ↦ ?_
obtain (⟨a, ha : a ∈ s, rfl : f a = b⟩) := by simpa using hb
exact base a ha
@[to_additive (attr := congr)]
theorem noncommProd_congr {s₁ s₂ : Finset α} {f g : α → β} (h₁ : s₁ = s₂)
(h₂ : ∀ x ∈ s₂, f x = g x) (comm) :
noncommProd s₁ f comm =
noncommProd s₂ g fun x hx y hy h => by
dsimp only [Function.onFun]
rw [← h₂ _ hx, ← h₂ _ hy]
subst h₁
exact comm hx hy h := by
simp_rw [noncommProd, Multiset.map_congr (congr_arg _ h₁) h₂]
@[to_additive (attr := simp)]
theorem noncommProd_toFinset [DecidableEq α] (l : List α) (f : α → β) (comm) (hl : l.Nodup) :
noncommProd l.toFinset f comm = (l.map f).prod := by
rw [← List.dedup_eq_self] at hl
simp [noncommProd, hl]
@[to_additive (attr := simp)]
theorem noncommProd_empty (f : α → β) (h) : noncommProd (∅ : Finset α) f h = 1 :=
rfl
@[to_additive (attr := simp)]
theorem noncommProd_cons (s : Finset α) (a : α) (f : α → β)
(ha : a ∉ s) (comm) :
noncommProd (cons a s ha) f comm =
f a * noncommProd s f (comm.mono fun _ => Finset.mem_cons.2 ∘ .inr) := by
simp_rw [noncommProd, Finset.cons_val, Multiset.map_cons, Multiset.noncommProd_cons]
@[to_additive]
theorem noncommProd_cons' (s : Finset α) (a : α) (f : α → β)
(ha : a ∉ s) (comm) :
noncommProd (cons a s ha) f comm =
noncommProd s f (comm.mono fun _ => Finset.mem_cons.2 ∘ .inr) * f a := by
simp_rw [noncommProd, Finset.cons_val, Multiset.map_cons, Multiset.noncommProd_cons']
@[to_additive (attr := simp)]
theorem noncommProd_insert_of_notMem [DecidableEq α] (s : Finset α) (a : α) (f : α → β) (comm)
(ha : a ∉ s) :
noncommProd (insert a s) f comm =
f a * noncommProd s f (comm.mono fun _ => mem_insert_of_mem) := by
simp only [← cons_eq_insert _ _ ha, noncommProd_cons]
@[deprecated (since := "2025-05-23")]
alias noncommSum_insert_of_not_mem := noncommSum_insert_of_notMem
@[to_additive existing, deprecated (since := "2025-05-23")]
alias noncommProd_insert_of_not_mem := noncommProd_insert_of_notMem
@[to_additive]
theorem noncommProd_insert_of_notMem' [DecidableEq α] (s : Finset α) (a : α) (f : α → β) (comm)
(ha : a ∉ s) :
noncommProd (insert a s) f comm =
noncommProd s f (comm.mono fun _ => mem_insert_of_mem) * f a := by
simp only [← cons_eq_insert _ _ ha, noncommProd_cons']
@[deprecated (since := "2025-05-23")]
alias noncommSum_insert_of_not_mem' := noncommSum_insert_of_notMem'
@[to_additive existing, deprecated (since := "2025-05-23")]
alias noncommProd_insert_of_not_mem' := noncommProd_insert_of_notMem'
@[to_additive (attr := simp)]
theorem noncommProd_singleton (a : α) (f : α → β) :
noncommProd ({a} : Finset α) f
(by
norm_cast
exact Set.pairwise_singleton _ _) =
f a := mul_one _
variable [FunLike F β γ]
@[to_additive]
theorem map_noncommProd [MonoidHomClass F β γ] (s : Finset α) (f : α → β) (comm) (g : F) :
g (s.noncommProd f comm) =
s.noncommProd (fun i => g (f i)) fun _ hx _ hy _ => (comm.of_refl hx hy).map g := by
simp [noncommProd, Multiset.map_noncommProd]
@[to_additive noncommSum_eq_card_nsmul]
theorem noncommProd_eq_pow_card (s : Finset α) (f : α → β) (comm) (m : β) (h : ∀ x ∈ s, f x = m) :
s.noncommProd f comm = m ^ s.card := by
rw [noncommProd, Multiset.noncommProd_eq_pow_card _ _ m]
· simp only [Finset.card_def, Multiset.card_map]
· simpa using h
@[to_additive]
theorem noncommProd_commute (s : Finset α) (f : α → β) (comm) (y : β)
(h : ∀ x ∈ s, Commute y (f x)) : Commute y (s.noncommProd f comm) := by
apply Multiset.noncommProd_commute
intro y
rw [Multiset.mem_map]
rintro ⟨x, ⟨hx, rfl⟩⟩
exact h x hx
theorem mul_noncommProd_erase [DecidableEq α] (s : Finset α) {a : α} (h : a ∈ s) (f : α → β) (comm)
(comm' := fun _ hx _ hy hxy ↦ comm (s.mem_of_mem_erase hx) (s.mem_of_mem_erase hy) hxy) :
f a * (s.erase a).noncommProd f comm' = s.noncommProd f comm := by
classical
simpa only [← Multiset.map_erase_of_mem _ _ h] using
Multiset.mul_noncommProd_erase (s.1.map f) (Multiset.mem_map_of_mem f h) _
theorem noncommProd_erase_mul [DecidableEq α] (s : Finset α) {a : α} (h : a ∈ s) (f : α → β) (comm)
(comm' := fun _ hx _ hy hxy ↦ comm (s.mem_of_mem_erase hx) (s.mem_of_mem_erase hy) hxy) :
(s.erase a).noncommProd f comm' * f a = s.noncommProd f comm := by
classical
simpa only [← Multiset.map_erase_of_mem _ _ h] using
Multiset.noncommProd_erase_mul (s.1.map f) (Multiset.mem_map_of_mem f h) _
@[to_additive]
theorem noncommProd_eq_prod {β : Type*} [CommMonoid β] (s : Finset α) (f : α → β) :
(noncommProd s f fun _ _ _ _ _ => Commute.all _ _) = s.prod f := by
induction s using Finset.cons_induction_on with
| empty => simp
| cons a s ha IH => simp [IH]
/-- The non-commutative version of `Finset.prod_union` -/
@[to_additive /-- The non-commutative version of `Finset.sum_union` -/]
theorem noncommProd_union_of_disjoint [DecidableEq α] {s t : Finset α} (h : Disjoint s t)
(f : α → β) (comm : { x | x ∈ s ∪ t }.Pairwise (Commute on f)) :
noncommProd (s ∪ t) f comm =
noncommProd s f (comm.mono <| coe_subset.2 subset_union_left) *
noncommProd t f (comm.mono <| coe_subset.2 subset_union_right) := by
obtain ⟨sl, sl', rfl⟩ := exists_list_nodup_eq s
obtain ⟨tl, tl', rfl⟩ := exists_list_nodup_eq t
rw [List.disjoint_toFinset_iff_disjoint] at h
calc noncommProd (List.toFinset sl ∪ List.toFinset tl) f comm
_ = noncommProd ⟨↑(sl ++ tl), Multiset.coe_nodup.2 (sl'.append tl' h)⟩ f
(by convert comm; simp [Set.ext_iff]) :=
noncommProd_congr (by ext; simp) (by simp) _
_ = noncommProd (List.toFinset sl) f (comm.mono <| coe_subset.2 subset_union_left) *
noncommProd (List.toFinset tl) f (comm.mono <| coe_subset.2 subset_union_right) := by
simp [noncommProd, List.dedup_eq_self.2 sl', List.dedup_eq_self.2 tl']
@[to_additive]
theorem noncommProd_mul_distrib_aux {s : Finset α} {f : α → β} {g : α → β}
(comm_ff : (s : Set α).Pairwise (Commute on f))
(comm_gg : (s : Set α).Pairwise (Commute on g))
(comm_gf : (s : Set α).Pairwise fun x y => Commute (g x) (f y)) :
(s : Set α).Pairwise fun x y => Commute ((f * g) x) ((f * g) y) := by
intro x hx y hy h
apply Commute.mul_left <;> apply Commute.mul_right
· exact comm_ff.of_refl hx hy
· exact (comm_gf hy hx h.symm).symm
· exact comm_gf hx hy h
· exact comm_gg.of_refl hx hy
/-- The non-commutative version of `Finset.prod_mul_distrib` -/
@[to_additive /-- The non-commutative version of `Finset.sum_add_distrib` -/]
theorem noncommProd_mul_distrib {s : Finset α} (f : α → β) (g : α → β) (comm_ff comm_gg comm_gf) :
noncommProd s (f * g) (noncommProd_mul_distrib_aux comm_ff comm_gg comm_gf) =
noncommProd s f comm_ff * noncommProd s g comm_gg := by
induction s using Finset.cons_induction_on with
| empty => simp
| cons x s hnotMem ih =>
rw [Finset.noncommProd_cons, Finset.noncommProd_cons, Finset.noncommProd_cons, Pi.mul_apply,
ih (comm_ff.mono fun _ => mem_cons_of_mem) (comm_gg.mono fun _ => mem_cons_of_mem)
(comm_gf.mono fun _ => mem_cons_of_mem),
(noncommProd_commute _ _ _ _ fun y hy => ?_).mul_mul_mul_comm]
exact comm_gf (mem_cons_self x s) (mem_cons_of_mem hy) (ne_of_mem_of_not_mem hy hnotMem).symm
section FinitePi
variable {M : ι → Type*} [∀ i, Monoid (M i)]
@[to_additive]
theorem noncommProd_mul_single [Fintype ι] [DecidableEq ι] (x : ∀ i, M i) :
(univ.noncommProd (fun i => Pi.mulSingle i (x i)) fun i _ j _ _ =>
Pi.mulSingle_apply_commute x i j) = x := by
ext i
apply (univ.map_noncommProd (fun i ↦ MonoidHom.mulSingle M i (x i)) ?a
(Pi.evalMonoidHom M i)).trans
case a =>
intro i _ j _ _
exact Pi.mulSingle_apply_commute x i j
convert (noncommProd_congr (insert_erase (mem_univ i)).symm _ _).trans _
· intro j
exact Pi.mulSingle j (x j) i
· intro j _; dsimp
· rw [noncommProd_insert_of_notMem _ _ _ _ (notMem_erase _ _),
noncommProd_eq_pow_card (univ.erase i), one_pow, mul_one]
· simp only [Pi.mulSingle_eq_same]
· intro j hj
simp? at hj says simp only [mem_erase, ne_eq, mem_univ, and_true] at hj
simp only [Pi.mulSingle, Function.update, Pi.one_apply,
dite_eq_right_iff]
intro h
simp [*] at *
@[to_additive]
theorem _root_.MonoidHom.pi_ext [Finite ι] [DecidableEq ι] {f g : (∀ i, M i) →* γ}
(h : ∀ i x, f (Pi.mulSingle i x) = g (Pi.mulSingle i x)) : f = g := by
cases nonempty_fintype ι
ext x
rw [← noncommProd_mul_single x, univ.map_noncommProd, univ.map_noncommProd]
congr 1 with i; exact h i (x i)
end FinitePi
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Option.lean | import Mathlib.Data.Finset.Card
import Mathlib.Data.Finset.Union
/-!
# Finite sets in `Option α`
In this file we define
* `Option.toFinset`: construct an empty or singleton `Finset α` from an `Option α`;
* `Finset.insertNone`: given `s : Finset α`, lift it to a finset on `Option α` using `Option.some`
and then insert `Option.none`;
* `Finset.eraseNone`: given `s : Finset (Option α)`, returns `t : Finset α` such that
`x ∈ t ↔ some x ∈ s`.
Then we prove some basic lemmas about these definitions.
## Tags
finset, option
-/
variable {α β : Type*}
open Function
namespace Option
/-- Construct an empty or singleton finset from an `Option` -/
def toFinset (o : Option α) : Finset α :=
o.elim ∅ singleton
@[simp]
theorem toFinset_none : none.toFinset = (∅ : Finset α) :=
rfl
@[simp]
theorem toFinset_some {a : α} : (some a).toFinset = {a} :=
rfl
@[simp]
theorem mem_toFinset {a : α} {o : Option α} : a ∈ o.toFinset ↔ a ∈ o := by
cases o <;> simp [eq_comm]
theorem card_toFinset (o : Option α) : o.toFinset.card = o.elim 0 1 := by cases o <;> rfl
end Option
namespace Finset
/-- Given a finset on `α`, lift it to being a finset on `Option α`
using `Option.some` and then insert `Option.none`. -/
def insertNone : Finset α ↪o Finset (Option α) :=
(OrderEmbedding.ofMapLEIff fun s => cons none (s.map Embedding.some) <| by simp) fun s t => by
rw [le_iff_subset, cons_subset_cons, map_subset_map, le_iff_subset]
@[simp]
theorem mem_insertNone {s : Finset α} : ∀ {o : Option α}, o ∈ insertNone s ↔ ∀ a ∈ o, a ∈ s
| none => iff_of_true (Multiset.mem_cons_self _ _) fun a h => by cases h
| some a => Multiset.mem_cons.trans <| by simp
lemma forall_mem_insertNone {s : Finset α} {p : Option α → Prop} :
(∀ a ∈ insertNone s, p a) ↔ p none ∧ ∀ a ∈ s, p a := by simp [Option.forall]
theorem some_mem_insertNone {s : Finset α} {a : α} : some a ∈ insertNone s ↔ a ∈ s := by simp
lemma none_mem_insertNone {s : Finset α} : none ∈ insertNone s := by simp
@[aesop safe apply (rule_sets := [finsetNonempty])]
lemma insertNone_nonempty {s : Finset α} : insertNone s |>.Nonempty := ⟨none, none_mem_insertNone⟩
@[simp]
theorem card_insertNone (s : Finset α) : s.insertNone.card = s.card + 1 := by simp [insertNone]
/-- Given `s : Finset (Option α)`, `eraseNone s : Finset α` is the set of `x : α` such that
`some x ∈ s`. -/
def eraseNone : Finset (Option α) →o Finset α :=
(Finset.mapEmbedding (Equiv.optionIsSomeEquiv α).toEmbedding).toOrderHom.comp
⟨Finset.subtype _, subtype_mono⟩
@[simp]
theorem mem_eraseNone {s : Finset (Option α)} {x : α} : x ∈ eraseNone s ↔ some x ∈ s := by
simp [eraseNone]
lemma forall_mem_eraseNone {s : Finset (Option α)} {p : Option α → Prop} :
(∀ a ∈ eraseNone s, p a) ↔ ∀ a : α, (a : Option α) ∈ s → p a := by simp
theorem eraseNone_eq_biUnion [DecidableEq α] (s : Finset (Option α)) :
eraseNone s = s.biUnion Option.toFinset := by
ext
simp
@[simp]
theorem eraseNone_map_some (s : Finset α) : eraseNone (s.map Embedding.some) = s := by
ext
simp
@[simp]
theorem eraseNone_image_some [DecidableEq (Option α)] (s : Finset α) :
eraseNone (s.image some) = s := by simpa only [map_eq_image] using eraseNone_map_some s
@[simp]
theorem coe_eraseNone (s : Finset (Option α)) : (eraseNone s : Set α) = some ⁻¹' s :=
Set.ext fun _ => mem_eraseNone
@[simp]
theorem eraseNone_union [DecidableEq (Option α)] [DecidableEq α] (s t : Finset (Option α)) :
eraseNone (s ∪ t) = eraseNone s ∪ eraseNone t := by
ext
simp
@[simp]
theorem eraseNone_inter [DecidableEq (Option α)] [DecidableEq α] (s t : Finset (Option α)) :
eraseNone (s ∩ t) = eraseNone s ∩ eraseNone t := by
ext
simp
@[simp]
theorem eraseNone_empty : eraseNone (∅ : Finset (Option α)) = ∅ := by
ext
simp
@[simp]
theorem eraseNone_none : eraseNone ({none} : Finset (Option α)) = ∅ := by
ext
simp
@[simp]
theorem image_some_eraseNone [DecidableEq (Option α)] (s : Finset (Option α)) :
(eraseNone s).image some = s.erase none := by ext (_ | x) <;> simp
@[simp]
theorem map_some_eraseNone [DecidableEq (Option α)] (s : Finset (Option α)) :
(eraseNone s).map Embedding.some = s.erase none := by
rw [map_eq_image, Embedding.some_apply, image_some_eraseNone]
@[simp]
theorem insertNone_eraseNone [DecidableEq (Option α)] (s : Finset (Option α)) :
insertNone (eraseNone s) = insert none s := by ext (_ | x) <;> simp
@[simp]
theorem eraseNone_insertNone (s : Finset α) : eraseNone (insertNone s) = s := by
ext
simp
theorem card_eraseNone_eq_card_erase [DecidableEq (Option α)] (s : Finset (Option α)) :
#s.eraseNone = #(s.erase none) := by
rw [← card_map Function.Embedding.some, map_some_eraseNone]
theorem card_eraseNone_le (s : Finset (Option α)) : #s.eraseNone ≤ #s := by
classical
rw [card_eraseNone_eq_card_erase]
apply card_erase_le
theorem card_eraseNone_of_mem {s : Finset (Option α)} (h : none ∈ s) : #s.eraseNone = #s - 1 := by
classical rw [card_eraseNone_eq_card_erase, card_erase_of_mem h]
theorem card_eraseNone_of_not_mem {s : Finset (Option α)} (h : none ∉ s) : #s.eraseNone = #s := by
classical rw [card_eraseNone_eq_card_erase, erase_eq_of_notMem h]
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Pairwise.lean | import Mathlib.Data.Finset.Lattice.Fold
import Mathlib.Data.Set.Pairwise.List
/-!
# Relations holding pairwise on finite sets
In this file we prove a few results about the interaction of `Set.PairwiseDisjoint` and `Finset`,
as well as the interaction of `List.Pairwise Disjoint` and the condition of
`Disjoint` on `List.toFinset`, in `Set` form.
-/
open Finset
variable {α ι ι' : Type*}
instance [DecidableEq α] {r : α → α → Prop} [DecidableRel r] {s : Finset α} :
Decidable ((s : Set α).Pairwise r) :=
decidable_of_iff' (∀ a ∈ s, ∀ b ∈ s, a ≠ b → r a b) Iff.rfl
theorem Finset.pairwiseDisjoint_range_singleton :
(Set.range (singleton : α → Finset α)).PairwiseDisjoint id := by
rintro _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ h
exact disjoint_singleton.2 (ne_of_apply_ne _ h)
namespace Set
theorem PairwiseDisjoint.elim_finset {s : Set ι} {f : ι → Finset α} (hs : s.PairwiseDisjoint f)
{i j : ι} (hi : i ∈ s) (hj : j ∈ s) (a : α) (hai : a ∈ f i) (haj : a ∈ f j) : i = j :=
hs.elim hi hj (Finset.not_disjoint_iff.2 ⟨a, hai, haj⟩)
section SemilatticeInf
variable [SemilatticeInf α] [OrderBot α] {s : Finset ι} {f : ι → α}
theorem PairwiseDisjoint.image_finset_of_le [DecidableEq ι] {s : Finset ι} {f : ι → α}
(hs : (s : Set ι).PairwiseDisjoint f) {g : ι → ι} (hf : ∀ a, f (g a) ≤ f a) :
(s.image g : Set ι).PairwiseDisjoint f := by
rw [coe_image]
exact hs.image_of_le hf
theorem PairwiseDisjoint.attach (hs : (s : Set ι).PairwiseDisjoint f) :
(s.attach : Set { x // x ∈ s }).PairwiseDisjoint (f ∘ Subtype.val) := fun i _ j _ hij =>
hs i.2 j.2 <| mt Subtype.ext hij
end SemilatticeInf
variable [Lattice α] [OrderBot α]
/-- Bind operation for `Set.PairwiseDisjoint`. In a complete lattice, you can use
`Set.PairwiseDisjoint.biUnion`. -/
theorem PairwiseDisjoint.biUnion_finset {s : Set ι'} {g : ι' → Finset ι} {f : ι → α}
(hs : s.PairwiseDisjoint fun i' : ι' => (g i').sup f)
(hg : ∀ i ∈ s, (g i : Set ι).PairwiseDisjoint f) : (⋃ i ∈ s, ↑(g i)).PairwiseDisjoint f := by
rintro a ha b hb hab
simp_rw [Set.mem_iUnion] at ha hb
obtain ⟨c, hc, ha⟩ := ha
obtain ⟨d, hd, hb⟩ := hb
obtain hcd | hcd := eq_or_ne (g c) (g d)
· exact hg d hd (by rwa [hcd] at ha) hb hab
· exact (hs hc hd (ne_of_apply_ne _ hcd)).mono (Finset.le_sup ha) (Finset.le_sup hb)
end Set
namespace List
variable {β : Type*} [DecidableEq α] {r : α → α → Prop} {l : List α}
theorem pairwise_of_coe_toFinset_pairwise (hl : (l.toFinset : Set α).Pairwise r) (hn : l.Nodup) :
l.Pairwise r := by
rw [coe_toFinset] at hl
exact hn.pairwise_of_set_pairwise hl
theorem pairwise_iff_coe_toFinset_pairwise (hn : l.Nodup) (hs : Symmetric r) :
(l.toFinset : Set α).Pairwise r ↔ l.Pairwise r := by
letI : IsSymm α r := ⟨hs⟩
rw [coe_toFinset, hn.pairwise_coe]
open scoped Function -- required for scoped `on` notation
theorem pairwise_disjoint_of_coe_toFinset_pairwiseDisjoint {α ι} [PartialOrder α] [OrderBot α]
[DecidableEq ι] {l : List ι} {f : ι → α} (hl : (l.toFinset : Set ι).PairwiseDisjoint f)
(hn : l.Nodup) : l.Pairwise (_root_.Disjoint on f) :=
pairwise_of_coe_toFinset_pairwise hl hn
theorem pairwiseDisjoint_iff_coe_toFinset_pairwise_disjoint {α ι} [PartialOrder α] [OrderBot α]
[DecidableEq ι] {l : List ι} {f : ι → α} (hn : l.Nodup) :
(l.toFinset : Set ι).PairwiseDisjoint f ↔ l.Pairwise (_root_.Disjoint on f) :=
pairwise_iff_coe_toFinset_pairwise hn (symmetric_disjoint.comap f)
end List |
.lake/packages/mathlib/Mathlib/Data/Finset/Attr.lean | import Mathlib.Init
import Aesop
import Qq
/-!
# Aesop rule set for finsets
This file defines `finsetNonempty`, an aesop rule set to prove that a given finset is nonempty.
-/
-- `finsetNonempty` rules try to prove that a given finset is nonempty,
-- for use in positivity extensions.
declare_aesop_rule_sets [finsetNonempty] (default := true)
open Qq Lean Meta |
.lake/packages/mathlib/Mathlib/Data/Finset/PImage.lean | import Mathlib.Data.Finset.Option
import Mathlib.Data.PFun
import Mathlib.Data.Part
/-!
# Image of a `Finset α` under a partially defined function
In this file we define `Part.toFinset` and `Finset.pimage`. We also prove some trivial lemmas about
these definitions.
## Tags
finite set, image, partial function
-/
variable {α β : Type*}
namespace Part
/-- Convert an `o : Part α` with decidable `Part.Dom o` to `Finset α`. -/
def toFinset (o : Part α) [Decidable o.Dom] : Finset α :=
o.toOption.toFinset
@[simp]
theorem mem_toFinset {o : Part α} [Decidable o.Dom] {x : α} : x ∈ o.toFinset ↔ x ∈ o := by
simp [toFinset]
@[simp]
theorem toFinset_none [Decidable (none : Part α).Dom] : none.toFinset = (∅ : Finset α) := by
simp [toFinset]
@[simp]
theorem toFinset_some {a : α} [Decidable (some a).Dom] : (some a).toFinset = {a} := by
simp [toFinset]
@[simp]
theorem coe_toFinset (o : Part α) [Decidable o.Dom] : (o.toFinset : Set α) = { x | x ∈ o } :=
Set.ext fun _ => mem_toFinset
end Part
namespace Finset
variable [DecidableEq β] {f g : α →. β} [∀ x, Decidable (f x).Dom] [∀ x, Decidable (g x).Dom]
{s t : Finset α} {b : β}
/-- Image of `s : Finset α` under a partially defined function `f : α →. β`. -/
def pimage (f : α →. β) [∀ x, Decidable (f x).Dom] (s : Finset α) : Finset β :=
s.biUnion fun x => (f x).toFinset
@[simp]
theorem mem_pimage : b ∈ s.pimage f ↔ ∃ a ∈ s, b ∈ f a := by
simp [pimage]
@[simp, norm_cast]
theorem coe_pimage : (s.pimage f : Set β) = f.image s :=
Set.ext fun _ => mem_pimage
@[simp]
theorem pimage_some (s : Finset α) (f : α → β) [∀ x, Decidable (Part.some <| f x).Dom] :
(s.pimage fun x => Part.some (f x)) = s.image f := by
ext
simp [eq_comm]
theorem pimage_congr (h₁ : s = t) (h₂ : ∀ x ∈ t, f x = g x) : s.pimage f = t.pimage g := by
aesop
/-- Rewrite `s.pimage f` in terms of `Finset.filter`, `Finset.attach`, and `Finset.image`. -/
theorem pimage_eq_image_filter : s.pimage f =
{x ∈ s | (f x).Dom}.attach.image
fun x : { x // x ∈ filter (fun x => (f x).Dom) s } =>
(f x).get (mem_filter.mp x.coe_prop).2 := by
aesop (add simp Part.mem_eq)
theorem pimage_union [DecidableEq α] : (s ∪ t).pimage f = s.pimage f ∪ t.pimage f :=
coe_inj.1 <| by
simp only [coe_pimage, coe_union, ← PFun.image_union]
@[simp]
theorem pimage_empty : pimage f ∅ = ∅ := by
ext
simp
theorem pimage_subset {t : Finset β} : s.pimage f ⊆ t ↔ ∀ x ∈ s, ∀ y ∈ f x, y ∈ t := by
simp [subset_iff, @forall_swap _ β]
@[mono]
theorem pimage_mono (h : s ⊆ t) : s.pimage f ⊆ t.pimage f :=
pimage_subset.2 fun x hx _ hy => mem_pimage.2 ⟨x, h hx, hy⟩
theorem pimage_inter [DecidableEq α] : (s ∩ t).pimage f ⊆ s.pimage f ∩ t.pimage f := by
simp only [← coe_subset, coe_pimage, coe_inter, PFun.image_inter]
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Sups.lean | import Mathlib.Data.Finset.NAry
import Mathlib.Data.Finset.Slice
import Mathlib.Data.Set.Sups
/-!
# Set family operations
This file defines a few binary operations on `Finset α` for use in set family combinatorics.
## Main declarations
* `Finset.sups s t`: Finset of elements of the form `a ⊔ b` where `a ∈ s`, `b ∈ t`.
* `Finset.infs s t`: Finset of elements of the form `a ⊓ b` where `a ∈ s`, `b ∈ t`.
* `Finset.disjSups s t`: Finset of elements of the form `a ⊔ b` where `a ∈ s`, `b ∈ t` and `a`
and `b` are disjoint.
* `Finset.diffs`: Finset of elements of the form `a \ b` where `a ∈ s`, `b ∈ t`.
* `Finset.compls`: Finset of elements of the form `aᶜ` where `a ∈ s`.
## Notation
We define the following notation in scope `FinsetFamily`:
* `s ⊻ t` for `Finset.sups`
* `s ⊼ t` for `Finset.infs`
* `s ○ t` for `Finset.disjSups s t`
* `s \\ t` for `Finset.diffs`
* `sᶜˢ` for `Finset.compls`
## References
[B. Bollobás, *Combinatorics*][bollobas1986]
-/
open Function
open SetFamily
variable {F α β : Type*}
namespace Finset
section Sups
variable [DecidableEq α] [DecidableEq β]
variable [SemilatticeSup α] [SemilatticeSup β] [FunLike F α β] [SupHomClass F α β]
variable (s s₁ s₂ t t₁ t₂ u v : Finset α)
/-- `s ⊻ t` is the finset of elements of the form `a ⊔ b` where `a ∈ s`, `b ∈ t`. -/
protected def hasSups : HasSups (Finset α) :=
⟨image₂ (· ⊔ ·)⟩
scoped[FinsetFamily] attribute [instance] Finset.hasSups
open FinsetFamily
variable {s t} {a b c : α}
@[simp]
theorem mem_sups : c ∈ s ⊻ t ↔ ∃ a ∈ s, ∃ b ∈ t, a ⊔ b = c := by simp [(· ⊻ ·)]
variable (s t)
@[simp, norm_cast]
theorem coe_sups : (↑(s ⊻ t) : Set α) = ↑s ⊻ ↑t :=
coe_image₂ _ _ _
theorem card_sups_le : #(s ⊻ t) ≤ #s * #t := card_image₂_le _ _ _
theorem card_sups_iff : #(s ⊻ t) = #s * #t ↔ (s ×ˢ t : Set (α × α)).InjOn fun x => x.1 ⊔ x.2 :=
card_image₂_iff
variable {s s₁ s₂ t t₁ t₂ u}
theorem sup_mem_sups : a ∈ s → b ∈ t → a ⊔ b ∈ s ⊻ t :=
mem_image₂_of_mem
theorem sups_subset : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ ⊻ t₁ ⊆ s₂ ⊻ t₂ :=
image₂_subset
theorem sups_subset_left : t₁ ⊆ t₂ → s ⊻ t₁ ⊆ s ⊻ t₂ :=
image₂_subset_left
theorem sups_subset_right : s₁ ⊆ s₂ → s₁ ⊻ t ⊆ s₂ ⊻ t :=
image₂_subset_right
lemma image_subset_sups_left : b ∈ t → s.image (· ⊔ b) ⊆ s ⊻ t := image_subset_image₂_left
lemma image_subset_sups_right : a ∈ s → t.image (a ⊔ ·) ⊆ s ⊻ t := image_subset_image₂_right
theorem forall_sups_iff {p : α → Prop} : (∀ c ∈ s ⊻ t, p c) ↔ ∀ a ∈ s, ∀ b ∈ t, p (a ⊔ b) :=
forall_mem_image₂
@[simp]
theorem sups_subset_iff : s ⊻ t ⊆ u ↔ ∀ a ∈ s, ∀ b ∈ t, a ⊔ b ∈ u :=
image₂_subset_iff
@[simp]
theorem sups_nonempty : (s ⊻ t).Nonempty ↔ s.Nonempty ∧ t.Nonempty :=
image₂_nonempty_iff
@[aesop safe apply (rule_sets := [finsetNonempty])]
protected theorem Nonempty.sups : s.Nonempty → t.Nonempty → (s ⊻ t).Nonempty :=
Nonempty.image₂
theorem Nonempty.of_sups_left : (s ⊻ t).Nonempty → s.Nonempty :=
Nonempty.of_image₂_left
theorem Nonempty.of_sups_right : (s ⊻ t).Nonempty → t.Nonempty :=
Nonempty.of_image₂_right
@[simp]
theorem empty_sups : ∅ ⊻ t = ∅ :=
image₂_empty_left
@[simp]
theorem sups_empty : s ⊻ ∅ = ∅ :=
image₂_empty_right
@[simp]
theorem sups_eq_empty : s ⊻ t = ∅ ↔ s = ∅ ∨ t = ∅ :=
image₂_eq_empty_iff
@[simp] lemma singleton_sups : {a} ⊻ t = t.image (a ⊔ ·) := image₂_singleton_left
@[simp] lemma sups_singleton : s ⊻ {b} = s.image (· ⊔ b) := image₂_singleton_right
theorem singleton_sups_singleton : ({a} ⊻ {b} : Finset α) = {a ⊔ b} :=
image₂_singleton
theorem sups_union_left : (s₁ ∪ s₂) ⊻ t = s₁ ⊻ t ∪ s₂ ⊻ t :=
image₂_union_left
theorem sups_union_right : s ⊻ (t₁ ∪ t₂) = s ⊻ t₁ ∪ s ⊻ t₂ :=
image₂_union_right
theorem sups_inter_subset_left : (s₁ ∩ s₂) ⊻ t ⊆ s₁ ⊻ t ∩ s₂ ⊻ t :=
image₂_inter_subset_left
theorem sups_inter_subset_right : s ⊻ (t₁ ∩ t₂) ⊆ s ⊻ t₁ ∩ s ⊻ t₂ :=
image₂_inter_subset_right
theorem subset_sups {s t : Set α} :
↑u ⊆ s ⊻ t → ∃ s' t' : Finset α, ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ s' ⊻ t' :=
subset_set_image₂
lemma image_sups (f : F) (s t : Finset α) : image f (s ⊻ t) = image f s ⊻ image f t :=
image_image₂_distrib <| map_sup f
lemma map_sups (f : F) (hf) (s t : Finset α) :
map ⟨f, hf⟩ (s ⊻ t) = map ⟨f, hf⟩ s ⊻ map ⟨f, hf⟩ t := by
simpa [map_eq_image] using image_sups f s t
lemma subset_sups_self : s ⊆ s ⊻ s := fun _a ha ↦ mem_sups.2 ⟨_, ha, _, ha, sup_idem _⟩
lemma sups_subset_self : s ⊻ s ⊆ s ↔ SupClosed (s : Set α) := sups_subset_iff
@[simp] lemma sups_eq_self : s ⊻ s = s ↔ SupClosed (s : Set α) := by simp [← coe_inj]
@[simp] lemma univ_sups_univ [Fintype α] : (univ : Finset α) ⊻ univ = univ := by simp
lemma filter_sups_le [DecidableLE α] (s t : Finset α) (a : α) :
{b ∈ s ⊻ t | b ≤ a} = {b ∈ s | b ≤ a} ⊻ {b ∈ t | b ≤ a} := by
simp only [← coe_inj, coe_filter, coe_sups, ← mem_coe, Set.sep_sups_le]
variable (s t u)
lemma biUnion_image_sup_left : s.biUnion (fun a ↦ t.image (a ⊔ ·)) = s ⊻ t := biUnion_image_left
lemma biUnion_image_sup_right : t.biUnion (fun b ↦ s.image (· ⊔ b)) = s ⊻ t := biUnion_image_right
theorem image_sup_product (s t : Finset α) : (s ×ˢ t).image (uncurry (· ⊔ ·)) = s ⊻ t :=
image_uncurry_product _ _ _
theorem sups_assoc : s ⊻ t ⊻ u = s ⊻ (t ⊻ u) := image₂_assoc sup_assoc
theorem sups_comm : s ⊻ t = t ⊻ s := image₂_comm sup_comm
theorem sups_left_comm : s ⊻ (t ⊻ u) = t ⊻ (s ⊻ u) :=
image₂_left_comm sup_left_comm
theorem sups_right_comm : s ⊻ t ⊻ u = s ⊻ u ⊻ t :=
image₂_right_comm sup_right_comm
theorem sups_sups_sups_comm : s ⊻ t ⊻ (u ⊻ v) = s ⊻ u ⊻ (t ⊻ v) :=
image₂_image₂_image₂_comm sup_sup_sup_comm
end Sups
section Infs
variable [DecidableEq α] [DecidableEq β]
variable [SemilatticeInf α] [SemilatticeInf β] [FunLike F α β] [InfHomClass F α β]
variable (s s₁ s₂ t t₁ t₂ u v : Finset α)
/-- `s ⊼ t` is the finset of elements of the form `a ⊓ b` where `a ∈ s`, `b ∈ t`. -/
protected def hasInfs : HasInfs (Finset α) :=
⟨image₂ (· ⊓ ·)⟩
scoped[FinsetFamily] attribute [instance] Finset.hasInfs
open FinsetFamily
variable {s t} {a b c : α}
@[simp]
theorem mem_infs : c ∈ s ⊼ t ↔ ∃ a ∈ s, ∃ b ∈ t, a ⊓ b = c := by simp [(· ⊼ ·)]
variable (s t)
@[simp, norm_cast]
theorem coe_infs : (↑(s ⊼ t) : Set α) = ↑s ⊼ ↑t :=
coe_image₂ _ _ _
theorem card_infs_le : #(s ⊼ t) ≤ #s * #t := card_image₂_le _ _ _
theorem card_infs_iff : #(s ⊼ t) = #s * #t ↔ (s ×ˢ t : Set (α × α)).InjOn fun x => x.1 ⊓ x.2 :=
card_image₂_iff
variable {s s₁ s₂ t t₁ t₂ u}
theorem inf_mem_infs : a ∈ s → b ∈ t → a ⊓ b ∈ s ⊼ t :=
mem_image₂_of_mem
theorem infs_subset : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ ⊼ t₁ ⊆ s₂ ⊼ t₂ :=
image₂_subset
theorem infs_subset_left : t₁ ⊆ t₂ → s ⊼ t₁ ⊆ s ⊼ t₂ :=
image₂_subset_left
theorem infs_subset_right : s₁ ⊆ s₂ → s₁ ⊼ t ⊆ s₂ ⊼ t :=
image₂_subset_right
lemma image_subset_infs_left : b ∈ t → s.image (· ⊓ b) ⊆ s ⊼ t := image_subset_image₂_left
lemma image_subset_infs_right : a ∈ s → t.image (a ⊓ ·) ⊆ s ⊼ t := image_subset_image₂_right
theorem forall_infs_iff {p : α → Prop} : (∀ c ∈ s ⊼ t, p c) ↔ ∀ a ∈ s, ∀ b ∈ t, p (a ⊓ b) :=
forall_mem_image₂
@[simp]
theorem infs_subset_iff : s ⊼ t ⊆ u ↔ ∀ a ∈ s, ∀ b ∈ t, a ⊓ b ∈ u :=
image₂_subset_iff
@[simp]
theorem infs_nonempty : (s ⊼ t).Nonempty ↔ s.Nonempty ∧ t.Nonempty :=
image₂_nonempty_iff
@[aesop safe apply (rule_sets := [finsetNonempty])]
protected theorem Nonempty.infs : s.Nonempty → t.Nonempty → (s ⊼ t).Nonempty :=
Nonempty.image₂
theorem Nonempty.of_infs_left : (s ⊼ t).Nonempty → s.Nonempty :=
Nonempty.of_image₂_left
theorem Nonempty.of_infs_right : (s ⊼ t).Nonempty → t.Nonempty :=
Nonempty.of_image₂_right
@[simp]
theorem empty_infs : ∅ ⊼ t = ∅ :=
image₂_empty_left
@[simp]
theorem infs_empty : s ⊼ ∅ = ∅ :=
image₂_empty_right
@[simp]
theorem infs_eq_empty : s ⊼ t = ∅ ↔ s = ∅ ∨ t = ∅ :=
image₂_eq_empty_iff
@[simp] lemma singleton_infs : {a} ⊼ t = t.image (a ⊓ ·) := image₂_singleton_left
@[simp] lemma infs_singleton : s ⊼ {b} = s.image (· ⊓ b) := image₂_singleton_right
theorem singleton_infs_singleton : ({a} ⊼ {b} : Finset α) = {a ⊓ b} :=
image₂_singleton
theorem infs_union_left : (s₁ ∪ s₂) ⊼ t = s₁ ⊼ t ∪ s₂ ⊼ t :=
image₂_union_left
theorem infs_union_right : s ⊼ (t₁ ∪ t₂) = s ⊼ t₁ ∪ s ⊼ t₂ :=
image₂_union_right
theorem infs_inter_subset_left : (s₁ ∩ s₂) ⊼ t ⊆ s₁ ⊼ t ∩ s₂ ⊼ t :=
image₂_inter_subset_left
theorem infs_inter_subset_right : s ⊼ (t₁ ∩ t₂) ⊆ s ⊼ t₁ ∩ s ⊼ t₂ :=
image₂_inter_subset_right
theorem subset_infs {s t : Set α} :
↑u ⊆ s ⊼ t → ∃ s' t' : Finset α, ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ s' ⊼ t' :=
subset_set_image₂
lemma image_infs (f : F) (s t : Finset α) : image f (s ⊼ t) = image f s ⊼ image f t :=
image_image₂_distrib <| map_inf f
lemma map_infs (f : F) (hf) (s t : Finset α) :
map ⟨f, hf⟩ (s ⊼ t) = map ⟨f, hf⟩ s ⊼ map ⟨f, hf⟩ t := by
simpa [map_eq_image] using image_infs f s t
lemma subset_infs_self : s ⊆ s ⊼ s := fun _a ha ↦ mem_infs.2 ⟨_, ha, _, ha, inf_idem _⟩
lemma infs_self_subset : s ⊼ s ⊆ s ↔ InfClosed (s : Set α) := infs_subset_iff
@[simp] lemma infs_self : s ⊼ s = s ↔ InfClosed (s : Set α) := by simp [← coe_inj]
@[simp] lemma univ_infs_univ [Fintype α] : (univ : Finset α) ⊼ univ = univ := by simp
lemma filter_infs_le [DecidableLE α] (s t : Finset α) (a : α) :
{b ∈ s ⊼ t | a ≤ b} = {b ∈ s | a ≤ b} ⊼ {b ∈ t | a ≤ b} := by
simp only [← coe_inj, coe_filter, coe_infs, ← mem_coe, Set.sep_infs_le]
variable (s t u)
lemma biUnion_image_inf_left : s.biUnion (fun a ↦ t.image (a ⊓ ·)) = s ⊼ t := biUnion_image_left
lemma biUnion_image_inf_right : t.biUnion (fun b ↦ s.image (· ⊓ b)) = s ⊼ t := biUnion_image_right
theorem image_inf_product (s t : Finset α) : (s ×ˢ t).image (uncurry (· ⊓ ·)) = s ⊼ t :=
image_uncurry_product _ _ _
theorem infs_assoc : s ⊼ t ⊼ u = s ⊼ (t ⊼ u) := image₂_assoc inf_assoc
theorem infs_comm : s ⊼ t = t ⊼ s := image₂_comm inf_comm
theorem infs_left_comm : s ⊼ (t ⊼ u) = t ⊼ (s ⊼ u) :=
image₂_left_comm inf_left_comm
theorem infs_right_comm : s ⊼ t ⊼ u = s ⊼ u ⊼ t :=
image₂_right_comm inf_right_comm
theorem infs_infs_infs_comm : s ⊼ t ⊼ (u ⊼ v) = s ⊼ u ⊼ (t ⊼ v) :=
image₂_image₂_image₂_comm inf_inf_inf_comm
end Infs
open FinsetFamily
section DistribLattice
variable [DecidableEq α]
variable [DistribLattice α] (s t u : Finset α)
theorem sups_infs_subset_left : s ⊻ t ⊼ u ⊆ (s ⊻ t) ⊼ (s ⊻ u) :=
image₂_distrib_subset_left sup_inf_left
theorem sups_infs_subset_right : t ⊼ u ⊻ s ⊆ (t ⊻ s) ⊼ (u ⊻ s) :=
image₂_distrib_subset_right sup_inf_right
theorem infs_sups_subset_left : s ⊼ (t ⊻ u) ⊆ s ⊼ t ⊻ s ⊼ u :=
image₂_distrib_subset_left inf_sup_left
theorem infs_sups_subset_right : (t ⊻ u) ⊼ s ⊆ t ⊼ s ⊻ u ⊼ s :=
image₂_distrib_subset_right inf_sup_right
end DistribLattice
section Finset
variable [DecidableEq α]
variable {𝒜 ℬ : Finset (Finset α)} {s t : Finset α}
@[simp] lemma powerset_union (s t : Finset α) : (s ∪ t).powerset = s.powerset ⊻ t.powerset := by
ext u
simp only [mem_sups, mem_powerset, sup_eq_union]
refine ⟨fun h ↦ ⟨_, inter_subset_left (s₂ := u), _, inter_subset_left (s₂ := u), ?_⟩, ?_⟩
· rwa [← union_inter_distrib_right, inter_eq_right]
· rintro ⟨v, hv, w, hw, rfl⟩
exact union_subset_union hv hw
@[simp] lemma powerset_inter (s t : Finset α) : (s ∩ t).powerset = s.powerset ⊼ t.powerset := by
ext u
simp only [mem_infs, mem_powerset, inf_eq_inter]
refine ⟨fun h ↦ ⟨_, inter_subset_left (s₂ := u), _, inter_subset_left (s₂ := u), ?_⟩, ?_⟩
· rwa [← inter_inter_distrib_right, inter_eq_right]
· rintro ⟨v, hv, w, hw, rfl⟩
exact inter_subset_inter hv hw
@[simp] lemma powerset_sups_powerset_self (s : Finset α) :
s.powerset ⊻ s.powerset = s.powerset := by simp [← powerset_union]
@[simp] lemma powerset_infs_powerset_self (s : Finset α) :
s.powerset ⊼ s.powerset = s.powerset := by simp [← powerset_inter]
lemma union_mem_sups : s ∈ 𝒜 → t ∈ ℬ → s ∪ t ∈ 𝒜 ⊻ ℬ := sup_mem_sups
lemma inter_mem_infs : s ∈ 𝒜 → t ∈ ℬ → s ∩ t ∈ 𝒜 ⊼ ℬ := inf_mem_infs
end Finset
section DisjSups
variable [DecidableEq α]
variable [SemilatticeSup α] [OrderBot α] [DecidableRel (α := α) Disjoint]
(s s₁ s₂ t t₁ t₂ u : Finset α)
/-- The finset of elements of the form `a ⊔ b` where `a ∈ s`, `b ∈ t` and `a` and `b` are disjoint.
-/
def disjSups : Finset α := {ab ∈ s ×ˢ t | Disjoint ab.1 ab.2}.image fun ab => ab.1 ⊔ ab.2
@[inherit_doc]
scoped[FinsetFamily] infixl:74 " ○ " => Finset.disjSups
variable {s t u} {a b c : α}
@[simp]
theorem mem_disjSups : c ∈ s ○ t ↔ ∃ a ∈ s, ∃ b ∈ t, Disjoint a b ∧ a ⊔ b = c := by
simp [disjSups, and_assoc]
theorem disjSups_subset_sups : s ○ t ⊆ s ⊻ t := by
simp_rw [subset_iff, mem_sups, mem_disjSups]
exact fun c ⟨a, b, ha, hb, _, hc⟩ => ⟨a, b, ha, hb, hc⟩
variable (s t)
theorem card_disjSups_le : #(s ○ t) ≤ #s * #t :=
(card_le_card disjSups_subset_sups).trans <| card_sups_le _ _
variable {s s₁ s₂ t t₁ t₂}
theorem disjSups_subset (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : s₁ ○ t₁ ⊆ s₂ ○ t₂ :=
image_subset_image <| filter_subset_filter _ <| product_subset_product hs ht
theorem disjSups_subset_left (ht : t₁ ⊆ t₂) : s ○ t₁ ⊆ s ○ t₂ :=
disjSups_subset Subset.rfl ht
theorem disjSups_subset_right (hs : s₁ ⊆ s₂) : s₁ ○ t ⊆ s₂ ○ t :=
disjSups_subset hs Subset.rfl
theorem forall_disjSups_iff {p : α → Prop} :
(∀ c ∈ s ○ t, p c) ↔ ∀ a ∈ s, ∀ b ∈ t, Disjoint a b → p (a ⊔ b) := by
simp_rw [mem_disjSups]
refine ⟨fun h a ha b hb hab => h _ ⟨_, ha, _, hb, hab, rfl⟩, ?_⟩
rintro h _ ⟨a, ha, b, hb, hab, rfl⟩
exact h _ ha _ hb hab
@[simp]
theorem disjSups_subset_iff : s ○ t ⊆ u ↔ ∀ a ∈ s, ∀ b ∈ t, Disjoint a b → a ⊔ b ∈ u :=
forall_disjSups_iff
theorem Nonempty.of_disjSups_left : (s ○ t).Nonempty → s.Nonempty := by
simp_rw [Finset.Nonempty, mem_disjSups]
exact fun ⟨_, a, ha, _⟩ => ⟨a, ha⟩
theorem Nonempty.of_disjSups_right : (s ○ t).Nonempty → t.Nonempty := by
simp_rw [Finset.Nonempty, mem_disjSups]
exact fun ⟨_, _, _, b, hb, _⟩ => ⟨b, hb⟩
@[simp]
theorem disjSups_empty_left : ∅ ○ t = ∅ := by simp [disjSups]
@[simp]
theorem disjSups_empty_right : s ○ ∅ = ∅ := by simp [disjSups]
theorem disjSups_singleton : ({a} ○ {b} : Finset α) = if Disjoint a b then {a ⊔ b} else ∅ := by
split_ifs with h <;> simp [disjSups, filter_singleton, h]
theorem disjSups_union_left : (s₁ ∪ s₂) ○ t = s₁ ○ t ∪ s₂ ○ t := by
simp [disjSups, filter_union, image_union]
theorem disjSups_union_right : s ○ (t₁ ∪ t₂) = s ○ t₁ ∪ s ○ t₂ := by
simp [disjSups, filter_union, image_union]
theorem disjSups_inter_subset_left : (s₁ ∩ s₂) ○ t ⊆ s₁ ○ t ∩ s₂ ○ t := by
simpa only [disjSups, inter_product, filter_inter_distrib] using image_inter_subset _ _ _
theorem disjSups_inter_subset_right : s ○ (t₁ ∩ t₂) ⊆ s ○ t₁ ∩ s ○ t₂ := by
simpa only [disjSups, product_inter, filter_inter_distrib] using image_inter_subset _ _ _
variable (s t)
theorem disjSups_comm : s ○ t = t ○ s := by
aesop (add simp disjoint_comm, simp sup_comm)
instance : @Std.Commutative (Finset α) (· ○ ·) := ⟨disjSups_comm⟩
end DisjSups
section DistribLattice
variable [DecidableEq α]
variable [DistribLattice α] [OrderBot α] [DecidableRel (α := α) Disjoint] (s t u v : Finset α)
theorem disjSups_assoc : ∀ s t u : Finset α, s ○ t ○ u = s ○ (t ○ u) := by
refine (associative_of_commutative_of_le inferInstance ?_).assoc
simp only [le_eq_subset, disjSups_subset_iff, mem_disjSups]
rintro s t u _ ⟨a, ha, b, hb, hab, rfl⟩ c hc habc
rw [disjoint_sup_left] at habc
exact ⟨a, ha, _, ⟨b, hb, c, hc, habc.2, rfl⟩, hab.sup_right habc.1, (sup_assoc ..).symm⟩
instance : @Std.Associative (Finset α) (· ○ ·) := ⟨disjSups_assoc⟩
theorem disjSups_left_comm : s ○ (t ○ u) = t ○ (s ○ u) := by
simp_rw [← disjSups_assoc, disjSups_comm s]
theorem disjSups_right_comm : s ○ t ○ u = s ○ u ○ t := by simp_rw [disjSups_assoc, disjSups_comm]
theorem disjSups_disjSups_disjSups_comm : s ○ t ○ (u ○ v) = s ○ u ○ (t ○ v) := by
simp_rw [← disjSups_assoc, disjSups_right_comm]
end DistribLattice
section Diffs
variable [DecidableEq α]
variable [GeneralizedBooleanAlgebra α] (s s₁ s₂ t t₁ t₂ u : Finset α)
/-- `s \\ t` is the finset of elements of the form `a \ b` where `a ∈ s`, `b ∈ t`. -/
def diffs : Finset α → Finset α → Finset α := image₂ (· \ ·)
@[inherit_doc]
scoped[FinsetFamily] infixl:74 " \\\\ " => Finset.diffs
-- This notation is meant to have higher precedence than `\` and `⊓`, but still within the
-- realm of other binary notation
variable {s t} {a b c : α}
@[simp] lemma mem_diffs : c ∈ s \\ t ↔ ∃ a ∈ s, ∃ b ∈ t, a \ b = c := by simp [(· \\ ·)]
variable (s t)
@[simp, norm_cast] lemma coe_diffs : (↑(s \\ t) : Set α) = Set.image2 (· \ ·) s t :=
coe_image₂ _ _ _
lemma card_diffs_le : #(s \\ t) ≤ #s * #t := card_image₂_le _ _ _
lemma card_diffs_iff : #(s \\ t) = #s * #t ↔ (s ×ˢ t : Set (α × α)).InjOn fun x ↦ x.1 \ x.2 :=
card_image₂_iff
variable {s s₁ s₂ t t₁ t₂ u}
lemma sdiff_mem_diffs : a ∈ s → b ∈ t → a \ b ∈ s \\ t := mem_image₂_of_mem
lemma diffs_subset : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ \\ t₁ ⊆ s₂ \\ t₂ := image₂_subset
lemma diffs_subset_left : t₁ ⊆ t₂ → s \\ t₁ ⊆ s \\ t₂ := image₂_subset_left
lemma diffs_subset_right : s₁ ⊆ s₂ → s₁ \\ t ⊆ s₂ \\ t := image₂_subset_right
lemma image_subset_diffs_left : b ∈ t → s.image (· \ b) ⊆ s \\ t := image_subset_image₂_left
lemma image_subset_diffs_right : a ∈ s → t.image (a \ ·) ⊆ s \\ t := image_subset_image₂_right
lemma forall_mem_diffs {p : α → Prop} : (∀ c ∈ s \\ t, p c) ↔ ∀ a ∈ s, ∀ b ∈ t, p (a \ b) :=
forall_mem_image₂
@[simp] lemma diffs_subset_iff : s \\ t ⊆ u ↔ ∀ a ∈ s, ∀ b ∈ t, a \ b ∈ u := image₂_subset_iff
@[simp]
lemma diffs_nonempty : (s \\ t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := image₂_nonempty_iff
@[aesop safe apply (rule_sets := [finsetNonempty])]
protected lemma Nonempty.diffs : s.Nonempty → t.Nonempty → (s \\ t).Nonempty := Nonempty.image₂
lemma Nonempty.of_diffs_left : (s \\ t).Nonempty → s.Nonempty := Nonempty.of_image₂_left
lemma Nonempty.of_diffs_right : (s \\ t).Nonempty → t.Nonempty := Nonempty.of_image₂_right
@[simp] lemma empty_diffs : ∅ \\ t = ∅ := image₂_empty_left
@[simp] lemma diffs_empty : s \\ ∅ = ∅ := image₂_empty_right
@[simp] lemma diffs_eq_empty : s \\ t = ∅ ↔ s = ∅ ∨ t = ∅ := image₂_eq_empty_iff
@[simp] lemma singleton_diffs : {a} \\ t = t.image (a \ ·) := image₂_singleton_left
@[simp] lemma diffs_singleton : s \\ {b} = s.image (· \ b) := image₂_singleton_right
lemma singleton_diffs_singleton : ({a} \\ {b} : Finset α) = {a \ b} := image₂_singleton
lemma diffs_union_left : (s₁ ∪ s₂) \\ t = s₁ \\ t ∪ s₂ \\ t := image₂_union_left
lemma diffs_union_right : s \\ (t₁ ∪ t₂) = s \\ t₁ ∪ s \\ t₂ := image₂_union_right
lemma diffs_inter_subset_left : (s₁ ∩ s₂) \\ t ⊆ s₁ \\ t ∩ s₂ \\ t := image₂_inter_subset_left
lemma diffs_inter_subset_right : s \\ (t₁ ∩ t₂) ⊆ s \\ t₁ ∩ s \\ t₂ := image₂_inter_subset_right
lemma subset_diffs {s t : Set α} :
↑u ⊆ Set.image2 (· \ ·) s t → ∃ s' t' : Finset α, ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ s' \\ t' :=
subset_set_image₂
variable (s t u)
lemma biUnion_image_sdiff_left : s.biUnion (fun a ↦ t.image (a \ ·)) = s \\ t := biUnion_image_left
lemma biUnion_image_sdiff_right : t.biUnion (fun b ↦ s.image (· \ b)) = s \\ t :=
biUnion_image_right
lemma image_sdiff_product (s t : Finset α) : (s ×ˢ t).image (uncurry (· \ ·)) = s \\ t :=
image_uncurry_product _ _ _
lemma diffs_right_comm : s \\ t \\ u = s \\ u \\ t := image₂_right_comm sdiff_right_comm
end Diffs
section Compls
variable [BooleanAlgebra α] (s s₁ s₂ t : Finset α)
/-- `sᶜˢ` is the finset of elements of the form `aᶜ` where `a ∈ s`. -/
def compls : Finset α → Finset α := map ⟨compl, compl_injective⟩
@[inherit_doc]
scoped[FinsetFamily] postfix:max "ᶜˢ" => Finset.compls
variable {s t} {a : α}
@[simp] lemma mem_compls : a ∈ sᶜˢ ↔ aᶜ ∈ s := by
rw [Iff.comm, ← mem_map' ⟨compl, compl_injective⟩, Embedding.coeFn_mk, compl_compl, compls]
variable (s t)
@[simp] lemma image_compl [DecidableEq α] : s.image compl = sᶜˢ := by simp [compls, map_eq_image]
@[simp, norm_cast] lemma coe_compls : (↑sᶜˢ : Set α) = compl '' ↑s := coe_map _ _
@[simp] lemma card_compls : #sᶜˢ = #s := card_map _
variable {s s₁ s₂ t}
lemma compl_mem_compls : a ∈ s → aᶜ ∈ sᶜˢ := mem_map_of_mem _
@[simp] lemma compls_subset_compls : s₁ᶜˢ ⊆ s₂ᶜˢ ↔ s₁ ⊆ s₂ := map_subset_map
lemma forall_mem_compls {p : α → Prop} : (∀ a ∈ sᶜˢ, p a) ↔ ∀ a ∈ s, p aᶜ := forall_mem_map
lemma exists_compls_iff {p : α → Prop} : (∃ a ∈ sᶜˢ, p a) ↔ ∃ a ∈ s, p aᶜ := by aesop
@[simp] lemma compls_compls (s : Finset α) : sᶜˢᶜˢ = s := by ext; simp
lemma compls_subset_iff : sᶜˢ ⊆ t ↔ s ⊆ tᶜˢ := by rw [← compls_subset_compls, compls_compls]
@[simp]
lemma compls_nonempty : sᶜˢ.Nonempty ↔ s.Nonempty := map_nonempty
protected alias ⟨Nonempty.of_compls, Nonempty.compls⟩ := compls_nonempty
attribute [aesop safe apply (rule_sets := [finsetNonempty])] Nonempty.compls
@[simp] lemma compls_empty : (∅ : Finset α)ᶜˢ = ∅ := map_empty _
@[simp] lemma compls_eq_empty : sᶜˢ = ∅ ↔ s = ∅ := map_eq_empty
@[simp] lemma compls_singleton (a : α) : {a}ᶜˢ = {aᶜ} := map_singleton _ _
@[simp] lemma compls_univ [Fintype α] : (univ : Finset α)ᶜˢ = univ := by ext; simp
variable [DecidableEq α]
@[simp] lemma compls_union (s t : Finset α) : (s ∪ t)ᶜˢ = sᶜˢ ∪ tᶜˢ := map_union _ _
@[simp] lemma compls_inter (s t : Finset α) : (s ∩ t)ᶜˢ = sᶜˢ ∩ tᶜˢ := map_inter _ _
@[simp] lemma compls_infs (s t : Finset α) : (s ⊼ t)ᶜˢ = sᶜˢ ⊻ tᶜˢ := by
simp_rw [← image_compl]; exact image_image₂_distrib fun _ _ ↦ compl_inf
@[simp] lemma compls_sups (s t : Finset α) : (s ⊻ t)ᶜˢ = sᶜˢ ⊼ tᶜˢ := by
simp_rw [← image_compl]; exact image_image₂_distrib fun _ _ ↦ compl_sup
@[simp] lemma infs_compls_eq_diffs (s t : Finset α) : s ⊼ tᶜˢ = s \\ t := by
ext; simp [sdiff_eq]; aesop
@[simp] lemma compls_infs_eq_diffs (s t : Finset α) : sᶜˢ ⊼ t = t \\ s := by
rw [infs_comm, infs_compls_eq_diffs]
@[simp] lemma diffs_compls_eq_infs (s t : Finset α) : s \\ tᶜˢ = s ⊼ t := by
rw [← infs_compls_eq_diffs, compls_compls]
variable {α : Type*} [DecidableEq α] [Fintype α] {𝒜 : Finset (Finset α)} {n : ℕ}
protected lemma _root_.Set.Sized.compls (h𝒜 : (𝒜 : Set (Finset α)).Sized n) :
(𝒜ᶜˢ : Set (Finset α)).Sized (Fintype.card α - n) :=
Finset.forall_mem_compls.2 <| fun s hs ↦ by rw [Finset.card_compl, h𝒜 hs]
lemma sized_compls (hn : n ≤ Fintype.card α) :
(𝒜ᶜˢ : Set (Finset α)).Sized n ↔ (𝒜 : Set (Finset α)).Sized (Fintype.card α - n) where
mp h𝒜 := by simpa using h𝒜.compls
mpr h𝒜 := by simpa only [Nat.sub_sub_self hn] using h𝒜.compls
end Compls
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Piecewise.lean | import Mathlib.Data.Finset.BooleanAlgebra
import Mathlib.Data.Set.Piecewise
import Mathlib.Order.Interval.Set.Basic
/-!
# Functions defined piecewise on a finset
This file defines `Finset.piecewise`: Given two functions `f`, `g`, `s.piecewise f g` is a function
which is equal to `f` on `s` and `g` on the complement.
## TODO
Should we deduplicate this from `Set.piecewise`?
-/
open Function
namespace Finset
variable {ι : Type*} {π : ι → Sort*} (s : Finset ι) (f g : ∀ i, π i)
/-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its
complement. -/
def piecewise [∀ j, Decidable (j ∈ s)] : ∀ i, π i := fun i ↦ if i ∈ s then f i else g i
lemma piecewise_insert_self [DecidableEq ι] {j : ι} [∀ i, Decidable (i ∈ insert j s)] :
(insert j s).piecewise f g j = f j := by simp [piecewise]
@[simp]
lemma piecewise_empty [∀ i : ι, Decidable (i ∈ (∅ : Finset ι))] : piecewise ∅ f g = g := by
ext i
simp [piecewise]
variable [∀ j, Decidable (j ∈ s)]
-- TODO: fix this in norm_cast
@[norm_cast move]
lemma piecewise_coe [∀ j, Decidable (j ∈ (s : Set ι))] :
(s : Set ι).piecewise f g = s.piecewise f g := by
ext
congr
@[simp]
lemma piecewise_eq_of_mem {i : ι} (hi : i ∈ s) : s.piecewise f g i = f i := by
simp [piecewise, hi]
@[simp]
lemma piecewise_eq_of_notMem {i : ι} (hi : i ∉ s) : s.piecewise f g i = g i := by
simp [piecewise, hi]
@[deprecated (since := "2025-05-23")] alias piecewise_eq_of_not_mem := piecewise_eq_of_notMem
lemma piecewise_congr {f f' g g' : ∀ i, π i} (hf : ∀ i ∈ s, f i = f' i)
(hg : ∀ i ∉ s, g i = g' i) : s.piecewise f g = s.piecewise f' g' :=
funext fun i => if_ctx_congr Iff.rfl (hf i) (hg i)
@[simp]
lemma piecewise_insert_of_ne [DecidableEq ι] {i j : ι} [∀ i, Decidable (i ∈ insert j s)]
(h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h]
lemma piecewise_insert [DecidableEq ι] (j : ι) [∀ i, Decidable (i ∈ insert j s)] :
(insert j s).piecewise f g = update (s.piecewise f g) j (f j) := by
classical simp only [← piecewise_coe, ← Set.piecewise_insert]
ext
congr
simp
lemma piecewise_cases {i} (p : π i → Prop) (hf : p (f i)) (hg : p (g i)) :
p (s.piecewise f g i) := by
by_cases hi : i ∈ s <;> simpa [hi]
lemma piecewise_singleton [DecidableEq ι] (i : ι) : piecewise {i} f g = update g i (f i) := by
rw [← insert_empty_eq, piecewise_insert, piecewise_empty]
lemma piecewise_piecewise_of_subset_left {s t : Finset ι} [∀ i, Decidable (i ∈ s)]
[∀ i, Decidable (i ∈ t)] (h : s ⊆ t) (f₁ f₂ g : ∀ a, π a) :
s.piecewise (t.piecewise f₁ f₂) g = s.piecewise f₁ g :=
s.piecewise_congr (fun _i hi => piecewise_eq_of_mem _ _ _ (h hi)) fun _ _ => rfl
@[simp]
lemma piecewise_idem_left (f₁ f₂ g : ∀ a, π a) :
s.piecewise (s.piecewise f₁ f₂) g = s.piecewise f₁ g :=
piecewise_piecewise_of_subset_left (Subset.refl _) _ _ _
lemma piecewise_piecewise_of_subset_right {s t : Finset ι} [∀ i, Decidable (i ∈ s)]
[∀ i, Decidable (i ∈ t)] (h : t ⊆ s) (f g₁ g₂ : ∀ a, π a) :
s.piecewise f (t.piecewise g₁ g₂) = s.piecewise f g₂ :=
s.piecewise_congr (fun _ _ => rfl) fun _i hi => t.piecewise_eq_of_notMem _ _ (mt (@h _) hi)
@[simp]
lemma piecewise_idem_right (f g₁ g₂ : ∀ a, π a) :
s.piecewise f (s.piecewise g₁ g₂) = s.piecewise f g₂ :=
piecewise_piecewise_of_subset_right (Subset.refl _) f g₁ g₂
lemma update_eq_piecewise {β : Type*} [DecidableEq ι] (f : ι → β) (i : ι) (v : β) :
update f i v = piecewise (singleton i) (fun _ => v) f :=
(piecewise_singleton (fun _ => v) _ _).symm
lemma update_piecewise [DecidableEq ι] (i : ι) (v : π i) :
update (s.piecewise f g) i v = s.piecewise (update f i v) (update g i v) := by
ext j
rcases em (j = i) with (rfl | hj) <;> by_cases hs : j ∈ s <;> simp [*]
lemma update_piecewise_of_mem [DecidableEq ι] {i : ι} (hi : i ∈ s) (v : π i) :
update (s.piecewise f g) i v = s.piecewise (update f i v) g := by
rw [update_piecewise]
refine s.piecewise_congr (fun _ _ => rfl) fun j hj => update_of_ne ?_ ..
exact fun h => hj (h.symm ▸ hi)
lemma update_piecewise_of_notMem [DecidableEq ι] {i : ι} (hi : i ∉ s) (v : π i) :
update (s.piecewise f g) i v = s.piecewise f (update g i v) := by
rw [update_piecewise]
refine s.piecewise_congr (fun j hj => update_of_ne ?_ ..) fun _ _ => rfl
exact fun h => hi (h ▸ hj)
@[deprecated (since := "2025-05-23")]
alias update_piecewise_of_not_mem := update_piecewise_of_notMem
lemma piecewise_same : s.piecewise f f = f := by
ext i
by_cases h : i ∈ s <;> simp [h]
section Fintype
variable [Fintype ι]
@[simp]
lemma piecewise_univ [∀ i, Decidable (i ∈ (univ : Finset ι))] (f g : ∀ i, π i) :
univ.piecewise f g = f := by
ext i
simp [piecewise]
lemma piecewise_compl [DecidableEq ι] (s : Finset ι) [∀ i, Decidable (i ∈ s)]
[∀ i, Decidable (i ∈ sᶜ)] (f g : ∀ i, π i) :
sᶜ.piecewise f g = s.piecewise g f := by
ext i
simp [piecewise]
@[simp]
lemma piecewise_erase_univ [DecidableEq ι] (i : ι) (f g : ∀ i, π i) :
(Finset.univ.erase i).piecewise f g = Function.update f i (g i) := by
rw [← compl_singleton, piecewise_compl, piecewise_singleton]
end Fintype
variable {π : ι → Type*} {t : Set ι} {t' : ∀ i, Set (π i)} {f g f' g' h : ∀ i, π i}
lemma piecewise_mem_set_pi (hf : f ∈ Set.pi t t') (hg : g ∈ Set.pi t t') :
s.piecewise f g ∈ Set.pi t t' := by
classical rw [← piecewise_coe]; exact Set.piecewise_mem_pi (↑s) hf hg
variable [∀ i, Preorder (π i)]
lemma piecewise_le_of_le_of_le (hf : f ≤ h) (hg : g ≤ h) : s.piecewise f g ≤ h := fun x =>
piecewise_cases s f g (· ≤ h x) (hf x) (hg x)
lemma le_piecewise_of_le_of_le (hf : h ≤ f) (hg : h ≤ g) : h ≤ s.piecewise f g := fun x =>
piecewise_cases s f g (fun y => h x ≤ y) (hf x) (hg x)
lemma piecewise_le_piecewise' (hf : ∀ x ∈ s, f x ≤ f' x) (hg : ∀ x ∉ s, g x ≤ g' x) :
s.piecewise f g ≤ s.piecewise f' g' := fun x => by by_cases hx : x ∈ s <;> simp [*]
lemma piecewise_le_piecewise (hf : f ≤ f') (hg : g ≤ g') : s.piecewise f g ≤ s.piecewise f' g' :=
s.piecewise_le_piecewise' (fun x _ => hf x) fun x _ => hg x
lemma piecewise_mem_Icc_of_mem_of_mem (hf : f ∈ Set.Icc f' g') (hg : g ∈ Set.Icc f' g') :
s.piecewise f g ∈ Set.Icc f' g' :=
⟨le_piecewise_of_le_of_le _ hf.1 hg.1, piecewise_le_of_le_of_le _ hf.2 hg.2⟩
lemma piecewise_mem_Icc (h : f ≤ g) : s.piecewise f g ∈ Set.Icc f g :=
piecewise_mem_Icc_of_mem_of_mem _ (Set.left_mem_Icc.2 h) (Set.right_mem_Icc.2 h)
lemma piecewise_mem_Icc' (h : g ≤ f) : s.piecewise f g ∈ Set.Icc g f :=
piecewise_mem_Icc_of_mem_of_mem _ (Set.right_mem_Icc.2 h) (Set.left_mem_Icc.2 h)
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Interval.lean | import Mathlib.Data.Finset.Grade
import Mathlib.Data.Finset.Powerset
import Mathlib.Order.Interval.Finset.Basic
/-!
# Intervals of finsets as finsets
This file provides the `LocallyFiniteOrder` instance for `Finset α` and calculates the cardinality
of finite intervals of finsets.
If `s t : Finset α`, then `Finset.Icc s t` is the finset of finsets which include `s` and are
included in `t`. For example,
`Finset.Icc {0, 1} {0, 1, 2, 3} = {{0, 1}, {0, 1, 2}, {0, 1, 3}, {0, 1, 2, 3}}`
and
`Finset.Icc {0, 1, 2} {0, 1, 3} = {}`.
In addition, this file gives characterizations of monotone and strictly monotone functions
out of `Finset α` in terms of `Finset.insert`
-/
variable {α β : Type*}
namespace Finset
section Decidable
/-- `LocallyFiniteOrder` instance for `Finset α`.
We provide an optimized definition for `Finset.Icc (s : Finset α) t`,
then define the other intervals based on `Icc`.
We do not define, e.g., `Finset.Ico` based on `Finset.ssubsets`,
because it would require more code without performance gain.
-/
instance instLocallyFiniteOrder [DecidableEq α] : LocallyFiniteOrder (Finset α) :=
.ofIcc _ (fun s t ↦
if s ⊆ t then
(t \ s).powerset.attach.map ⟨fun u ↦ u.1.disjUnion s <|
disjoint_sdiff_self_left.mono_left <| mem_powerset.mp u.2, fun u₁ u₂ h ↦ by
simpa only [disjUnion_inj_left, Subtype.eq_iff] using h⟩
else ∅) fun s t u ↦ by
by_cases hst : s ⊆ t
· suffices (∃ a ⊆ t, Disjoint a s ∧ a ∪ s = u) ↔ s ⊆ u ∧ u ⊆ t by
simpa [hst, subset_sdiff, and_assoc]
constructor
· rintro ⟨u, hut, -, rfl⟩
exact ⟨subset_union_right, union_subset hut hst⟩
· rintro ⟨hsu, hut⟩
exact ⟨u \ s, sdiff_subset.trans hut, disjoint_sdiff_self_left, sdiff_union_of_subset hsu⟩
· suffices s ⊆ u → ¬u ⊆ t by simpa [hst]
exact fun hsu hut ↦ hst (hsu.trans hut)
variable [DecidableEq α] (s t : Finset α)
theorem Icc_eq_filter_powerset : Icc s t = {u ∈ t.powerset | s ⊆ u} := by ext; simp [and_comm]
theorem Ico_eq_filter_ssubsets : Ico s t = {u ∈ t.ssubsets | s ⊆ u} := by ext; simp [and_comm]
theorem Ioc_eq_filter_powerset : Ioc s t = {u ∈ t.powerset | s ⊂ u} := by ext; simp [and_comm]
theorem Ioo_eq_filter_ssubsets : Ioo s t = {u ∈ t.ssubsets | s ⊂ u} := by ext; simp [and_comm]
theorem Iic_eq_powerset : Iic s = s.powerset := by ext; simp
theorem Iio_eq_ssubsets : Iio s = s.ssubsets := by ext; simp
variable {s t}
theorem Icc_eq_image_powerset (h : s ⊆ t) : Icc s t = (t \ s).powerset.image (s ∪ ·) := by
unfold Finset.Icc instLocallyFiniteOrder LocallyFiniteOrder.ofIcc
ext
simp [h, union_comm]
theorem Ico_eq_image_ssubsets (h : s ⊆ t) : Ico s t = (t \ s).ssubsets.image (s ∪ ·) := by
ext u
simp_rw [mem_Ico, mem_image, mem_ssubsets]
constructor
· rintro ⟨hs, ht⟩
exact ⟨u \ s, sdiff_lt_sdiff_right ht hs, sup_sdiff_cancel_right hs⟩
· rintro ⟨v, hv, rfl⟩
exact ⟨le_sup_left, sup_lt_of_lt_sdiff_left hv h⟩
/-- Cardinality of a non-empty `Icc` of finsets. -/
theorem card_Icc_finset (h : s ⊆ t) : (Icc s t).card = 2 ^ (t.card - s.card) := by
unfold Finset.Icc instLocallyFiniteOrder LocallyFiniteOrder.ofIcc
simp [h, card_sdiff_of_subset]
/-- Cardinality of an `Ico` of finsets. -/
theorem card_Ico_finset (h : s ⊆ t) : (Ico s t).card = 2 ^ (t.card - s.card) - 1 := by
rw [card_Ico_eq_card_Icc_sub_one, card_Icc_finset h]
/-- Cardinality of an `Ioc` of finsets. -/
theorem card_Ioc_finset (h : s ⊆ t) : (Ioc s t).card = 2 ^ (t.card - s.card) - 1 := by
rw [card_Ioc_eq_card_Icc_sub_one, card_Icc_finset h]
/-- Cardinality of an `Ioo` of finsets. -/
theorem card_Ioo_finset (h : s ⊆ t) : (Ioo s t).card = 2 ^ (t.card - s.card) - 2 := by
rw [card_Ioo_eq_card_Icc_sub_two, card_Icc_finset h]
/-- Cardinality of an `Iic` of finsets. -/
theorem card_Iic_finset : (Iic s).card = 2 ^ s.card := by rw [Iic_eq_powerset, card_powerset]
/-- Cardinality of an `Iio` of finsets. -/
theorem card_Iio_finset : (Iio s).card = 2 ^ s.card - 1 := by
rw [Iio_eq_ssubsets, ssubsets, card_erase_of_mem (mem_powerset_self _), card_powerset]
end Decidable
variable [Preorder β] {s t : Finset α} {f : Finset α → β}
section Cons
/-- A function `f` from `Finset α` is monotone if and only if `f s ≤ f (cons a s ha)` for all `s`
and `a ∉ s`. -/
lemma monotone_iff_forall_le_cons : Monotone f ↔ ∀ s, ∀ ⦃a⦄ (ha), f s ≤ f (cons a s ha) := by
classical simp [monotone_iff_forall_covBy, covBy_iff_exists_cons]
/-- A function `f` from `Finset α` is antitone if and only if `f (cons a s ha) ≤ f s` for all
`s` and `a ∉ s`. -/
lemma antitone_iff_forall_cons_le : Antitone f ↔ ∀ s ⦃a⦄ ha, f (cons a s ha) ≤ f s :=
monotone_iff_forall_le_cons (β := βᵒᵈ)
/-- A function `f` from `Finset α` is strictly monotone if and only if `f s < f (cons a s ha)` for
all `s` and `a ∉ s`. -/
lemma strictMono_iff_forall_lt_cons : StrictMono f ↔ ∀ s ⦃a⦄ ha, f s < f (cons a s ha) := by
classical simp [strictMono_iff_forall_covBy, covBy_iff_exists_cons]
/-- A function `f` from `Finset α` is strictly antitone if and only if `f (cons a s ha) < f s` for
all `s` and `a ∉ s`. -/
lemma strictAnti_iff_forall_cons_lt : StrictAnti f ↔ ∀ s ⦃a⦄ ha, f (cons a s ha) < f s :=
strictMono_iff_forall_lt_cons (β := βᵒᵈ)
end Cons
section Insert
variable [DecidableEq α]
/-- A function `f` from `Finset α` is monotone if and only if `f s ≤ f (insert a s)` for all `s` and
`a ∉ s`. -/
lemma monotone_iff_forall_le_insert : Monotone f ↔ ∀ s ⦃a⦄, a ∉ s → f s ≤ f (insert a s) := by
simp [monotone_iff_forall_le_cons]
/-- A function `f` from `Finset α` is antitone if and only if `f (insert a s) ≤ f s` for all
`s` and `a ∉ s`. -/
lemma antitone_iff_forall_insert_le : Antitone f ↔ ∀ s ⦃a⦄, a ∉ s → f (insert a s) ≤ f s :=
monotone_iff_forall_le_insert (β := βᵒᵈ)
/-- A function `f` from `Finset α` is strictly monotone if and only if `f s < f (insert a s)` for
all `s` and `a ∉ s`. -/
lemma strictMono_iff_forall_lt_insert : StrictMono f ↔ ∀ s ⦃a⦄, a ∉ s → f s < f (insert a s) := by
simp [strictMono_iff_forall_lt_cons]
/-- A function `f` from `Finset α` is strictly antitone if and only if `f (insert a s) < f s` for
all `s` and `a ∉ s`. -/
lemma strictAnti_iff_forall_lt_insert : StrictAnti f ↔ ∀ s ⦃a⦄, a ∉ s → f (insert a s) < f s :=
strictMono_iff_forall_lt_insert (β := βᵒᵈ)
end Insert
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/NAry.lean | import Mathlib.Data.Finset.Lattice.Prod
import Mathlib.Data.Finite.Prod
import Mathlib.Data.Set.Lattice.Image
/-!
# N-ary images of finsets
This file defines `Finset.image₂`, the binary image of finsets. This is the finset version of
`Set.image2`. This is mostly useful to define pointwise operations.
## Notes
This file is very similar to `Data.Set.NAry`, `Order.Filter.NAry` and `Data.Option.NAry`. Please
keep them in sync.
We do not define `Finset.image₃` as its only purpose would be to prove properties of `Finset.image₂`
and `Set.image2` already fulfills this task.
-/
open Function Set
variable {α α' β β' γ γ' δ δ' ε ε' ζ ζ' ν : Type*}
namespace Finset
variable [DecidableEq α'] [DecidableEq β'] [DecidableEq γ] [DecidableEq γ']
[DecidableEq δ'] [DecidableEq ε] [DecidableEq ε'] {f f' : α → β → γ} {g g' : α → β → γ → δ}
{s s' : Finset α} {t t' : Finset β} {u u' : Finset γ} {a a' : α} {b b' : β} {c : γ}
/-- The image of a binary function `f : α → β → γ` as a function `Finset α → Finset β → Finset γ`.
Mathematically this should be thought of as the image of the corresponding function `α × β → γ`. -/
def image₂ (f : α → β → γ) (s : Finset α) (t : Finset β) : Finset γ :=
(s ×ˢ t).image <| uncurry f
@[simp]
theorem mem_image₂ : c ∈ image₂ f s t ↔ ∃ a ∈ s, ∃ b ∈ t, f a b = c := by
simp [image₂, and_assoc]
@[simp, norm_cast]
theorem coe_image₂ (f : α → β → γ) (s : Finset α) (t : Finset β) :
(image₂ f s t : Set γ) = Set.image2 f s t :=
Set.ext fun _ => mem_image₂
theorem card_image₂_le (f : α → β → γ) (s : Finset α) (t : Finset β) :
#(image₂ f s t) ≤ #s * #t :=
card_image_le.trans_eq <| card_product _ _
theorem card_image₂_iff :
#(image₂ f s t) = #s * #t ↔ (s ×ˢ t : Set (α × β)).InjOn fun x => f x.1 x.2 := by
rw [← card_product, ← coe_product]
exact card_image_iff
theorem card_image₂ (hf : Injective2 f) (s : Finset α) (t : Finset β) :
#(image₂ f s t) = #s * #t :=
(card_image_of_injective _ hf.uncurry).trans <| card_product _ _
theorem mem_image₂_of_mem (ha : a ∈ s) (hb : b ∈ t) : f a b ∈ image₂ f s t :=
mem_image₂.2 ⟨a, ha, b, hb, rfl⟩
theorem mem_image₂_iff (hf : Injective2 f) : f a b ∈ image₂ f s t ↔ a ∈ s ∧ b ∈ t := by
rw [← mem_coe, coe_image₂, mem_image2_iff hf, mem_coe, mem_coe]
@[gcongr]
theorem image₂_subset (hs : s ⊆ s') (ht : t ⊆ t') : image₂ f s t ⊆ image₂ f s' t' := by
rw [← coe_subset, coe_image₂, coe_image₂]
exact image2_subset hs ht
theorem image₂_subset_left (ht : t ⊆ t') : image₂ f s t ⊆ image₂ f s t' :=
image₂_subset Subset.rfl ht
theorem image₂_subset_right (hs : s ⊆ s') : image₂ f s t ⊆ image₂ f s' t :=
image₂_subset hs Subset.rfl
theorem image_subset_image₂_left (hb : b ∈ t) : s.image (fun a => f a b) ⊆ image₂ f s t :=
image_subset_iff.2 fun _ ha => mem_image₂_of_mem ha hb
theorem image_subset_image₂_right (ha : a ∈ s) : t.image (fun b => f a b) ⊆ image₂ f s t :=
image_subset_iff.2 fun _ => mem_image₂_of_mem ha
lemma forall_mem_image₂ {p : γ → Prop} :
(∀ z ∈ image₂ f s t, p z) ↔ ∀ x ∈ s, ∀ y ∈ t, p (f x y) := by
simp_rw [← mem_coe, coe_image₂, forall_mem_image2]
lemma exists_mem_image₂ {p : γ → Prop} :
(∃ z ∈ image₂ f s t, p z) ↔ ∃ x ∈ s, ∃ y ∈ t, p (f x y) := by
simp_rw [← mem_coe, coe_image₂, exists_mem_image2]
@[simp]
theorem image₂_subset_iff : image₂ f s t ⊆ u ↔ ∀ x ∈ s, ∀ y ∈ t, f x y ∈ u :=
forall_mem_image₂
theorem image₂_subset_iff_left : image₂ f s t ⊆ u ↔ ∀ a ∈ s, (t.image fun b => f a b) ⊆ u := by
simp_rw [image₂_subset_iff, image_subset_iff]
theorem image₂_subset_iff_right : image₂ f s t ⊆ u ↔ ∀ b ∈ t, (s.image fun a => f a b) ⊆ u := by
simp_rw [image₂_subset_iff, image_subset_iff, @forall₂_swap α]
@[simp]
theorem image₂_nonempty_iff : (image₂ f s t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := by
rw [← coe_nonempty, coe_image₂]
exact image2_nonempty_iff
@[aesop safe apply (rule_sets := [finsetNonempty])]
theorem Nonempty.image₂ (hs : s.Nonempty) (ht : t.Nonempty) : (image₂ f s t).Nonempty :=
image₂_nonempty_iff.2 ⟨hs, ht⟩
theorem Nonempty.of_image₂_left (h : (s.image₂ f t).Nonempty) : s.Nonempty :=
(image₂_nonempty_iff.1 h).1
theorem Nonempty.of_image₂_right (h : (s.image₂ f t).Nonempty) : t.Nonempty :=
(image₂_nonempty_iff.1 h).2
@[simp]
theorem image₂_empty_left : image₂ f ∅ t = ∅ :=
coe_injective <| by simp
@[simp]
theorem image₂_empty_right : image₂ f s ∅ = ∅ :=
coe_injective <| by simp
@[simp]
theorem image₂_eq_empty_iff : image₂ f s t = ∅ ↔ s = ∅ ∨ t = ∅ := by
simp_rw [← not_nonempty_iff_eq_empty, image₂_nonempty_iff, not_and_or]
@[simp]
theorem image₂_singleton_left : image₂ f {a} t = t.image fun b => f a b :=
ext fun x => by simp
@[simp]
theorem image₂_singleton_right : image₂ f s {b} = s.image fun a => f a b :=
ext fun x => by simp
theorem image₂_singleton_left' : image₂ f {a} t = t.image (f a) :=
image₂_singleton_left
theorem image₂_singleton : image₂ f {a} {b} = {f a b} := by simp
theorem image₂_union_left [DecidableEq α] : image₂ f (s ∪ s') t = image₂ f s t ∪ image₂ f s' t :=
coe_injective <| by
push_cast
exact image2_union_left
theorem image₂_union_right [DecidableEq β] : image₂ f s (t ∪ t') = image₂ f s t ∪ image₂ f s t' :=
coe_injective <| by
push_cast
exact image2_union_right
@[simp]
theorem image₂_insert_left [DecidableEq α] :
image₂ f (insert a s) t = (t.image fun b => f a b) ∪ image₂ f s t :=
coe_injective <| by
push_cast
exact image2_insert_left
@[simp]
theorem image₂_insert_right [DecidableEq β] :
image₂ f s (insert b t) = (s.image fun a => f a b) ∪ image₂ f s t :=
coe_injective <| by
push_cast
exact image2_insert_right
theorem image₂_inter_left [DecidableEq α] (hf : Injective2 f) :
image₂ f (s ∩ s') t = image₂ f s t ∩ image₂ f s' t :=
coe_injective <| by
push_cast
exact image2_inter_left hf
theorem image₂_inter_right [DecidableEq β] (hf : Injective2 f) :
image₂ f s (t ∩ t') = image₂ f s t ∩ image₂ f s t' :=
coe_injective <| by
push_cast
exact image2_inter_right hf
theorem image₂_inter_subset_left [DecidableEq α] :
image₂ f (s ∩ s') t ⊆ image₂ f s t ∩ image₂ f s' t :=
coe_subset.1 <| by
push_cast
exact image2_inter_subset_left
theorem image₂_inter_subset_right [DecidableEq β] :
image₂ f s (t ∩ t') ⊆ image₂ f s t ∩ image₂ f s t' :=
coe_subset.1 <| by
push_cast
exact image2_inter_subset_right
theorem image₂_congr (h : ∀ a ∈ s, ∀ b ∈ t, f a b = f' a b) : image₂ f s t = image₂ f' s t :=
coe_injective <| by
push_cast
exact image2_congr h
/-- A common special case of `image₂_congr` -/
theorem image₂_congr' (h : ∀ a b, f a b = f' a b) : image₂ f s t = image₂ f' s t :=
image₂_congr fun a _ b _ => h a b
variable (s t)
theorem card_image₂_singleton_left (hf : Injective (f a)) : #(image₂ f {a} t) = #t := by
rw [image₂_singleton_left, card_image_of_injective _ hf]
theorem card_image₂_singleton_right (hf : Injective fun a => f a b) :
#(image₂ f s {b}) = #s := by rw [image₂_singleton_right, card_image_of_injective _ hf]
theorem image₂_singleton_inter [DecidableEq β] (t₁ t₂ : Finset β) (hf : Injective (f a)) :
image₂ f {a} (t₁ ∩ t₂) = image₂ f {a} t₁ ∩ image₂ f {a} t₂ := by
simp_rw [image₂_singleton_left, image_inter _ _ hf]
theorem image₂_inter_singleton [DecidableEq α] (s₁ s₂ : Finset α) (hf : Injective fun a => f a b) :
image₂ f (s₁ ∩ s₂) {b} = image₂ f s₁ {b} ∩ image₂ f s₂ {b} := by
simp_rw [image₂_singleton_right, image_inter _ _ hf]
theorem card_le_card_image₂_left {s : Finset α} (ha : a ∈ s) (hf : Injective (f a)) :
#t ≤ #(image₂ f s t) :=
card_le_card_of_injOn (f a) (fun _ hb ↦ mem_image₂_of_mem ha hb) hf.injOn
theorem card_le_card_image₂_right {t : Finset β} (hb : b ∈ t) (hf : Injective (f · b)) :
#s ≤ #(image₂ f s t) :=
card_le_card_of_injOn (f · b) (fun _ ha ↦ mem_image₂_of_mem ha hb) hf.injOn
variable {s t}
theorem biUnion_image_left : (s.biUnion fun a => t.image <| f a) = image₂ f s t :=
coe_injective <| by
push_cast
exact Set.iUnion_image_left _
theorem biUnion_image_right : (t.biUnion fun b => s.image fun a => f a b) = image₂ f s t :=
coe_injective <| by
push_cast
exact Set.iUnion_image_right _
/-!
### Algebraic replacement rules
A collection of lemmas to transfer associativity, commutativity, distributivity, ... of operations
to the associativity, commutativity, distributivity, ... of `Finset.image₂` of those operations.
The proof pattern is `image₂_lemma operation_lemma`. For example, `image₂_comm mul_comm` proves that
`image₂ (*) f g = image₂ (*) g f` in a `CommSemigroup`.
-/
section
variable [DecidableEq δ]
theorem image_image₂ (f : α → β → γ) (g : γ → δ) :
(image₂ f s t).image g = image₂ (fun a b => g (f a b)) s t :=
coe_injective <| by
push_cast
exact image_image2 _ _
theorem image₂_image_left (f : γ → β → δ) (g : α → γ) :
image₂ f (s.image g) t = image₂ (fun a b => f (g a) b) s t :=
coe_injective <| by
push_cast
exact image2_image_left _ _
theorem image₂_image_right (f : α → γ → δ) (g : β → γ) :
image₂ f s (t.image g) = image₂ (fun a b => f a (g b)) s t :=
coe_injective <| by
push_cast
exact image2_image_right _ _
@[simp]
theorem image₂_mk_eq_product [DecidableEq α] [DecidableEq β] (s : Finset α) (t : Finset β) :
image₂ Prod.mk s t = s ×ˢ t := by ext; simp [Prod.ext_iff]
@[simp]
theorem image₂_curry (f : α × β → γ) (s : Finset α) (t : Finset β) :
image₂ (curry f) s t = (s ×ˢ t).image f := rfl
@[simp]
theorem image_uncurry_product (f : α → β → γ) (s : Finset α) (t : Finset β) :
(s ×ˢ t).image (uncurry f) = image₂ f s t := rfl
theorem image₂_swap (f : α → β → γ) (s : Finset α) (t : Finset β) :
image₂ f s t = image₂ (fun a b => f b a) t s :=
coe_injective <| by
push_cast
exact image2_swap _ _ _
@[simp]
theorem image₂_left [DecidableEq α] (h : t.Nonempty) : image₂ (fun x _ => x) s t = s :=
coe_injective <| by
push_cast
exact image2_left h
@[simp]
theorem image₂_right [DecidableEq β] (h : s.Nonempty) : image₂ (fun _ y => y) s t = t :=
coe_injective <| by
push_cast
exact image2_right h
theorem image₂_assoc {γ : Type*} {u : Finset γ}
{f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε}
{g' : β → γ → ε'} (h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) :
image₂ f (image₂ g s t) u = image₂ f' s (image₂ g' t u) :=
coe_injective <| by
push_cast
exact image2_assoc h_assoc
theorem image₂_comm {g : β → α → γ} (h_comm : ∀ a b, f a b = g b a) : image₂ f s t = image₂ g t s :=
(image₂_swap _ _ _).trans <| by simp_rw [h_comm]
theorem image₂_left_comm {γ : Type*} {u : Finset γ} {f : α → δ → ε} {g : β → γ → δ}
{f' : α → γ → δ'} {g' : β → δ' → ε} (h_left_comm : ∀ a b c, f a (g b c) = g' b (f' a c)) :
image₂ f s (image₂ g t u) = image₂ g' t (image₂ f' s u) :=
coe_injective <| by
push_cast
exact image2_left_comm h_left_comm
theorem image₂_right_comm {γ : Type*} {u : Finset γ} {f : δ → γ → ε} {g : α → β → δ}
{f' : α → γ → δ'} {g' : δ' → β → ε} (h_right_comm : ∀ a b c, f (g a b) c = g' (f' a c) b) :
image₂ f (image₂ g s t) u = image₂ g' (image₂ f' s u) t :=
coe_injective <| by
push_cast
exact image2_right_comm h_right_comm
theorem image₂_image₂_image₂_comm {γ δ : Type*} {u : Finset γ} {v : Finset δ} [DecidableEq ζ]
[DecidableEq ζ'] [DecidableEq ν] {f : ε → ζ → ν} {g : α → β → ε} {h : γ → δ → ζ}
{f' : ε' → ζ' → ν} {g' : α → γ → ε'} {h' : β → δ → ζ'}
(h_comm : ∀ a b c d, f (g a b) (h c d) = f' (g' a c) (h' b d)) :
image₂ f (image₂ g s t) (image₂ h u v) = image₂ f' (image₂ g' s u) (image₂ h' t v) :=
coe_injective <| by
push_cast
exact image2_image2_image2_comm h_comm
theorem image_image₂_distrib {g : γ → δ} {f' : α' → β' → δ} {g₁ : α → α'} {g₂ : β → β'}
(h_distrib : ∀ a b, g (f a b) = f' (g₁ a) (g₂ b)) :
(image₂ f s t).image g = image₂ f' (s.image g₁) (t.image g₂) :=
coe_injective <| by
push_cast
exact image_image2_distrib h_distrib
/-- Symmetric statement to `Finset.image₂_image_left_comm`. -/
theorem image_image₂_distrib_left {g : γ → δ} {f' : α' → β → δ} {g' : α → α'}
(h_distrib : ∀ a b, g (f a b) = f' (g' a) b) :
(image₂ f s t).image g = image₂ f' (s.image g') t :=
coe_injective <| by
push_cast
exact image_image2_distrib_left h_distrib
/-- Symmetric statement to `Finset.image_image₂_right_comm`. -/
theorem image_image₂_distrib_right {g : γ → δ} {f' : α → β' → δ} {g' : β → β'}
(h_distrib : ∀ a b, g (f a b) = f' a (g' b)) :
(image₂ f s t).image g = image₂ f' s (t.image g') :=
coe_injective <| by
push_cast
exact image_image2_distrib_right h_distrib
/-- Symmetric statement to `Finset.image_image₂_distrib_left`. -/
theorem image₂_image_left_comm {f : α' → β → γ} {g : α → α'} {f' : α → β → δ} {g' : δ → γ}
(h_left_comm : ∀ a b, f (g a) b = g' (f' a b)) :
image₂ f (s.image g) t = (image₂ f' s t).image g' :=
(image_image₂_distrib_left fun a b => (h_left_comm a b).symm).symm
/-- Symmetric statement to `Finset.image_image₂_distrib_right`. -/
theorem image_image₂_right_comm {f : α → β' → γ} {g : β → β'} {f' : α → β → δ} {g' : δ → γ}
(h_right_comm : ∀ a b, f a (g b) = g' (f' a b)) :
image₂ f s (t.image g) = (image₂ f' s t).image g' :=
(image_image₂_distrib_right fun a b => (h_right_comm a b).symm).symm
/-- The other direction does not hold because of the `s`-`s` cross terms on the RHS. -/
theorem image₂_distrib_subset_left {γ : Type*} {u : Finset γ} {f : α → δ → ε} {g : β → γ → δ}
{f₁ : α → β → β'} {f₂ : α → γ → γ'} {g' : β' → γ' → ε}
(h_distrib : ∀ a b c, f a (g b c) = g' (f₁ a b) (f₂ a c)) :
image₂ f s (image₂ g t u) ⊆ image₂ g' (image₂ f₁ s t) (image₂ f₂ s u) :=
coe_subset.1 <| by
push_cast
exact Set.image2_distrib_subset_left h_distrib
/-- The other direction does not hold because of the `u`-`u` cross terms on the RHS. -/
theorem image₂_distrib_subset_right {γ : Type*} {u : Finset γ} {f : δ → γ → ε} {g : α → β → δ}
{f₁ : α → γ → α'} {f₂ : β → γ → β'} {g' : α' → β' → ε}
(h_distrib : ∀ a b c, f (g a b) c = g' (f₁ a c) (f₂ b c)) :
image₂ f (image₂ g s t) u ⊆ image₂ g' (image₂ f₁ s u) (image₂ f₂ t u) :=
coe_subset.1 <| by
push_cast
exact Set.image2_distrib_subset_right h_distrib
theorem image_image₂_antidistrib {g : γ → δ} {f' : β' → α' → δ} {g₁ : β → β'} {g₂ : α → α'}
(h_antidistrib : ∀ a b, g (f a b) = f' (g₁ b) (g₂ a)) :
(image₂ f s t).image g = image₂ f' (t.image g₁) (s.image g₂) := by
rw [image₂_swap f]
exact image_image₂_distrib fun _ _ => h_antidistrib _ _
/-- Symmetric statement to `Finset.image₂_image_left_anticomm`. -/
theorem image_image₂_antidistrib_left {g : γ → δ} {f' : β' → α → δ} {g' : β → β'}
(h_antidistrib : ∀ a b, g (f a b) = f' (g' b) a) :
(image₂ f s t).image g = image₂ f' (t.image g') s :=
coe_injective <| by
push_cast
exact image_image2_antidistrib_left h_antidistrib
/-- Symmetric statement to `Finset.image_image₂_right_anticomm`. -/
theorem image_image₂_antidistrib_right {g : γ → δ} {f' : β → α' → δ} {g' : α → α'}
(h_antidistrib : ∀ a b, g (f a b) = f' b (g' a)) :
(image₂ f s t).image g = image₂ f' t (s.image g') :=
coe_injective <| by
push_cast
exact image_image2_antidistrib_right h_antidistrib
/-- Symmetric statement to `Finset.image_image₂_antidistrib_left`. -/
theorem image₂_image_left_anticomm {f : α' → β → γ} {g : α → α'} {f' : β → α → δ} {g' : δ → γ}
(h_left_anticomm : ∀ a b, f (g a) b = g' (f' b a)) :
image₂ f (s.image g) t = (image₂ f' t s).image g' :=
(image_image₂_antidistrib_left fun a b => (h_left_anticomm b a).symm).symm
/-- Symmetric statement to `Finset.image_image₂_antidistrib_right`. -/
theorem image_image₂_right_anticomm {f : α → β' → γ} {g : β → β'} {f' : β → α → δ} {g' : δ → γ}
(h_right_anticomm : ∀ a b, f a (g b) = g' (f' b a)) :
image₂ f s (t.image g) = (image₂ f' t s).image g' :=
(image_image₂_antidistrib_right fun a b => (h_right_anticomm b a).symm).symm
/-- If `a` is a left identity for `f : α → β → β`, then `{a}` is a left identity for
`Finset.image₂ f`. -/
theorem image₂_left_identity {f : α → γ → γ} {a : α} (h : ∀ b, f a b = b) (t : Finset γ) :
image₂ f {a} t = t :=
coe_injective <| by rw [coe_image₂, coe_singleton, Set.image2_left_identity h]
/-- If `b` is a right identity for `f : α → β → α`, then `{b}` is a right identity for
`Finset.image₂ f`. -/
theorem image₂_right_identity {f : γ → β → γ} {b : β} (h : ∀ a, f a b = a) (s : Finset γ) :
image₂ f s {b} = s := by rw [image₂_singleton_right, funext h, image_id']
/-- If each partial application of `f` is injective, and images of `s` under those partial
applications are disjoint (but not necessarily distinct!), then the size of `t` divides the size of
`Finset.image₂ f s t`. -/
theorem card_dvd_card_image₂_right (hf : ∀ a ∈ s, Injective (f a))
(hs : ((fun a => t.image <| f a) '' s).PairwiseDisjoint id) : #t ∣ #(image₂ f s t) := by
classical
induction s using Finset.induction with
| empty => simp
| insert a s _ ih => ?_
specialize ih (forall_of_forall_insert hf)
(hs.subset <| Set.image_mono <| coe_subset.2 <| subset_insert _ _)
rw [image₂_insert_left]
by_cases h : Disjoint (image (f a) t) (image₂ f s t)
· rw [card_union_of_disjoint h]
exact Nat.dvd_add (card_image_of_injective _ <| hf _ <| mem_insert_self _ _).symm.dvd ih
simp_rw [← biUnion_image_left, disjoint_biUnion_right, not_forall] at h
obtain ⟨b, hb, h⟩ := h
rwa [union_eq_right.2]
exact (hs.eq (Set.mem_image_of_mem _ <| mem_insert_self _ _)
(Set.mem_image_of_mem _ <| mem_insert_of_mem hb) h).trans_subset
(image_subset_image₂_right hb)
/-- If each partial application of `f` is injective, and images of `t` under those partial
applications are disjoint (but not necessarily distinct!), then the size of `s` divides the size of
`Finset.image₂ f s t`. -/
theorem card_dvd_card_image₂_left (hf : ∀ b ∈ t, Injective fun a => f a b)
(ht : ((fun b => s.image fun a => f a b) '' t).PairwiseDisjoint id) :
#s ∣ #(image₂ f s t) := by rw [← image₂_swap]; exact card_dvd_card_image₂_right hf ht
/-- If a `Finset` is a subset of the image of two `Set`s under a binary operation,
then it is a subset of the `Finset.image₂` of two `Finset` subsets of these `Set`s. -/
theorem subset_set_image₂ {s : Set α} {t : Set β} (hu : ↑u ⊆ image2 f s t) :
∃ (s' : Finset α) (t' : Finset β), ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ image₂ f s' t' := by
rw [← Set.image_prod, subset_set_image_iff] at hu
rcases hu with ⟨u, hu, rfl⟩
classical
use u.image Prod.fst, u.image Prod.snd
simp only [coe_image, Set.image_subset_iff, image₂_image_left, image₂_image_right,
image_subset_iff]
exact ⟨fun _ h ↦ (hu h).1, fun _ h ↦ (hu h).2, fun x hx ↦ mem_image₂_of_mem hx hx⟩
end
section UnionInter
variable [DecidableEq α] [DecidableEq β]
theorem image₂_inter_union_subset_union :
image₂ f (s ∩ s') (t ∪ t') ⊆ image₂ f s t ∪ image₂ f s' t' :=
coe_subset.1 <| by
push_cast
exact Set.image2_inter_union_subset_union
theorem image₂_union_inter_subset_union :
image₂ f (s ∪ s') (t ∩ t') ⊆ image₂ f s t ∪ image₂ f s' t' :=
coe_subset.1 <| by
push_cast
exact Set.image2_union_inter_subset_union
theorem image₂_inter_union_subset {f : α → α → β} {s t : Finset α} (hf : ∀ a b, f a b = f b a) :
image₂ f (s ∩ t) (s ∪ t) ⊆ image₂ f s t :=
coe_subset.1 <| by
push_cast
exact image2_inter_union_subset hf
theorem image₂_union_inter_subset {f : α → α → β} {s t : Finset α} (hf : ∀ a b, f a b = f b a) :
image₂ f (s ∪ t) (s ∩ t) ⊆ image₂ f s t :=
coe_subset.1 <| by
push_cast
exact image2_union_inter_subset hf
end UnionInter
section SemilatticeSup
variable [SemilatticeSup δ]
@[simp (default + 1)] -- otherwise `simp` doesn't use `forall_mem_image₂`
lemma sup'_image₂_le {g : γ → δ} {a : δ} (h : (image₂ f s t).Nonempty) :
sup' (image₂ f s t) h g ≤ a ↔ ∀ x ∈ s, ∀ y ∈ t, g (f x y) ≤ a := by
rw [sup'_le_iff, forall_mem_image₂]
lemma sup'_image₂_left (g : γ → δ) (h : (image₂ f s t).Nonempty) :
sup' (image₂ f s t) h g =
sup' s h.of_image₂_left fun x ↦ sup' t h.of_image₂_right (g <| f x ·) := by
simp only [image₂, sup'_image, sup'_product_left]; rfl
lemma sup'_image₂_right (g : γ → δ) (h : (image₂ f s t).Nonempty) :
sup' (image₂ f s t) h g =
sup' t h.of_image₂_right fun y ↦ sup' s h.of_image₂_left (g <| f · y) := by
simp only [image₂, sup'_image, sup'_product_right]; rfl
variable [OrderBot δ]
@[simp (default + 1)] -- otherwise `simp` doesn't use `forall_mem_image₂`
lemma sup_image₂_le {g : γ → δ} {a : δ} :
sup (image₂ f s t) g ≤ a ↔ ∀ x ∈ s, ∀ y ∈ t, g (f x y) ≤ a := by
rw [Finset.sup_le_iff, forall_mem_image₂]
variable (s t)
lemma sup_image₂_left (g : γ → δ) : sup (image₂ f s t) g = sup s fun x ↦ sup t (g <| f x ·) := by
simp only [image₂, sup_image, sup_product_left]; rfl
lemma sup_image₂_right (g : γ → δ) : sup (image₂ f s t) g = sup t fun y ↦ sup s (g <| f · y) := by
simp only [image₂, sup_image, sup_product_right]; rfl
end SemilatticeSup
section SemilatticeInf
variable [SemilatticeInf δ]
@[simp (default + 1)] -- otherwise `simp` doesn't use `forall_mem_image₂`
lemma le_inf'_image₂ {g : γ → δ} {a : δ} (h : (image₂ f s t).Nonempty) :
a ≤ inf' (image₂ f s t) h g ↔ ∀ x ∈ s, ∀ y ∈ t, a ≤ g (f x y) := by
rw [le_inf'_iff, forall_mem_image₂]
lemma inf'_image₂_left (g : γ → δ) (h : (image₂ f s t).Nonempty) :
inf' (image₂ f s t) h g =
inf' s h.of_image₂_left fun x ↦ inf' t h.of_image₂_right (g <| f x ·) :=
sup'_image₂_left (δ := δᵒᵈ) g h
lemma inf'_image₂_right (g : γ → δ) (h : (image₂ f s t).Nonempty) :
inf' (image₂ f s t) h g =
inf' t h.of_image₂_right fun y ↦ inf' s h.of_image₂_left (g <| f · y) :=
sup'_image₂_right (δ := δᵒᵈ) g h
variable [OrderTop δ]
@[simp (default + 1)] -- otherwise `simp` doesn't use `forall_mem_image₂`
lemma le_inf_image₂ {g : γ → δ} {a : δ} :
a ≤ inf (image₂ f s t) g ↔ ∀ x ∈ s, ∀ y ∈ t, a ≤ g (f x y) :=
sup_image₂_le (δ := δᵒᵈ)
variable (s t)
lemma inf_image₂_left (g : γ → δ) : inf (image₂ f s t) g = inf s fun x ↦ inf t (g ∘ f x) :=
sup_image₂_left (δ := δᵒᵈ) ..
lemma inf_image₂_right (g : γ → δ) : inf (image₂ f s t) g = inf t fun y ↦ inf s (g <| f · y) :=
sup_image₂_right (δ := δᵒᵈ) ..
end SemilatticeInf
end Finset
open Finset
namespace Fintype
variable {ι : Type*} {α β γ : ι → Type*} [DecidableEq ι] [Fintype ι] [∀ i, DecidableEq (γ i)]
lemma piFinset_image₂ (f : ∀ i, α i → β i → γ i) (s : ∀ i, Finset (α i)) (t : ∀ i, Finset (β i)) :
piFinset (fun i ↦ image₂ (f i) (s i) (t i)) =
image₂ (fun a b i ↦ f _ (a i) (b i)) (piFinset s) (piFinset t) := by
ext; simp only [mem_piFinset, mem_image₂, Classical.skolem, forall_and, funext_iff]
end Fintype
namespace Set
variable [DecidableEq γ] {s : Set α} {t : Set β}
@[simp]
theorem toFinset_image2 (f : α → β → γ) (s : Set α) (t : Set β) [Fintype s] [Fintype t]
[Fintype (image2 f s t)] : (image2 f s t).toFinset = Finset.image₂ f s.toFinset t.toFinset :=
Finset.coe_injective <| by simp
theorem Finite.toFinset_image2 (f : α → β → γ) (hs : s.Finite) (ht : t.Finite)
(hf := hs.image2 f ht) : hf.toFinset = Finset.image₂ f hs.toFinset ht.toFinset :=
Finset.coe_injective <| by simp
end Set |
.lake/packages/mathlib/Mathlib/Data/Finset/Sigma.lean | import Mathlib.Data.Finset.Lattice.Fold
import Mathlib.Data.Set.Sigma
import Mathlib.Order.CompleteLattice.Finset
/-!
# Finite sets in a sigma type
This file defines a few `Finset` constructions on `Σ i, α i`.
## Main declarations
* `Finset.sigma`: Given a finset `s` in `ι` and finsets `t i` in each `α i`, `s.sigma t` is the
finset of the dependent sum `Σ i, α i`
* `Finset.sigmaLift`: Lifts maps `α i → β i → Finset (γ i)` to a map
`Σ i, α i → Σ i, β i → Finset (Σ i, γ i)`.
## TODO
`Finset.sigmaLift` can be generalized to any alternative functor. But to make the generalization
worth it, we must first refactor the functor library so that the `alternative` instance for `Finset`
is computable and universe-polymorphic.
-/
open Function Multiset
variable {ι : Type*}
namespace Finset
section Sigma
variable {α : ι → Type*} {β : Type*} (s s₁ s₂ : Finset ι) (t t₁ t₂ : ∀ i, Finset (α i))
/-- `s.sigma t` is the finset of dependent pairs `⟨i, a⟩` such that `i ∈ s` and `a ∈ t i`. -/
protected def sigma : Finset (Σ i, α i) :=
⟨_, s.nodup.sigma fun i => (t i).nodup⟩
variable {s s₁ s₂ t t₁ t₂}
@[simp, grind =]
theorem mem_sigma {a : Σ i, α i} : a ∈ s.sigma t ↔ a.1 ∈ s ∧ a.2 ∈ t a.1 :=
Multiset.mem_sigma
@[simp, norm_cast]
theorem coe_sigma (s : Finset ι) (t : ∀ i, Finset (α i)) :
(s.sigma t : Set (Σ i, α i)) = (s : Set ι).sigma fun i ↦ (t i : Set (α i)) :=
Set.ext fun _ => mem_sigma
@[simp]
theorem sigma_nonempty : (s.sigma t).Nonempty ↔ ∃ i ∈ s, (t i).Nonempty := by simp [Finset.Nonempty]
@[aesop safe apply (rule_sets := [finsetNonempty])]
alias ⟨_, Aesop.sigma_nonempty_of_exists_nonempty⟩ := sigma_nonempty
@[simp]
theorem sigma_eq_empty : s.sigma t = ∅ ↔ ∀ i ∈ s, t i = ∅ := by
simp only [← not_nonempty_iff_eq_empty, sigma_nonempty, not_exists, not_and]
@[mono]
theorem sigma_mono (hs : s₁ ⊆ s₂) (ht : ∀ i, t₁ i ⊆ t₂ i) : s₁.sigma t₁ ⊆ s₂.sigma t₂ :=
fun ⟨i, _⟩ h =>
let ⟨hi, ha⟩ := mem_sigma.1 h
mem_sigma.2 ⟨hs hi, ht i ha⟩
theorem pairwiseDisjoint_map_sigmaMk :
(s : Set ι).PairwiseDisjoint fun i => (t i).map (Embedding.sigmaMk i) := by
intro i _ j _ hij
rw [Function.onFun, disjoint_left]
simp_rw [mem_map, Function.Embedding.sigmaMk_apply]
rintro _ ⟨y, _, rfl⟩ ⟨z, _, hz'⟩
exact hij (congr_arg Sigma.fst hz'.symm)
@[simp]
theorem disjiUnion_map_sigma_mk :
s.disjiUnion (fun i => (t i).map (Embedding.sigmaMk i)) pairwiseDisjoint_map_sigmaMk =
s.sigma t :=
rfl
theorem sigma_eq_biUnion [DecidableEq (Σ i, α i)] (s : Finset ι) (t : ∀ i, Finset (α i)) :
s.sigma t = s.biUnion fun i => (t i).map <| Embedding.sigmaMk i := by
ext ⟨x, y⟩
simp [and_left_comm]
variable (s t) (f : (Σ i, α i) → β)
theorem sup_sigma [SemilatticeSup β] [OrderBot β] :
(s.sigma t).sup f = s.sup fun i => (t i).sup fun b => f ⟨i, b⟩ := by
simp only [le_antisymm_iff, Finset.sup_le_iff, mem_sigma, and_imp, Sigma.forall]
exact
⟨fun i a hi ha => (le_sup hi).trans' <| le_sup (f := fun a => f ⟨i, a⟩) ha, fun i hi a ha =>
le_sup <| mem_sigma.2 ⟨hi, ha⟩⟩
theorem inf_sigma [SemilatticeInf β] [OrderTop β] :
(s.sigma t).inf f = s.inf fun i => (t i).inf fun b => f ⟨i, b⟩ :=
@sup_sigma _ _ βᵒᵈ _ _ _ _ _
theorem _root_.biSup_finsetSigma [CompleteLattice β] (s : Finset ι) (t : ∀ i, Finset (α i))
(f : Sigma α → β) : ⨆ ij ∈ s.sigma t, f ij = ⨆ (i ∈ s) (j ∈ t i), f ⟨i, j⟩ := by
simp_rw [← Finset.iSup_coe, Finset.coe_sigma, biSup_sigma]
theorem _root_.biSup_finsetSigma' [CompleteLattice β] (s : Finset ι) (t : ∀ i, Finset (α i))
(f : ∀ i, α i → β) : ⨆ (i ∈ s) (j ∈ t i), f i j = ⨆ ij ∈ s.sigma t, f ij.fst ij.snd :=
Eq.symm (biSup_finsetSigma _ _ _)
theorem _root_.biInf_finsetSigma [CompleteLattice β] (s : Finset ι) (t : ∀ i, Finset (α i))
(f : Sigma α → β) : ⨅ ij ∈ s.sigma t, f ij = ⨅ (i ∈ s) (j ∈ t i), f ⟨i, j⟩ :=
biSup_finsetSigma (β := βᵒᵈ) _ _ _
theorem _root_.biInf_finsetSigma' [CompleteLattice β] (s : Finset ι) (t : ∀ i, Finset (α i))
(f : ∀ i, α i → β) : ⨅ (i ∈ s) (j ∈ t i), f i j = ⨅ ij ∈ s.sigma t, f ij.fst ij.snd :=
Eq.symm (biInf_finsetSigma _ _ _)
theorem _root_.Set.biUnion_finsetSigma (s : Finset ι) (t : ∀ i, Finset (α i))
(f : Sigma α → Set β) : ⋃ ij ∈ s.sigma t, f ij = ⋃ i ∈ s, ⋃ j ∈ t i, f ⟨i, j⟩ :=
biSup_finsetSigma _ _ _
theorem _root_.Set.biUnion_finsetSigma' (s : Finset ι) (t : ∀ i, Finset (α i))
(f : ∀ i, α i → Set β) : ⋃ i ∈ s, ⋃ j ∈ t i, f i j = ⋃ ij ∈ s.sigma t, f ij.fst ij.snd :=
biSup_finsetSigma' _ _ _
theorem _root_.Set.biInter_finsetSigma (s : Finset ι) (t : ∀ i, Finset (α i))
(f : Sigma α → Set β) : ⋂ ij ∈ s.sigma t, f ij = ⋂ i ∈ s, ⋂ j ∈ t i, f ⟨i, j⟩ :=
biInf_finsetSigma _ _ _
theorem _root_.Set.biInter_finsetSigma' (s : Finset ι) (t : ∀ i, Finset (α i))
(f : ∀ i, α i → Set β) : ⋂ i ∈ s, ⋂ j ∈ t i, f i j = ⋂ ij ∈ s.sigma t, f ij.1 ij.2 :=
biInf_finsetSigma' _ _ _
end Sigma
section SigmaLift
variable {α β γ : ι → Type*} [DecidableEq ι]
/-- Lifts maps `α i → β i → Finset (γ i)` to a map `Σ i, α i → Σ i, β i → Finset (Σ i, γ i)`. -/
def sigmaLift (f : ∀ ⦃i⦄, α i → β i → Finset (γ i)) (a : Sigma α) (b : Sigma β) :
Finset (Sigma γ) :=
dite (a.1 = b.1) (fun h => (f (h ▸ a.2) b.2).map <| Embedding.sigmaMk _) fun _ => ∅
theorem mem_sigmaLift (f : ∀ ⦃i⦄, α i → β i → Finset (γ i)) (a : Sigma α) (b : Sigma β)
(x : Sigma γ) :
x ∈ sigmaLift f a b ↔ ∃ (ha : a.1 = x.1) (hb : b.1 = x.1), x.2 ∈ f (ha ▸ a.2) (hb ▸ b.2) := by
obtain ⟨⟨i, a⟩, j, b⟩ := a, b
obtain rfl | h := Decidable.eq_or_ne i j
· constructor
· simp_rw [sigmaLift]
simp only [dite_eq_ite, ite_true, mem_map, Embedding.sigmaMk_apply, forall_exists_index,
and_imp]
rintro x hx rfl
exact ⟨rfl, rfl, hx⟩
· rintro ⟨⟨⟩, ⟨⟩, hx⟩
rw [sigmaLift, dif_pos rfl, mem_map]
exact ⟨_, hx, by simp⟩
· rw [sigmaLift, dif_neg h]
refine iff_of_false (notMem_empty _) ?_
rintro ⟨⟨⟩, ⟨⟩, _⟩
exact h rfl
theorem mk_mem_sigmaLift (f : ∀ ⦃i⦄, α i → β i → Finset (γ i)) (i : ι) (a : α i) (b : β i)
(x : γ i) : (⟨i, x⟩ : Sigma γ) ∈ sigmaLift f ⟨i, a⟩ ⟨i, b⟩ ↔ x ∈ f a b := by
rw [sigmaLift, dif_pos rfl, mem_map]
refine ⟨?_, fun hx => ⟨_, hx, rfl⟩⟩
rintro ⟨x, hx, _, rfl⟩
exact hx
theorem notMem_sigmaLift_of_ne_left (f : ∀ ⦃i⦄, α i → β i → Finset (γ i)) (a : Sigma α)
(b : Sigma β) (x : Sigma γ) (h : a.1 ≠ x.1) : x ∉ sigmaLift f a b := by
rw [mem_sigmaLift]
exact fun H => h H.fst
@[deprecated (since := "2025-05-23")]
alias not_mem_sigmaLift_of_ne_left := notMem_sigmaLift_of_ne_left
theorem notMem_sigmaLift_of_ne_right (f : ∀ ⦃i⦄, α i → β i → Finset (γ i)) {a : Sigma α}
(b : Sigma β) {x : Sigma γ} (h : b.1 ≠ x.1) : x ∉ sigmaLift f a b := by
rw [mem_sigmaLift]
exact fun H => h H.snd.fst
@[deprecated (since := "2025-05-23")]
alias not_mem_sigmaLift_of_ne_right := notMem_sigmaLift_of_ne_right
variable {f g : ∀ ⦃i⦄, α i → β i → Finset (γ i)} {a : Σ i, α i} {b : Σ i, β i}
theorem sigmaLift_nonempty :
(sigmaLift f a b).Nonempty ↔ ∃ h : a.1 = b.1, (f (h ▸ a.2) b.2).Nonempty := by
simp_rw [nonempty_iff_ne_empty, sigmaLift]
split_ifs with h <;> simp [h]
theorem sigmaLift_eq_empty : sigmaLift f a b = ∅ ↔ ∀ h : a.1 = b.1, f (h ▸ a.2) b.2 = ∅ := by
simp_rw [sigmaLift]
split_ifs with h
· simp [h]
· simp [h]
theorem sigmaLift_mono
(h : ∀ ⦃i⦄ ⦃a : α i⦄ ⦃b : β i⦄, f a b ⊆ g a b) (a : Σ i, α i) (b : Σ i, β i) :
sigmaLift f a b ⊆ sigmaLift g a b := by
rintro x hx
rw [mem_sigmaLift] at hx ⊢
obtain ⟨ha, hb, hx⟩ := hx
exact ⟨ha, hb, h hx⟩
variable (f a b)
theorem card_sigmaLift :
(sigmaLift f a b).card = dite (a.1 = b.1) (fun h => (f (h ▸ a.2) b.2).card) fun _ => 0 := by
simp_rw [sigmaLift]
split_ifs with h <;> simp
end SigmaLift
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Update.lean | import Mathlib.Data.Finset.Pi
import Mathlib.Logic.Function.DependsOn
/-!
# Update a function on a set of values
This file defines `Function.updateFinset`, the operation that updates a function on a
(finite) set of values.
This is a very specific function used for `MeasureTheory.marginal`, and possibly not that useful
for other purposes.
-/
variable {ι : Sort _} {π : ι → Sort _} {x : ∀ i, π i} [DecidableEq ι]
namespace Function
/-- `updateFinset x s y` is the vector `x` with the coordinates in `s` changed to the values of `y`.
-/
def updateFinset (x : ∀ i, π i) (s : Finset ι) (y : ∀ i : ↥s, π i) (i : ι) : π i :=
if hi : i ∈ s then y ⟨i, hi⟩ else x i
open Finset Equiv
theorem updateFinset_def {s : Finset ι} {y} :
updateFinset x s y = fun i ↦ if hi : i ∈ s then y ⟨i, hi⟩ else x i :=
rfl
@[simp] theorem updateFinset_empty {y} : updateFinset x ∅ y = x :=
rfl
theorem updateFinset_singleton {i y} :
updateFinset x {i} y = Function.update x i (y ⟨i, mem_singleton_self i⟩) := by
congr with j
by_cases hj : j = i
· cases hj
simp only [dif_pos, Finset.mem_singleton, update_self, updateFinset]
· simp [hj, updateFinset]
theorem update_eq_updateFinset {i y} :
Function.update x i y = updateFinset x {i} (uniqueElim y) := by
congr with j
by_cases hj : j = i
· cases hj
simp only [dif_pos, Finset.mem_singleton, update_self, updateFinset]
exact uniqueElim_default (α := fun j : ({i} : Finset ι) => π j) y
· simp [hj, updateFinset]
/-- If one replaces the variables indexed by a finite set `t`, then `f` no longer depends on
those variables. -/
theorem _root_.DependsOn.updateFinset {α : Type*} {f : (Π i, π i) → α} {s : Set ι}
(hf : DependsOn f s) {t : Finset ι} (y : Π i : t, π i) :
DependsOn (fun x ↦ f (updateFinset x t y)) (s \ t) := by
refine fun x₁ x₂ h ↦ hf (fun i hi ↦ ?_)
simp only [Function.updateFinset]
split_ifs; · rfl
simp_all
/-- If one replaces the variable indexed by `i`, then `f` no longer depends on
this variable. -/
theorem _root_.DependsOn.update {α : Type*} {f : (Π i, π i) → α} {s : Finset ι} (hf : DependsOn f s)
(i : ι) (y : π i) : DependsOn (fun x ↦ f (Function.update x i y)) (s.erase i) := by
simp_rw [Function.update_eq_updateFinset, erase_eq, coe_sdiff]
exact hf.updateFinset _
theorem updateFinset_updateFinset {s t : Finset ι} (hst : Disjoint s t)
{y : ∀ i : ↥s, π i} {z : ∀ i : ↥t, π i} :
updateFinset (updateFinset x s y) t z =
updateFinset x (s ∪ t) (Equiv.piFinsetUnion π hst ⟨y, z⟩) := by
set e := Equiv.Finset.union s t hst
ext i
by_cases his : i ∈ s <;> by_cases hit : i ∈ t <;>
simp only [updateFinset, his, hit, dif_pos, dif_neg, Finset.mem_union, false_or, not_false_iff]
· exfalso; exact Finset.disjoint_left.mp hst his hit
· exact piCongrLeft_sumInl (fun b : ↥(s ∪ t) => π b) e y z ⟨i, his⟩ |>.symm
· exact piCongrLeft_sumInr (fun b : ↥(s ∪ t) => π b) e y z ⟨i, hit⟩ |>.symm
lemma updateFinset_updateFinset_of_subset {s t : Finset ι} (hst : s ⊆ t)
(x : Π i, π i) (y : Π i : s, π i) (z : Π i : t, π i) :
updateFinset (updateFinset x s y) t z = updateFinset x t z := by
ext i
simp only [updateFinset]
split_ifs with h1 h2 <;> try rfl
exact (h1 (hst h2)).elim
lemma restrict_updateFinset_of_subset {s t : Finset ι} (hst : s ⊆ t) (x : Π i, π i)
(y : Π i : t, π i) : s.restrict (updateFinset x t y) = restrict₂ hst y := by
ext i
simp [updateFinset, dif_pos (hst i.2)]
lemma restrict_updateFinset {s : Finset ι} (x : Π i, π i) (y : Π i : s, π i) :
s.restrict (updateFinset x s y) = y := by
rw [restrict_updateFinset_of_subset subset_rfl]
rfl
@[simp]
lemma updateFinset_restrict {s : Finset ι} (x : Π i, π i) :
updateFinset x s (s.restrict x) = x := by
ext i
simp [updateFinset]
end Function |
.lake/packages/mathlib/Mathlib/Data/Finset/SMulAntidiagonal.lean | import Mathlib.Algebra.Group.Pointwise.Set.Scalar
import Mathlib.Data.Set.SMulAntidiagonal
/-!
# Antidiagonal for scalar multiplication as a `Finset`.
Given partially ordered sets `G` and `P`, with an action of `G` on `P` that preserves and reflects
the order relation, we construct, for any element `a` in `P` and partially well-ordered subsets `s`
in `G` and `t` in `P`, the `Finset` of all pairs of an element in `s` and an element in `t` that
scalar-multiply to `a`.
## Definitions
* Finset.SMulAntidiagonal : Finset antidiagonal for PWO inputs.
* Finset.VAddAntidiagonal : Finset antidiagonal for PWO inputs.
-/
variable {G P : Type*}
open Pointwise
namespace Set
@[to_additive]
theorem IsPWO.smul [Preorder G] [Preorder P] [SMul G P] [IsOrderedSMul G P]
{s : Set G} {t : Set P} (hs : s.IsPWO) (ht : t.IsPWO) : IsPWO (s • t) := by
rw [← @image_smul_prod]
exact (hs.prod ht).image_of_monotone (monotone_fst.smul monotone_snd)
@[to_additive]
theorem IsWF.smul [LinearOrder G] [LinearOrder P] [SMul G P] [IsOrderedSMul G P] {s : Set G}
{t : Set P} (hs : s.IsWF) (ht : t.IsWF) : IsWF (s • t) :=
(hs.isPWO.smul ht.isPWO).isWF
@[to_additive]
theorem IsWF.min_smul [LinearOrder G] [LinearOrder P] [SMul G P] [IsOrderedSMul G P]
{s : Set G} {t : Set P} (hs : s.IsWF) (ht : t.IsWF) (hsn : s.Nonempty) (htn : t.Nonempty) :
(hs.smul ht).min (hsn.smul htn) = hs.min hsn • ht.min htn := by
refine le_antisymm (IsWF.min_le _ _ (mem_smul.2 ⟨_, hs.min_mem _, _, ht.min_mem _, rfl⟩)) ?_
rw [IsWF.le_min_iff]
rintro _ ⟨x, hx, y, hy, rfl⟩
exact IsOrderedSMul.smul_le_smul (hs.min_le _ hx) (ht.min_le _ hy)
end Set
namespace Finset
section
open Set
variable [PartialOrder G] [PartialOrder P] [SMul G P] [IsOrderedCancelSMul G P] {s : Set G}
{t : Set P} (hs : s.IsPWO) (ht : t.IsPWO) (a : P) {u : Set G} {hu : u.IsPWO} {v : Set P}
{hv : v.IsPWO} {x : G × P}
/-- `Finset.SMulAntidiagonal hs ht a` is the set of all pairs of an element in `s` and an
element in `t` whose scalar multiplication yields `a`, but its construction requires proofs that `s`
and `t` are well-ordered. -/
@[to_additive /-- `Finset.VAddAntidiagonal hs ht a` is the set of all pairs of an element in `s`
and an element in `t` whose vector addition yields `a`, but its construction requires proofs that
`s` and `t` are well-ordered. -/]
noncomputable def SMulAntidiagonal [PartialOrder G] [PartialOrder P] [IsOrderedCancelSMul G P]
{s : Set G} {t : Set P} (hs : s.IsPWO) (ht : t.IsPWO) (a : P) : Finset (G × P) :=
(SMulAntidiagonal.finite_of_isPWO hs ht a).toFinset
@[to_additive (attr := simp)]
theorem mem_smulAntidiagonal :
x ∈ SMulAntidiagonal hs ht a ↔ x.1 ∈ s ∧ x.2 ∈ t ∧ x.1 • x.2 = a := by
simp only [SMulAntidiagonal, Set.Finite.mem_toFinset]
exact Set.mem_sep_iff
@[to_additive]
theorem smulAntidiagonal_mono_left {a : P} {hs : s.IsPWO} {ht : t.IsPWO} (h : u ⊆ s) :
SMulAntidiagonal hu ht a ⊆ SMulAntidiagonal hs ht a :=
Set.Finite.toFinset_mono <| Set.smulAntidiagonal_mono_left h
@[to_additive]
theorem smulAntidiagonal_mono_right {a : P} {hs : s.IsPWO} {ht : t.IsPWO} (h : v ⊆ t) :
SMulAntidiagonal hs hv a ⊆ SMulAntidiagonal hs ht a :=
Set.Finite.toFinset_mono <| Set.smulAntidiagonal_mono_right h
@[to_additive]
theorem support_smulAntidiagonal_subset_smul {hs : s.IsPWO} {ht : t.IsPWO} :
{ a | (SMulAntidiagonal hs ht a).Nonempty } ⊆ (s • t) :=
fun a ⟨b, hb⟩ => by
rw [mem_smulAntidiagonal] at hb
rw [Set.mem_smul]
use b.1
refine { left := hb.1, right := ?_ }
use b.2
exact { left := hb.2.1, right := hb.2.2 }
@[to_additive]
theorem isPWO_support_smulAntidiagonal {hs : s.IsPWO} {ht : t.IsPWO} :
{ a | (SMulAntidiagonal hs ht a).Nonempty }.IsPWO :=
(hs.smul ht).mono (support_smulAntidiagonal_subset_smul)
end
@[to_additive]
theorem smulAntidiagonal_min_smul_min [LinearOrder G] [LinearOrder P] [SMul G P]
[IsOrderedCancelSMul G P] {s : Set G} {t : Set P} (hs : s.IsWF) (ht : t.IsWF) (hns : s.Nonempty)
(hnt : t.Nonempty) :
SMulAntidiagonal hs.isPWO ht.isPWO (hs.min hns • ht.min hnt) = {(hs.min hns, ht.min hnt)} := by
ext ⟨a, b⟩
simp only [mem_smulAntidiagonal, mem_singleton, Prod.ext_iff]
constructor
· rintro ⟨has, hat, hst⟩
obtain rfl :=
(hs.min_le hns has).eq_of_not_lt fun hlt =>
(SMul.smul_lt_smul_of_lt_of_le hlt <| ht.min_le hnt hat).ne' hst
exact ⟨rfl, IsCancelSMul.left_cancel _ _ _ hst⟩
· rintro ⟨rfl, rfl⟩
exact ⟨hs.min_mem _, ht.min_mem _, rfl⟩
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Prod.lean | import Mathlib.Data.Finset.Card
import Mathlib.Data.Finset.Union
/-!
# Finsets in product types
This file defines finset constructions on the product type `α × β`. Beware not to confuse with the
`Finset.prod` operation which computes the multiplicative product.
## Main declarations
* `Finset.product`: Turns `s : Finset α`, `t : Finset β` into their product in `Finset (α × β)`.
* `Finset.diag`: For `s : Finset α`, `s.diag` is the `Finset (α × α)` of pairs `(a, a)` with
`a ∈ s`.
* `Finset.offDiag`: For `s : Finset α`, `s.offDiag` is the `Finset (α × α)` of pairs `(a, b)` with
`a, b ∈ s` and `a ≠ b`.
-/
assert_not_exists MonoidWithZero
open Multiset
variable {α β γ : Type*}
namespace Finset
/-! ### prod -/
section Prod
variable {s s' : Finset α} {t t' : Finset β} {a : α} {b : β}
/-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/
protected def product (s : Finset α) (t : Finset β) : Finset (α × β) :=
⟨_, s.nodup.product t.nodup⟩
instance instSProd : SProd (Finset α) (Finset β) (Finset (α × β)) where
sprod := Finset.product
@[simp]
theorem product_eq_sprod : Finset.product s t = s ×ˢ t :=
rfl
@[simp]
theorem product_val : (s ×ˢ t).1 = s.1 ×ˢ t.1 :=
rfl
@[simp, grind =]
theorem mem_product {p : α × β} : p ∈ s ×ˢ t ↔ p.1 ∈ s ∧ p.2 ∈ t :=
Multiset.mem_product
theorem mk_mem_product (ha : a ∈ s) (hb : b ∈ t) : (a, b) ∈ s ×ˢ t :=
mem_product.2 ⟨ha, hb⟩
@[simp, norm_cast]
theorem coe_product (s : Finset α) (t : Finset β) :
(↑(s ×ˢ t) : Set (α × β)) = (s : Set α) ×ˢ t :=
Set.ext fun _ => Finset.mem_product
theorem subset_product_image_fst [DecidableEq α] : (s ×ˢ t).image Prod.fst ⊆ s := fun i => by
simp +contextual [mem_image]
theorem subset_product_image_snd [DecidableEq β] : (s ×ˢ t).image Prod.snd ⊆ t := fun i => by
simp +contextual [mem_image]
theorem product_image_fst [DecidableEq α] (ht : t.Nonempty) : (s ×ˢ t).image Prod.fst = s := by
ext i
simp [mem_image, ht.exists_mem]
theorem product_image_snd [DecidableEq β] (ht : s.Nonempty) : (s ×ˢ t).image Prod.snd = t := by
ext i
simp [mem_image, ht.exists_mem]
theorem subset_product [DecidableEq α] [DecidableEq β] {s : Finset (α × β)} :
s ⊆ s.image Prod.fst ×ˢ s.image Prod.snd := by grind
@[gcongr]
theorem product_subset_product (hs : s ⊆ s') (ht : t ⊆ t') : s ×ˢ t ⊆ s' ×ˢ t' := fun ⟨_, _⟩ h =>
mem_product.2 ⟨hs (mem_product.1 h).1, ht (mem_product.1 h).2⟩
theorem product_subset_product_left (hs : s ⊆ s') : s ×ˢ t ⊆ s' ×ˢ t :=
product_subset_product hs (Subset.refl _)
theorem product_subset_product_right (ht : t ⊆ t') : s ×ˢ t ⊆ s ×ˢ t' :=
product_subset_product (Subset.refl _) ht
theorem prodMap_image_product {δ : Type*} [DecidableEq β] [DecidableEq δ]
(f : α → β) (g : γ → δ) (s : Finset α) (t : Finset γ) :
(s ×ˢ t).image (Prod.map f g) = s.image f ×ˢ t.image g :=
mod_cast Set.prodMap_image_prod f g s t
theorem prodMap_map_product {δ : Type*} (f : α ↪ β) (g : γ ↪ δ) (s : Finset α) (t : Finset γ) :
(s ×ˢ t).map (f.prodMap g) = s.map f ×ˢ t.map g := by
simpa [← coe_inj] using Set.prodMap_image_prod f g s t
theorem map_swap_product (s : Finset α) (t : Finset β) :
(t ×ˢ s).map ⟨Prod.swap, Prod.swap_injective⟩ = s ×ˢ t :=
coe_injective <| by
push_cast
exact Set.image_swap_prod _ _
@[simp]
theorem image_swap_product [DecidableEq (α × β)] (s : Finset α) (t : Finset β) :
(t ×ˢ s).image Prod.swap = s ×ˢ t :=
coe_injective <| by
push_cast
exact Set.image_swap_prod _ _
theorem product_eq_biUnion [DecidableEq (α × β)] (s : Finset α) (t : Finset β) :
s ×ˢ t = s.biUnion fun a => t.image fun b => (a, b) := by grind
theorem product_eq_biUnion_right [DecidableEq (α × β)] (s : Finset α) (t : Finset β) :
s ×ˢ t = t.biUnion fun b => s.image fun a => (a, b) := by grind
/-- See also `Finset.sup_product_left`. -/
@[simp]
theorem product_biUnion [DecidableEq γ] (s : Finset α) (t : Finset β) (f : α × β → Finset γ) :
(s ×ˢ t).biUnion f = s.biUnion fun a => t.biUnion fun b => f (a, b) := by grind
@[simp]
theorem card_product (s : Finset α) (t : Finset β) : card (s ×ˢ t) = card s * card t :=
Multiset.card_product _ _
/-- The product of two Finsets is nontrivial iff both are nonempty
at least one of them is nontrivial. -/
lemma nontrivial_prod_iff : (s ×ˢ t).Nontrivial ↔
s.Nonempty ∧ t.Nonempty ∧ (s.Nontrivial ∨ t.Nontrivial) := by
simp_rw [← card_pos, ← one_lt_card_iff_nontrivial, card_product]; apply Nat.one_lt_mul_iff
theorem filter_product (p : α → Prop) (q : β → Prop) [DecidablePred p] [DecidablePred q] :
((s ×ˢ t).filter fun x : α × β => p x.1 ∧ q x.2) = s.filter p ×ˢ t.filter q := by grind
theorem filter_product_left (p : α → Prop) [DecidablePred p] :
((s ×ˢ t).filter fun x : α × β => p x.1) = s.filter p ×ˢ t := by
simpa using filter_product p fun _ => true
theorem filter_product_right (q : β → Prop) [DecidablePred q] :
((s ×ˢ t).filter fun x : α × β => q x.2) = s ×ˢ t.filter q := by
simpa using filter_product (fun _ : α => true) q
theorem filter_product_card (s : Finset α) (t : Finset β) (p : α → Prop) (q : β → Prop)
[DecidablePred p] [DecidablePred q] :
((s ×ˢ t).filter fun x : α × β => (p x.1) = (q x.2)).card =
(s.filter p).card * (t.filter q).card +
(s.filter (¬ p ·)).card * (t.filter (¬ q ·)).card := by
classical
rw [← card_product, ← card_product, ← filter_product, ← filter_product, ← card_union_of_disjoint]
· apply congr_arg
ext ⟨a, b⟩
simp only [filter_union_right, mem_filter, mem_product]
constructor <;> intro h <;> use h.1
· simp only [h.2, Decidable.em, and_self]
· revert h
simp only [and_imp]
rintro _ _ (_ | _) <;> simp [*]
· apply Finset.disjoint_filter_filter'
exact (disjoint_compl_right.inf_left _).inf_right _
@[simp]
theorem empty_product (t : Finset β) : (∅ : Finset α) ×ˢ t = ∅ :=
rfl
@[simp]
theorem product_empty (s : Finset α) : s ×ˢ (∅ : Finset β) = ∅ :=
eq_empty_of_forall_notMem fun _ h => notMem_empty _ (Finset.mem_product.1 h).2
@[aesop safe apply (rule_sets := [finsetNonempty])]
theorem Nonempty.product (hs : s.Nonempty) (ht : t.Nonempty) : (s ×ˢ t).Nonempty :=
let ⟨x, hx⟩ := hs
let ⟨y, hy⟩ := ht
⟨(x, y), mem_product.2 ⟨hx, hy⟩⟩
theorem Nonempty.fst (h : (s ×ˢ t).Nonempty) : s.Nonempty :=
let ⟨xy, hxy⟩ := h
⟨xy.1, (mem_product.1 hxy).1⟩
theorem Nonempty.snd (h : (s ×ˢ t).Nonempty) : t.Nonempty :=
let ⟨xy, hxy⟩ := h
⟨xy.2, (mem_product.1 hxy).2⟩
@[simp]
theorem nonempty_product : (s ×ˢ t).Nonempty ↔ s.Nonempty ∧ t.Nonempty :=
⟨fun h => ⟨h.fst, h.snd⟩, fun h => h.1.product h.2⟩
@[simp]
theorem product_eq_empty {s : Finset α} {t : Finset β} : s ×ˢ t = ∅ ↔ s = ∅ ∨ t = ∅ := by
rw [← not_nonempty_iff_eq_empty, nonempty_product, not_and_or, not_nonempty_iff_eq_empty,
not_nonempty_iff_eq_empty]
@[simp]
theorem singleton_product {a : α} :
({a} : Finset α) ×ˢ t = t.map ⟨Prod.mk a, Prod.mk_right_injective _⟩ := by
ext ⟨x, y⟩
simp [and_left_comm, eq_comm]
@[simp]
lemma product_singleton : s ×ˢ {b} = s.map ⟨fun i => (i, b), Prod.mk_left_injective _⟩ := by
ext ⟨x, y⟩
simp [and_left_comm, eq_comm]
theorem singleton_product_singleton {a : α} {b : β} :
({a} ×ˢ {b} : Finset _) = {(a, b)} := by
simp only [product_singleton, Function.Embedding.coeFn_mk, map_singleton]
@[simp]
theorem union_product [DecidableEq α] [DecidableEq β] : (s ∪ s') ×ˢ t = s ×ˢ t ∪ s' ×ˢ t := by grind
@[simp]
theorem product_union [DecidableEq α] [DecidableEq β] : s ×ˢ (t ∪ t') = s ×ˢ t ∪ s ×ˢ t' := by grind
theorem inter_product [DecidableEq α] [DecidableEq β] : (s ∩ s') ×ˢ t = s ×ˢ t ∩ s' ×ˢ t := by grind
theorem product_inter [DecidableEq α] [DecidableEq β] : s ×ˢ (t ∩ t') = s ×ˢ t ∩ s ×ˢ t' := by grind
theorem product_inter_product [DecidableEq α] [DecidableEq β] :
s ×ˢ t ∩ s' ×ˢ t' = (s ∩ s') ×ˢ (t ∩ t') := by grind
theorem disjoint_product : Disjoint (s ×ˢ t) (s' ×ˢ t') ↔ Disjoint s s' ∨ Disjoint t t' := by
simp_rw [← disjoint_coe, coe_product, Set.disjoint_prod]
@[simp]
theorem disjUnion_product (hs : Disjoint s s') :
s.disjUnion s' hs ×ˢ t = (s ×ˢ t).disjUnion (s' ×ˢ t) (disjoint_product.mpr <| Or.inl hs) :=
eq_of_veq <| Multiset.add_product _ _ _
@[simp]
theorem product_disjUnion (ht : Disjoint t t') :
s ×ˢ t.disjUnion t' ht = (s ×ˢ t).disjUnion (s ×ˢ t') (disjoint_product.mpr <| Or.inr ht) :=
eq_of_veq <| Multiset.product_add _ _ _
end Prod
section Diag
variable [DecidableEq α] (s t : Finset α)
/-- Given a finite set `s`, the diagonal, `s.diag` is the set of pairs of the form `(a, a)` for
`a ∈ s`. -/
def diag :=
(s ×ˢ s).filter fun a : α × α => a.fst = a.snd
/-- Given a finite set `s`, the off-diagonal, `s.offDiag` is the set of pairs `(a, b)` with `a ≠ b`
for `a, b ∈ s`. -/
def offDiag :=
(s ×ˢ s).filter fun a : α × α => a.fst ≠ a.snd
variable {s} {x : α × α}
@[simp, grind =]
theorem mem_diag : x ∈ s.diag ↔ x.1 ∈ s ∧ x.1 = x.2 := by
simp +contextual [diag]
@[simp, grind =]
theorem mem_offDiag : x ∈ s.offDiag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 := by
simp [offDiag, and_assoc]
@[simp, grind =]
theorem diag_nonempty : s.diag.Nonempty ↔ s.Nonempty := by
simp [Finset.Nonempty]
@[simp, grind =]
theorem diag_eq_empty : s.diag = ∅ ↔ s = ∅ := by
have := (diag_nonempty (s := s)).not
rwa [not_nonempty_iff_eq_empty, not_nonempty_iff_eq_empty] at this
variable (s)
@[simp]
theorem image_diag [DecidableEq β] (f : α × α → β) (s : Finset α) :
s.diag.image f = s.image fun x ↦ f (x, x) := by
ext y
aesop
@[simp, norm_cast]
theorem coe_offDiag : (s.offDiag : Set (α × α)) = (s : Set α).offDiag :=
Set.ext fun _ => mem_offDiag
@[simp]
theorem diag_card : (diag s).card = s.card := by
suffices diag s = s.image fun a => (a, a) by
rw [this]
apply card_image_of_injOn
exact fun x1 _ x2 _ h3 => (Prod.mk.inj h3).1
grind
@[simp]
theorem offDiag_card : (offDiag s).card = s.card * s.card - s.card :=
suffices (diag s).card + (offDiag s).card = s.card * s.card by rw [s.diag_card] at this; cutsat
by rw [← card_product, diag, offDiag]
conv_rhs => rw [← filter_card_add_filter_neg_card_eq_card (fun a => a.1 = a.2)]
@[mono]
theorem diag_mono : Monotone (diag : Finset α → Finset (α × α)) := fun _ _ h _ hx =>
mem_diag.2 <| And.imp_left (@h _) <| mem_diag.1 hx
@[mono]
theorem offDiag_mono : Monotone (offDiag : Finset α → Finset (α × α)) := fun _ _ h _ hx =>
mem_offDiag.2 <| And.imp (@h _) (And.imp_left <| @h _) <| mem_offDiag.1 hx
@[simp]
theorem diag_empty : (∅ : Finset α).diag = ∅ :=
rfl
@[simp]
theorem offDiag_empty : (∅ : Finset α).offDiag = ∅ :=
rfl
@[simp]
theorem diag_union_offDiag : s.diag ∪ s.offDiag = s ×ˢ s := by
grind
@[simp]
theorem disjoint_diag_offDiag : Disjoint s.diag s.offDiag :=
disjoint_filter_filter_neg (s ×ˢ s) (s ×ˢ s) (fun a => a.1 = a.2)
theorem product_sdiff_diag : s ×ˢ s \ s.diag = s.offDiag := by grind
theorem product_sdiff_offDiag : s ×ˢ s \ s.offDiag = s.diag := by grind
theorem diag_inter : (s ∩ t).diag = s.diag ∩ t.diag := by grind
theorem offDiag_inter : (s ∩ t).offDiag = s.offDiag ∩ t.offDiag :=
coe_injective <| by
push_cast
exact Set.offDiag_inter _ _
theorem diag_union : (s ∪ t).diag = s.diag ∪ t.diag := by grind
variable {s t}
theorem offDiag_union (h : Disjoint s t) :
(s ∪ t).offDiag = s.offDiag ∪ t.offDiag ∪ s ×ˢ t ∪ t ×ˢ s :=
coe_injective <| by
push_cast
exact Set.offDiag_union (disjoint_coe.2 h)
variable (a : α)
@[simp]
theorem offDiag_singleton : ({a} : Finset α).offDiag = ∅ := by simp [← Finset.card_eq_zero]
theorem diag_singleton : ({a} : Finset α).diag = {(a, a)} := by grind
theorem diag_insert : (insert a s).diag = insert (a, a) s.diag := by grind
theorem offDiag_insert (has : a ∉ s) : (insert a s).offDiag = s.offDiag ∪ {a} ×ˢ s ∪ s ×ˢ {a} := by
grind
theorem offDiag_filter_lt_eq_filter_le {ι} [PartialOrder ι]
[DecidableEq ι] [DecidableLE ι] [DecidableLT ι] (s : Finset ι) :
s.offDiag.filter (fun i => i.1 < i.2) = s.offDiag.filter (fun i => i.1 ≤ i.2) := by
rw [Finset.filter_inj']
rintro ⟨i, j⟩
simp_rw [mem_offDiag, and_imp]
rintro _ _ h
rw [Ne.le_iff_lt h]
end Diag
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Dedup.lean | import Mathlib.Data.Finset.Defs
import Mathlib.Data.Multiset.Dedup
import Mathlib.Data.Multiset.Basic
/-!
# Deduplicating Multisets to make Finsets
This file concerns `Multiset.dedup` and `List.dedup` as a way to create `Finset`s.
## Tags
finite sets, finset
-/
-- Assert that we define `Finset` without the material on `List.sublists`.
-- Note that we cannot use `List.sublists` itself as that is defined very early.
assert_not_exists List.sublistsLen Multiset.powerset CompleteLattice IsOrderedMonoid
open Multiset Subtype Function
universe u
variable {α : Type*} {β : Type*} {γ : Type*}
namespace Finset
@[simp]
theorem dedup_eq_self [DecidableEq α] (s : Finset α) : dedup s.1 = s.1 :=
s.2.dedup
end Finset
/-! ### dedup on list and multiset -/
namespace Multiset
variable [DecidableEq α] {s t : Multiset α}
/-- `toFinset s` removes duplicates from the multiset `s` to produce a finset. -/
def toFinset (s : Multiset α) : Finset α :=
⟨_, nodup_dedup s⟩
@[simp]
theorem toFinset_val (s : Multiset α) : s.toFinset.1 = s.dedup :=
rfl
theorem toFinset_eq {s : Multiset α} (n : Nodup s) : Finset.mk s n = s.toFinset :=
Finset.val_inj.1 n.dedup.symm
theorem Nodup.toFinset_inj {l l' : Multiset α} (hl : Nodup l) (hl' : Nodup l')
(h : l.toFinset = l'.toFinset) : l = l' := by
simpa [← toFinset_eq hl, ← toFinset_eq hl'] using h
@[simp]
theorem mem_toFinset {a : α} {s : Multiset α} : a ∈ s.toFinset ↔ a ∈ s :=
mem_dedup
@[simp]
theorem toFinset_subset : s.toFinset ⊆ t.toFinset ↔ s ⊆ t := by
simp only [Finset.subset_iff, Multiset.subset_iff, Multiset.mem_toFinset]
@[simp]
theorem toFinset_ssubset : s.toFinset ⊂ t.toFinset ↔ s ⊂ t := by
simp_rw [Finset.ssubset_def, toFinset_subset]
rfl
@[simp]
theorem toFinset_dedup (m : Multiset α) : m.dedup.toFinset = m.toFinset := by
simp_rw [toFinset, dedup_idem]
instance isWellFounded_ssubset : IsWellFounded (Multiset β) (· ⊂ ·) := by
classical
exact Subrelation.isWellFounded (InvImage _ toFinset) toFinset_ssubset.2
end Multiset
namespace Finset
@[simp]
theorem val_toFinset [DecidableEq α] (s : Finset α) : s.val.toFinset = s := by
ext
rw [Multiset.mem_toFinset, ← mem_def]
theorem val_le_iff_val_subset {a : Finset α} {b : Multiset α} : a.val ≤ b ↔ a.val ⊆ b :=
Multiset.le_iff_subset a.nodup
end Finset
namespace List
variable [DecidableEq α] {l l' : List α} {a : α} {f : α → β}
{s : Finset α} {t : Set β} {t' : Finset β}
/-- `toFinset l` removes duplicates from the list `l` to produce a finset. -/
def toFinset (l : List α) : Finset α :=
Multiset.toFinset l
@[simp]
theorem toFinset_val (l : List α) : l.toFinset.1 = (l.dedup : Multiset α) :=
rfl
@[simp]
theorem toFinset_coe (l : List α) : (l : Multiset α).toFinset = l.toFinset :=
rfl
theorem toFinset_eq (n : Nodup l) : @Finset.mk α l n = l.toFinset :=
Multiset.toFinset_eq <| by rwa [Multiset.coe_nodup]
@[simp]
theorem mem_toFinset : a ∈ l.toFinset ↔ a ∈ l :=
mem_dedup
@[simp, norm_cast]
theorem coe_toFinset (l : List α) : (l.toFinset : Set α) = { a | a ∈ l } :=
Set.ext fun _ => List.mem_toFinset
theorem toFinset_surj_on : Set.SurjOn toFinset { l : List α | l.Nodup } Set.univ := by
rintro ⟨⟨l⟩, hl⟩ _
exact ⟨l, hl, (toFinset_eq hl).symm⟩
theorem toFinset_surjective : Surjective (toFinset : List α → Finset α) := fun s =>
let ⟨l, _, hls⟩ := toFinset_surj_on (Set.mem_univ s)
⟨l, hls⟩
theorem toFinset_eq_iff_perm_dedup : l.toFinset = l'.toFinset ↔ l.dedup ~ l'.dedup := by
simp [Finset.ext_iff, perm_ext_iff_of_nodup (nodup_dedup _) (nodup_dedup _)]
theorem toFinset.ext_iff {a b : List α} : a.toFinset = b.toFinset ↔ ∀ x, x ∈ a ↔ x ∈ b := by
simp only [Finset.ext_iff, mem_toFinset]
theorem toFinset.ext : (∀ x, x ∈ l ↔ x ∈ l') → l.toFinset = l'.toFinset :=
toFinset.ext_iff.mpr
theorem toFinset_eq_of_perm (l l' : List α) (h : l ~ l') : l.toFinset = l'.toFinset :=
toFinset_eq_iff_perm_dedup.mpr h.dedup
theorem perm_of_nodup_nodup_toFinset_eq (hl : Nodup l) (hl' : Nodup l')
(h : l.toFinset = l'.toFinset) : l ~ l' := by
rw [← Multiset.coe_eq_coe]
exact Multiset.Nodup.toFinset_inj hl hl' h
@[simp]
theorem toFinset_reverse {l : List α} : toFinset l.reverse = l.toFinset :=
toFinset_eq_of_perm _ _ (reverse_perm l)
end List
namespace Finset
section ToList
/-- Produce a list of the elements in the finite set using choice. -/
noncomputable def toList (s : Finset α) : List α :=
s.1.toList
theorem nodup_toList (s : Finset α) : s.toList.Nodup := by
rw [toList, ← Multiset.coe_nodup, Multiset.coe_toList]
exact s.nodup
@[simp]
theorem mem_toList {a : α} {s : Finset α} : a ∈ s.toList ↔ a ∈ s :=
Multiset.mem_toList
@[simp, norm_cast]
theorem coe_toList (s : Finset α) : (s.toList : Multiset α) = s.val :=
s.val.coe_toList
@[simp]
theorem toList_toFinset [DecidableEq α] (s : Finset α) : s.toList.toFinset = s := by
ext
simp
theorem _root_.List.toFinset_toList [DecidableEq α] {s : List α} (hs : s.Nodup) :
s.toFinset.toList.Perm s := by
apply List.perm_of_nodup_nodup_toFinset_eq (nodup_toList _) hs
rw [toList_toFinset]
theorem exists_list_nodup_eq [DecidableEq α] (s : Finset α) :
∃ l : List α, l.Nodup ∧ l.toFinset = s :=
⟨s.toList, s.nodup_toList, s.toList_toFinset⟩
@[simp]
protected theorem perm_toList {f₁ f₂ : Finset α} : f₁.toList.Perm f₂.toList ↔ f₁ = f₂ where
mp h := Finset.ext fun x => by simp [← Finset.mem_toList, h.mem_iff]
mpr h := .of_eq <| congrArg Finset.toList h
@[deprecated (since := "2025-08-05")] alias _root_.perm_toList := Finset.perm_toList
end ToList
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/SDiff.lean | import Mathlib.Data.Finset.Insert
import Mathlib.Data.Finset.Lattice.Basic
/-!
# Difference of finite sets
## Main declarations
* `Finset.instSDiff`: Defines the set difference `s \ t` for finsets `s` and `t`.
* `Finset.instGeneralizedBooleanAlgebra`: Finsets almost have a Boolean algebra structure
## Tags
finite sets, finset
-/
-- Assert that we define `Finset` without the material on `List.sublists`.
-- Note that we cannot use `List.sublists` itself as that is defined very early.
assert_not_exists List.sublistsLen Multiset.powerset CompleteLattice IsOrderedMonoid
open Multiset Subtype Function
universe u
variable {α : Type*} {β : Type*} {γ : Type*}
namespace Finset
-- TODO: these should be global attributes, but this will require fixing other files
attribute [local trans] Subset.trans Superset.trans
/-! ### sdiff -/
section Sdiff
variable [DecidableEq α] {s t u v : Finset α} {a b : α}
/-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/
instance instSDiff : SDiff (Finset α) :=
⟨fun s₁ s₂ => ⟨s₁.1 - s₂.1, nodup_of_le (Multiset.sub_le_self ..) s₁.2⟩⟩
@[simp]
theorem sdiff_val (s₁ s₂ : Finset α) : (s₁ \ s₂).val = s₁.val - s₂.val :=
rfl
@[simp, grind =]
theorem mem_sdiff : a ∈ s \ t ↔ a ∈ s ∧ a ∉ t :=
mem_sub_of_nodup s.2
@[simp]
theorem inter_sdiff_self (s₁ s₂ : Finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := by grind
instance : GeneralizedBooleanAlgebra (Finset α) where
sup_inf_sdiff := by grind
inf_inf_sdiff := by grind
theorem notMem_sdiff_of_mem_right (h : a ∈ t) : a ∉ s \ t := by grind
@[deprecated (since := "2025-05-23")] alias not_mem_sdiff_of_mem_right := notMem_sdiff_of_mem_right
theorem notMem_sdiff_of_notMem_left (h : a ∉ s) : a ∉ s \ t := by simp [h]
@[deprecated (since := "2025-05-23")]
alias not_mem_sdiff_of_not_mem_left := notMem_sdiff_of_notMem_left
theorem union_sdiff_of_subset (h : s ⊆ t) : s ∪ t \ s = t := by grind
theorem sdiff_union_of_subset {s₁ s₂ : Finset α} (h : s₁ ⊆ s₂) : s₂ \ s₁ ∪ s₁ = s₂ := by grind
/-- See also `Finset.sdiff_inter_right_comm`. -/
lemma inter_sdiff_assoc (s t u : Finset α) : (s ∩ t) \ u = s ∩ (t \ u) := inf_sdiff_assoc ..
/-- See also `Finset.inter_sdiff_assoc`. -/
lemma sdiff_inter_right_comm (s t u : Finset α) : s \ t ∩ u = (s ∩ u) \ t := sdiff_inf_right_comm ..
lemma inter_sdiff_left_comm (s t u : Finset α) : s ∩ (t \ u) = t ∩ (s \ u) := inf_sdiff_left_comm ..
@[simp]
theorem sdiff_inter_self (s₁ s₂ : Finset α) : s₂ \ s₁ ∩ s₁ = ∅ :=
inf_sdiff_self_left
protected theorem sdiff_self (s₁ : Finset α) : s₁ \ s₁ = ∅ :=
_root_.sdiff_self
theorem sdiff_inter_distrib_right (s t u : Finset α) : s \ (t ∩ u) = s \ t ∪ s \ u :=
sdiff_inf
@[simp]
theorem sdiff_inter_self_left (s t : Finset α) : s \ (s ∩ t) = s \ t :=
sdiff_inf_self_left _ _
@[simp]
theorem sdiff_inter_self_right (s t : Finset α) : s \ (t ∩ s) = s \ t :=
sdiff_inf_self_right _ _
@[simp]
theorem sdiff_empty : s \ ∅ = s :=
sdiff_bot
@[mono, gcongr]
theorem sdiff_subset_sdiff (hst : s ⊆ t) (hvu : v ⊆ u) : s \ u ⊆ t \ v := by grind
theorem sdiff_subset_sdiff_iff_subset {r : Finset α} (hs : s ⊆ r) (ht : t ⊆ r) :
r \ s ⊆ r \ t ↔ t ⊆ s := by
simpa only [← le_eq_subset] using sdiff_le_sdiff_iff_le hs ht
@[simp, grind =, norm_cast]
theorem coe_sdiff (s₁ s₂ : Finset α) : ↑(s₁ \ s₂) = (s₁ \ s₂ : Set α) :=
Set.ext fun _ => mem_sdiff
@[simp]
theorem union_sdiff_self_eq_union : s ∪ t \ s = s ∪ t :=
sup_sdiff_self_right _ _
@[simp]
theorem sdiff_union_self_eq_union : s \ t ∪ t = s ∪ t :=
sup_sdiff_self_left _ _
theorem union_sdiff_left (s t : Finset α) : (s ∪ t) \ s = t \ s :=
sup_sdiff_left_self
theorem union_sdiff_right (s t : Finset α) : (s ∪ t) \ t = s \ t :=
sup_sdiff_right_self
theorem union_sdiff_cancel_left (h : Disjoint s t) : (s ∪ t) \ s = t :=
h.sup_sdiff_cancel_left
theorem union_sdiff_cancel_right (h : Disjoint s t) : (s ∪ t) \ t = s :=
h.sup_sdiff_cancel_right
theorem union_sdiff_symm : s ∪ t \ s = t ∪ s \ t := by simp [union_comm]
theorem sdiff_union_inter (s t : Finset α) : s \ t ∪ s ∩ t = s :=
sup_sdiff_inf _ _
theorem sdiff_idem (s t : Finset α) : (s \ t) \ t = s \ t :=
_root_.sdiff_idem
theorem subset_sdiff : s ⊆ t \ u ↔ s ⊆ t ∧ Disjoint s u :=
le_iff_subset.symm.trans le_sdiff
@[simp]
theorem sdiff_eq_empty_iff_subset : s \ t = ∅ ↔ s ⊆ t :=
sdiff_eq_bot_iff
@[grind =]
theorem sdiff_nonempty : (s \ t).Nonempty ↔ ¬s ⊆ t :=
nonempty_iff_ne_empty.trans sdiff_eq_empty_iff_subset.not
@[simp]
theorem empty_sdiff (s : Finset α) : ∅ \ s = ∅ :=
bot_sdiff
theorem insert_sdiff_of_notMem (s : Finset α) {t : Finset α} {x : α} (h : x ∉ t) :
insert x s \ t = insert x (s \ t) := by grind
@[deprecated (since := "2025-05-23")] alias insert_sdiff_of_not_mem := insert_sdiff_of_notMem
theorem insert_sdiff_of_mem (s : Finset α) {x : α} (h : x ∈ t) : insert x s \ t = s \ t := by grind
@[simp] lemma insert_sdiff_self_of_mem (ha : a ∈ s) : insert a (s \ {a}) = s := by grind
@[simp] lemma insert_sdiff_cancel (ha : a ∉ s) : insert a s \ s = {a} := by grind
@[simp]
theorem insert_sdiff_insert (s t : Finset α) (x : α) : insert x s \ insert x t = s \ insert x t :=
insert_sdiff_of_mem _ (mem_insert_self _ _)
lemma insert_sdiff_insert' (hab : a ≠ b) (ha : a ∉ s) : insert a s \ insert b s = {a} := by
ext; aesop
lemma cons_sdiff_cons (hab : a ≠ b) (ha hb) : s.cons a ha \ s.cons b hb = {a} := by grind
theorem sdiff_insert_of_notMem {x : α} (h : x ∉ s) (t : Finset α) : s \ insert x t = s \ t := by
grind
@[deprecated (since := "2025-05-23")] alias sdiff_insert_of_not_mem := sdiff_insert_of_notMem
@[simp] theorem sdiff_subset {s t : Finset α} : s \ t ⊆ s := le_iff_subset.mp sdiff_le
theorem sdiff_ssubset (h : t ⊆ s) (ht : t.Nonempty) : s \ t ⊂ s := by grind
theorem union_sdiff_distrib (s₁ s₂ t : Finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t :=
sup_sdiff
theorem sdiff_union_distrib (s t₁ t₂ : Finset α) : s \ (t₁ ∪ t₂) = s \ t₁ ∩ (s \ t₂) :=
sdiff_sup
theorem union_sdiff_self (s t : Finset α) : (s ∪ t) \ t = s \ t :=
sup_sdiff_right_self
theorem Nontrivial.sdiff_singleton_nonempty {c : α} {s : Finset α} (hS : s.Nontrivial) :
(s \ {c}).Nonempty := by grind
theorem sdiff_sdiff_left' (s t u : Finset α) : (s \ t) \ u = s \ t ∩ (s \ u) :=
_root_.sdiff_sdiff_left'
theorem sdiff_union_sdiff_cancel (hts : t ⊆ s) (hut : u ⊆ t) : s \ t ∪ t \ u = s \ u :=
sdiff_sup_sdiff_cancel hts hut
theorem sdiff_sdiff_eq_sdiff_union (h : u ⊆ s) : s \ (t \ u) = s \ t ∪ u :=
sdiff_sdiff_eq_sdiff_sup h
theorem sdiff_sdiff_self_left (s t : Finset α) : s \ (s \ t) = s ∩ t :=
sdiff_sdiff_right_self
theorem sdiff_sdiff_eq_self (h : t ⊆ s) : s \ (s \ t) = t :=
_root_.sdiff_sdiff_eq_self h
theorem sdiff_eq_sdiff_iff_inter_eq_inter {s t₁ t₂ : Finset α} :
s \ t₁ = s \ t₂ ↔ s ∩ t₁ = s ∩ t₂ :=
sdiff_eq_sdiff_iff_inf_eq_inf
theorem union_eq_sdiff_union_sdiff_union_inter (s t : Finset α) : s ∪ t = s \ t ∪ t \ s ∪ s ∩ t :=
sup_eq_sdiff_sup_sdiff_sup_inf
theorem sdiff_eq_self_iff_disjoint : s \ t = s ↔ Disjoint s t :=
sdiff_eq_left
theorem sdiff_eq_self_of_disjoint (h : Disjoint s t) : s \ t = s :=
sdiff_eq_self_iff_disjoint.2 h
end Sdiff
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Union.lean | import Mathlib.Data.Finset.Fold
import Mathlib.Data.Multiset.Bind
import Mathlib.Order.SetNotation
/-!
# Unions of finite sets
This file defines the union of a family `t : α → Finset β` of finsets bounded by a finset
`s : Finset α`.
## Main declarations
* `Finset.disjUnion`: Given a hypothesis `h` which states that finsets `s` and `t` are disjoint,
`s.disjUnion t h` is the set such that `a ∈ disjUnion s t h` iff `a ∈ s` or `a ∈ t`; this does
not require decidable equality on the type `α`.
* `Finset.biUnion`: Finite unions of finsets; given an indexing function `f : α → Finset β` and an
`s : Finset α`, `s.biUnion f` is the union of all finsets of the form `f a` for `a ∈ s`.
## TODO
Remove `Finset.biUnion` in favour of `Finset.sup`.
-/
assert_not_exists MonoidWithZero MulAction
variable {α β γ : Type*} {s s₁ s₂ : Finset α} {t t₁ t₂ : α → Finset β}
namespace Finset
section DisjiUnion
/-- `disjiUnion s f h` is the set such that `a ∈ disjiUnion s f` iff `a ∈ f i` for some `i ∈ s`.
It is the same as `s.biUnion f`, but it does not require decidable equality on the type. The
hypothesis ensures that the sets are disjoint. -/
def disjiUnion (s : Finset α) (t : α → Finset β) (hf : (s : Set α).PairwiseDisjoint t) : Finset β :=
⟨s.val.bind (Finset.val ∘ t), Multiset.nodup_bind.2
⟨fun a _ ↦ (t a).nodup, s.nodup.pairwise fun _ ha _ hb hab ↦ disjoint_val.2 <| hf ha hb hab⟩⟩
@[simp]
lemma disjiUnion_val (s : Finset α) (t : α → Finset β) (h) :
(s.disjiUnion t h).1 = s.1.bind fun a ↦ (t a).1 := rfl
@[simp] lemma disjiUnion_empty (t : α → Finset β) : disjiUnion ∅ t (by simp) = ∅ := rfl
@[simp, grind =] lemma mem_disjiUnion {b : β} {h} : b ∈ s.disjiUnion t h ↔ ∃ a ∈ s, b ∈ t a := by
simp only [mem_def, disjiUnion_val, Multiset.mem_bind]
@[simp, norm_cast]
lemma coe_disjiUnion {h} : (s.disjiUnion t h : Set β) = ⋃ x ∈ (s : Set α), t x := by
simp [Set.ext_iff, mem_disjiUnion, Set.mem_iUnion]
@[simp] lemma disjiUnion_cons (a : α) (s : Finset α) (ha : a ∉ s) (f : α → Finset β) (H) :
disjiUnion (cons a s ha) f H =
(f a).disjUnion ((s.disjiUnion f) fun _ hb _ hc ↦ H (mem_cons_of_mem hb) (mem_cons_of_mem hc))
(disjoint_left.2 fun _ hb h ↦
let ⟨_, hc, h⟩ := mem_disjiUnion.mp h
disjoint_left.mp
(H (mem_cons_self a s) (mem_cons_of_mem hc) (ne_of_mem_of_not_mem hc ha).symm) hb h) :=
eq_of_veq <| Multiset.cons_bind _ _ _
@[simp] lemma singleton_disjiUnion (a : α) {h} : Finset.disjiUnion {a} t h = t a :=
eq_of_veq <| Multiset.singleton_bind _ _
lemma disjiUnion_disjiUnion (s : Finset α) (f : α → Finset β) (g : β → Finset γ) (h1 h2) :
(s.disjiUnion f h1).disjiUnion g h2 =
s.attach.disjiUnion
(fun a ↦ ((f a).disjiUnion g) fun _ hb _ hc ↦
h2 (mem_disjiUnion.mpr ⟨_, a.prop, hb⟩) (mem_disjiUnion.mpr ⟨_, a.prop, hc⟩))
fun a _ b _ hab ↦
disjoint_left.mpr fun x hxa hxb ↦ by
obtain ⟨xa, hfa, hga⟩ := mem_disjiUnion.mp hxa
obtain ⟨xb, hfb, hgb⟩ := mem_disjiUnion.mp hxb
refine disjoint_left.mp
(h2 (mem_disjiUnion.mpr ⟨_, a.prop, hfa⟩) (mem_disjiUnion.mpr ⟨_, b.prop, hfb⟩) ?_) hga
hgb
rintro rfl
exact disjoint_left.mp (h1 a.prop b.prop <| Subtype.coe_injective.ne hab) hfa hfb :=
eq_of_veq <| Multiset.bind_assoc.trans (Multiset.attach_bind_coe _ _).symm
lemma sUnion_disjiUnion {f : α → Finset (Set β)} (I : Finset α)
(hf : (I : Set α).PairwiseDisjoint f) :
⋃₀ (I.disjiUnion f hf : Set (Set β)) = ⋃ a ∈ I, ⋃₀ ↑(f a) := by
ext
simp only [coe_disjiUnion, Set.mem_sUnion, Set.mem_iUnion, mem_coe, exists_prop]
tauto
section DecidableEq
variable [DecidableEq β] {s : Finset α} {t : Finset β} {f : α → β}
private lemma pairwiseDisjoint_fibers : Set.PairwiseDisjoint ↑t fun a ↦ s.filter (f · = a) :=
fun x' hx y' hy hne ↦ by
simp_rw [disjoint_left, mem_filter]; rintro i ⟨_, rfl⟩ ⟨_, rfl⟩; exact hne rfl
@[simp] lemma disjiUnion_filter_eq (s : Finset α) (t : Finset β) (f : α → β) :
t.disjiUnion (fun a ↦ s.filter (f · = a)) pairwiseDisjoint_fibers =
s.filter fun c ↦ f c ∈ t :=
ext fun b => by simpa using and_comm
lemma disjiUnion_filter_eq_of_maps_to (h : ∀ x ∈ s, f x ∈ t) :
t.disjiUnion (fun a ↦ s.filter (f · = a)) pairwiseDisjoint_fibers = s := by
simpa [filter_eq_self]
end DecidableEq
theorem map_disjiUnion {f : α ↪ β} {s : Finset α} {t : β → Finset γ} {h} :
(s.map f).disjiUnion t h =
s.disjiUnion (fun a => t (f a)) fun _ ha _ hb hab =>
h (mem_map_of_mem _ ha) (mem_map_of_mem _ hb) (f.injective.ne hab) :=
eq_of_veq <| Multiset.bind_map _ _ _
theorem disjiUnion_map {s : Finset α} {t : α → Finset β} {f : β ↪ γ} {h} :
(s.disjiUnion t h).map f =
s.disjiUnion (fun a => (t a).map f) (h.mono' fun _ _ ↦ (disjoint_map _).2) :=
eq_of_veq <| Multiset.map_bind _ _ _
variable {f : α → β} {op : β → β → β} [hc : Std.Commutative op] [ha : Std.Associative op]
theorem fold_disjiUnion {ι : Type*} {s : Finset ι} {t : ι → Finset α} {b : ι → β} {b₀ : β} (h) :
(s.disjiUnion t h).fold op (s.fold op b₀ b) f = s.fold op b₀ fun i => (t i).fold op (b i) f :=
(congr_arg _ <| Multiset.map_bind _ _ _).trans (Multiset.fold_bind _ _ _ _ _)
lemma pairwiseDisjoint_filter {f : α → Finset β} (h : Set.PairwiseDisjoint ↑s f)
(p : β → Prop) [DecidablePred p] : Set.PairwiseDisjoint ↑s fun a ↦ (f a).filter p :=
fun _ h₁ _ h₂ hne ↦ Finset.disjoint_filter_filter (h h₁ h₂ hne)
theorem filter_disjiUnion (s : Finset α) (f : α → Finset β) (h) (p : β → Prop) [DecidablePred p] :
(s.disjiUnion f h).filter p
= s.disjiUnion (fun a ↦ (f a).filter p) (pairwiseDisjoint_filter h p) := by grind
end DisjiUnion
section BUnion
variable [DecidableEq β]
/-- `Finset.biUnion s t` is the union of `t a` over `a ∈ s`.
(This was formerly `bind` due to the monad structure on types with `DecidableEq`.) -/
protected def biUnion (s : Finset α) (t : α → Finset β) : Finset β :=
(s.1.bind fun a ↦ (t a).1).toFinset
@[simp] lemma biUnion_val (s : Finset α) (t : α → Finset β) :
(s.biUnion t).1 = (s.1.bind fun a ↦ (t a).1).dedup := rfl
@[simp] lemma biUnion_empty : Finset.biUnion ∅ t = ∅ := rfl
@[simp, grind =] lemma mem_biUnion {b : β} : b ∈ s.biUnion t ↔ ∃ a ∈ s, b ∈ t a := by
simp only [mem_def, biUnion_val, Multiset.mem_dedup, Multiset.mem_bind]
@[simp, norm_cast]
lemma coe_biUnion : (s.biUnion t : Set β) = ⋃ x ∈ (s : Set α), t x := by
simp [Set.ext_iff, mem_biUnion, Set.mem_iUnion]
@[simp]
lemma biUnion_insert [DecidableEq α] {a : α} : (insert a s).biUnion t = t a ∪ s.biUnion t := by
aesop
lemma biUnion_congr (hs : s₁ = s₂) (ht : ∀ a ∈ s₁, t₁ a = t₂ a) :
s₁.biUnion t₁ = s₂.biUnion t₂ := by
aesop
@[simp]
lemma disjiUnion_eq_biUnion (s : Finset α) (f : α → Finset β) (hf) :
s.disjiUnion f hf = s.biUnion f := eq_of_veq (s.disjiUnion f hf).nodup.dedup.symm
lemma biUnion_subset {s' : Finset β} : s.biUnion t ⊆ s' ↔ ∀ x ∈ s, t x ⊆ s' := by grind
@[simp]
lemma singleton_biUnion {a : α} : Finset.biUnion {a} t = t a := by grind
lemma biUnion_inter (s : Finset α) (f : α → Finset β) (t : Finset β) :
s.biUnion f ∩ t = s.biUnion fun x ↦ f x ∩ t := by grind
lemma inter_biUnion (t : Finset β) (s : Finset α) (f : α → Finset β) :
t ∩ s.biUnion f = s.biUnion fun x ↦ t ∩ f x := by grind
lemma biUnion_biUnion [DecidableEq γ] (s : Finset α) (f : α → Finset β) (g : β → Finset γ) :
(s.biUnion f).biUnion g = s.biUnion fun a ↦ (f a).biUnion g := by grind
lemma bind_toFinset [DecidableEq α] (s : Multiset α) (t : α → Multiset β) :
(s.bind t).toFinset = s.toFinset.biUnion fun a ↦ (t a).toFinset :=
ext fun x ↦ by simp only [Multiset.mem_toFinset, mem_biUnion, Multiset.mem_bind]
lemma biUnion_mono (h : ∀ a ∈ s, t₁ a ⊆ t₂ a) : s.biUnion t₁ ⊆ s.biUnion t₂ := by grind
@[gcongr]
lemma biUnion_subset_biUnion_of_subset_left (t : α → Finset β) (h : s₁ ⊆ s₂) :
s₁.biUnion t ⊆ s₂.biUnion t := by grind
lemma subset_biUnion_of_mem (u : α → Finset β) {x : α} (xs : x ∈ s) : u x ⊆ s.biUnion u := by grind
@[simp]
lemma biUnion_subset_iff_forall_subset {α β : Type*} [DecidableEq β] {s : Finset α}
{t : Finset β} {f : α → Finset β} : s.biUnion f ⊆ t ↔ ∀ x ∈ s, f x ⊆ t := by grind
@[simp]
lemma biUnion_singleton_eq_self [DecidableEq α] : s.biUnion (singleton : α → Finset α) = s := by
grind
lemma filter_biUnion (s : Finset α) (f : α → Finset β) (p : β → Prop) [DecidablePred p] :
(s.biUnion f).filter p = s.biUnion fun a ↦ (f a).filter p := by grind
lemma biUnion_filter_eq_of_maps_to [DecidableEq α] {s : Finset α} {t : Finset β} {f : α → β}
(h : ∀ x ∈ s, f x ∈ t) : (t.biUnion fun a ↦ s.filter fun c ↦ f c = a) = s := by grind
lemma erase_biUnion (f : α → Finset β) (s : Finset α) (b : β) :
(s.biUnion f).erase b = s.biUnion fun x ↦ (f x).erase b := by grind
@[simp]
lemma biUnion_nonempty : (s.biUnion t).Nonempty ↔ ∃ x ∈ s, (t x).Nonempty := by
simp only [Finset.Nonempty, mem_biUnion]
rw [exists_swap]
simp [exists_and_left]
lemma Nonempty.biUnion (hs : s.Nonempty) (ht : ∀ x ∈ s, (t x).Nonempty) :
(s.biUnion t).Nonempty := biUnion_nonempty.2 <| hs.imp fun x hx ↦ ⟨hx, ht x hx⟩
lemma disjoint_biUnion_left (s : Finset α) (f : α → Finset β) (t : Finset β) :
Disjoint (s.biUnion f) t ↔ ∀ i ∈ s, Disjoint (f i) t := by
classical
refine s.induction ?_ ?_
· simp only [forall_mem_empty_iff, biUnion_empty, disjoint_empty_left]
· intro i s his ih
simp only [disjoint_union_left, biUnion_insert, forall_mem_insert, ih]
lemma disjoint_biUnion_right (s : Finset β) (t : Finset α) (f : α → Finset β) :
Disjoint s (t.biUnion f) ↔ ∀ i ∈ t, Disjoint s (f i) := by
simpa only [_root_.disjoint_comm] using disjoint_biUnion_left t f s
theorem image_biUnion [DecidableEq γ] {f : α → β} {s : Finset α} {t : β → Finset γ} :
(s.image f).biUnion t = s.biUnion fun a => t (f a) :=
haveI := Classical.decEq α
Finset.induction_on s rfl fun a s _ ih => by simp only [image_insert, biUnion_insert, ih]
theorem biUnion_image [DecidableEq γ] {s : Finset α} {t : α → Finset β} {f : β → γ} :
(s.biUnion t).image f = s.biUnion fun a => (t a).image f :=
haveI := Classical.decEq α
Finset.induction_on s rfl fun a s _ ih => by simp only [biUnion_insert, image_union, ih]
theorem image_biUnion_filter_eq [DecidableEq α] (s : Finset β) (g : β → α) :
((s.image g).biUnion fun a => s.filter fun c => g c = a) = s :=
biUnion_filter_eq_of_maps_to fun _ => mem_image_of_mem g
theorem biUnion_singleton {f : α → β} : (s.biUnion fun a => {f a}) = s.image f := by grind
end BUnion
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Order.lean | import Mathlib.Data.Finset.Defs
import Mathlib.Data.Multiset.ZeroCons
import Mathlib.Order.Directed
/-!
# Finsets of ordered types
-/
universe u v w
variable {α : Type u}
theorem Directed.finset_le {r : α → α → Prop} [IsTrans α r] {ι} [hι : Nonempty ι] {f : ι → α}
(D : Directed r f) (s : Finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) :=
show ∃ z, ∀ i ∈ s.1, r (f i) (f z) from
Multiset.induction_on s.1 (let ⟨z⟩ := hι; ⟨z, fun _ ↦ by simp⟩)
fun i _ ⟨j, H⟩ ↦
let ⟨k, h₁, h₂⟩ := D i j
⟨k, fun _ h ↦ (Multiset.mem_cons.1 h).casesOn (fun h ↦ h.symm ▸ h₁)
fun h ↦ _root_.trans (H _ h) h₂⟩
theorem Finset.exists_le [Nonempty α] [Preorder α] [IsDirected α (· ≤ ·)] (s : Finset α) :
∃ M, ∀ i ∈ s, i ≤ M :=
directed_id.finset_le _ |
.lake/packages/mathlib/Mathlib/Data/Finset/BooleanAlgebra.lean | import Mathlib.Data.Finset.Basic
import Mathlib.Data.Finset.Image
import Mathlib.Data.Fintype.Defs
/-!
# `Finset`s are a Boolean algebra
This file provides the `BooleanAlgebra (Finset α)` instance, under the assumption that `α` is a
`Fintype`.
## Main results
* `Finset.boundedOrder`: `Finset.univ` is the top element of `Finset α`
* `Finset.booleanAlgebra`: `Finset α` is a Boolean algebra if `α` is finite
-/
assert_not_exists Monoid
open Function
open Nat
universe u v
variable {α β γ : Type*}
namespace Finset
variable {s t : Finset α}
section Fintypeα
variable [Fintype α]
theorem Nonempty.eq_univ [Subsingleton α] : s.Nonempty → s = univ := by
rintro ⟨x, hx⟩
exact eq_univ_of_forall fun y => by rwa [Subsingleton.elim y x]
theorem univ_nonempty_iff : (univ : Finset α).Nonempty ↔ Nonempty α := by
rw [← coe_nonempty, coe_univ, Set.nonempty_iff_univ_nonempty]
@[simp, aesop unsafe apply (rule_sets := [finsetNonempty])]
theorem univ_nonempty [Nonempty α] : (univ : Finset α).Nonempty :=
univ_nonempty_iff.2 ‹_›
theorem univ_eq_empty_iff : (univ : Finset α) = ∅ ↔ IsEmpty α := by
rw [← not_nonempty_iff, ← univ_nonempty_iff, not_nonempty_iff_eq_empty]
theorem univ_nontrivial_iff :
(Finset.univ : Finset α).Nontrivial ↔ Nontrivial α := by
rw [Finset.Nontrivial, Finset.coe_univ, Set.nontrivial_univ_iff]
theorem univ_nontrivial [h : Nontrivial α] :
(Finset.univ : Finset α).Nontrivial :=
univ_nontrivial_iff.mpr h
@[simp] lemma singleton_ne_univ [Nontrivial α] (a : α) : {a} ≠ univ := by
apply SetLike.coe_ne_coe.1
simp
@[simp]
theorem univ_eq_empty [IsEmpty α] : (univ : Finset α) = ∅ :=
univ_eq_empty_iff.2 ‹_›
@[simp]
theorem univ_unique [Unique α] : (univ : Finset α) = {default} :=
Finset.ext fun x => iff_of_true (mem_univ _) <| mem_singleton.2 <| Subsingleton.elim x default
instance boundedOrder : BoundedOrder (Finset α) :=
{ inferInstanceAs (OrderBot (Finset α)) with
top := univ
le_top := subset_univ }
@[simp]
theorem top_eq_univ : (⊤ : Finset α) = univ :=
rfl
theorem ssubset_univ_iff {s : Finset α} : s ⊂ univ ↔ s ≠ univ :=
@lt_top_iff_ne_top _ _ _ s
@[simp]
theorem univ_subset_iff {s : Finset α} : univ ⊆ s ↔ s = univ :=
@top_le_iff _ _ _ s
theorem codisjoint_left : Codisjoint s t ↔ ∀ ⦃a⦄, a ∉ s → a ∈ t := by
classical simp [codisjoint_iff, eq_univ_iff_forall, or_iff_not_imp_left]
theorem codisjoint_right : Codisjoint s t ↔ ∀ ⦃a⦄, a ∉ t → a ∈ s :=
codisjoint_comm.trans codisjoint_left
instance booleanAlgebra [DecidableEq α] : BooleanAlgebra (Finset α) :=
GeneralizedBooleanAlgebra.toBooleanAlgebra
section BooleanAlgebra
variable [DecidableEq α] {a : α}
theorem sdiff_eq_inter_compl (s t : Finset α) : s \ t = s ∩ tᶜ :=
sdiff_eq
theorem compl_eq_univ_sdiff (s : Finset α) : sᶜ = univ \ s :=
rfl
@[simp]
theorem mem_compl : a ∈ sᶜ ↔ a ∉ s := by simp [compl_eq_univ_sdiff]
theorem notMem_compl : a ∉ sᶜ ↔ a ∈ s := by rw [mem_compl, not_not]
@[deprecated (since := "2025-05-23")] alias not_mem_compl := notMem_compl
@[simp, norm_cast]
theorem coe_compl (s : Finset α) : ↑sᶜ = (↑s : Set α)ᶜ :=
Set.ext fun _ => mem_compl
@[simp] lemma compl_subset_compl : sᶜ ⊆ tᶜ ↔ t ⊆ s := @compl_le_compl_iff_le (Finset α) _ _ _
@[simp] lemma compl_ssubset_compl : sᶜ ⊂ tᶜ ↔ t ⊂ s := @compl_lt_compl_iff_lt (Finset α) _ _ _
lemma subset_compl_comm : s ⊆ tᶜ ↔ t ⊆ sᶜ := le_compl_iff_le_compl (α := Finset α)
lemma subset_compl_iff_disjoint_right : s ⊆ tᶜ ↔ Disjoint s t :=
le_compl_iff_disjoint_right (α := Finset α)
lemma subset_compl_iff_disjoint_left : s ⊆ tᶜ ↔ Disjoint t s :=
le_compl_iff_disjoint_left (α := Finset α)
@[simp] lemma subset_compl_singleton : s ⊆ {a}ᶜ ↔ a ∉ s := by
rw [subset_compl_comm, singleton_subset_iff, mem_compl]
@[simp]
theorem compl_empty : (∅ : Finset α)ᶜ = univ :=
compl_bot
@[simp]
theorem compl_univ : (univ : Finset α)ᶜ = ∅ :=
compl_top
@[simp]
theorem compl_eq_empty_iff (s : Finset α) : sᶜ = ∅ ↔ s = univ :=
compl_eq_bot
@[simp]
theorem compl_eq_univ_iff (s : Finset α) : sᶜ = univ ↔ s = ∅ :=
compl_eq_top
@[simp]
theorem union_compl (s : Finset α) : s ∪ sᶜ = univ :=
sup_compl_eq_top
@[simp]
theorem inter_compl (s : Finset α) : s ∩ sᶜ = ∅ :=
inf_compl_eq_bot
@[simp]
theorem compl_union (s t : Finset α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ :=
compl_sup
@[simp]
theorem compl_inter (s t : Finset α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ :=
compl_inf
@[simp]
theorem compl_erase : (s.erase a)ᶜ = insert a sᶜ := by
ext
simp only [or_iff_not_imp_left, mem_insert, not_and, mem_compl, mem_erase]
@[simp]
theorem compl_insert : (insert a s)ᶜ = sᶜ.erase a := by
ext
simp only [not_or, mem_insert, mem_compl, mem_erase]
theorem insert_compl_insert (ha : a ∉ s) : insert a (insert a s)ᶜ = sᶜ := by
simp_rw [compl_insert, insert_erase (mem_compl.2 ha)]
@[simp]
theorem insert_compl_self (x : α) : insert x ({x}ᶜ : Finset α) = univ := by
rw [← compl_erase, erase_singleton, compl_empty]
@[simp]
theorem compl_filter (p : α → Prop) [DecidablePred p] [∀ x, Decidable ¬p x] :
(univ.filter p)ᶜ = univ.filter fun x => ¬p x :=
ext <| by simp
theorem compl_ne_univ_iff_nonempty (s : Finset α) : sᶜ ≠ univ ↔ s.Nonempty := by
simp [eq_univ_iff_forall, Finset.Nonempty]
theorem compl_singleton (a : α) : ({a} : Finset α)ᶜ = univ.erase a := by
rw [compl_eq_univ_sdiff, sdiff_singleton_eq_erase]
theorem insert_inj_on' (s : Finset α) : Set.InjOn (fun a => insert a s) (sᶜ : Finset α) := by
rw [coe_compl]
exact s.insert_inj_on
theorem image_univ_of_surjective [Fintype β] {f : β → α} (hf : Surjective f) :
univ.image f = univ :=
eq_univ_of_forall <| hf.forall.2 fun _ => mem_image_of_mem _ <| mem_univ _
@[simp]
theorem image_univ_equiv [Fintype β] (f : β ≃ α) : univ.image f = univ :=
Finset.image_univ_of_surjective f.surjective
@[simp] lemma univ_inter (s : Finset α) : univ ∩ s = s := by ext a; simp
@[simp] lemma inter_univ (s : Finset α) : s ∩ univ = s := by rw [inter_comm, univ_inter]
@[simp] lemma inter_eq_univ : s ∩ t = univ ↔ s = univ ∧ t = univ := inf_eq_top_iff
end BooleanAlgebra
-- @[simp] --Note this would loop with `Finset.univ_unique`
lemma singleton_eq_univ [Subsingleton α] (a : α) : ({a} : Finset α) = univ := by
ext b; simp [Subsingleton.elim a b]
theorem map_univ_of_surjective [Fintype β] {f : β ↪ α} (hf : Surjective f) : univ.map f = univ :=
eq_univ_of_forall <| hf.forall.2 fun _ => mem_map_of_mem _ <| mem_univ _
@[simp]
theorem map_univ_equiv [Fintype β] (f : β ≃ α) : univ.map f.toEmbedding = univ :=
map_univ_of_surjective f.surjective
theorem univ_map_equiv_to_embedding {α β : Type*} [Fintype α] [Fintype β] (e : α ≃ β) :
univ.map e.toEmbedding = univ :=
eq_univ_iff_forall.mpr fun b => mem_map.mpr ⟨e.symm b, mem_univ _, by simp⟩
@[simp]
theorem univ_filter_exists (f : α → β) [Fintype β] [DecidablePred fun y => ∃ x, f x = y]
[DecidableEq β] : (Finset.univ.filter fun y => ∃ x, f x = y) = Finset.univ.image f := by
ext
simp
/-- Note this is a special case of `(Finset.image_preimage f univ _).symm`. -/
theorem univ_filter_mem_range (f : α → β) [Fintype β] [DecidablePred fun y => y ∈ Set.range f]
[DecidableEq β] : (Finset.univ.filter fun y => y ∈ Set.range f) = Finset.univ.image f := by
grind
theorem coe_filter_univ (p : α → Prop) [DecidablePred p] :
(univ.filter p : Set α) = { x | p x } := by simp
end Fintypeα
@[simp] lemma subtype_eq_univ {p : α → Prop} [DecidablePred p] [Fintype {a // p a}] :
s.subtype p = univ ↔ ∀ ⦃a⦄, p a → a ∈ s := by simp [Finset.ext_iff]
@[simp] lemma subtype_univ [Fintype α] (p : α → Prop) [DecidablePred p] [Fintype {a // p a}] :
univ.subtype p = univ := by simp
lemma univ_map_subtype [Fintype α] (p : α → Prop) [DecidablePred p] [Fintype {a // p a}] :
univ.map (Function.Embedding.subtype p) = univ.filter p := by
rw [← subtype_map, subtype_univ]
lemma univ_val_map_subtype_val [Fintype α] (p : α → Prop) [DecidablePred p] [Fintype {a // p a}] :
univ.val.map ((↑) : { a // p a } → α) = (univ.filter p).val := by
apply (map_val (Function.Embedding.subtype p) univ).symm.trans
apply congr_arg
apply univ_map_subtype
lemma univ_val_map_subtype_restrict [Fintype α] (f : α → β)
(p : α → Prop) [DecidablePred p] [Fintype {a // p a}] :
univ.val.map (Subtype.restrict p f) = (univ.filter p).val.map f := by
rw [← univ_val_map_subtype_val, Multiset.map_map, Subtype.restrict_def]
section DecEq
variable [Fintype α] [DecidableEq α]
@[simp]
lemma filter_univ_mem (s : Finset α) : univ.filter (· ∈ s) = s := by simp [filter_mem_eq_inter]
instance decidableCodisjoint : Decidable (Codisjoint s t) :=
decidable_of_iff _ codisjoint_left.symm
instance decidableIsCompl : Decidable (IsCompl s t) :=
decidable_of_iff' _ isCompl_iff
end DecEq
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Insert.lean | import Mathlib.Data.Finset.Attr
import Mathlib.Data.Finset.Dedup
import Mathlib.Data.Finset.Empty
import Mathlib.Data.Multiset.FinsetOps
/-!
# Constructing finite sets by adding one element
This file contains the definitions of `{a} : Finset α`, `insert a s : Finset α` and `Finset.cons`,
all ways to construct a `Finset` by adding one element.
## Main declarations
* `Finset.induction_on`: Induction on finsets. To prove a proposition about an arbitrary `Finset α`,
it suffices to prove it for the empty finset, and to show that if it holds for some `Finset α`,
then it holds for the finset obtained by inserting a new element.
* `Finset.instSingletonFinset`: Denoted by `{a}`; the finset consisting of one element.
* `insert` and `Finset.cons`: For any `a : α`, `insert s a` returns `s ∪ {a}`. `cons s a h`
returns the same except that it requires a hypothesis stating that `a` is not already in `s`.
This does not require decidable equality on the type `α`.
## Tags
finite sets, finset
-/
-- Assert that we define `Finset` without the material on `List.sublists`.
-- Note that we cannot use `List.sublists` itself as that is defined very early.
assert_not_exists List.sublistsLen Multiset.powerset CompleteLattice IsOrderedMonoid
open Multiset Subtype Function
universe u
variable {α : Type*} {β : Type*}
namespace Finset
/-! ### Subset and strict subset relations -/
-- TODO: these should be global attributes, but this will require fixing other files
attribute [local trans] Subset.trans Superset.trans
/-! ### singleton -/
section Singleton
variable {s : Finset α} {a b : α}
/-- `{a} : Finset a` is the set `{a}` containing `a` and nothing else.
This differs from `insert a ∅` in that it does not require a `DecidableEq` instance for `α`.
-/
instance : Singleton α (Finset α) :=
⟨fun a => ⟨{a}, nodup_singleton a⟩⟩
@[simp]
theorem singleton_val (a : α) : ({a} : Finset α).1 = {a} :=
rfl
@[simp, grind =]
theorem mem_singleton {a b : α} : b ∈ ({a} : Finset α) ↔ b = a :=
Multiset.mem_singleton
theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : Finset α)) : x = y :=
mem_singleton.1 h
theorem notMem_singleton {a b : α} : a ∉ ({b} : Finset α) ↔ a ≠ b :=
not_congr mem_singleton
@[deprecated (since := "2025-05-23")] alias not_mem_singleton := notMem_singleton
theorem mem_singleton_self (a : α) : a ∈ ({a} : Finset α) :=
mem_singleton.mpr rfl
@[simp]
theorem val_eq_singleton_iff {a : α} {s : Finset α} : s.val = {a} ↔ s = {a} := by
rw [← val_inj]
rfl
theorem singleton_injective : Injective (singleton : α → Finset α) := fun _a _b h =>
mem_singleton.1 (h ▸ mem_singleton_self _)
@[simp]
theorem singleton_inj : ({a} : Finset α) = {b} ↔ a = b :=
singleton_injective.eq_iff
@[simp, aesop safe apply (rule_sets := [finsetNonempty])]
theorem singleton_nonempty (a : α) : ({a} : Finset α).Nonempty :=
⟨a, mem_singleton_self a⟩
@[simp]
theorem singleton_ne_empty (a : α) : ({a} : Finset α) ≠ ∅ :=
(singleton_nonempty a).ne_empty
@[simp]
theorem empty_ne_singleton (a : α) : ∅ ≠ ({a} : Finset α) :=
(singleton_ne_empty a).symm
theorem empty_ssubset_singleton : (∅ : Finset α) ⊂ {a} :=
(singleton_nonempty _).empty_ssubset
@[simp, norm_cast]
theorem coe_singleton (a : α) : (({a} : Finset α) : Set α) = {a} := by grind
@[simp, norm_cast]
theorem coe_eq_singleton {s : Finset α} {a : α} : (s : Set α) = {a} ↔ s = {a} := by grind
@[norm_cast]
lemma coe_subset_singleton : (s : Set α) ⊆ {a} ↔ s ⊆ {a} := by grind
@[norm_cast]
lemma singleton_subset_coe : {a} ⊆ (s : Set α) ↔ {a} ⊆ s := by grind
theorem eq_singleton_iff_unique_mem {s : Finset α} {a : α} : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := by
grind
theorem eq_singleton_iff_nonempty_unique_mem {s : Finset α} {a : α} :
s = {a} ↔ s.Nonempty ∧ ∀ x ∈ s, x = a := by
constructor
· rintro rfl
simp
· rintro ⟨hne, h_uniq⟩
rw [eq_singleton_iff_unique_mem]
refine ⟨?_, h_uniq⟩
rw [← h_uniq hne.choose hne.choose_spec]
exact hne.choose_spec
theorem nonempty_iff_eq_singleton_default [Unique α] {s : Finset α} :
s.Nonempty ↔ s = {default} := by
simp [eq_singleton_iff_nonempty_unique_mem, eq_iff_true_of_subsingleton]
alias ⟨Nonempty.eq_singleton_default, _⟩ := nonempty_iff_eq_singleton_default
theorem singleton_iff_unique_mem (s : Finset α) : (∃ a, s = {a}) ↔ ∃! a, a ∈ s := by
simp only [eq_singleton_iff_unique_mem, ExistsUnique]
theorem singleton_subset_set_iff {s : Set α} {a : α} : ↑({a} : Finset α) ⊆ s ↔ a ∈ s := by
grind
@[simp, grind =]
theorem singleton_subset_iff {s : Finset α} {a : α} : {a} ⊆ s ↔ a ∈ s :=
singleton_subset_set_iff
@[simp]
theorem subset_singleton_iff {s : Finset α} {a : α} : s ⊆ {a} ↔ s = ∅ ∨ s = {a} := by
grind
theorem singleton_subset_singleton : ({a} : Finset α) ⊆ {b} ↔ a = b := by simp
protected theorem Nonempty.subset_singleton_iff {s : Finset α} {a : α} (h : s.Nonempty) :
s ⊆ {a} ↔ s = {a} :=
subset_singleton_iff.trans <| or_iff_right h.ne_empty
theorem subset_singleton_iff' {s : Finset α} {a : α} : s ⊆ {a} ↔ ∀ b ∈ s, b = a :=
forall₂_congr fun _ _ => mem_singleton
@[simp]
theorem ssubset_singleton_iff {s : Finset α} {a : α} : s ⊂ {a} ↔ s = ∅ := by grind
theorem eq_empty_of_ssubset_singleton {s : Finset α} {x : α} (hs : s ⊂ {x}) : s = ∅ :=
ssubset_singleton_iff.1 hs
/-- A finset is nontrivial if it has at least two elements. -/
protected abbrev Nontrivial (s : Finset α) : Prop := (s : Set α).Nontrivial
@[grind =]
theorem nontrivial_def {s : Finset α} : s.Nontrivial ↔ ∃ a, a ∈ s ∧ ∃ b, b ∈ s ∧ a ≠ b := Iff.rfl
nonrec lemma Nontrivial.nonempty (hs : s.Nontrivial) : s.Nonempty := hs.nonempty
@[simp]
theorem not_nontrivial_empty : ¬(∅ : Finset α).Nontrivial := by simp [Finset.Nontrivial]
@[simp]
theorem not_nontrivial_singleton : ¬({a} : Finset α).Nontrivial := by simp [Finset.Nontrivial]
theorem Nontrivial.ne_singleton (hs : s.Nontrivial) : s ≠ {a} := by
rintro rfl; exact not_nontrivial_singleton hs
nonrec lemma Nontrivial.exists_ne (hs : s.Nontrivial) (a : α) : ∃ b ∈ s, b ≠ a := hs.exists_ne _
theorem eq_singleton_or_nontrivial (ha : a ∈ s) : s = {a} ∨ s.Nontrivial := by
rw [← coe_eq_singleton]; exact Set.eq_singleton_or_nontrivial ha
theorem nontrivial_iff_ne_singleton (ha : a ∈ s) : s.Nontrivial ↔ s ≠ {a} :=
⟨Nontrivial.ne_singleton, (eq_singleton_or_nontrivial ha).resolve_left⟩
theorem Nonempty.exists_eq_singleton_or_nontrivial : s.Nonempty → (∃ a, s = {a}) ∨ s.Nontrivial :=
fun ⟨a, ha⟩ => (eq_singleton_or_nontrivial ha).imp_left <| Exists.intro a
@[simp, norm_cast] lemma nontrivial_coe : (s : Set α).Nontrivial ↔ s.Nontrivial := .rfl
alias ⟨Nontrivial.of_coe, Nontrivial.coe⟩ := nontrivial_coe
lemma Nontrivial.not_subset_singleton (hs : s.Nontrivial) : ¬s ⊆ {a} :=
mod_cast hs.coe.not_subset_singleton
instance instNontrivial [Nonempty α] : Nontrivial (Finset α) :=
‹Nonempty α›.elim fun a => ⟨⟨{a}, ∅, singleton_ne_empty _⟩⟩
instance [IsEmpty α] : Unique (Finset α) where
default := ∅
uniq _ := eq_empty_of_forall_notMem isEmptyElim
instance (i : α) : Unique ({i} : Finset α) where
default := ⟨i, mem_singleton_self i⟩
uniq j := Subtype.ext <| mem_singleton.mp j.2
@[simp]
lemma default_singleton (i : α) : ((default : ({i} : Finset α)) : α) = i := rfl
instance Nontrivial.instDecidablePred : DecidablePred (Finset.Nontrivial (α := α)) := fun s =>
/-
We don't use `Finset.one_lt_card_iff_nontrivial`
because `Finset.card` is defined in a different file.
-/
Quotient.recOnSubsingleton (motive := fun (s : Multiset α) =>
(h : s.Nodup) → Decidable (Finset.Nontrivial ⟨s, h⟩))
s.val (fun l h => match l with
| [] => isFalse (by simp)
| [_] => isFalse (by simp [SetLike.coe])
| a :: b :: _ => isTrue ⟨a, by simp, b, by simp,
List.ne_of_not_mem_cons (List.nodup_cons.mp h).left⟩) s.nodup
end Singleton
/-! ### cons -/
section Cons
variable {s t : Finset α} {a b : α}
/-- `cons a s h` is the set `{a} ∪ s` containing `a` and the elements of `s`. It is the same as
`insert a s` when it is defined, but unlike `insert a s` it does not require `DecidableEq α`,
and the union is guaranteed to be disjoint. -/
def cons (a : α) (s : Finset α) (h : a ∉ s) : Finset α :=
⟨a ::ₘ s.1, nodup_cons.2 ⟨h, s.2⟩⟩
@[simp, grind =]
theorem mem_cons {h} : b ∈ s.cons a h ↔ b = a ∨ b ∈ s :=
Multiset.mem_cons
theorem mem_cons_of_mem {a b : α} {s : Finset α} {hb : b ∉ s} (ha : a ∈ s) : a ∈ cons b s hb :=
Multiset.mem_cons_of_mem ha
theorem mem_cons_self (a : α) (s : Finset α) {h} : a ∈ cons a s h :=
Multiset.mem_cons_self _ _
@[simp]
theorem cons_val (h : a ∉ s) : (cons a s h).1 = a ::ₘ s.1 :=
rfl
theorem eq_of_mem_cons_of_notMem (has : a ∉ s) (h : b ∈ cons a s has) (hb : b ∉ s) : b = a :=
(mem_cons.1 h).resolve_right hb
@[deprecated (since := "2025-05-23")] alias eq_of_mem_cons_of_not_mem := eq_of_mem_cons_of_notMem
theorem mem_of_mem_cons_of_ne {s : Finset α} {a : α} {has} {i : α}
(hi : i ∈ cons a s has) (hia : i ≠ a) : i ∈ s :=
(mem_cons.1 hi).resolve_left hia
theorem forall_mem_cons (h : a ∉ s) (p : α → Prop) :
(∀ x, x ∈ cons a s h → p x) ↔ p a ∧ ∀ x, x ∈ s → p x := by
grind
/-- Useful in proofs by induction. -/
theorem forall_of_forall_cons {p : α → Prop} {h : a ∉ s} (H : ∀ x, x ∈ cons a s h → p x) (x)
(h : x ∈ s) : p x :=
H _ <| mem_cons.2 <| Or.inr h
@[simp]
theorem mk_cons {s : Multiset α} (h : (a ::ₘ s).Nodup) :
(⟨a ::ₘ s, h⟩ : Finset α) = cons a ⟨s, (nodup_cons.1 h).2⟩ (nodup_cons.1 h).1 :=
rfl
@[simp]
theorem cons_empty (a : α) : cons a ∅ (notMem_empty _) = {a} := rfl
@[simp, aesop safe apply (rule_sets := [finsetNonempty])]
theorem cons_nonempty (h : a ∉ s) : (cons a s h).Nonempty :=
⟨a, mem_cons.2 <| Or.inl rfl⟩
@[simp] theorem cons_ne_empty (h : a ∉ s) : cons a s h ≠ ∅ := (cons_nonempty _).ne_empty
@[simp]
theorem nonempty_mk {m : Multiset α} {hm} : (⟨m, hm⟩ : Finset α).Nonempty ↔ m ≠ 0 := by
induction m using Multiset.induction_on <;> simp
@[simp]
theorem coe_cons {a s h} : (@cons α a s h : Set α) = insert a (s : Set α) := by
ext
simp
theorem subset_cons (h : a ∉ s) : s ⊆ s.cons a h :=
Multiset.subset_cons _ _
theorem ssubset_cons (h : a ∉ s) : s ⊂ s.cons a h :=
Multiset.ssubset_cons h
theorem cons_subset {h : a ∉ s} : s.cons a h ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
Multiset.cons_subset
@[simp]
theorem cons_subset_cons {hs ht} : s.cons a hs ⊆ t.cons a ht ↔ s ⊆ t := by
rwa [← coe_subset, coe_cons, coe_cons, Set.insert_subset_insert_iff, coe_subset]
theorem ssubset_iff_exists_cons_subset : s ⊂ t ↔ ∃ (a : _) (h : a ∉ s), s.cons a h ⊆ t := by
grind
theorem cons_swap (hb : b ∉ s) (ha : a ∉ s.cons b hb) :
(s.cons b hb).cons a ha = (s.cons a fun h ↦ ha (mem_cons.mpr (.inr h))).cons b fun h ↦
ha (mem_cons.mpr (.inl ((mem_cons.mp h).elim symm (fun h ↦ False.elim (hb h))))) :=
eq_of_veq <| Multiset.cons_swap a b s.val
/-- Split the added element of cons off a Pi type. -/
@[simps!]
def consPiProd (f : α → Type*) (has : a ∉ s) (x : Π i ∈ cons a s has, f i) : f a × Π i ∈ s, f i :=
(x a (mem_cons_self a s), fun i hi => x i (mem_cons_of_mem hi))
/-- Combine a product with a pi type to pi of cons. -/
def prodPiCons [DecidableEq α] (f : α → Type*) {a : α} (has : a ∉ s) (x : f a × Π i ∈ s, f i) :
(Π i ∈ cons a s has, f i) :=
fun i hi =>
if h : i = a then cast (congrArg f h.symm) x.1 else x.2 i (mem_of_mem_cons_of_ne hi h)
/-- The equivalence between pi types on cons and the product. -/
def consPiProdEquiv [DecidableEq α] {s : Finset α} (f : α → Type*) {a : α} (has : a ∉ s) :
(Π i ∈ cons a s has, f i) ≃ f a × Π i ∈ s, f i where
toFun := consPiProd f has
invFun := prodPiCons f has
left_inv _ := by grind [prodPiCons, consPiProd]
right_inv _ := by
-- I'm surprised `grind` needs this `ext` step: it is just `Prod.ext` and `funext`.
ext _ hi <;> grind [prodPiCons, consPiProd]
end Cons
/-! ### insert -/
section Insert
variable [DecidableEq α] {s t : Finset α} {a b : α} {f : α → β}
/-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/
instance : Insert α (Finset α) :=
⟨fun a s => ⟨_, s.2.ndinsert a⟩⟩
theorem insert_def (a : α) (s : Finset α) : insert a s = ⟨_, s.2.ndinsert a⟩ :=
rfl
@[simp]
theorem insert_val (a : α) (s : Finset α) : (insert a s).1 = ndinsert a s.1 :=
rfl
theorem insert_val' (a : α) (s : Finset α) : (insert a s).1 = dedup (a ::ₘ s.1) := by
rw [dedup_cons, dedup_eq_self]; rfl
theorem insert_val_of_notMem {a : α} {s : Finset α} (h : a ∉ s) : (insert a s).1 = a ::ₘ s.1 := by
rw [insert_val, ndinsert_of_notMem h]
@[deprecated (since := "2025-05-23")] alias insert_val_of_not_mem := insert_val_of_notMem
@[simp, grind =]
theorem mem_insert : a ∈ insert b s ↔ a = b ∨ a ∈ s :=
mem_ndinsert
theorem mem_insert_self (a : α) (s : Finset α) : a ∈ insert a s :=
mem_ndinsert_self a s.1
theorem mem_insert_of_mem (h : a ∈ s) : a ∈ insert b s :=
mem_ndinsert_of_mem h
theorem mem_of_mem_insert_of_ne (h : b ∈ insert a s) : b ≠ a → b ∈ s :=
(mem_insert.1 h).resolve_left
theorem eq_of_mem_insert_of_notMem (ha : b ∈ insert a s) (hb : b ∉ s) : b = a :=
(mem_insert.1 ha).resolve_right hb
@[deprecated (since := "2025-05-23")]
alias eq_of_mem_insert_of_not_mem := eq_of_mem_insert_of_notMem
/-- A version of `LawfulSingleton.insert_empty_eq` that works with `dsimp`. -/
@[simp] lemma insert_empty : insert a (∅ : Finset α) = {a} := rfl
@[simp, grind =]
theorem cons_eq_insert (a s h) : @cons α a s h = insert a s :=
ext fun a => by simp
@[simp, norm_cast]
theorem coe_insert (a : α) (s : Finset α) : ↑(insert a s) = (insert a s : Set α) := by grind
theorem mem_insert_coe {s : Finset α} {x y : α} : x ∈ insert y s ↔ x ∈ insert y (s : Set α) := by
simp
instance : LawfulSingleton α (Finset α) :=
⟨fun a => by simp⟩
@[simp, grind =]
theorem insert_eq_of_mem (h : a ∈ s) : insert a s = s :=
eq_of_veq <| ndinsert_of_mem h
@[simp]
theorem insert_eq_self : insert a s = s ↔ a ∈ s := by grind
theorem insert_ne_self : insert a s ≠ s ↔ a ∉ s :=
insert_eq_self.not
theorem pair_eq_singleton (a : α) : ({a, a} : Finset α) = {a} :=
insert_eq_of_mem <| mem_singleton_self _
theorem insert_comm (a b : α) (s : Finset α) : insert a (insert b s) = insert b (insert a s) := by
grind
@[norm_cast]
theorem coe_pair {a b : α} : (({a, b} : Finset α) : Set α) = {a, b} := by grind
@[simp, norm_cast]
theorem coe_eq_pair {s : Finset α} {a b : α} : (s : Set α) = {a, b} ↔ s = {a, b} := by
rw [← coe_pair, coe_inj]
theorem pair_comm (a b : α) : ({a, b} : Finset α) = {b, a} :=
insert_comm a b ∅
theorem insert_idem (a : α) (s : Finset α) : insert a (insert a s) = insert a s := by grind
@[simp, aesop safe apply (rule_sets := [finsetNonempty])]
theorem insert_nonempty (a : α) (s : Finset α) : (insert a s).Nonempty :=
⟨a, mem_insert_self a s⟩
@[simp]
theorem insert_ne_empty (a : α) (s : Finset α) : insert a s ≠ ∅ :=
(insert_nonempty a s).ne_empty
instance (i : α) (s : Finset α) : Nonempty ((insert i s : Finset α) : Set α) :=
(Finset.coe_nonempty.mpr (s.insert_nonempty i)).to_subtype
theorem ne_insert_of_notMem (s t : Finset α) {a : α} (h : a ∉ s) : s ≠ insert a t := by
contrapose! h
simp [h]
@[deprecated (since := "2025-05-23")] alias ne_insert_of_not_mem := ne_insert_of_notMem
theorem insert_subset_iff : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by grind
theorem insert_subset (ha : a ∈ t) (hs : s ⊆ t) : insert a s ⊆ t :=
insert_subset_iff.mpr ⟨ha,hs⟩
@[simp] theorem subset_insert (a : α) (s : Finset α) : s ⊆ insert a s := fun _b => mem_insert_of_mem
@[gcongr, simp]
theorem insert_subset_insert (a : α) {s t : Finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := by
grind
@[simp] lemma insert_subset_insert_iff (ha : a ∉ s) : insert a s ⊆ insert a t ↔ s ⊆ t := by
simp_rw [← coe_subset]; simp [ha]
theorem insert_inj (ha : a ∉ s) : insert a s = insert b s ↔ a = b :=
⟨fun h => eq_of_mem_insert_of_notMem (h ▸ mem_insert_self _ _) ha, congr_arg (insert · s)⟩
theorem insert_inj_on (s : Finset α) : Set.InjOn (fun a => insert a s) sᶜ := fun _ h _ _ =>
(insert_inj h).1
theorem ssubset_iff : s ⊂ t ↔ ∃ a ∉ s, insert a s ⊆ t := mod_cast @Set.ssubset_iff_insert α s t
theorem ssubset_insert (h : a ∉ s) : s ⊂ insert a s :=
ssubset_iff.mpr ⟨a, h, Subset.rfl⟩
@[elab_as_elim]
theorem cons_induction {α : Type*} {motive : Finset α → Prop} (empty : motive ∅)
(cons : ∀ (a : α) (s : Finset α) (h : a ∉ s), motive s → motive (cons a s h)) : ∀ s, motive s
| ⟨s, nd⟩ => by
induction s using Multiset.induction with
| empty => exact empty
| cons a s IH =>
rw [mk_cons nd]
exact cons a _ _ (IH _)
@[elab_as_elim]
theorem cons_induction_on {α : Type*} {motive : Finset α → Prop} (s : Finset α) (empty : motive ∅)
(cons : ∀ (a : α) (s : Finset α) (h : a ∉ s), motive s → motive (cons a s h)) : motive s :=
cons_induction empty cons s
@[elab_as_elim]
protected theorem induction {α : Type*} {motive : Finset α → Prop} [DecidableEq α]
(empty : motive ∅)
(insert : ∀ (a : α) (s : Finset α), a ∉ s → motive s → motive (insert a s)) : ∀ s, motive s :=
cons_induction empty fun a s ha => (s.cons_eq_insert a ha).symm ▸ insert a s ha
/-- To prove a proposition about an arbitrary `Finset α`,
it suffices to prove it for the empty `Finset`,
and to show that if it holds for some `Finset α`,
then it holds for the `Finset` obtained by inserting a new element.
-/
@[elab_as_elim]
protected theorem induction_on {α : Type*} {motive : Finset α → Prop} [DecidableEq α] (s : Finset α)
(empty : motive ∅)
(insert : ∀ (a : α) (s : Finset α), a ∉ s → motive s → motive (insert a s)) : motive s :=
Finset.induction empty insert s
/-- To prove a proposition about `S : Finset α`,
it suffices to prove it for the empty `Finset`,
and to show that if it holds for some `Finset α ⊆ S`,
then it holds for the `Finset` obtained by inserting a new element of `S`.
-/
@[elab_as_elim]
theorem induction_on' {α : Type*} {motive : Finset α → Prop} [DecidableEq α] (S : Finset α)
(empty : motive ∅)
(insert : ∀ (a s), a ∈ S → s ⊆ S → a ∉ s → motive s → motive (insert a s)) : motive S :=
@Finset.induction_on α (fun T => T ⊆ S → motive T) _ S (fun _ => empty)
(fun a s has hqs hs =>
let ⟨hS, sS⟩ := Finset.insert_subset_iff.1 hs
insert a s hS sS has (hqs sS))
(Finset.Subset.refl S)
/-- To prove a proposition about a nonempty `s : Finset α`, it suffices to show it holds for all
singletons and that if it holds for nonempty `t : Finset α`, then it also holds for the `Finset`
obtained by inserting an element in `t`. -/
@[elab_as_elim]
theorem Nonempty.cons_induction {α : Type*} {motive : ∀ s : Finset α, s.Nonempty → Prop}
(singleton : ∀ a, motive {a} (singleton_nonempty _))
(cons : ∀ a s (h : a ∉ s) (hs), motive s hs → motive (Finset.cons a s h) (cons_nonempty h))
{s : Finset α} (hs : s.Nonempty) : motive s hs := by
induction s using Finset.cons_induction with
| empty => exact (not_nonempty_empty hs).elim
| cons a t ha h =>
obtain rfl | ht := t.eq_empty_or_nonempty
· exact singleton a
· exact cons a t ha ht (h ht)
-- We use a fresh `α` here to exclude the unneeded `DecidableEq α` instance from the section.
lemma Nonempty.exists_cons_eq {α} {s : Finset α} (hs : s.Nonempty) : ∃ t a ha, cons a t ha = s :=
hs.cons_induction (fun a ↦ ⟨∅, a, _, cons_empty _⟩) fun _ _ _ _ _ ↦ ⟨_, _, _, rfl⟩
/-- Inserting an element to a finite set is equivalent to the option type. -/
def subtypeInsertEquivOption {t : Finset α} {x : α} (h : x ∉ t) :
{ i // i ∈ insert x t } ≃ Option { i // i ∈ t } where
toFun y := if h : ↑y = x then none else some ⟨y, (mem_insert.mp y.2).resolve_left h⟩
invFun y := (y.elim ⟨x, mem_insert_self _ _⟩) fun z => ⟨z, mem_insert_of_mem z.2⟩
left_inv y := by grind
right_inv := by rintro (_ | y) <;> grind
/-- Split the added element of insert off a Pi type. -/
@[simps!]
def insertPiProd (f : α → Type*) (x : Π i ∈ insert a s, f i) : f a × Π i ∈ s, f i :=
(x a (mem_insert_self a s), fun i hi => x i (mem_insert_of_mem hi))
/-- Combine a product with a pi type to pi of insert. -/
def prodPiInsert (f : α → Type*) {a : α} (x : f a × Π i ∈ s, f i) : (Π i ∈ insert a s, f i) :=
fun i hi =>
if h : i = a then cast (congrArg f h.symm) x.1 else x.2 i (mem_of_mem_insert_of_ne hi h)
/-- The equivalence between pi types on insert and the product. -/
def insertPiProdEquiv [DecidableEq α] {s : Finset α} (f : α → Type*) {a : α} (has : a ∉ s) :
(Π i ∈ insert a s, f i) ≃ f a × Π i ∈ s, f i where
toFun := insertPiProd f
invFun := prodPiInsert f
left_inv _ := by grind [prodPiInsert, insertPiProd]
right_inv _ := by ext _ hi <;> grind [prodPiInsert, insertPiProd]
-- useful rules for calculations with quantifiers
theorem exists_mem_insert (a : α) (s : Finset α) (p : α → Prop) :
(∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ ∃ x, x ∈ s ∧ p x := by grind
theorem forall_mem_insert (a : α) (s : Finset α) (p : α → Prop) :
(∀ x, x ∈ insert a s → p x) ↔ p a ∧ ∀ x, x ∈ s → p x := by grind
/-- Useful in proofs by induction. -/
theorem forall_of_forall_insert {p : α → Prop} {a : α} {s : Finset α}
(H : ∀ x, x ∈ insert a s → p x) (x) (h : x ∈ s) : p x :=
H _ <| mem_insert_of_mem h
end Insert
end Finset
namespace Multiset
variable [DecidableEq α]
@[simp]
theorem toFinset_zero : toFinset (0 : Multiset α) = ∅ :=
rfl
@[simp]
theorem toFinset_cons (a : α) (s : Multiset α) : toFinset (a ::ₘ s) = insert a (toFinset s) :=
Finset.eq_of_veq dedup_cons
@[simp]
theorem toFinset_singleton (a : α) : toFinset ({a} : Multiset α) = {a} := by
rw [← cons_zero, toFinset_cons, toFinset_zero, LawfulSingleton.insert_empty_eq]
end Multiset
namespace List
variable [DecidableEq α] {l : List α} {a : α}
@[simp]
theorem toFinset_nil : toFinset (@nil α) = ∅ :=
rfl
@[simp]
theorem toFinset_cons : toFinset (a :: l) = insert a (toFinset l) :=
Finset.eq_of_veq <| by by_cases h : a ∈ l <;> simp [h]
theorem toFinset_replicate_of_ne_zero {n : ℕ} (hn : n ≠ 0) :
(List.replicate n a).toFinset = {a} := by
ext x
simp [hn, List.mem_replicate]
@[simp]
theorem toFinset_eq_empty_iff (l : List α) : l.toFinset = ∅ ↔ l = nil := by
cases l <;> simp
@[simp]
theorem toFinset_nonempty_iff (l : List α) : l.toFinset.Nonempty ↔ l ≠ [] := by
simp [Finset.nonempty_iff_ne_empty]
end List
namespace Finset
section ToList
@[simp]
theorem toList_eq_singleton_iff {a : α} {s : Finset α} : s.toList = [a] ↔ s = {a} := by
rw [toList, Multiset.toList_eq_singleton_iff, val_eq_singleton_iff]
@[simp]
theorem toList_singleton : ∀ a, ({a} : Finset α).toList = [a] :=
Multiset.toList_singleton
open scoped List in
theorem toList_cons {a : α} {s : Finset α} (h : a ∉ s) : (cons a s h).toList ~ a :: s.toList :=
(List.perm_ext_iff_of_nodup (nodup_toList _) (by simp [h, nodup_toList s])).2 fun x => by
simp only [List.mem_cons, Finset.mem_toList, Finset.mem_cons]
open scoped List in
theorem toList_insert [DecidableEq α] {a : α} {s : Finset α} (h : a ∉ s) :
(insert a s).toList ~ a :: s.toList :=
cons_eq_insert _ _ h ▸ toList_cons _
end ToList
section Pairwise
variable {s : Finset α}
theorem pairwise_cons' {a : α} (ha : a ∉ s) (r : β → β → Prop) (f : α → β) :
Pairwise (r on fun a : s.cons a ha => f a) ↔
Pairwise (r on fun a : s => f a) ∧ ∀ b ∈ s, r (f a) (f b) ∧ r (f b) (f a) := by
simp only [pairwise_subtype_iff_pairwise_finset', Finset.coe_cons, Set.pairwise_insert]
grind
theorem pairwise_cons {a : α} (ha : a ∉ s) (r : α → α → Prop) :
Pairwise (r on fun a : s.cons a ha => a) ↔
Pairwise (r on fun a : s => a) ∧ ∀ b ∈ s, r a b ∧ r b a :=
pairwise_cons' ha r id
end Pairwise
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Pi.lean | import Mathlib.Data.Finset.Card
import Mathlib.Data.Finset.Union
import Mathlib.Data.Multiset.Pi
import Mathlib.Logic.Function.DependsOn
/-!
# The Cartesian product of finsets
## Main definitions
* `Finset.pi`: Cartesian product of finsets indexed by a finset.
-/
open Function
namespace Finset
open Multiset
/-! ### pi -/
section Pi
variable {α : Type*}
/-- The empty dependent product function, defined on the empty set. The assumption `a ∈ ∅` is never
satisfied. -/
def Pi.empty (β : α → Sort*) (a : α) (h : a ∈ (∅ : Finset α)) : β a :=
Multiset.Pi.empty β a h
universe u v
variable {β : α → Type u} {δ : α → Sort v} {s : Finset α} {t : ∀ a, Finset (β a)}
section
variable [DecidableEq α]
/-- Given a finset `s` of `α` and for all `a : α` a finset `t a` of `δ a`, then one can define the
finset `s.pi t` of all functions defined on elements of `s` taking values in `t a` for `a ∈ s`.
Note that the elements of `s.pi t` are only partially defined, on `s`. -/
def pi (s : Finset α) (t : ∀ a, Finset (β a)) : Finset (∀ a ∈ s, β a) :=
⟨s.1.pi fun a => (t a).1, s.nodup.pi fun a _ => (t a).nodup⟩
@[simp]
theorem pi_val (s : Finset α) (t : ∀ a, Finset (β a)) : (s.pi t).1 = s.1.pi fun a => (t a).1 :=
rfl
@[simp]
theorem mem_pi {s : Finset α} {t : ∀ a, Finset (β a)} {f : ∀ a ∈ s, β a} :
f ∈ s.pi t ↔ ∀ (a) (h : a ∈ s), f a h ∈ t a :=
Multiset.mem_pi _ _ _
/-- Given a function `f` defined on a finset `s`, define a new function on the finset `s ∪ {a}`,
equal to `f` on `s` and sending `a` to a given value `b`. This function is denoted
`s.Pi.cons a b f`. If `a` already belongs to `s`, the new function takes the value `b` at `a`
anyway. -/
def Pi.cons (s : Finset α) (a : α) (b : δ a) (f : ∀ a, a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) :
δ a' :=
Multiset.Pi.cons s.1 a b f _ (Multiset.mem_cons.2 <| mem_insert.symm.2 h)
@[simp]
theorem Pi.cons_same (s : Finset α) (a : α) (b : δ a) (f : ∀ a, a ∈ s → δ a) (h : a ∈ insert a s) :
Pi.cons s a b f a h = b :=
Multiset.Pi.cons_same _
theorem Pi.cons_ne {s : Finset α} {a a' : α} {b : δ a} {f : ∀ a, a ∈ s → δ a} {h : a' ∈ insert a s}
(ha : a ≠ a') : Pi.cons s a b f a' h = f a' ((mem_insert.1 h).resolve_left ha.symm) :=
Multiset.Pi.cons_ne _ (Ne.symm ha)
theorem Pi.cons_injective {a : α} {b : δ a} {s : Finset α} (hs : a ∉ s) :
Function.Injective (Pi.cons s a b) := fun e₁ e₂ eq =>
@Multiset.Pi.cons_injective α _ δ a b s.1 hs _ _ <|
funext fun e =>
funext fun h =>
have :
Pi.cons s a b e₁ e (by simpa only [Multiset.mem_cons, mem_insert] using h) =
Pi.cons s a b e₂ e (by simpa only [Multiset.mem_cons, mem_insert] using h) := by
rw [eq]
this
@[simp]
theorem pi_empty {t : ∀ a : α, Finset (β a)} : pi (∅ : Finset α) t = singleton (Pi.empty β) :=
rfl
@[simp]
lemma pi_nonempty : (s.pi t).Nonempty ↔ ∀ a ∈ s, (t a).Nonempty := by
simp [Finset.Nonempty, Classical.skolem]
@[aesop safe apply (rule_sets := [finsetNonempty])]
alias ⟨_, pi_nonempty_of_forall_nonempty⟩ := pi_nonempty
@[simp]
lemma pi_eq_empty : s.pi t = ∅ ↔ ∃ a ∈ s, t a = ∅ := by
simp [← not_nonempty_iff_eq_empty]
@[simp]
theorem pi_insert [∀ a, DecidableEq (β a)] {s : Finset α} {t : ∀ a : α, Finset (β a)} {a : α}
(ha : a ∉ s) : pi (insert a s) t = (t a).biUnion fun b => (pi s t).image (Pi.cons s a b) := by
apply eq_of_veq
rw [← (pi (insert a s) t).2.dedup]
refine
(fun s' (h : s' = a ::ₘ s.1) =>
(?_ :
dedup (Multiset.pi s' fun a => (t a).1) =
dedup
((t a).1.bind fun b =>
dedup <|
(Multiset.pi s.1 fun a : α => (t a).val).map fun f a' h' =>
Multiset.Pi.cons s.1 a b f a' (h ▸ h'))))
_ (insert_val_of_notMem ha)
subst s'; rw [pi_cons]
congr; funext b
exact ((pi s t).nodup.map <| Multiset.Pi.cons_injective ha).dedup.symm
theorem pi_singletons {β : Type*} (s : Finset α) (f : α → β) :
(s.pi fun a => ({f a} : Finset β)) = {fun a _ => f a} := by
rw [eq_singleton_iff_unique_mem]
constructor
· simp
intro a ha
ext i hi
rw [mem_pi] at ha
simpa using ha i hi
theorem pi_const_singleton {β : Type*} (s : Finset α) (i : β) :
(s.pi fun _ => ({i} : Finset β)) = {fun _ _ => i} :=
pi_singletons s fun _ => i
theorem pi_subset {s : Finset α} (t₁ t₂ : ∀ a, Finset (β a)) (h : ∀ a ∈ s, t₁ a ⊆ t₂ a) :
s.pi t₁ ⊆ s.pi t₂ := fun _ hg => mem_pi.2 fun a ha => h a ha (mem_pi.mp hg a ha)
theorem pi_disjoint_of_disjoint {δ : α → Type*} {s : Finset α} (t₁ t₂ : ∀ a, Finset (δ a)) {a : α}
(ha : a ∈ s) (h : Disjoint (t₁ a) (t₂ a)) : Disjoint (s.pi t₁) (s.pi t₂) :=
disjoint_iff_ne.2 fun f₁ hf₁ f₂ hf₂ eq₁₂ =>
disjoint_iff_ne.1 h (f₁ a ha) (mem_pi.mp hf₁ a ha) (f₂ a ha) (mem_pi.mp hf₂ a ha) <|
congr_fun (congr_fun eq₁₂ a) ha
end
/-! ### Diagonal -/
variable {ι : Type*} [DecidableEq (ι → α)] {s : Finset α} {f : ι → α}
/-- The diagonal of a finset `s : Finset α` as a finset of functions `ι → α`, namely the set of
constant functions valued in `s`. -/
def piDiag (s : Finset α) (ι : Type*) [DecidableEq (ι → α)] : Finset (ι → α) := s.image (const ι)
@[simp] lemma mem_piDiag : f ∈ s.piDiag ι ↔ ∃ a ∈ s, const ι a = f := mem_image
@[simp] lemma card_piDiag (s : Finset α) (ι : Type*) [DecidableEq (ι → α)] [Nonempty ι] :
(s.piDiag ι).card = s.card := by rw [piDiag, card_image_of_injective _ const_injective]
/-! ### Restriction -/
variable {π : ι → Type*}
/-- Restrict domain of a function `f` to a finite set `s`. -/
@[simp]
def restrict (s : Finset ι) (f : (i : ι) → π i) : (i : s) → π i := fun x ↦ f x
theorem restrict_def (s : Finset ι) : s.restrict (π := π) = fun f x ↦ f x := rfl
variable {s t u : Finset ι}
theorem _root_.Set.piCongrLeft_comp_restrict :
(s.equivToSet.symm.piCongrLeft (fun i : s ↦ π i)) ∘ (s : Set ι).restrict = s.restrict := rfl
theorem piCongrLeft_comp_restrict :
(s.equivToSet.piCongrLeft (fun i : s ↦ π i)) ∘ s.restrict = (s : Set ι).restrict := rfl
/-- If a function `f` is restricted to a finite set `t`, and `s ⊆ t`,
this is the restriction to `s`. -/
@[simp]
def restrict₂ (hst : s ⊆ t) (f : (i : t) → π i) (i : s) : π i := f ⟨i.1, hst i.2⟩
theorem restrict₂_def (hst : s ⊆ t) : restrict₂ (π := π) hst = fun f x ↦ f ⟨x.1, hst x.2⟩ := rfl
theorem restrict₂_comp_restrict (hst : s ⊆ t) :
(restrict₂ (π := π) hst) ∘ t.restrict = s.restrict := rfl
theorem restrict₂_comp_restrict₂ (hst : s ⊆ t) (htu : t ⊆ u) :
(restrict₂ (π := π) hst) ∘ (restrict₂ htu) = restrict₂ (hst.trans htu) := rfl
lemma dependsOn_restrict (s : Finset ι) : DependsOn (s.restrict (π := π)) s :=
(s : Set ι).dependsOn_restrict
lemma restrict_preimage [DecidablePred (· ∈ s)] (t : (i : s) → Set (π i)) :
s.restrict ⁻¹' (Set.univ.pi t) =
Set.pi s (fun i ↦ if h : i ∈ s then t ⟨i, h⟩ else Set.univ) := by
ext x
simp only [Set.mem_preimage, Set.mem_pi, Set.mem_univ, restrict, forall_const, Subtype.forall,
mem_coe]
refine ⟨fun h i hi ↦ by simpa [hi] using h i hi, fun h i hi ↦ ?_⟩
convert h i hi
rw [dif_pos hi]
lemma restrict₂_preimage [DecidablePred (· ∈ s)] (hst : s ⊆ t) (u : (i : s) → Set (π i)) :
(restrict₂ hst) ⁻¹' (Set.univ.pi u) =
(@Set.univ t).pi (fun j ↦ if h : j.1 ∈ s then u ⟨j.1, h⟩ else Set.univ) := by
ext x
simp only [Set.mem_preimage, Set.mem_pi, Set.mem_univ, restrict₂, forall_const, Subtype.forall]
refine ⟨fun h i hi ↦ ?_, fun h i i_mem ↦ by simpa [i_mem] using h i (hst i_mem)⟩
split_ifs with i_mem
· exact h i i_mem
· exact Set.mem_univ _
end Pi
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Density.lean | import Mathlib.Algebra.Order.Field.Rat
import Mathlib.Data.Fintype.Card
import Mathlib.Data.NNRat.Order
import Mathlib.Data.Rat.Cast.CharZero
import Mathlib.Tactic.Positivity.Basic
/-!
# Density of a finite set
This defines the density of a `Finset` and provides induction principles for finsets.
## Main declarations
* `Finset.dens s`: Density of `s : Finset α` in `α` as a nonnegative rational number.
## Implementation notes
There are many other ways to talk about the density of a finset and provide its API:
1. Use the uniform measure
2. Define finitely additive functions and generalise the `Finset.card` API to it. This could either
be done with
a. A structure `FinitelyAdditiveFun`
b. A typeclass `IsFinitelyAdditiveFun`
Solution 1 would mean importing measure theory in simple files (not necessarily bad, but not
amazing), and every single API lemma would require the user to prove that all the sets they are
talking about are measurable in the trivial sigma-algebra (quite terrible user experience).
Solution 2 would mean that some API lemmas about density don't contain `dens` in their name because
they are general results about finitely additive functions. But not all lemmas would be like that
either since some really are `dens`-specific. Hence the user would need to think about whether the
lemma they are looking for is generally true for finitely additive measure or whether it is
`dens`-specific.
On top of this, solution 2.a would break dot notation on `Finset.dens` (possibly fixable by
introducing notation for `⇑Finset.dens`) and solution 2.b would run the risk of being bad
performance-wise.
These considerations more generally apply to `Finset.card` and `Finset.sum` and demonstrate that
overengineering basic definitions is likely to hinder user experience.
-/
-- TODO
-- assert_not_exists Ring
open Function Multiset Nat
variable {𝕜 α β : Type*} [Fintype α]
namespace Finset
variable {s t : Finset α} {a b : α}
/-- Density of a finset.
`dens s` is the number of elements of `s` divided by the size of the ambient type `α`. -/
def dens (s : Finset α) : ℚ≥0 := s.card / Fintype.card α
lemma dens_eq_card_div_card (s : Finset α) : dens s = s.card / Fintype.card α := rfl
@[simp] lemma dens_empty : dens (∅ : Finset α) = 0 := by simp [dens]
@[simp] lemma dens_singleton (a : α) : dens ({a} : Finset α) = (Fintype.card α : ℚ≥0)⁻¹ := by
simp [dens]
@[simp] lemma dens_cons (h : a ∉ s) : (s.cons a h).dens = dens s + (Fintype.card α : ℚ≥0)⁻¹ := by
simp [dens, add_div]
@[simp] lemma dens_disjUnion (s t : Finset α) (h) : dens (s.disjUnion t h) = dens s + dens t := by
simp_rw [dens, card_disjUnion, Nat.cast_add, add_div]
@[simp] lemma dens_eq_zero : dens s = 0 ↔ s = ∅ := by
simp +contextual [dens, Fintype.card_eq_zero_iff, eq_empty_of_isEmpty]
lemma dens_ne_zero : dens s ≠ 0 ↔ s.Nonempty := dens_eq_zero.not.trans nonempty_iff_ne_empty.symm
@[simp] lemma dens_pos : 0 < dens s ↔ s.Nonempty := pos_iff_ne_zero.trans dens_ne_zero
protected alias ⟨_, Nonempty.dens_pos⟩ := dens_pos
protected alias ⟨_, Nonempty.dens_ne_zero⟩ := dens_ne_zero
@[gcongr]
lemma dens_le_dens (h : s ⊆ t) : dens s ≤ dens t :=
div_le_div_of_nonneg_right (mod_cast card_mono h) <| by positivity
@[gcongr]
lemma dens_lt_dens (h : s ⊂ t) : dens s < dens t :=
div_lt_div_of_pos_right (by gcongr) <| mod_cast calc
0 ≤ #s := Nat.zero_le _
_ < #t := by gcongr
_ ≤ Fintype.card α := card_le_univ t
@[mono] lemma dens_mono : Monotone (dens : Finset α → ℚ≥0) := fun _ _ ↦ dens_le_dens
@[mono] lemma dens_strictMono : StrictMono (dens : Finset α → ℚ≥0) := fun _ _ ↦ dens_lt_dens
lemma dens_map_le [Fintype β] (f : α ↪ β) : dens (s.map f) ≤ dens s := by
cases isEmpty_or_nonempty α
· simp [Subsingleton.elim s ∅]
simp_rw [dens, card_map]
gcongr
· exact mod_cast Fintype.card_pos
· exact Fintype.card_le_of_injective _ f.2
@[simp] lemma dens_map_equiv [Fintype β] (e : α ≃ β) : (s.map e.toEmbedding).dens = s.dens := by
simp [dens, Fintype.card_congr e]
lemma dens_image [Fintype β] [DecidableEq β] {f : α → β} (hf : Bijective f) (s : Finset α) :
(s.image f).dens = s.dens := by
simpa [map_eq_image, -dens_map_equiv] using dens_map_equiv (.ofBijective f hf)
@[simp] lemma card_mul_dens (s : Finset α) : Fintype.card α * s.dens = s.card := by
cases isEmpty_or_nonempty α
· simp [Subsingleton.elim s ∅]
rw [dens, mul_div_cancel₀]
exact mod_cast Fintype.card_ne_zero
@[simp] lemma dens_mul_card (s : Finset α) : s.dens * Fintype.card α = s.card := by
rw [mul_comm, card_mul_dens]
section Semifield
variable [Semifield 𝕜] [CharZero 𝕜]
@[simp] lemma natCast_card_mul_nnratCast_dens (s : Finset α) :
(Fintype.card α * s.dens : 𝕜) = s.card := mod_cast s.card_mul_dens
@[simp] lemma nnratCast_dens_mul_natCast_card (s : Finset α) :
(s.dens * Fintype.card α : 𝕜) = s.card := mod_cast s.dens_mul_card
@[norm_cast] lemma nnratCast_dens (s : Finset α) : (s.dens : 𝕜) = s.card / Fintype.card α := by
simp [dens]
end Semifield
section Nonempty
variable [Nonempty α]
@[simp] lemma dens_univ : dens (univ : Finset α) = 1 := by simp [dens, card_univ]
@[simp] lemma dens_eq_one : dens s = 1 ↔ s = univ := by
simp [dens, div_eq_one_iff_eq, card_eq_iff_eq_univ]
lemma dens_ne_one : dens s ≠ 1 ↔ s ≠ univ := dens_eq_one.not
end Nonempty
@[simp] lemma dens_le_one : s.dens ≤ 1 := by
cases isEmpty_or_nonempty α
· simp [Subsingleton.elim s ∅]
· simpa using dens_le_dens s.subset_univ
section Lattice
variable [DecidableEq α]
lemma dens_union_add_dens_inter (s t : Finset α) :
dens (s ∪ t) + dens (s ∩ t) = dens s + dens t := by
simp_rw [dens, ← add_div, ← Nat.cast_add, card_union_add_card_inter]
lemma dens_inter_add_dens_union (s t : Finset α) :
dens (s ∩ t) + dens (s ∪ t) = dens s + dens t := by rw [add_comm, dens_union_add_dens_inter]
@[simp] lemma dens_union_of_disjoint (h : Disjoint s t) : dens (s ∪ t) = dens s + dens t := by
rw [← disjUnion_eq_union s t h, dens_disjUnion _ _ _]
lemma dens_sdiff_add_dens_eq_dens (h : s ⊆ t) : dens (t \ s) + dens s = dens t := by
simp [dens, ← card_sdiff_add_card_eq_card h, add_div]
lemma dens_sdiff_add_dens (s t : Finset α) : dens (s \ t) + dens t = (s ∪ t).dens := by
rw [← dens_union_of_disjoint sdiff_disjoint, sdiff_union_self_eq_union]
lemma dens_sdiff_comm (h : card s = card t) : dens (s \ t) = dens (t \ s) :=
add_left_injective (dens t) <| by
simp_rw [dens_sdiff_add_dens, union_comm s, ← dens_sdiff_add_dens, dens, h]
@[simp]
lemma dens_sdiff_add_dens_inter (s t : Finset α) : dens (s \ t) + dens (s ∩ t) = dens s := by
rw [← dens_union_of_disjoint (disjoint_sdiff_inter _ _), sdiff_union_inter]
@[simp]
lemma dens_inter_add_dens_sdiff (s t : Finset α) : dens (s ∩ t) + dens (s \ t) = dens s := by
rw [add_comm, dens_sdiff_add_dens_inter]
lemma dens_filter_add_dens_filter_not_eq_dens {α : Type*} [Fintype α] {s : Finset α}
(p : α → Prop) [DecidablePred p] [∀ x, Decidable (¬p x)] :
dens {a ∈ s | p a} + dens {a ∈ s | ¬ p a} = dens s := by
classical
rw [← dens_union_of_disjoint (disjoint_filter_filter_neg ..), filter_union_filter_neg_eq]
lemma dens_union_le (s t : Finset α) : dens (s ∪ t) ≤ dens s + dens t :=
dens_union_add_dens_inter s t ▸ le_add_of_nonneg_right zero_le'
lemma dens_le_dens_sdiff_add_dens : dens s ≤ dens (s \ t) + dens t :=
dens_sdiff_add_dens s _ ▸ dens_le_dens subset_union_left
lemma dens_sdiff (h : s ⊆ t) : dens (t \ s) = dens t - dens s :=
eq_tsub_of_add_eq (dens_sdiff_add_dens_eq_dens h)
lemma le_dens_sdiff (s t : Finset α) : dens t - dens s ≤ dens (t \ s) :=
tsub_le_iff_right.2 dens_le_dens_sdiff_add_dens
end Lattice
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Image.lean | import Mathlib.Algebra.NeZero
import Mathlib.Data.Finset.Attach
import Mathlib.Data.Finset.Disjoint
import Mathlib.Data.Finset.Erase
import Mathlib.Data.Finset.Filter
import Mathlib.Data.Finset.Range
import Mathlib.Data.Finset.Lattice.Lemmas
import Mathlib.Data.Finset.SDiff
import Mathlib.Data.Fintype.Defs
/-! # Image and map operations on finite sets
This file provides the finite analog of `Set.image`, along with some other similar functions.
Note there are two ways to take the image over a finset; via `Finset.image` which applies the
function then removes duplicates (requiring `DecidableEq`), or via `Finset.map` which exploits
injectivity of the function to avoid needing to deduplicate. Choosing between these is similar to
choosing between `insert` and `Finset.cons`, or between `Finset.union` and `Finset.disjUnion`.
## Main definitions
* `Finset.image`: Given a function `f : α → β`, `s.image f` is the image finset in `β`.
* `Finset.map`: Given an embedding `f : α ↪ β`, `s.map f` is the image finset in `β`.
* `Finset.filterMap` Given a function `f : α → Option β`, `s.filterMap f` is the
image finset in `β`, filtering out `none`s.
* `Finset.subtype`: `s.subtype p` is the finset of `Subtype p` whose elements belong to `s`.
* `Finset.fin`:`s.fin n` is the finset of all elements of `s` less than `n`.
-/
assert_not_exists Monoid IsOrderedMonoid
variable {α β γ : Type*}
open Multiset
open Function
namespace Finset
/-! ### map -/
section Map
/-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image
finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/
def map (f : α ↪ β) (s : Finset α) : Finset β :=
⟨s.1.map f, s.2.map f.2⟩
@[simp]
theorem map_val (f : α ↪ β) (s : Finset α) : (map f s).1 = s.1.map f :=
rfl
@[simp]
theorem map_empty (f : α ↪ β) : (∅ : Finset α).map f = ∅ :=
rfl
variable {f : α ↪ β} {s : Finset α}
@[simp, grind =]
theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b :=
Multiset.mem_map
-- Higher priority to apply before `mem_map`.
@[simp 1100]
theorem mem_map_equiv {f : α ≃ β} {b : β} : b ∈ s.map f.toEmbedding ↔ f.symm b ∈ s := by
rw [mem_map]
exact
⟨by
rintro ⟨a, H, rfl⟩
simpa, fun h => ⟨_, h, by simp⟩⟩
@[simp 1100]
theorem mem_map' (f : α ↪ β) {a} {s : Finset α} : f a ∈ s.map f ↔ a ∈ s :=
mem_map_of_injective f.2
@[simp 1100]
theorem mem_map_mk (f : α → β) {a : α} {s : Finset α} (hf : Function.Injective f) :
f a ∈ s.map ⟨f, hf⟩ ↔ a ∈ s :=
Finset.mem_map' _
theorem mem_map_of_mem (f : α ↪ β) {a} {s : Finset α} : a ∈ s → f a ∈ s.map f :=
(mem_map' _).2
theorem forall_mem_map {f : α ↪ β} {s : Finset α} {p : ∀ a, a ∈ s.map f → Prop} :
(∀ y (H : y ∈ s.map f), p y H) ↔ ∀ x (H : x ∈ s), p (f x) (mem_map_of_mem _ H) := by grind
theorem apply_coe_mem_map (f : α ↪ β) (s : Finset α) (x : s) : f x ∈ s.map f :=
mem_map_of_mem f x.prop
@[simp, norm_cast]
theorem coe_map (f : α ↪ β) (s : Finset α) : (s.map f : Set β) = f '' s := by grind
theorem coe_map_subset_range (f : α ↪ β) (s : Finset α) : (s.map f : Set β) ⊆ Set.range f := by
grind
/-- If the only elements outside `s` are those left fixed by `σ`, then mapping by `σ` has no effect.
-/
theorem map_perm {σ : Equiv.Perm α} (hs : { a | σ a ≠ a } ⊆ s) : s.map (σ : α ↪ α) = s :=
coe_injective <| (coe_map _ _).trans <| Set.image_perm hs
theorem map_toFinset [DecidableEq α] [DecidableEq β] {s : Multiset α} :
s.toFinset.map f = (s.map f).toFinset :=
ext fun _ => by simp only [mem_map, Multiset.mem_map, Multiset.mem_toFinset]
@[simp]
theorem map_refl : s.map (Embedding.refl _) = s :=
ext fun _ => by simpa only [mem_map, exists_prop] using exists_eq_right
@[simp]
theorem map_cast_heq {α β} (h : α = β) (s : Finset α) :
s.map (Equiv.cast h).toEmbedding ≍ s := by
subst h
simp
theorem map_map (f : α ↪ β) (g : β ↪ γ) (s : Finset α) : (s.map f).map g = s.map (f.trans g) :=
eq_of_veq <| by simp only [map_val, Multiset.map_map]; rfl
theorem map_comm {β'} {f : β ↪ γ} {g : α ↪ β} {f' : α ↪ β'} {g' : β' ↪ γ}
(h_comm : ∀ a, f (g a) = g' (f' a)) : (s.map g).map f = (s.map f').map g' := by
simp_rw [map_map, Embedding.trans, Function.comp_def, h_comm]
theorem _root_.Function.Semiconj.finset_map {f : α ↪ β} {ga : α ↪ α} {gb : β ↪ β}
(h : Function.Semiconj f ga gb) : Function.Semiconj (map f) (map ga) (map gb) := fun _ =>
map_comm h
theorem _root_.Function.Commute.finset_map {f g : α ↪ α} (h : Function.Commute f g) :
Function.Commute (map f) (map g) :=
Function.Semiconj.finset_map h
@[simp]
theorem map_subset_map {s₁ s₂ : Finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ :=
⟨fun h _ xs => (mem_map' _).1 <| h <| (mem_map' f).2 xs,
fun h => by simp [subset_def, Multiset.map_subset_map h]⟩
@[gcongr] alias ⟨_, _root_.GCongr.finsetMap_subset⟩ := map_subset_map
/-- The `Finset` version of `Equiv.subset_symm_image`. -/
theorem subset_map_symm {t : Finset β} {f : α ≃ β} : s ⊆ t.map f.symm ↔ s.map f ⊆ t := by
constructor <;> intro h x hx
· simp only [mem_map_equiv] at hx
simpa using h hx
· simp only [mem_map_equiv]
exact h (by simp [hx])
/-- The `Finset` version of `Equiv.symm_image_subset`. -/
theorem map_symm_subset {t : Finset β} {f : α ≃ β} : t.map f.symm ⊆ s ↔ t ⊆ s.map f := by
simp only [← subset_map_symm, Equiv.symm_symm]
/-- Associate to an embedding `f` from `α` to `β` the order embedding that maps a finset to its
image under `f`. -/
def mapEmbedding (f : α ↪ β) : Finset α ↪o Finset β :=
OrderEmbedding.ofMapLEIff (map f) fun _ _ => map_subset_map
@[simp]
theorem map_inj {s₁ s₂ : Finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ :=
(mapEmbedding f).injective.eq_iff
theorem map_injective (f : α ↪ β) : Injective (map f) :=
(mapEmbedding f).injective
@[simp]
theorem map_ssubset_map {s t : Finset α} : s.map f ⊂ t.map f ↔ s ⊂ t := (mapEmbedding f).lt_iff_lt
@[gcongr] alias ⟨_, _root_.GCongr.finsetMap_ssubset⟩ := map_ssubset_map
@[simp]
theorem mapEmbedding_apply : mapEmbedding f s = map f s :=
rfl
theorem filter_map {p : β → Prop} [DecidablePred p] :
(s.map f).filter p = (s.filter (p ∘ f)).map f :=
eq_of_veq (Multiset.filter_map _ _ _)
lemma map_filter' (p : α → Prop) [DecidablePred p] (f : α ↪ β) (s : Finset α)
[DecidablePred (∃ a, p a ∧ f a = ·)] :
(s.filter p).map f = (s.map f).filter fun b => ∃ a, p a ∧ f a = b := by
simp [Function.comp_def, filter_map, f.injective.eq_iff]
lemma filter_attach' [DecidableEq α] (s : Finset α) (p : s → Prop) [DecidablePred p] :
s.attach.filter p =
(s.filter fun x => ∃ h, p ⟨x, h⟩).attach.map
⟨Subtype.map id <| filter_subset _ _, Subtype.map_injective _ injective_id⟩ :=
eq_of_veq <| Multiset.filter_attach' _ _
lemma filter_attach (p : α → Prop) [DecidablePred p] (s : Finset α) :
s.attach.filter (fun a : s ↦ p a) =
(s.filter p).attach.map ((Embedding.refl _).subtypeMap mem_of_mem_filter) :=
eq_of_veq <| Multiset.filter_attach _ _
theorem map_filter {f : α ≃ β} {p : α → Prop} [DecidablePred p] :
(s.filter p).map f.toEmbedding = (s.map f.toEmbedding).filter (p ∘ f.symm) := by
simp only [filter_map, Function.comp_def, Equiv.toEmbedding_apply, Equiv.symm_apply_apply]
@[simp]
theorem disjoint_map {s t : Finset α} (f : α ↪ β) :
Disjoint (s.map f) (t.map f) ↔ Disjoint s t :=
mod_cast Set.disjoint_image_iff f.injective (s := s) (t := t)
theorem map_disjUnion {f : α ↪ β} (s₁ s₂ : Finset α) (h) (h' := (disjoint_map _).mpr h) :
(s₁.disjUnion s₂ h).map f = (s₁.map f).disjUnion (s₂.map f) h' :=
eq_of_veq <| Multiset.map_add _ _ _
/-- A version of `Finset.map_disjUnion` for writing in the other direction. -/
theorem map_disjUnion' {f : α ↪ β} (s₁ s₂ : Finset α) (h') (h := (disjoint_map _).mp h') :
(s₁.disjUnion s₂ h).map f = (s₁.map f).disjUnion (s₂.map f) h' :=
map_disjUnion _ _ _
theorem map_union [DecidableEq α] [DecidableEq β] {f : α ↪ β} (s₁ s₂ : Finset α) :
(s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f :=
mod_cast Set.image_union f s₁ s₂
theorem map_inter [DecidableEq α] [DecidableEq β] {f : α ↪ β} (s₁ s₂ : Finset α) :
(s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f :=
mod_cast Set.image_inter f.injective (s := s₁) (t := s₂)
theorem map_sdiff [DecidableEq α] [DecidableEq β] {f : α ↪ β} (s₁ s₂ : Finset α) :
(s₁ \ s₂).map f = s₁.map f \ s₂.map f :=
mod_cast Set.image_diff f.injective (s := s₁) (t := s₂)
@[simp]
theorem map_singleton (f : α ↪ β) (a : α) : map f {a} = {f a} :=
coe_injective <| by simp only [coe_map, coe_singleton, Set.image_singleton]
@[simp]
theorem map_insert [DecidableEq α] [DecidableEq β] (f : α ↪ β) (a : α) (s : Finset α) :
(insert a s).map f = insert (f a) (s.map f) := by
simp only [insert_eq, map_union, map_singleton]
@[simp]
theorem map_cons (f : α ↪ β) (a : α) (s : Finset α) (ha : a ∉ s) :
(cons a s ha).map f = cons (f a) (s.map f) (by simpa using ha) :=
eq_of_veq <| Multiset.map_cons f a s.val
@[simp]
theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ := (map_injective f).eq_iff' (map_empty f)
@[simp]
theorem map_nonempty : (s.map f).Nonempty ↔ s.Nonempty :=
mod_cast Set.image_nonempty (f := f) (s := s)
@[aesop safe apply (rule_sets := [finsetNonempty])]
protected alias ⟨_, Nonempty.map⟩ := map_nonempty
@[simp]
theorem map_nontrivial : (s.map f).Nontrivial ↔ s.Nontrivial :=
mod_cast Set.image_nontrivial f.injective (s := s)
theorem attach_map_val {s : Finset α} : s.attach.map (Embedding.subtype _) = s :=
eq_of_veq <| by rw [map_val, attach_val]; exact Multiset.attach_map_val _
end Map
theorem range_add_one' (n : ℕ) :
range (n + 1) = insert 0 ((range n).map ⟨fun i => i + 1, fun i j => by simp⟩) := by
ext (⟨⟩ | ⟨n⟩) <;> simp [Nat.zero_lt_succ n]
/-! ### image -/
section Image
variable [DecidableEq β]
/-- `image f s` is the forward image of `s` under `f`. -/
def image (f : α → β) (s : Finset α) : Finset β :=
(s.1.map f).toFinset
@[simp]
theorem image_val (f : α → β) (s : Finset α) : (image f s).1 = (s.1.map f).dedup :=
rfl
@[simp]
theorem image_empty (f : α → β) : (∅ : Finset α).image f = ∅ :=
rfl
variable {f g : α → β} {s : Finset α} {t : Finset β} {a : α} {b c : β}
@[simp, grind =]
theorem mem_image : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by
simp only [mem_def, image_val, mem_dedup, Multiset.mem_map]
theorem mem_image_of_mem (f : α → β) {a} (h : a ∈ s) : f a ∈ s.image f :=
mem_image.2 ⟨_, h, rfl⟩
lemma forall_mem_image {p : β → Prop} : (∀ y ∈ s.image f, p y) ↔ ∀ ⦃x⦄, x ∈ s → p (f x) := by simp
lemma exists_mem_image {p : β → Prop} : (∃ y ∈ s.image f, p y) ↔ ∃ x ∈ s, p (f x) := by simp
theorem map_eq_image (f : α ↪ β) (s : Finset α) : s.map f = s.image f :=
eq_of_veq (s.map f).2.dedup.symm
-- Not `@[simp]` since `mem_image` already gets most of the way there.
theorem mem_image_const : c ∈ s.image (const α b) ↔ s.Nonempty ∧ b = c := by
grind
theorem mem_image_const_self : b ∈ s.image (const α b) ↔ s.Nonempty :=
mem_image_const.trans <| and_iff_left rfl
instance canLift (c) (p) [CanLift β α c p] :
CanLift (Finset β) (Finset α) (image c) fun s => ∀ x ∈ s, p x where
prf := by
rintro ⟨⟨l⟩, hd : l.Nodup⟩ hl
lift l to List α using hl
exact ⟨⟨l, hd.of_map _⟩, ext fun a => by simp⟩
theorem image_congr (h : (s : Set α).EqOn f g) : Finset.image f s = Finset.image g s := by
ext
simp_rw [mem_image, ← bex_def]
exact exists₂_congr fun x hx => by rw [h hx]
theorem _root_.Function.Injective.mem_finset_image (hf : Injective f) :
f a ∈ s.image f ↔ a ∈ s := by
refine ⟨fun h => ?_, Finset.mem_image_of_mem f⟩
obtain ⟨y, hy, heq⟩ := mem_image.1 h
exact hf heq ▸ hy
@[simp, norm_cast]
theorem coe_image : ↑(s.image f) = f '' ↑s :=
Set.ext <| by simp only [mem_coe, mem_image, Set.mem_image, implies_true]
@[simp]
lemma image_nonempty : (s.image f).Nonempty ↔ s.Nonempty :=
mod_cast Set.image_nonempty (f := f) (s := (s : Set α))
@[aesop safe apply (rule_sets := [finsetNonempty])]
protected theorem Nonempty.image (h : s.Nonempty) (f : α → β) : (s.image f).Nonempty :=
image_nonempty.2 h
alias ⟨Nonempty.of_image, _⟩ := image_nonempty
theorem image_toFinset [DecidableEq α] {s : Multiset α} :
s.toFinset.image f = (s.map f).toFinset :=
ext fun _ => by simp only [mem_image, Multiset.mem_toFinset, Multiset.mem_map]
theorem image_val_of_injOn (H : Set.InjOn f s) : (image f s).1 = s.1.map f :=
(s.2.map_on H).dedup
@[simp]
theorem image_id [DecidableEq α] : s.image id = s :=
ext fun _ => by simp only [mem_image, id, exists_eq_right]
@[simp]
theorem image_id' [DecidableEq α] : (s.image fun x => x) = s :=
image_id
theorem image_image [DecidableEq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) :=
eq_of_veq <| by simp only [image_val, dedup_map_dedup_eq, Multiset.map_map]
theorem image_comm {β'} [DecidableEq β'] [DecidableEq γ] {f : β → γ} {g : α → β} {f' : α → β'}
{g' : β' → γ} (h_comm : ∀ a, f (g a) = g' (f' a)) :
(s.image g).image f = (s.image f').image g' := by simp_rw [image_image, comp_def, h_comm]
theorem _root_.Function.Semiconj.finset_image [DecidableEq α] {f : α → β} {ga : α → α} {gb : β → β}
(h : Function.Semiconj f ga gb) : Function.Semiconj (image f) (image ga) (image gb) := fun _ =>
image_comm h
theorem _root_.Function.Commute.finset_image [DecidableEq α] {f g : α → α}
(h : Function.Commute f g) : Function.Commute (image f) (image g) :=
Function.Semiconj.finset_image h
theorem image_subset_image {s₁ s₂ : Finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by
simp only [subset_def, image_val, subset_dedup', dedup_subset', Multiset.map_subset_map h]
theorem image_subset_iff : s.image f ⊆ t ↔ ∀ x ∈ s, f x ∈ t :=
calc
s.image f ⊆ t ↔ f '' ↑s ⊆ ↑t := by norm_cast
_ ↔ _ := Set.image_subset_iff
theorem image_mono (f : α → β) : Monotone (Finset.image f) := fun _ _ => image_subset_image
lemma image_injective (hf : Injective f) : Injective (image f) := by
simpa only [funext (map_eq_image _)] using map_injective ⟨f, hf⟩
lemma image_inj {t : Finset α} (hf : Injective f) : s.image f = t.image f ↔ s = t :=
(image_injective hf).eq_iff
theorem image_subset_image_iff {t : Finset α} (hf : Injective f) :
s.image f ⊆ t.image f ↔ s ⊆ t :=
mod_cast Set.image_subset_image_iff hf (s := s) (t := t)
lemma image_ssubset_image {t : Finset α} (hf : Injective f) : s.image f ⊂ t.image f ↔ s ⊂ t := by
simp_rw [← lt_iff_ssubset]
exact lt_iff_lt_of_le_iff_le' (image_subset_image_iff hf) (image_subset_image_iff hf)
theorem coe_image_subset_range : ↑(s.image f) ⊆ Set.range f :=
calc
↑(s.image f) = f '' ↑s := coe_image
_ ⊆ Set.range f := Set.image_subset_range f ↑s
theorem filter_image {p : β → Prop} [DecidablePred p] :
(s.image f).filter p = (s.filter fun a ↦ p (f a)).image f := by grind
theorem fiber_nonempty_iff_mem_image {y : β} : (s.filter (f · = y)).Nonempty ↔ y ∈ s.image f := by
simp [Finset.Nonempty]
theorem image_union [DecidableEq α] {f : α → β} (s₁ s₂ : Finset α) :
(s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f :=
mod_cast Set.image_union f s₁ s₂
theorem image_inter_subset [DecidableEq α] (f : α → β) (s t : Finset α) :
(s ∩ t).image f ⊆ s.image f ∩ t.image f :=
(image_mono f).map_inf_le s t
theorem image_inter_of_injOn [DecidableEq α] {f : α → β} (s t : Finset α)
(hf : Set.InjOn f (s ∪ t)) : (s ∩ t).image f = s.image f ∩ t.image f :=
coe_injective <| by
push_cast
exact Set.image_inter_on fun a ha b hb => hf (Or.inr ha) <| Or.inl hb
theorem image_inter [DecidableEq α] (s₁ s₂ : Finset α) (hf : Injective f) :
(s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f :=
image_inter_of_injOn _ _ hf.injOn
@[simp]
theorem image_singleton (f : α → β) (a : α) : image f {a} = {f a} := by grind
@[simp]
theorem image_insert [DecidableEq α] (f : α → β) (a : α) (s : Finset α) :
(insert a s).image f = insert (f a) (s.image f) := by grind
theorem erase_image_subset_image_erase [DecidableEq α] (f : α → β) (s : Finset α) (a : α) :
(s.image f).erase (f a) ⊆ (s.erase a).image f := by grind
@[simp]
theorem image_erase [DecidableEq α] {f : α → β} (hf : Injective f) (s : Finset α) (a : α) :
(s.erase a).image f = (s.image f).erase (f a) :=
coe_injective <| by push_cast [Set.image_diff hf, Set.image_singleton]; rfl
@[simp]
theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ := mod_cast Set.image_eq_empty (f := f) (s := s)
theorem image_sdiff [DecidableEq α] {f : α → β} (s t : Finset α) (hf : Injective f) :
(s \ t).image f = s.image f \ t.image f :=
mod_cast Set.image_diff hf s t
lemma image_sdiff_of_injOn [DecidableEq α] {t : Finset α} (hf : Set.InjOn f s) (hts : t ⊆ s) :
(s \ t).image f = s.image f \ t.image f :=
mod_cast Set.image_diff_of_injOn hf <| coe_subset.2 hts
theorem _root_.Disjoint.of_image_finset {s t : Finset α} {f : α → β}
(h : Disjoint (s.image f) (t.image f)) : Disjoint s t :=
disjoint_iff_ne.2 fun _ ha _ hb =>
ne_of_apply_ne f <| h.forall_ne_finset (mem_image_of_mem _ ha) (mem_image_of_mem _ hb)
theorem mem_range_iff_mem_finset_range_of_mod_eq' [DecidableEq α] {f : ℕ → α} {a : α} {n : ℕ}
(hn : 0 < n) (h : ∀ i, f (i % n) = f i) :
a ∈ Set.range f ↔ a ∈ (Finset.range n).image fun i => f i := by
constructor
· rintro ⟨i, hi⟩
simp only [mem_image, mem_range]
exact ⟨i % n, Nat.mod_lt i hn, (rfl.congr hi).mp (h i)⟩
· rintro h
simp only [mem_image, Set.mem_range, mem_range] at *
rcases h with ⟨i, _, ha⟩
exact ⟨i, ha⟩
theorem mem_range_iff_mem_finset_range_of_mod_eq [DecidableEq α] {f : ℤ → α} {a : α} {n : ℕ}
(hn : 0 < n) (h : ∀ i, f (i % n) = f i) :
a ∈ Set.range f ↔ a ∈ (Finset.range n).image (fun (i : ℕ) => f i) :=
suffices (∃ i, f (i % n) = a) ↔ ∃ i, i < n ∧ f ↑i = a by simpa [h]
have hn' : 0 < (n : ℤ) := Int.ofNat_lt.mpr hn
Iff.intro
(fun ⟨i, hi⟩ =>
have : 0 ≤ i % ↑n := Int.emod_nonneg _ (ne_of_gt hn')
⟨Int.toNat (i % n), by
rw [← Int.ofNat_lt, Int.toNat_of_nonneg this]; exact ⟨Int.emod_lt_of_pos i hn', hi⟩⟩)
fun ⟨i, hi, ha⟩ =>
⟨i, by rw [Int.emod_eq_of_lt (Int.ofNat_zero_le _) (Int.ofNat_lt_ofNat_of_lt hi), ha]⟩
@[simp]
theorem attach_image_val [DecidableEq α] {s : Finset α} : s.attach.image Subtype.val = s :=
eq_of_veq <| by rw [image_val, attach_val, Multiset.attach_map_val, dedup_eq_self]
@[simp]
lemma attach_cons (a : α) (s : Finset α) (ha) :
attach (cons a s ha) =
cons ⟨a, mem_cons_self a s⟩
((attach s).map ⟨fun x ↦ ⟨x.1, mem_cons_of_mem x.2⟩, fun x y => by simp⟩)
(by simpa) := by ext ⟨x, hx⟩; simpa using hx
@[simp]
theorem attach_insert [DecidableEq α] (s : Finset α) (a : α) :
attach (insert a s) =
insert (⟨a, mem_insert_self a s⟩ : { x // x ∈ insert a s })
((attach s).image fun x => ⟨x.1, mem_insert_of_mem x.2⟩) := by ext ⟨x, hx⟩; simpa using hx
@[simp]
theorem disjoint_image {s t : Finset α} {f : α → β} (hf : Injective f) :
Disjoint (s.image f) (t.image f) ↔ Disjoint s t :=
mod_cast Set.disjoint_image_iff hf (s := s) (t := t)
theorem image_const {s : Finset α} (h : s.Nonempty) (b : β) : (s.image fun _ => b) = singleton b :=
mod_cast Set.Nonempty.image_const (coe_nonempty.2 h) b
@[simp]
theorem map_erase [DecidableEq α] (f : α ↪ β) (s : Finset α) (a : α) :
(s.erase a).map f = (s.map f).erase (f a) := by
simp_rw [map_eq_image]
exact s.image_erase f.2 a
end Image
/-! ### filterMap -/
section FilterMap
/-- `filterMap f s` is a combination filter/map operation on `s`.
The function `f : α → Option β` is applied to each element of `s`;
if `f a` is `some b` then `b` is included in the result, otherwise
`a` is excluded from the resulting finset.
In notation, `filterMap f s` is the finset `{b : β | ∃ a ∈ s, f a = some b}`. -/
-- TODO: should there be `filterImage` too?
def filterMap (f : α → Option β) (s : Finset α)
(f_inj : ∀ a a' b, b ∈ f a → b ∈ f a' → a = a') : Finset β :=
⟨s.val.filterMap f, s.nodup.filterMap f f_inj⟩
variable (f : α → Option β) (s' : Finset α) {s t : Finset α}
{f_inj : ∀ a a' b, b ∈ f a → b ∈ f a' → a = a'}
@[simp]
theorem filterMap_val : (filterMap f s' f_inj).1 = s'.1.filterMap f := rfl
@[simp]
theorem filterMap_empty : (∅ : Finset α).filterMap f f_inj = ∅ := rfl
@[simp, grind =]
theorem mem_filterMap {b : β} : b ∈ s.filterMap f f_inj ↔ ∃ a ∈ s, f a = some b :=
s.val.mem_filterMap f
@[simp, norm_cast]
theorem coe_filterMap : (s.filterMap f f_inj : Set β) = {b | ∃ a ∈ s, f a = some b} :=
Set.ext (by simp only [mem_coe, mem_filterMap, Set.mem_setOf_eq, implies_true])
@[simp]
theorem filterMap_some : s.filterMap some (by simp) = s :=
ext fun _ => by simp only [mem_filterMap, Option.some.injEq, exists_eq_right]
theorem filterMap_mono (h : s ⊆ t) :
filterMap f s f_inj ⊆ filterMap f t f_inj := by grind
theorem _root_.List.toFinset_filterMap [DecidableEq α] [DecidableEq β]
(f_inj : ∀ (a a' : α) (b : β), f a = some b → f a' = some b → a = a') (s : List α) :
(s.filterMap f).toFinset = s.toFinset.filterMap f f_inj := by
simp [← Finset.coe_inj]
end FilterMap
/-! ### Subtype -/
section Subtype
/-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `Subtype p` whose
elements belong to `s`. -/
protected def subtype {α} (p : α → Prop) [DecidablePred p] (s : Finset α) : Finset (Subtype p) :=
(s.filter p).attach.map
⟨fun x => ⟨x.1, by simpa using (Finset.mem_filter.1 x.2).2⟩,
fun _ _ H => Subtype.eq <| Subtype.mk.inj H⟩
@[simp, grind =]
theorem mem_subtype {p : α → Prop} [DecidablePred p] {s : Finset α} :
∀ {a : Subtype p}, a ∈ s.subtype p ↔ (a : α) ∈ s
| ⟨a, ha⟩ => by simp [Finset.subtype, ha]
theorem subtype_eq_empty {p : α → Prop} [DecidablePred p] {s : Finset α} :
s.subtype p = ∅ ↔ ∀ x, p x → x ∉ s := by simp [Finset.ext_iff, Subtype.forall]
@[mono]
theorem subtype_mono {p : α → Prop} [DecidablePred p] : Monotone (Finset.subtype p) :=
fun _ _ h _ hx => mem_subtype.2 <| h <| mem_subtype.1 hx
/-- `s.subtype p` converts back to `s.filter p` with
`Embedding.subtype`. -/
@[simp]
theorem subtype_map (p : α → Prop) [DecidablePred p] {s : Finset α} :
(s.subtype p).map (Embedding.subtype _) = s.filter p := by
ext x
simp [@and_comm _ (_ = _), @and_comm (p x) (x ∈ s)]
/-- If all elements of a `Finset` satisfy the predicate `p`,
`s.subtype p` converts back to `s` with `Embedding.subtype`. -/
theorem subtype_map_of_mem {p : α → Prop} [DecidablePred p] {s : Finset α} (h : ∀ x ∈ s, p x) :
(s.subtype p).map (Embedding.subtype _) = s := ext <| by simpa [subtype_map] using h
/-- If a `Finset` of a subtype is converted to the main type with
`Embedding.subtype`, all elements of the result have the property of
the subtype. -/
theorem property_of_mem_map_subtype {p : α → Prop} (s : Finset { x // p x }) {a : α}
(h : a ∈ s.map (Embedding.subtype _)) : p a := by
rcases mem_map.1 h with ⟨x, _, rfl⟩
exact x.2
/-- If a `Finset` of a subtype is converted to the main type with
`Embedding.subtype`, the result does not contain any value that does
not satisfy the property of the subtype. -/
theorem notMem_map_subtype_of_not_property {p : α → Prop} (s : Finset { x // p x }) {a : α}
(h : ¬p a) : a ∉ s.map (Embedding.subtype _) :=
mt s.property_of_mem_map_subtype h
@[deprecated (since := "2025-05-23")]
alias not_mem_map_subtype_of_not_property := notMem_map_subtype_of_not_property
/-- If a `Finset` of a subtype is converted to the main type with
`Embedding.subtype`, the result is a subset of the set giving the
subtype. -/
theorem map_subtype_subset {t : Set α} (s : Finset t) : ↑(s.map (Embedding.subtype _)) ⊆ t := by
intro a ha
rw [mem_coe] at ha
convert property_of_mem_map_subtype s ha
end Subtype
/-- If a `Finset` is a subset of the image of a `Set` under `f`,
then it is equal to the `Finset.image` of a `Finset` subset of that `Set`. -/
theorem subset_set_image_iff [DecidableEq β] {s : Set α} {t : Finset β} {f : α → β} :
↑t ⊆ f '' s ↔ ∃ s' : Finset α, ↑s' ⊆ s ∧ s'.image f = t := by
constructor
· intro h
letI : CanLift β s (f ∘ (↑)) fun y => y ∈ f '' s := ⟨fun y ⟨x, hxt, hy⟩ => ⟨⟨x, hxt⟩, hy⟩⟩
lift t to Finset s using h
refine ⟨t.map (Embedding.subtype _), map_subtype_subset _, ?_⟩
ext y; simp
· grind
/--
If a finset `t` is a subset of the image of another finset `s` under `f`, then it is equal to the
image of a subset of `s`.
For the version where `s` is a set, see `subset_set_image_iff`.
-/
theorem subset_image_iff [DecidableEq β] {s : Finset α} {t : Finset β} {f : α → β} :
t ⊆ s.image f ↔ ∃ s' : Finset α, s' ⊆ s ∧ s'.image f = t := by
simp only [← coe_subset, coe_image, subset_set_image_iff]
/--
A special case of `subset_image_iff`,
which corresponds to `Set.subset_range_iff_exists_image_eq` for `Set`.
-/
theorem subset_univ_image_iff [Fintype α] [DecidableEq β] {t : Finset β} {f : α → β} :
t ⊆ univ.image f ↔ ∃ s' : Finset α, s'.image f = t := by simp [subset_image_iff]
theorem range_sdiff_zero {n : ℕ} : range (n + 1) \ {0} = (range n).image Nat.succ := by
induction n with
| zero => simp
| succ k hk =>
conv_rhs => rw [range_add_one]
rw [range_add_one, image_insert, ← hk, insert_sdiff_of_notMem]
simp
end Finset
theorem Multiset.toFinset_map [DecidableEq α] [DecidableEq β] (f : α → β) (m : Multiset α) :
(m.map f).toFinset = m.toFinset.image f :=
Finset.val_inj.1 (Multiset.dedup_map_dedup_eq _ _).symm
namespace Equiv
/-- Given an equivalence `α` to `β`, produce an equivalence between `Finset α` and `Finset β`. -/
protected def finsetCongr (e : α ≃ β) : Finset α ≃ Finset β where
toFun s := s.map e.toEmbedding
invFun s := s.map e.symm.toEmbedding
left_inv s := by simp [Finset.map_map]
right_inv s := by simp [Finset.map_map]
@[simp]
theorem finsetCongr_apply (e : α ≃ β) (s : Finset α) : e.finsetCongr s = s.map e.toEmbedding :=
rfl
@[simp]
theorem finsetCongr_refl : (Equiv.refl α).finsetCongr = Equiv.refl _ := by
ext
simp
@[simp]
theorem finsetCongr_symm (e : α ≃ β) : e.finsetCongr.symm = e.symm.finsetCongr :=
rfl
@[simp]
theorem finsetCongr_trans (e : α ≃ β) (e' : β ≃ γ) :
e.finsetCongr.trans e'.finsetCongr = (e.trans e').finsetCongr := by
ext
simp [-Finset.mem_map, -Equiv.trans_toEmbedding]
theorem finsetCongr_toEmbedding (e : α ≃ β) :
e.finsetCongr.toEmbedding = (Finset.mapEmbedding e.toEmbedding).toEmbedding :=
rfl
/-- Given a predicate `p : α → Prop`, produces an equivalence between
`Finset {a : α // p a}` and `{s : Finset α // ∀ a ∈ s, p a}`. -/
@[simps]
protected def finsetSubtypeComm (p : α → Prop) :
Finset {a : α // p a} ≃ {s : Finset α // ∀ a ∈ s, p a} where
toFun s := ⟨s.map ⟨fun a ↦ a.val, Subtype.val_injective⟩, fun _ h ↦
have ⟨v, _, h⟩ := Embedding.coeFn_mk _ _ ▸ mem_map.mp h; h ▸ v.property⟩
invFun s := s.val.attach.map (Subtype.impEmbedding _ _ s.property)
left_inv s := by
ext a; constructor <;> intro h <;>
simp only [Finset.mem_map, Finset.mem_attach, true_and, Subtype.exists, Embedding.coeFn_mk,
exists_and_right, exists_eq_right, Subtype.impEmbedding] at * <;>
grind
right_inv s := by
ext a; constructor <;> intro h <;>
simp only [Finset.mem_map, Finset.mem_attach, Subtype.exists, Embedding.coeFn_mk,
Subtype.impEmbedding] at * <;>
grind
end Equiv |
.lake/packages/mathlib/Mathlib/Data/Finset/Basic.lean | import Mathlib.Data.Finset.Attach
import Mathlib.Data.Finset.Disjoint
import Mathlib.Data.Finset.Erase
import Mathlib.Data.Finset.Filter
import Mathlib.Data.Finset.Range
import Mathlib.Data.Finset.SDiff
import Mathlib.Data.Multiset.Basic
import Mathlib.Logic.Equiv.Set
import Mathlib.Order.Directed
import Mathlib.Order.Interval.Set.Defs
import Mathlib.Data.Set.SymmDiff
/-!
# Basic lemmas on finite sets
This file contains lemmas on the interaction of various definitions on the `Finset` type.
For an explanation of `Finset` design decisions, please see `Mathlib/Data/Finset/Defs.lean`.
## Main declarations
### Main definitions
* `Finset.choose`: Given a proof `h` of existence and uniqueness of a certain element
satisfying a predicate, `choose s h` returns the element of `s` satisfying that predicate.
### Equivalences between finsets
* The `Mathlib/Logic/Equiv/Defs.lean` file describes a general type of equivalence, so look in there
for any lemmas. There is some API for rewriting sums and products from `s` to `t` given that
`s ≃ t`.
TODO: examples
## Tags
finite sets, finset
-/
-- Assert that we define `Finset` without the material on `List.sublists`.
-- Note that we cannot use `List.sublists` itself as that is defined very early.
assert_not_exists List.sublistsLen Multiset.powerset CompleteLattice Monoid
open Multiset Subtype Function
universe u
variable {α : Type*} {β : Type*} {γ : Type*}
namespace Finset
-- TODO: these should be global attributes, but this will require fixing other files
attribute [local trans] Subset.trans Superset.trans
/-! ### Lattice structure -/
section Lattice
variable [DecidableEq α] {s s₁ s₂ t t₁ t₂ u v : Finset α} {a b : α}
/-! #### union -/
@[simp]
theorem disjUnion_eq_union (s t h) : @disjUnion α s t h = s ∪ t := by grind
@[simp]
theorem disjoint_union_left : Disjoint (s ∪ t) u ↔ Disjoint s u ∧ Disjoint t u := by
simp only [disjoint_left, mem_union, or_imp, forall_and]
@[simp]
theorem disjoint_union_right : Disjoint s (t ∪ u) ↔ Disjoint s t ∧ Disjoint s u := by
simp only [disjoint_right, mem_union, or_imp, forall_and]
/-! #### inter -/
theorem not_disjoint_iff_nonempty_inter : ¬Disjoint s t ↔ (s ∩ t).Nonempty :=
not_disjoint_iff.trans <| by simp [Finset.Nonempty]
alias ⟨_, Nonempty.not_disjoint⟩ := not_disjoint_iff_nonempty_inter
theorem disjoint_or_nonempty_inter (s t : Finset α) : Disjoint s t ∨ (s ∩ t).Nonempty := by
rw [← not_disjoint_iff_nonempty_inter]
exact em _
omit [DecidableEq α] in
theorem disjoint_of_subset_iff_left_eq_empty (h : s ⊆ t) :
Disjoint s t ↔ s = ∅ :=
disjoint_of_le_iff_left_eq_bot h
lemma pairwiseDisjoint_iff {ι : Type*} {s : Set ι} {f : ι → Finset α} :
s.PairwiseDisjoint f ↔ ∀ ⦃i⦄, i ∈ s → ∀ ⦃j⦄, j ∈ s → (f i ∩ f j).Nonempty → i = j := by
simp [Set.PairwiseDisjoint, Set.Pairwise, Function.onFun, not_imp_comm (a := _ = _),
not_disjoint_iff_nonempty_inter]
end Lattice
instance isDirected_le : IsDirected (Finset α) (· ≤ ·) := by classical infer_instance
instance isDirected_subset : IsDirected (Finset α) (· ⊆ ·) := isDirected_le
/-! ### erase -/
section Erase
variable [DecidableEq α] {s t u v : Finset α} {a b : α}
@[simp]
theorem erase_empty (a : α) : erase ∅ a = ∅ :=
rfl
protected lemma Nontrivial.erase_nonempty (hs : s.Nontrivial) : (s.erase a).Nonempty :=
(hs.exists_ne a).imp <| by simp_all
@[simp] lemma erase_nonempty (ha : a ∈ s) : (s.erase a).Nonempty ↔ s.Nontrivial := by
simp only [Finset.Nonempty, mem_erase, and_comm (b := _ ∈ _)]
refine ⟨?_, fun hs ↦ hs.exists_ne a⟩
rintro ⟨b, hb, hba⟩
exact ⟨_, hb, _, ha, hba⟩
@[simp]
theorem erase_singleton (a : α) : ({a} : Finset α).erase a = ∅ := by grind
@[simp]
theorem erase_insert_eq_erase (s : Finset α) (a : α) : (insert a s).erase a = s.erase a := by grind
theorem erase_insert {a : α} {s : Finset α} (h : a ∉ s) : erase (insert a s) a = s := by grind
theorem erase_insert_of_ne {a b : α} {s : Finset α} (h : a ≠ b) :
erase (insert a s) b = insert a (erase s b) := by grind
theorem erase_cons_of_ne {a b : α} {s : Finset α} (ha : a ∉ s) (hb : a ≠ b) :
erase (cons a s ha) b = cons a (erase s b) fun h => ha <| erase_subset _ _ h := by grind
@[simp] theorem insert_erase (h : a ∈ s) : insert a (erase s a) = s := by grind
lemma erase_eq_iff_eq_insert (hs : a ∈ s) (ht : a ∉ t) : erase s a = t ↔ s = insert a t := by
aesop
lemma insert_erase_invOn :
Set.InvOn (insert a) (fun s ↦ erase s a) {s : Finset α | a ∈ s} {s : Finset α | a ∉ s} :=
⟨fun _s ↦ insert_erase, fun _s ↦ erase_insert⟩
theorem erase_ssubset {a : α} {s : Finset α} (h : a ∈ s) : s.erase a ⊂ s := by grind
theorem ssubset_iff_exists_subset_erase {s t : Finset α} : s ⊂ t ↔ ∃ a ∈ t, s ⊆ t.erase a := by
grind
theorem erase_ssubset_insert (s : Finset α) (a : α) : s.erase a ⊂ insert a s :=
ssubset_iff_exists_subset_erase.2 <| by
exact ⟨a, mem_insert_self _ _, by grw [← subset_insert]⟩
theorem erase_cons {s : Finset α} {a : α} (h : a ∉ s) : (s.cons a h).erase a = s := by grind
theorem subset_insert_iff {a : α} {s t : Finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by grind
theorem erase_insert_subset (a : α) (s : Finset α) : erase (insert a s) a ⊆ s :=
subset_insert_iff.1 <| Subset.rfl
theorem insert_erase_subset (a : α) (s : Finset α) : s ⊆ insert a (erase s a) :=
subset_insert_iff.2 <| Subset.rfl
theorem subset_insert_iff_of_notMem (h : a ∉ s) : s ⊆ insert a t ↔ s ⊆ t := by
rw [subset_insert_iff, erase_eq_of_notMem h]
@[deprecated (since := "2025-05-23")]
alias subset_insert_iff_of_not_mem := subset_insert_iff_of_notMem
theorem erase_subset_iff_of_mem (h : a ∈ t) : s.erase a ⊆ t ↔ s ⊆ t := by
rw [← subset_insert_iff, insert_eq_of_mem h]
theorem erase_injOn' (a : α) : { s : Finset α | a ∈ s }.InjOn fun s => erase s a :=
fun s hs t ht (h : s.erase a = _) => by rw [← insert_erase hs, ← insert_erase ht, h]
end Erase
lemma Nontrivial.exists_cons_eq {s : Finset α} (hs : s.Nontrivial) :
∃ t a ha b hb hab, (cons b t hb).cons a (mem_cons.not.2 <| not_or_intro hab ha) = s := by
classical
obtain ⟨a, ha, b, hb, hab⟩ := hs
have : b ∈ s.erase a := mem_erase.2 ⟨hab.symm, hb⟩
refine ⟨(s.erase a).erase b, a, ?_, b, ?_, ?_, ?_⟩ <;>
simp [insert_erase this, insert_erase ha, *]
/-! ### sdiff -/
section Sdiff
variable [DecidableEq α] {s t u v : Finset α} {a b : α}
lemma erase_sdiff_erase (hab : a ≠ b) (hb : b ∈ s) : s.erase a \ s.erase b = {b} := by
ext; aesop
-- TODO: Do we want to delete this lemma and `Finset.disjUnion_singleton`,
-- or instead add `Finset.union_singleton`/`Finset.singleton_union`?
theorem sdiff_singleton_eq_erase (a : α) (s : Finset α) : s \ {a} = erase s a := by grind
-- This lemma matches `Finset.insert_eq` in functionality.
theorem erase_eq (s : Finset α) (a : α) : s.erase a = s \ {a} :=
(sdiff_singleton_eq_erase _ _).symm
theorem disjoint_erase_comm : Disjoint (s.erase a) t ↔ Disjoint s (t.erase a) := by
simp_rw [erase_eq, disjoint_sdiff_comm]
lemma disjoint_insert_erase (ha : a ∉ t) : Disjoint (s.erase a) (insert a t) ↔ Disjoint s t := by
rw [disjoint_erase_comm, erase_insert ha]
lemma disjoint_erase_insert (ha : a ∉ s) : Disjoint (insert a s) (t.erase a) ↔ Disjoint s t := by
rw [← disjoint_erase_comm, erase_insert ha]
theorem disjoint_of_erase_left (ha : a ∉ t) (hst : Disjoint (s.erase a) t) : Disjoint s t := by
rw [← erase_insert ha, ← disjoint_erase_comm, disjoint_insert_right]
exact ⟨notMem_erase _ _, hst⟩
theorem disjoint_of_erase_right (ha : a ∉ s) (hst : Disjoint s (t.erase a)) : Disjoint s t := by
rw [← erase_insert ha, disjoint_erase_comm, disjoint_insert_left]
exact ⟨notMem_erase _ _, hst⟩
theorem inter_erase (a : α) (s t : Finset α) : s ∩ t.erase a = (s ∩ t).erase a := by grind
@[simp]
theorem erase_inter (a : α) (s t : Finset α) : s.erase a ∩ t = (s ∩ t).erase a := by grind
theorem erase_sdiff_comm (s t : Finset α) (a : α) : s.erase a \ t = (s \ t).erase a := by grind
theorem erase_inter_comm (s t : Finset α) (a : α) : s.erase a ∩ t = s ∩ t.erase a := by grind
theorem erase_union_distrib (s t : Finset α) (a : α) : (s ∪ t).erase a = s.erase a ∪ t.erase a := by
grind
theorem insert_inter_distrib (s t : Finset α) (a : α) :
insert a (s ∩ t) = insert a s ∩ insert a t := by grind
theorem erase_sdiff_distrib (s t : Finset α) (a : α) : (s \ t).erase a = s.erase a \ t.erase a := by
grind
theorem erase_union_of_mem (ha : a ∈ t) (s : Finset α) : s.erase a ∪ t = s ∪ t := by
grind
theorem union_erase_of_mem (ha : a ∈ s) (t : Finset α) : s ∪ t.erase a = s ∪ t := by
grind
theorem sdiff_union_erase_cancel (hts : t ⊆ s) (ha : a ∈ t) : s \ t ∪ t.erase a = s.erase a := by
grind
theorem sdiff_insert (s t : Finset α) (x : α) : s \ insert x t = (s \ t).erase x := by
grind
theorem sdiff_insert_insert_of_mem_of_notMem {s t : Finset α} {x : α} (hxs : x ∈ s) (hxt : x ∉ t) :
insert x (s \ insert x t) = s \ t := by
grind
@[deprecated (since := "2025-05-23")]
alias sdiff_insert_insert_of_mem_of_not_mem := sdiff_insert_insert_of_mem_of_notMem
theorem sdiff_erase (h : a ∈ s) : s \ t.erase a = insert a (s \ t) := by
grind
theorem sdiff_erase_self (ha : a ∈ s) : s \ s.erase a = {a} := by
grind
theorem erase_eq_empty_iff (s : Finset α) (a : α) : s.erase a = ∅ ↔ s = ∅ ∨ s = {a} := by
rw [← sdiff_singleton_eq_erase, sdiff_eq_empty_iff_subset, subset_singleton_iff]
--TODO@Yaël: Kill lemmas duplicate with `BooleanAlgebra`
theorem sdiff_disjoint : Disjoint (t \ s) s :=
disjoint_left.2 fun _a ha => (mem_sdiff.1 ha).2
theorem disjoint_sdiff : Disjoint s (t \ s) :=
sdiff_disjoint.symm
theorem disjoint_sdiff_inter (s t : Finset α) : Disjoint (s \ t) (s ∩ t) :=
disjoint_of_subset_right inter_subset_right sdiff_disjoint
end Sdiff
/-! ### attach -/
@[simp]
theorem attach_empty : attach (∅ : Finset α) = ∅ :=
rfl
@[simp]
theorem attach_nonempty_iff {s : Finset α} : s.attach.Nonempty ↔ s.Nonempty := by
simp [Finset.Nonempty]
@[aesop safe apply (rule_sets := [finsetNonempty])]
protected alias ⟨_, Nonempty.attach⟩ := attach_nonempty_iff
@[simp]
theorem attach_eq_empty_iff {s : Finset α} : s.attach = ∅ ↔ s = ∅ := by
simp [eq_empty_iff_forall_notMem]
/-! ### filter -/
section Filter
variable (p q : α → Prop) [DecidablePred p] [DecidablePred q] {s t : Finset α}
theorem filter_singleton (a : α) : filter p {a} = if p a then {a} else ∅ := by grind
theorem filter_cons_of_pos (a : α) (s : Finset α) (ha : a ∉ s) (hp : p a) :
filter p (cons a s ha) = cons a (filter p s) ((mem_of_mem_filter _).mt ha) :=
eq_of_veq <| Multiset.filter_cons_of_pos s.val hp
theorem filter_cons_of_neg (a : α) (s : Finset α) (ha : a ∉ s) (hp : ¬p a) :
filter p (cons a s ha) = filter p s :=
eq_of_veq <| Multiset.filter_cons_of_neg s.val hp
theorem disjoint_filter {s : Finset α} {p q : α → Prop} [DecidablePred p] [DecidablePred q] :
Disjoint (s.filter p) (s.filter q) ↔ ∀ x ∈ s, p x → ¬q x := by
constructor <;> simp +contextual [disjoint_left]
theorem disjoint_filter_filter' (s t : Finset α)
{p q : α → Prop} [DecidablePred p] [DecidablePred q] (h : Disjoint p q) :
Disjoint (s.filter p) (t.filter q) := by
simp_rw [disjoint_left, mem_filter]
rintro a ⟨_, hp⟩ ⟨_, hq⟩
rw [Pi.disjoint_iff] at h
simpa [hp, hq] using h a
theorem disjoint_filter_filter_neg (s t : Finset α) (p : α → Prop)
[DecidablePred p] [∀ x, Decidable (¬p x)] :
Disjoint (s.filter p) (t.filter fun a => ¬p a) :=
disjoint_filter_filter' s t disjoint_compl_right
theorem filter_disjUnion (s : Finset α) (t : Finset α) (h : Disjoint s t) :
filter p (disjUnion s t h) = (filter p s).disjUnion (filter p t) (disjoint_filter_filter h) :=
eq_of_veq <| Multiset.filter_add _ _ _
@[deprecated (since := "2025-06-11")]
alias filter_disj_union := filter_disjUnion
theorem filter_cons {a : α} (s : Finset α) (ha : a ∉ s) :
filter p (cons a s ha) =
if p a then cons a (filter p s) ((mem_of_mem_filter _).mt ha) else filter p s := by grind
section
variable [DecidableEq α]
theorem filter_union (s₁ s₂ : Finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := by
grind
theorem filter_union_right (s : Finset α) :
s.filter p ∪ s.filter q = s.filter fun x => p x ∨ q x := by grind
theorem filter_mem_eq_inter {s t : Finset α} [∀ i, Decidable (i ∈ t)] :
(s.filter fun i => i ∈ t) = s ∩ t := by grind
theorem filter_notMem_eq_sdiff {s t : Finset α} [∀ i, Decidable (i ∉ t)] :
(s.filter fun i => i ∉ t) = s \ t := by grind
theorem filter_inter_distrib (s t : Finset α) : (s ∩ t).filter p = s.filter p ∩ t.filter p := by
grind
theorem filter_inter (s t : Finset α) : filter p s ∩ t = filter p (s ∩ t) := by grind
theorem inter_filter (s t : Finset α) : s ∩ filter p t = filter p (s ∩ t) := by grind
theorem filter_insert (a : α) (s : Finset α) :
filter p (insert a s) = if p a then insert a (filter p s) else filter p s := by grind
theorem filter_erase (a : α) (s : Finset α) : filter p (erase s a) = erase (filter p s) a := by
grind
theorem filter_or (s : Finset α) : (s.filter fun a => p a ∨ q a) = s.filter p ∪ s.filter q := by
grind
theorem filter_and (s : Finset α) : (s.filter fun a => p a ∧ q a) = s.filter p ∩ s.filter q := by
grind
theorem filter_not (s : Finset α) : (s.filter fun a => ¬p a) = s \ s.filter p := by
grind
lemma filter_and_not (s : Finset α) (p q : α → Prop) [DecidablePred p] [DecidablePred q] :
s.filter (fun a ↦ p a ∧ ¬ q a) = s.filter p \ s.filter q := by grind
theorem sdiff_eq_filter (s₁ s₂ : Finset α) : s₁ \ s₂ = filter (· ∉ s₂) s₁ := by grind
theorem subset_union_elim {s : Finset α} {t₁ t₂ : Set α} (h : ↑s ⊆ t₁ ∪ t₂) :
∃ s₁ s₂ : Finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := by
classical
refine ⟨s.filter (· ∈ t₁), s.filter (· ∉ t₁), ?_, ?_, ?_⟩
· grind
· grind
· intro x
simp only [coe_filter, Set.mem_setOf_eq, Set.mem_diff, and_imp]
intro hx hx₂
exact ⟨Or.resolve_left (h hx) hx₂, hx₂⟩
-- This is not a good simp lemma, as it would prevent `Finset.mem_filter` from firing
-- on, e.g. `x ∈ s.filter (Eq b)`.
/-- After filtering out everything that does not equal a given value, at most that value remains.
This is equivalent to `filter_eq'` with the equality the other way.
-/
theorem filter_eq [DecidableEq β] (s : Finset β) (b : β) :
s.filter (Eq b) = ite (b ∈ s) {b} ∅ := by grind
/-- After filtering out everything that does not equal a given value, at most that value remains.
This is equivalent to `filter_eq` with the equality the other way.
-/
theorem filter_eq' [DecidableEq β] (s : Finset β) (b : β) :
(s.filter fun a => a = b) = ite (b ∈ s) {b} ∅ := by grind
theorem filter_ne [DecidableEq β] (s : Finset β) (b : β) :
(s.filter fun a => b ≠ a) = s.erase b := by grind
theorem filter_ne' [DecidableEq β] (s : Finset β) (b : β) : (s.filter fun a => a ≠ b) = s.erase b :=
_root_.trans (filter_congr fun _ _ => by simp_rw [@ne_comm _ b]) (filter_ne s b)
theorem filter_union_filter_of_codisjoint (s : Finset α) (h : Codisjoint p q) :
s.filter p ∪ s.filter q = s :=
(filter_or _ _ _).symm.trans <| filter_true_of_mem fun x _ => h.top_le x trivial
theorem filter_union_filter_neg_eq [∀ x, Decidable (¬p x)] (s : Finset α) :
(s.filter p ∪ s.filter fun a => ¬p a) = s :=
filter_union_filter_of_codisjoint _ _ _ <| @codisjoint_hnot_right _ _ p
end
end Filter
/-! ### range -/
section Range
open Nat
variable {n m l : ℕ}
@[simp]
theorem range_filter_eq {n m : ℕ} : (range n).filter (· = m) = if m < n then {m} else ∅ := by grind
end Range
end Finset
/-! ### dedup on list and multiset -/
namespace Multiset
variable [DecidableEq α] {s t : Multiset α}
@[simp]
theorem toFinset_add (s t : Multiset α) : toFinset (s + t) = toFinset s ∪ toFinset t :=
Finset.ext <| by simp
@[simp]
theorem toFinset_inter (s t : Multiset α) : toFinset (s ∩ t) = toFinset s ∩ toFinset t :=
Finset.ext <| by simp
@[simp]
theorem toFinset_union (s t : Multiset α) : (s ∪ t).toFinset = s.toFinset ∪ t.toFinset := by
ext; simp
@[simp]
theorem toFinset_eq_empty {m : Multiset α} : m.toFinset = ∅ ↔ m = 0 :=
Finset.val_inj.symm.trans Multiset.dedup_eq_zero
@[simp]
theorem toFinset_nonempty : s.toFinset.Nonempty ↔ s ≠ 0 := by
simp only [toFinset_eq_empty, Ne, Finset.nonempty_iff_ne_empty]
@[aesop safe apply (rule_sets := [finsetNonempty])]
protected alias ⟨_, Aesop.toFinset_nonempty_of_ne⟩ := toFinset_nonempty
@[simp]
theorem toFinset_filter (s : Multiset α) (p : α → Prop) [DecidablePred p] :
Multiset.toFinset (s.filter p) = s.toFinset.filter p := by
ext; simp
end Multiset
namespace List
variable [DecidableEq α] {l l' : List α} {a : α} {f : α → β}
{s : Finset α} {t : Set β} {t' : Finset β}
@[simp]
theorem toFinset_union (l l' : List α) : (l ∪ l').toFinset = l.toFinset ∪ l'.toFinset := by
ext
simp
@[simp]
theorem toFinset_inter (l l' : List α) : (l ∩ l').toFinset = l.toFinset ∩ l'.toFinset := by
ext
simp
@[aesop safe apply (rule_sets := [finsetNonempty])]
alias ⟨_, Aesop.toFinset_nonempty_of_ne⟩ := toFinset_nonempty_iff
@[simp]
theorem toFinset_filter (s : List α) (p : α → Bool) :
(s.filter p).toFinset = s.toFinset.filter (p ·) := by
ext; simp [List.mem_filter]
end List
namespace Finset
section ToList
@[simp]
theorem toList_eq_nil {s : Finset α} : s.toList = [] ↔ s = ∅ :=
Multiset.toList_eq_nil.trans val_eq_zero
theorem empty_toList {s : Finset α} : s.toList.isEmpty ↔ s = ∅ := by simp
@[simp]
theorem toList_empty : (∅ : Finset α).toList = [] :=
toList_eq_nil.mpr rfl
theorem Nonempty.toList_ne_nil {s : Finset α} (hs : s.Nonempty) : s.toList ≠ [] :=
mt toList_eq_nil.mp hs.ne_empty
theorem Nonempty.not_empty_toList {s : Finset α} (hs : s.Nonempty) : ¬s.toList.isEmpty :=
mt empty_toList.mp hs.ne_empty
end ToList
/-! ### choose -/
section Choose
variable (p : α → Prop) [DecidablePred p] (l : Finset α)
/-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of
`l` satisfying `p` this unique element, as an element of the corresponding subtype. -/
def chooseX (hp : ∃! a, a ∈ l ∧ p a) : { a // a ∈ l ∧ p a } :=
Multiset.chooseX p l.val hp
/-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of
`l` satisfying `p` this unique element, as an element of the ambient type. -/
def choose (hp : ∃! a, a ∈ l ∧ p a) : α :=
chooseX p l hp
theorem choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(chooseX p l hp).property
theorem choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l :=
(choose_spec _ _ _).1
theorem choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) :=
(choose_spec _ _ _).2
end Choose
end Finset
namespace Equiv
variable [DecidableEq α] {s t : Finset α}
open Finset
/-- The disjoint union of finsets is a sum -/
def Finset.union (s t : Finset α) (h : Disjoint s t) :
s ⊕ t ≃ (s ∪ t : Finset α) :=
Equiv.setCongr (coe_union _ _) |>.trans (Equiv.Set.union (disjoint_coe.mpr h)) |>.symm
@[simp]
theorem Finset.union_symm_inl (h : Disjoint s t) (x : s) :
Equiv.Finset.union s t h (Sum.inl x) = ⟨x, Finset.mem_union.mpr <| Or.inl x.2⟩ :=
rfl
@[simp]
theorem Finset.union_symm_inr (h : Disjoint s t) (y : t) :
Equiv.Finset.union s t h (Sum.inr y) = ⟨y, Finset.mem_union.mpr <| Or.inr y.2⟩ :=
rfl
/-- The type of dependent functions on the disjoint union of finsets `s ∪ t` is equivalent to the
type of pairs of functions on `s` and on `t`. This is similar to `Equiv.sumPiEquivProdPi`. -/
def piFinsetUnion {ι} [DecidableEq ι] (α : ι → Type*) {s t : Finset ι} (h : Disjoint s t) :
((∀ i : s, α i) × ∀ i : t, α i) ≃ ∀ i : (s ∪ t : Finset ι), α i :=
let e := Equiv.Finset.union s t h
sumPiEquivProdPi (fun b ↦ α (e b)) |>.symm.trans (.piCongrLeft (fun i : ↥(s ∪ t) ↦ α i) e)
/-- A finset is equivalent to its coercion as a set. -/
def _root_.Finset.equivToSet (s : Finset α) : s ≃ (s : Set α) where
toFun a := ⟨a.1, mem_coe.2 a.2⟩
invFun a := ⟨a.1, mem_coe.1 a.2⟩
end Equiv
namespace Multiset
variable [DecidableEq α]
@[simp]
lemma toFinset_replicate (n : ℕ) (a : α) :
(replicate n a).toFinset = if n = 0 then ∅ else {a} := by
ext x
simp only [mem_toFinset, mem_replicate]
split_ifs with hn <;> simp [hn]
end Multiset
namespace Finset
variable {α : Type*}
theorem mem_union_of_disjoint [DecidableEq α]
{s t : Finset α} (h : Disjoint s t) {x : α} :
x ∈ s ∪ t ↔ Xor' (x ∈ s) (x ∈ t) := by
rw [Finset.mem_union, Xor']
have := disjoint_left.1 h
tauto
@[simp]
theorem univ_finset_of_isEmpty [h : IsEmpty α] : (Set.univ : Set (Finset α)) = {∅} :=
subset_antisymm (fun S hS ↦ by simp [Finset.eq_empty_of_isEmpty S]) (by simp)
theorem isEmpty_of_forall_eq_empty (H : ∀ s : Finset α, s = ∅) : IsEmpty α :=
isEmpty_iff.mpr fun a ↦ by specialize H {a}; aesop
@[simp]
theorem univ_finset_eq_singleton_empty_iff : @Set.univ (Finset α) = {∅} ↔ IsEmpty α :=
⟨fun h ↦ isEmpty_of_forall_eq_empty fun s ↦ Set.mem_singleton_iff.mp
(Set.ext_iff.mp h s |>.mp (Set.mem_univ s)), fun _ ↦ by simp⟩
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Disjoint.lean | import Mathlib.Data.Finset.Insert
/-!
# Disjoint finite sets
## Main declarations
* `Disjoint`: defined via the lattice structure on finsets; two sets are disjoint if their
intersection is empty.
* `Finset.disjUnion`: the union of the finite sets `s` and `t`, given a proof `Disjoint s t`
## Tags
finite sets, finset
-/
-- Assert that we define `Finset` without the material on `List.sublists`.
-- Note that we cannot use `List.sublists` itself as that is defined very early.
assert_not_exists List.sublistsLen Multiset.powerset CompleteLattice Monoid
open Multiset Subtype Function
universe u
variable {α : Type*} {β : Type*} {γ : Type*}
namespace Finset
-- TODO: these should be global attributes, but this will require fixing other files
attribute [local trans] Subset.trans Superset.trans
/-! ### disjoint -/
section Disjoint
variable {f : α → β} {s t u : Finset α} {a b : α}
theorem disjoint_left : Disjoint s t ↔ ∀ ⦃a⦄, a ∈ s → a ∉ t :=
⟨fun h a hs ht => notMem_empty a <|
singleton_subset_iff.mp (h (singleton_subset_iff.mpr hs) (singleton_subset_iff.mpr ht)),
fun h _ hs ht _ ha => (h (hs ha) (ht ha)).elim⟩
alias ⟨_root_.Disjoint.notMem_of_mem_left_finset, _⟩ := disjoint_left
@[deprecated (since := "2025-05-23")]
alias _root_.Disjoint.not_mem_of_mem_left_finset := Disjoint.notMem_of_mem_left_finset
theorem disjoint_right : Disjoint s t ↔ ∀ ⦃a⦄, a ∈ t → a ∉ s := by
rw [_root_.disjoint_comm, disjoint_left]
alias ⟨_root_.Disjoint.notMem_of_mem_right_finset, _⟩ := disjoint_right
@[deprecated (since := "2025-05-23")]
alias _root_.Disjoint.not_mem_of_mem_right_finset := Disjoint.notMem_of_mem_right_finset
theorem disjoint_iff_ne : Disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by
simp only [disjoint_left, imp_not_comm, forall_eq']
@[simp]
theorem disjoint_val : Disjoint s.1 t.1 ↔ Disjoint s t :=
Multiset.disjoint_left.trans disjoint_left.symm
theorem _root_.Disjoint.forall_ne_finset (h : Disjoint s t) (ha : a ∈ s) (hb : b ∈ t) : a ≠ b :=
disjoint_iff_ne.1 h _ ha _ hb
theorem not_disjoint_iff : ¬Disjoint s t ↔ ∃ a, a ∈ s ∧ a ∈ t :=
disjoint_left.not.trans <| not_forall.trans <| exists_congr fun _ => by
rw [Classical.not_imp, not_not]
theorem disjoint_of_subset_left (h : s ⊆ u) (d : Disjoint u t) : Disjoint s t :=
disjoint_left.2 fun _x m₁ => (disjoint_left.1 d) (h m₁)
theorem disjoint_of_subset_right (h : t ⊆ u) (d : Disjoint s u) : Disjoint s t :=
disjoint_right.2 fun _x m₁ => (disjoint_right.1 d) (h m₁)
@[simp]
theorem disjoint_empty_left (s : Finset α) : Disjoint ∅ s :=
disjoint_bot_left
@[simp]
theorem disjoint_empty_right (s : Finset α) : Disjoint s ∅ :=
disjoint_bot_right
@[simp]
theorem disjoint_singleton_left : Disjoint (singleton a) s ↔ a ∉ s := by
simp only [disjoint_left, mem_singleton, forall_eq]
@[simp]
theorem disjoint_singleton_right : Disjoint s (singleton a) ↔ a ∉ s :=
disjoint_comm.trans disjoint_singleton_left
-- Not `simp` since `disjoint_singleton_{left,right}` prove it.
theorem disjoint_singleton : Disjoint ({a} : Finset α) {b} ↔ a ≠ b := by
rw [disjoint_singleton_left, mem_singleton]
theorem disjoint_self_iff_empty (s : Finset α) : Disjoint s s ↔ s = ∅ :=
disjoint_self
@[simp, norm_cast]
theorem disjoint_coe : Disjoint (s : Set α) t ↔ Disjoint s t := by
simp only [Finset.disjoint_left, Set.disjoint_left, mem_coe]
@[simp, norm_cast]
theorem pairwiseDisjoint_coe {ι : Type*} {s : Set ι} {f : ι → Finset α} :
s.PairwiseDisjoint (fun i => f i : ι → Set α) ↔ s.PairwiseDisjoint f :=
forall₅_congr fun _ _ _ _ _ => disjoint_coe
variable [DecidableEq α]
instance decidableDisjoint (U V : Finset α) : Decidable (Disjoint U V) :=
decidable_of_iff _ disjoint_left.symm
end Disjoint
/-! ### disjoint union -/
/-- `disjUnion s t h` is the set such that `a ∈ disjUnion s t h` iff `a ∈ s` or `a ∈ t`.
It is the same as `s ∪ t`, but it does not require decidable equality on the type. The hypothesis
ensures that the sets are disjoint. -/
@[simps]
def disjUnion (s t : Finset α) (h : Disjoint s t) : Finset α :=
⟨s.1 + t.1, Multiset.nodup_add.2 ⟨s.2, t.2, disjoint_val.2 h⟩⟩
@[simp, grind =]
theorem mem_disjUnion {α s t h a} : a ∈ @disjUnion α s t h ↔ a ∈ s ∨ a ∈ t := by
rcases s with ⟨⟨s⟩⟩; rcases t with ⟨⟨t⟩⟩; apply List.mem_append
@[simp, norm_cast]
theorem coe_disjUnion {s t : Finset α} (h : Disjoint s t) :
(disjUnion s t h : Set α) = (s : Set α) ∪ t :=
Set.ext <| by simp
theorem disjUnion_comm (s t : Finset α) (h : Disjoint s t) :
disjUnion s t h = disjUnion t s h.symm :=
eq_of_veq <| Multiset.add_comm _ _
@[simp]
theorem disjUnion_inj_left {s₁ s₂ t : Finset α} (h₁ : Disjoint s₁ t) (h₂ : Disjoint s₂ t) :
s₁.disjUnion t h₁ = s₂.disjUnion t h₂ ↔ s₁ = s₂ := by
simp [← val_inj, Multiset.add_left_inj]
@[simp]
theorem disjUnion_inj_right {s t₁ t₂ : Finset α} (h₁ : Disjoint s t₁) (h₂ : Disjoint s t₂) :
s.disjUnion t₁ h₁ = s.disjUnion t₂ h₂ ↔ t₁ = t₂ := by
simp [← val_inj, Multiset.add_right_inj]
@[simp]
theorem empty_disjUnion (t : Finset α) (h : Disjoint ∅ t := disjoint_bot_left) :
disjUnion ∅ t h = t :=
eq_of_veq <| Multiset.zero_add _
@[simp]
theorem disjUnion_empty (s : Finset α) (h : Disjoint s ∅ := disjoint_bot_right) :
disjUnion s ∅ h = s :=
eq_of_veq <| Multiset.add_zero _
theorem singleton_disjUnion (a : α) (t : Finset α) (h : Disjoint {a} t) :
disjUnion {a} t h = cons a t (disjoint_singleton_left.mp h) :=
eq_of_veq <| Multiset.singleton_add _ _
theorem disjUnion_singleton (s : Finset α) (a : α) (h : Disjoint s {a}) :
disjUnion s {a} h = cons a s (disjoint_singleton_right.mp h) := by
rw [disjUnion_comm, singleton_disjUnion]
/-! ### insert -/
section Insert
variable [DecidableEq α] {s t u v : Finset α} {a b : α} {f : α → β}
@[simp]
theorem disjoint_insert_left : Disjoint (insert a s) t ↔ a ∉ t ∧ Disjoint s t := by
simp only [disjoint_left, mem_insert, or_imp, forall_and, forall_eq]
@[simp, grind =]
theorem disjoint_insert_right : Disjoint s (insert a t) ↔ a ∉ s ∧ Disjoint s t :=
disjoint_comm.trans <| by rw [disjoint_insert_left, _root_.disjoint_comm]
end Insert
end Finset
namespace Multiset
variable [DecidableEq α]
@[simp]
theorem disjoint_toFinset {m1 m2 : Multiset α} :
_root_.Disjoint m1.toFinset m2.toFinset ↔ Disjoint m1 m2 := by
simp [disjoint_left, Finset.disjoint_left]
end Multiset
namespace List
variable [DecidableEq α] {l l' : List α}
@[simp]
theorem disjoint_toFinset_iff_disjoint : _root_.Disjoint l.toFinset l'.toFinset ↔ l.Disjoint l' :=
Multiset.disjoint_toFinset.trans (Multiset.coe_disjoint _ _)
end List |
.lake/packages/mathlib/Mathlib/Data/Finset/Sort.lean | import Mathlib.Data.Finset.Max
import Mathlib.Data.Fintype.EquivFin
import Mathlib.Data.Multiset.Sort
import Mathlib.Order.RelIso.Set
/-!
# Construct a sorted list from a finset.
-/
namespace Finset
open Multiset Nat
variable {α β : Type*}
/-! ### sort -/
section sort
/-- `sort s` constructs a sorted list from the unordered set `s`.
(Uses merge sort algorithm.) -/
def sort (s : Finset α) (r : α → α → Prop := by exact fun a b => a ≤ b)
[DecidableRel r] [IsTrans α r] [IsAntisymm α r] [IsTotal α r] : List α :=
Multiset.sort s.1 r
section
variable (f : α ↪ β) (s : Finset α)
variable (r : α → α → Prop) [DecidableRel r] [IsTrans α r] [IsAntisymm α r] [IsTotal α r]
variable (r' : β → β → Prop) [DecidableRel r'] [IsTrans β r'] [IsAntisymm β r'] [IsTotal β r']
@[simp]
theorem sort_val : Multiset.sort s.val r = sort s r :=
rfl
@[simp]
theorem sort_sorted : List.Sorted r (sort s r) :=
Multiset.sort_sorted _ _
@[simp]
theorem sort_eq : ↑(sort s r) = s.1 :=
Multiset.sort_eq _ _
@[simp]
theorem sort_nodup : (sort s r).Nodup :=
(by rw [sort_eq]; exact s.2 : @Multiset.Nodup α (sort s r))
@[simp]
theorem sort_toFinset [DecidableEq α] : (sort s r).toFinset = s :=
List.toFinset_eq (s.sort_nodup r) ▸ eq_of_veq (s.sort_eq r)
@[simp]
theorem sort_empty : sort ∅ r = [] :=
Multiset.sort_zero r
@[simp]
theorem sort_singleton (a : α) : sort {a} r = [a] :=
Multiset.sort_singleton a r
theorem map_sort
(hs : ∀ a ∈ s, ∀ b ∈ s, r a b ↔ r' (f a) (f b)) :
(s.sort r).map f = (s.map f).sort r' :=
Multiset.map_sort _ _ _ _ hs
theorem _root_.StrictMonoOn.map_finsetSort [LinearOrder α] [LinearOrder β]
(hf : StrictMonoOn f s) :
s.sort.map f = (s.map f).sort :=
Finset.map_sort _ _ _ _ fun _a ha _b hb => (hf.le_iff_le ha hb).symm
@[simp]
theorem sort_range (n : ℕ) : sort (range n) = List.range n :=
Multiset.sort_range n
open scoped List in
theorem sort_perm_toList : sort s r ~ s.toList := by
rw [← Multiset.coe_eq_coe]
simp only [coe_toList, sort_eq]
theorem _root_.List.toFinset_sort [DecidableEq α] {l : List α} (hl : l.Nodup) :
sort l.toFinset r = l ↔ l.Sorted r := by
refine ⟨?_, List.eq_of_perm_of_sorted ((sort_perm_toList _ r).trans (List.toFinset_toList hl))
(sort_sorted _ r)⟩
intro h
rw [← h]
exact sort_sorted _ r
end
section
variable {m : Multiset α} {s : Finset α}
variable (r : α → α → Prop) [DecidableRel r] [IsTrans α r] [IsAntisymm α r] [IsTotal α r]
@[simp]
theorem sort_mk (h : m.Nodup) : sort ⟨m, h⟩ r = m.sort r := rfl
@[simp]
theorem mem_sort {a : α} : a ∈ sort s r ↔ a ∈ s :=
Multiset.mem_sort _
@[simp]
theorem length_sort : (sort s r).length = s.card :=
Multiset.length_sort _
theorem sort_cons {a : α} (h₁ : ∀ b ∈ s, r a b) (h₂ : a ∉ s) :
sort (cons a s h₂) r = a :: sort s r := by
rw [sort, cons_val, Multiset.sort_cons a _ r h₁, sort_val]
theorem sort_insert [DecidableEq α] {a : α} (h₁ : ∀ b ∈ s, r a b) (h₂ : a ∉ s) :
sort (insert a s) r = a :: sort s r := by
rw [← cons_eq_insert _ _ h₂, sort_cons r h₁]
end
end sort
section SortLinearOrder
variable [LinearOrder α]
theorem sort_sorted_lt (s : Finset α) : List.Sorted (· < ·) (sort s) :=
(sort_sorted _ _).lt_of_le (sort_nodup _ _)
theorem sort_sorted_gt (s : Finset α) : List.Sorted (· > ·) (sort s (· ≥ ·)) :=
(sort_sorted _ _).gt_of_ge (sort_nodup _ _)
theorem sorted_zero_eq_min'_aux (s : Finset α) (h : 0 < s.sort.length) (H : s.Nonempty) :
s.sort.get ⟨0, h⟩ = s.min' H := by
let l := s.sort
apply le_antisymm
· have : s.min' H ∈ l := (s.mem_sort (· ≤ ·)).mpr (s.min'_mem H)
obtain ⟨i, hi⟩ : ∃ i, l.get i = s.min' H := List.mem_iff_get.1 this
rw [← hi]
exact (s.sort_sorted (· ≤ ·)).rel_get_of_le (Nat.zero_le i)
· have : l.get ⟨0, h⟩ ∈ s := (s.mem_sort (· ≤ ·)).1 (List.get_mem l _)
exact s.min'_le _ this
theorem sorted_zero_eq_min' {s : Finset α} {h : 0 < s.sort.length} :
s.sort[0] = s.min' (card_pos.1 <| by rwa [length_sort] at h) :=
sorted_zero_eq_min'_aux _ _ _
theorem min'_eq_sorted_zero {s : Finset α} {h : s.Nonempty} :
s.min' h = s.sort[0]'(by rw [length_sort]; exact card_pos.2 h) :=
(sorted_zero_eq_min'_aux _ _ _).symm
theorem sorted_last_eq_max'_aux (s : Finset α)
(h : s.sort.length - 1 < s.sort.length) (H : s.Nonempty) :
s.sort[s.sort.length - 1] = s.max' H := by
let l := s.sort
apply le_antisymm
· have : l.get ⟨s.sort.length - 1, h⟩ ∈ s :=
(s.mem_sort (· ≤ ·)).1 (List.get_mem l _)
exact s.le_max' _ this
· have : s.max' H ∈ l := (s.mem_sort (· ≤ ·)).mpr (s.max'_mem H)
obtain ⟨i, hi⟩ : ∃ i, l.get i = s.max' H := List.mem_iff_get.1 this
rw [← hi]
exact (s.sort_sorted (· ≤ ·)).rel_get_of_le (Nat.le_sub_one_of_lt i.prop)
theorem sorted_last_eq_max' {s : Finset α}
{h : s.sort.length - 1 < s.sort.length} :
s.sort[s.sort.length - 1] =
s.max' (by rw [length_sort] at h; exact card_pos.1 (lt_of_le_of_lt bot_le h)) :=
sorted_last_eq_max'_aux _ h _
theorem max'_eq_sorted_last {s : Finset α} {h : s.Nonempty} :
s.max' h =
s.sort[s.sort.length - 1]'
(by simpa using Nat.sub_lt (card_pos.mpr h) Nat.zero_lt_one) :=
(sorted_last_eq_max'_aux _ (by simpa using Nat.sub_lt (card_pos.mpr h) Nat.zero_lt_one) _).symm
/-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `orderIsoOfFin s h`
is the increasing bijection between `Fin k` and `s` as an `OrderIso`. Here, `h` is a proof that
the cardinality of `s` is `k`. We use this instead of an iso `Fin s.card ≃o s` to avoid
casting issues in further uses of this function. -/
def orderIsoOfFin (s : Finset α) {k : ℕ} (h : s.card = k) : Fin k ≃o s :=
OrderIso.trans (Fin.castOrderIso ((s.length_sort (· ≤ ·)).trans h).symm) <|
(s.sort_sorted_lt.getIso _).trans <| OrderIso.setCongr _ _ <| Set.ext fun _ => mem_sort _
/-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `orderEmbOfFin s h` is
the increasing bijection between `Fin k` and `s` as an order embedding into `α`. Here, `h` is a
proof that the cardinality of `s` is `k`. We use this instead of an embedding `Fin s.card ↪o α` to
avoid casting issues in further uses of this function. -/
def orderEmbOfFin (s : Finset α) {k : ℕ} (h : s.card = k) : Fin k ↪o α :=
(orderIsoOfFin s h).toOrderEmbedding.trans (OrderEmbedding.subtype _)
@[simp]
theorem coe_orderIsoOfFin_apply (s : Finset α) {k : ℕ} (h : s.card = k) (i : Fin k) :
↑(orderIsoOfFin s h i) = orderEmbOfFin s h i :=
rfl
theorem orderIsoOfFin_symm_apply (s : Finset α) {k : ℕ} (h : s.card = k) (x : s) :
↑((s.orderIsoOfFin h).symm x) = s.sort.idxOf ↑x :=
rfl
theorem orderEmbOfFin_apply (s : Finset α) {k : ℕ} (h : s.card = k) (i : Fin k) :
s.orderEmbOfFin h i = s.sort[i]'(by rw [length_sort, h]; exact i.2) :=
rfl
@[simp]
theorem orderEmbOfFin_mem (s : Finset α) {k : ℕ} (h : s.card = k) (i : Fin k) :
s.orderEmbOfFin h i ∈ s :=
(s.orderIsoOfFin h i).2
@[simp]
theorem range_orderEmbOfFin (s : Finset α) {k : ℕ} (h : s.card = k) :
Set.range (s.orderEmbOfFin h) = s := by
simp only [orderEmbOfFin, Set.range_comp ((↑) : _ → α) (s.orderIsoOfFin h),
RelEmbedding.coe_trans, Set.image_univ, Finset.orderEmbOfFin, RelIso.range_eq,
OrderEmbedding.coe_subtype, OrderIso.coe_toOrderEmbedding,
Subtype.range_coe_subtype, Finset.setOf_mem]
@[simp]
theorem image_orderEmbOfFin_univ (s : Finset α) {k : ℕ} (h : s.card = k) :
Finset.image (s.orderEmbOfFin h) Finset.univ = s := by
apply Finset.coe_injective
simp
@[simp]
theorem map_orderEmbOfFin_univ (s : Finset α) {k : ℕ} (h : s.card = k) :
Finset.map (s.orderEmbOfFin h).toEmbedding Finset.univ = s := by
simp [map_eq_image]
@[simp]
theorem listMap_orderEmbOfFin_finRange (s : Finset α) {k : ℕ} (h : s.card = k) :
(List.finRange k).map (s.orderEmbOfFin h) = s.sort := by
obtain rfl : k = s.sort.length := by simp [h]
exact List.finRange_map_getElem s.sort
/-- The bijection `orderEmbOfFin s h` sends `0` to the minimum of `s`. -/
theorem orderEmbOfFin_zero {s : Finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) :
orderEmbOfFin s h ⟨0, hz⟩ = s.min' (card_pos.mp (h.symm ▸ hz)) := by
simp only [orderEmbOfFin_apply, Fin.getElem_fin, sorted_zero_eq_min']
/-- The bijection `orderEmbOfFin s h` sends `k-1` to the maximum of `s`. -/
theorem orderEmbOfFin_last {s : Finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) :
orderEmbOfFin s h ⟨k - 1, Nat.sub_lt hz (Nat.succ_pos 0)⟩ =
s.max' (card_pos.mp (h.symm ▸ hz)) := by
simp [orderEmbOfFin_apply, max'_eq_sorted_last, h]
/-- `orderEmbOfFin {a} h` sends any argument to `a`. -/
@[simp]
theorem orderEmbOfFin_singleton (a : α) (i : Fin 1) :
orderEmbOfFin {a} (card_singleton a) i = a := by
rw [Subsingleton.elim i ⟨0, Nat.zero_lt_one⟩, orderEmbOfFin_zero _ Nat.zero_lt_one,
min'_singleton]
/-- Any increasing map `f` from `Fin k` to a finset of cardinality `k` has to coincide with
the increasing bijection `orderEmbOfFin s h`. -/
theorem orderEmbOfFin_unique {s : Finset α} {k : ℕ} (h : s.card = k) {f : Fin k → α}
(hfs : ∀ x, f x ∈ s) (hmono : StrictMono f) : f = s.orderEmbOfFin h := by
rw [← hmono.range_inj (s.orderEmbOfFin h).strictMono, range_orderEmbOfFin, ← Set.image_univ,
← coe_univ, ← coe_image, coe_inj]
refine eq_of_subset_of_card_le (fun x hx => ?_) ?_
· rcases mem_image.1 hx with ⟨x, _, rfl⟩
exact hfs x
· rw [h, card_image_of_injective _ hmono.injective, card_univ, Fintype.card_fin]
/-- An order embedding `f` from `Fin k` to a finset of cardinality `k` has to coincide with
the increasing bijection `orderEmbOfFin s h`. -/
theorem orderEmbOfFin_unique' {s : Finset α} {k : ℕ} (h : s.card = k) {f : Fin k ↪o α}
(hfs : ∀ x, f x ∈ s) : f = s.orderEmbOfFin h :=
RelEmbedding.ext <| funext_iff.1 <| orderEmbOfFin_unique h hfs f.strictMono
/-- Two parametrizations `orderEmbOfFin` of the same set take the same value on `i` and `j` if
and only if `i = j`. Since they can be defined on a priori not defeq types `Fin k` and `Fin l`
(although necessarily `k = l`), the conclusion is rather written `(i : ℕ) = (j : ℕ)`. -/
@[simp]
theorem orderEmbOfFin_eq_orderEmbOfFin_iff {k l : ℕ} {s : Finset α} {i : Fin k} {j : Fin l}
{h : s.card = k} {h' : s.card = l} :
s.orderEmbOfFin h i = s.orderEmbOfFin h' j ↔ (i : ℕ) = (j : ℕ) := by
substs k l
exact (s.orderEmbOfFin rfl).eq_iff_eq.trans Fin.ext_iff
/-- Given a finset `s` of size at least `k` in a linear order `α`, the map `orderEmbOfCardLe`
is an order embedding from `Fin k` to `α` whose image is contained in `s`. Specifically, it maps
`Fin k` to an initial segment of `s`. -/
def orderEmbOfCardLe (s : Finset α) {k : ℕ} (h : k ≤ s.card) : Fin k ↪o α :=
(Fin.castLEOrderEmb h).trans (s.orderEmbOfFin rfl)
theorem orderEmbOfCardLe_mem (s : Finset α) {k : ℕ} (h : k ≤ s.card) (a) :
orderEmbOfCardLe s h a ∈ s := by
simp only [orderEmbOfCardLe, RelEmbedding.coe_trans, Finset.orderEmbOfFin_mem,
Function.comp_apply]
lemma orderEmbOfFin_compl_singleton {n : ℕ} {i : Fin (n + 1)} {k : ℕ}
(h : ({i}ᶜ : Finset _).card = k) :
({i}ᶜ : Finset _).orderEmbOfFin h =
(Fin.castOrderIso <| by simp_all [card_compl]).toOrderEmbedding.trans
(Fin.succAboveOrderEmb i) := by
apply DFunLike.coe_injective
rw [eq_comm]
convert orderEmbOfFin_unique _ (fun x ↦ ?_)
((Fin.strictMono_succAbove _).comp (Fin.cast_strictMono _))
· simp
· simp [← h, card_compl]
@[simp]
lemma orderEmbOfFin_compl_singleton_eq_succAboveOrderEmb {n : ℕ} (i : Fin (n + 1)) :
({i}ᶜ : Finset _).orderEmbOfFin (by simp [card_compl]) = Fin.succAboveOrderEmb i :=
orderEmbOfFin_compl_singleton _
lemma orderEmbOfFin_compl_singleton_apply {n : ℕ} {i : Fin (n + 1)} {k : ℕ}
(h : ({i}ᶜ : Finset _).card = k) (j : Fin k) : ({i}ᶜ : Finset _).orderEmbOfFin h j =
Fin.succAbove i (Fin.cast (h.symm.trans (by simp [card_compl])) j) := by
rw [orderEmbOfFin_compl_singleton]
simp
end SortLinearOrder
unsafe instance [Repr α] : Repr (Finset α) where
reprPrec s _ :=
-- multiset uses `0` not `∅` for empty sets
if s.card = 0 then "∅" else repr s.1
end Finset
namespace Fin
theorem sort_univ (n : ℕ) : Finset.univ.sort (fun x y : Fin n => x ≤ y) = List.finRange n :=
List.eq_of_perm_of_sorted
(List.perm_of_nodup_nodup_toFinset_eq
(Finset.univ.sort_nodup _) (List.nodup_finRange n) (by simp))
(Finset.univ.sort_sorted LE.le)
(List.pairwise_le_finRange n)
end Fin
/-- Given a `Fintype` `α` of cardinality `k`, the map `orderIsoFinOfCardEq s h` is the increasing
bijection between `Fin k` and `α` as an `OrderIso`. Here, `h` is a proof that the cardinality of `α`
is `k`. We use this instead of an iso `Fin (Fintype.card α) ≃o α` to avoid casting issues in further
uses of this function. -/
def Fintype.orderIsoFinOfCardEq
(α : Type*) [LinearOrder α] [Fintype α] {k : ℕ} (h : Fintype.card α = k) :
Fin k ≃o α :=
(Finset.univ.orderIsoOfFin h).trans
((OrderIso.setCongr _ _ Finset.coe_univ).trans OrderIso.Set.univ)
/-- Any finite linear order order-embeds into any infinite linear order. -/
lemma nonempty_orderEmbedding_of_finite_infinite
(α : Type*) [LinearOrder α] [hα : Finite α]
(β : Type*) [LinearOrder β] [hβ : Infinite β] : Nonempty (α ↪o β) := by
haveI := Fintype.ofFinite α
obtain ⟨s, hs⟩ := Infinite.exists_subset_card_eq β (Fintype.card α)
exact ⟨((Fintype.orderIsoFinOfCardEq α rfl).symm.toOrderEmbedding).trans (s.orderEmbOfFin hs)⟩ |
.lake/packages/mathlib/Mathlib/Data/Finset/Powerset.lean | import Mathlib.Data.Finset.Card
import Mathlib.Data.Finset.Lattice.Union
import Mathlib.Data.Multiset.Powerset
import Mathlib.Data.Set.Pairwise.Lattice
/-!
# The powerset of a finset
-/
namespace Finset
open Function Multiset
variable {α : Type*} {s t : Finset α}
/-! ### powerset -/
section Powerset
/-- When `s` is a finset, `s.powerset` is the finset of all subsets of `s` (seen as finsets). -/
def powerset (s : Finset α) : Finset (Finset α) :=
⟨(s.1.powerset.pmap Finset.mk) fun _t h => nodup_of_le (mem_powerset.1 h) s.nodup,
s.nodup.powerset.pmap fun _a _ha _b _hb => congr_arg Finset.val⟩
@[simp, grind =]
theorem mem_powerset {s t : Finset α} : s ∈ powerset t ↔ s ⊆ t := by
cases s
simp [powerset, mem_mk, mem_pmap, mk.injEq, exists_prop, exists_eq_right,
← val_le_iff]
@[simp, norm_cast]
theorem coe_powerset (s : Finset α) :
(s.powerset : Set (Finset α)) = ((↑) : Finset α → Set α) ⁻¹' (s : Set α).powerset := by
ext
simp
theorem empty_mem_powerset (s : Finset α) : ∅ ∈ powerset s := by simp
theorem mem_powerset_self (s : Finset α) : s ∈ powerset s := by simp
@[aesop safe apply (rule_sets := [finsetNonempty])]
theorem powerset_nonempty (s : Finset α) : s.powerset.Nonempty :=
⟨∅, empty_mem_powerset _⟩
@[simp]
theorem powerset_mono {s t : Finset α} : powerset s ⊆ powerset t ↔ s ⊆ t :=
⟨fun h => mem_powerset.1 <| h <| mem_powerset_self _, fun st _u h =>
mem_powerset.2 <| Subset.trans (mem_powerset.1 h) st⟩
theorem powerset_injective : Injective (powerset : Finset α → Finset (Finset α)) :=
(injective_of_le_imp_le _) powerset_mono.1
@[simp]
theorem powerset_inj : powerset s = powerset t ↔ s = t :=
powerset_injective.eq_iff
@[simp]
theorem powerset_empty : (∅ : Finset α).powerset = {∅} :=
rfl
@[simp]
theorem powerset_eq_singleton_empty : s.powerset = {∅} ↔ s = ∅ := by
rw [← powerset_empty, powerset_inj]
/-- **Number of Subsets of a Set** -/
@[simp]
theorem card_powerset (s : Finset α) : card (powerset s) = 2 ^ card s :=
(card_pmap _ _ _).trans (Multiset.card_powerset s.1)
theorem notMem_of_mem_powerset_of_notMem {s t : Finset α} {a : α} (ht : t ∈ s.powerset)
(h : a ∉ s) : a ∉ t := by
apply mt _ h
apply mem_powerset.1 ht
@[deprecated (since := "2025-05-23")]
alias not_mem_of_mem_powerset_of_not_mem := notMem_of_mem_powerset_of_notMem
theorem powerset_insert [DecidableEq α] (s : Finset α) (a : α) :
powerset (insert a s) = s.powerset ∪ s.powerset.image (insert a) := by
ext t
simp only [mem_powerset, mem_image, mem_union, subset_insert_iff]
grind
lemma pairwiseDisjoint_pair_insert [DecidableEq α] {a : α} (ha : a ∉ s) :
(s.powerset : Set (Finset α)).PairwiseDisjoint fun t ↦ ({t, insert a t} : Set (Finset α)) := by
simp_rw [Set.pairwiseDisjoint_iff, mem_coe, mem_powerset]
rintro i hi j hj
simp only [Set.Nonempty, Set.mem_inter_iff, Set.mem_insert_iff, Set.mem_singleton_iff,
exists_eq_or_imp, exists_eq_left, or_imp, imp_self, true_and]
refine ⟨?_, ?_, insert_erase_invOn.2.injOn (notMem_mono hi ha) (notMem_mono hj ha)⟩ <;>
rintro rfl <;>
cases Finset.notMem_mono ‹_› ha (Finset.mem_insert_self _ _)
/-- For predicate `p` decidable on subsets, it is decidable whether `p` holds for any subset. -/
instance decidableExistsOfDecidableSubsets {s : Finset α} {p : ∀ t ⊆ s, Prop}
[∀ (t) (h : t ⊆ s), Decidable (p t h)] : Decidable (∃ (t : _) (h : t ⊆ s), p t h) :=
decidable_of_iff (∃ (t : _) (hs : t ∈ s.powerset), p t (mem_powerset.1 hs))
⟨fun ⟨t, _, hp⟩ => ⟨t, _, hp⟩, fun ⟨t, hs, hp⟩ => ⟨t, mem_powerset.2 hs, hp⟩⟩
/-- For predicate `p` decidable on subsets, it is decidable whether `p` holds for every subset. -/
instance decidableForallOfDecidableSubsets {s : Finset α} {p : ∀ t ⊆ s, Prop}
[∀ (t) (h : t ⊆ s), Decidable (p t h)] : Decidable (∀ (t) (h : t ⊆ s), p t h) :=
decidable_of_iff (∀ (t) (h : t ∈ s.powerset), p t (mem_powerset.1 h))
⟨fun h t hs => h t (mem_powerset.2 hs), fun h _ _ => h _ _⟩
/-- For predicate `p` decidable on subsets, it is decidable whether `p` holds for any subset. -/
instance decidableExistsOfDecidableSubsets' {s : Finset α} {p : Finset α → Prop}
[∀ t, Decidable (p t)] : Decidable (∃ t ⊆ s, p t) :=
decidable_of_iff (∃ (t : _) (_h : t ⊆ s), p t) <| by simp
/-- For predicate `p` decidable on subsets, it is decidable whether `p` holds for every subset. -/
instance decidableForallOfDecidableSubsets' {s : Finset α} {p : Finset α → Prop}
[∀ t, Decidable (p t)] : Decidable (∀ t ⊆ s, p t) :=
decidable_of_iff (∀ (t : _) (_h : t ⊆ s), p t) <| by simp
end Powerset
section SSubsets
variable [DecidableEq α]
/-- For `s` a finset, `s.ssubsets` is the finset comprising strict subsets of `s`. -/
def ssubsets (s : Finset α) : Finset (Finset α) :=
erase (powerset s) s
@[simp, grind =]
theorem mem_ssubsets {s t : Finset α} : t ∈ s.ssubsets ↔ t ⊂ s := by
rw [ssubsets, mem_erase, mem_powerset, ssubset_iff_subset_ne, and_comm]
theorem empty_mem_ssubsets {s : Finset α} (h : s.Nonempty) : ∅ ∈ s.ssubsets := by
rw [mem_ssubsets, ssubset_iff_subset_ne]
exact ⟨empty_subset s, h.ne_empty.symm⟩
/-- For predicate `p` decidable on ssubsets, it is decidable whether `p` holds for any ssubset. -/
def decidableExistsOfDecidableSSubsets {s : Finset α} {p : ∀ t ⊂ s, Prop}
[∀ t h, Decidable (p t h)] : Decidable (∃ t h, p t h) :=
decidable_of_iff (∃ (t : _) (hs : t ∈ s.ssubsets), p t (mem_ssubsets.1 hs))
⟨fun ⟨t, _, hp⟩ => ⟨t, _, hp⟩, fun ⟨t, hs, hp⟩ => ⟨t, mem_ssubsets.2 hs, hp⟩⟩
/-- For predicate `p` decidable on ssubsets, it is decidable whether `p` holds for every ssubset. -/
def decidableForallOfDecidableSSubsets {s : Finset α} {p : ∀ t ⊂ s, Prop}
[∀ t h, Decidable (p t h)] : Decidable (∀ t h, p t h) :=
decidable_of_iff (∀ (t) (h : t ∈ s.ssubsets), p t (mem_ssubsets.1 h))
⟨fun h t hs => h t (mem_ssubsets.2 hs), fun h _ _ => h _ _⟩
/-- A version of `Finset.decidableExistsOfDecidableSSubsets` with a non-dependent `p`.
Typeclass inference cannot find `hu` here, so this is not an instance. -/
def decidableExistsOfDecidableSSubsets' {s : Finset α} {p : Finset α → Prop}
(hu : ∀ t ⊂ s, Decidable (p t)) : Decidable (∃ (t : _) (_h : t ⊂ s), p t) :=
@Finset.decidableExistsOfDecidableSSubsets _ _ _ _ hu
/-- A version of `Finset.decidableForallOfDecidableSSubsets` with a non-dependent `p`.
Typeclass inference cannot find `hu` here, so this is not an instance. -/
def decidableForallOfDecidableSSubsets' {s : Finset α} {p : Finset α → Prop}
(hu : ∀ t ⊂ s, Decidable (p t)) : Decidable (∀ t ⊂ s, p t) :=
@Finset.decidableForallOfDecidableSSubsets _ _ _ _ hu
end SSubsets
section powersetCard
variable {n} {s t : Finset α}
/-- Given an integer `n` and a finset `s`, then `powersetCard n s` is the finset of subsets of `s`
of cardinality `n`. -/
def powersetCard (n : ℕ) (s : Finset α) : Finset (Finset α) :=
⟨((s.1.powersetCard n).pmap Finset.mk) fun _t h => nodup_of_le (mem_powersetCard.1 h).1 s.2,
s.2.powersetCard.pmap fun _a _ha _b _hb => congr_arg Finset.val⟩
@[simp, grind =] lemma mem_powersetCard : s ∈ powersetCard n t ↔ s ⊆ t ∧ card s = n := by
cases s; simp [powersetCard, val_le_iff.symm]
@[simp]
theorem powersetCard_mono {n} {s t : Finset α} (h : s ⊆ t) : powersetCard n s ⊆ powersetCard n t :=
fun _u h' => mem_powersetCard.2 <|
And.imp (fun h₂ => Subset.trans h₂ h) id (mem_powersetCard.1 h')
/-- **Formula for the Number of Combinations** -/
@[simp]
theorem card_powersetCard (n : ℕ) (s : Finset α) :
card (powersetCard n s) = Nat.choose (card s) n :=
(card_pmap _ _ _).trans (Multiset.card_powersetCard n s.1)
@[simp]
theorem powersetCard_zero (s : Finset α) : s.powersetCard 0 = {∅} := by
grind
lemma powersetCard_empty_subsingleton (n : ℕ) :
(powersetCard n (∅ : Finset α) : Set <| Finset α).Subsingleton := by
simp [Set.Subsingleton, subset_empty]
@[simp]
theorem map_val_val_powersetCard (s : Finset α) (i : ℕ) :
(s.powersetCard i).val.map Finset.val = s.1.powersetCard i := by
simp [Finset.powersetCard, map_pmap, pmap_eq_map, map_id']
theorem powersetCard_one (s : Finset α) :
s.powersetCard 1 = s.map ⟨_, Finset.singleton_injective⟩ :=
eq_of_veq <| Multiset.map_injective val_injective <| by simp [Multiset.powersetCard_one]
@[simp]
lemma powersetCard_eq_empty : powersetCard n s = ∅ ↔ s.card < n := by
refine ⟨?_, fun h ↦ card_eq_zero.1 <| by rw [card_powersetCard, Nat.choose_eq_zero_of_lt h]⟩
contrapose!
exact fun h ↦ nonempty_iff_ne_empty.1 <| (exists_subset_card_eq h).imp <| by simp
@[simp] lemma powersetCard_card_add (s : Finset α) (hn : 0 < n) :
s.powersetCard (s.card + n) = ∅ := by simpa
theorem powersetCard_eq_filter {n} {s : Finset α} :
powersetCard n s = (powerset s).filter fun x => x.card = n := by
ext
simp [mem_powersetCard]
theorem powersetCard_succ_insert [DecidableEq α] {x : α} {s : Finset α} (h : x ∉ s) (n : ℕ) :
powersetCard n.succ (insert x s) =
powersetCard n.succ s ∪ (powersetCard n s).image (insert x) := by
rw [powersetCard_eq_filter, powerset_insert, filter_union, ← powersetCard_eq_filter]
grind
@[simp]
lemma powersetCard_nonempty : (powersetCard n s).Nonempty ↔ n ≤ s.card := by
aesop (add simp [Finset.Nonempty, exists_subset_card_eq, card_le_card])
@[aesop safe apply (rule_sets := [finsetNonempty])]
alias ⟨_, powersetCard_nonempty_of_le⟩ := powersetCard_nonempty
@[simp]
theorem powersetCard_self (s : Finset α) : powersetCard s.card s = {s} := by
ext
rw [mem_powersetCard, mem_singleton]
constructor
· exact fun ⟨hs, hc⟩ => eq_of_subset_of_card_le hs hc.ge
· rintro rfl
simp
theorem pairwise_disjoint_powersetCard (s : Finset α) :
Pairwise fun i j => Disjoint (s.powersetCard i) (s.powersetCard j) := fun _i _j hij =>
Finset.disjoint_left.mpr fun _x hi hj =>
hij <| (mem_powersetCard.mp hi).2.symm.trans (mem_powersetCard.mp hj).2
theorem powerset_card_disjiUnion (s : Finset α) :
Finset.powerset s =
(range (s.card + 1)).disjiUnion (fun i => powersetCard i s)
(s.pairwise_disjoint_powersetCard.set_pairwise _) := by
refine ext fun a => ⟨fun ha => ?_, fun ha => ?_⟩
· rw [mem_disjiUnion]
exact
⟨a.card, mem_range.mpr (Nat.lt_succ_of_le (card_le_card (mem_powerset.mp ha))),
mem_powersetCard.mpr ⟨mem_powerset.mp ha, rfl⟩⟩
· rcases mem_disjiUnion.mp ha with ⟨i, _hi, ha⟩
exact mem_powerset.mpr (mem_powersetCard.mp ha).1
theorem powerset_card_biUnion [DecidableEq (Finset α)] (s : Finset α) :
Finset.powerset s = (range (s.card + 1)).biUnion fun i => powersetCard i s := by
simpa only [disjiUnion_eq_biUnion] using powerset_card_disjiUnion s
theorem powersetCard_sup [DecidableEq α] (u : Finset α) (n : ℕ) (hn : n < u.card) :
(powersetCard n.succ u).sup id = u := by
apply le_antisymm
· simp_rw [Finset.sup_le_iff, mem_powersetCard]
rintro x ⟨h, -⟩
exact h
· rw [sup_eq_biUnion, le_iff_subset, subset_iff]
intro x hx
simp only [mem_biUnion, id]
obtain ⟨t, ht⟩ : ∃ t, t ∈ powersetCard n (u.erase x) := powersetCard_nonempty.2
(le_trans (Nat.le_sub_one_of_lt hn) pred_card_le_card_erase)
refine ⟨insert x t, ?_, mem_insert_self _ _⟩
rw [← insert_erase hx, powersetCard_succ_insert (notMem_erase _ _)]
exact mem_union_right _ (mem_image_of_mem _ ht)
theorem powersetCard_map {β : Type*} (f : α ↪ β) (n : ℕ) (s : Finset α) :
powersetCard n (s.map f) = (powersetCard n s).map (mapEmbedding f).toEmbedding :=
ext fun t => by
-- `le_eq_subset` is a dangerous lemma since it turns the type `↪o` into `(· ⊆ ·) ↪r (· ⊆ ·)`,
-- which makes `simp` have trouble working with `mapEmbedding_apply`.
simp only [mem_powersetCard, mem_map, RelEmbedding.coe_toEmbedding, mapEmbedding_apply]
constructor
· classical
intro h
have : map f (filter (fun x => (f x ∈ t)) s) = t := by grind
refine ⟨_, ?_, this⟩
rw [← card_map f, this, h.2]; simp
· rintro ⟨a, ⟨has, rfl⟩, rfl⟩
simp only [map_subset_map, has, card_map, and_self]
end powersetCard
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Filter.lean | import Mathlib.Data.Finset.Empty
import Mathlib.Data.Multiset.Filter
/-!
# Filtering a finite set
## Main declarations
* `Finset.filter`: Given a decidable predicate `p : α → Prop`, `s.filter p` is
the finset consisting of those elements in `s` satisfying the predicate `p`.
## Tags
finite sets, finset
-/
-- Assert that we define `Finset` without the material on `List.sublists`.
-- Note that we cannot use `List.sublists` itself as that is defined very early.
assert_not_exists List.sublistsLen Multiset.powerset CompleteLattice IsOrderedMonoid
open Multiset Subtype Function
universe u
variable {α : Type*} {β : Type*} {γ : Type*}
namespace Finset
-- TODO: these should be global attributes, but this will require fixing other files
attribute [local trans] Subset.trans Superset.trans
/-! ### filter -/
section Filter
variable (p q : α → Prop) [DecidablePred p] [DecidablePred q] {s t : Finset α}
/-- `Finset.filter p s` is the set of elements of `s` that satisfy `p`.
For example, one can use `s.filter (· ∈ t)` to get the intersection of `s` with `t : Set α`
as a `Finset α` (when a `DecidablePred (· ∈ t)` instance is available). -/
def filter (s : Finset α) : Finset α :=
⟨_, s.2.filter p⟩
end Finset.Filter
namespace Mathlib.Meta
open Lean Elab Term Meta Batteries.ExtendedBinder
/-- Return `true` if `expectedType?` is `some (Finset ?α)`, throws `throwUnsupportedSyntax` if it is
`some (Set ?α)`, and returns `false` otherwise. -/
def knownToBeFinsetNotSet (expectedType? : Option Expr) : TermElabM Bool :=
-- As we want to reason about the expected type, we would like to wait for it to be available.
-- However this means that if we fall back on `elabSetBuilder` we will have postponed.
-- This is undesirable as we want set builder notation to quickly elaborate to a `Set` when no
-- expected type is available.
-- tryPostponeIfNoneOrMVar expectedType?
match expectedType? with
| some expectedType =>
match_expr expectedType with
-- If the expected type is known to be `Finset ?α`, return `true`.
| Finset _ => pure true
-- If the expected type is known to be `Set ?α`, give up.
| Set _ => throwUnsupportedSyntax
-- If the expected type is known to not be `Finset ?α` or `Set ?α`, return `false`.
| _ => pure false
-- If the expected type is not known, return `false`.
| none => pure false
/-- Elaborate set builder notation for `Finset`.
`{x ∈ s | p x}` is elaborated as `Finset.filter (fun x ↦ p x) s` if either the expected type is
`Finset ?α` or the expected type is not `Set ?α` and `s` has expected type `Finset ?α`.
See also
* `Data.Set.Defs` for the `Set` builder notation elaborator that this elaborator partly overrides.
* `Data.Fintype.Basic` for the `Finset` builder notation elaborator handling syntax of the form
`{x | p x}`, `{x : α | p x}`, `{x ∉ s | p x}`, `{x ≠ a | p x}`.
* `Order.LocallyFinite.Basic` for the `Finset` builder notation elaborator handling syntax of the
form `{x ≤ a | p x}`, `{x ≥ a | p x}`, `{x < a | p x}`, `{x > a | p x}`.
TODO: Write a delaborator
-/
@[term_elab setBuilder]
def elabFinsetBuilderSep : TermElab
| `({ $x:ident ∈ $s:term | $p }), expectedType? => do
-- If the expected type is known to be `Set ?α`, give up. If it is not known to be `Set ?α` or
-- `Finset ?α`, check the expected type of `s`.
unless ← knownToBeFinsetNotSet expectedType? do
let ty ← try whnfR (← inferType (← elabTerm s none)) catch _ => throwUnsupportedSyntax
-- If the expected type of `s` is not known to be `Finset ?α`, give up.
match_expr ty with
| Finset _ => pure ()
| _ => throwUnsupportedSyntax
-- Finally, we can elaborate the syntax as a finset.
-- TODO: Seems a bit wasteful to have computed the expected type but still use `expectedType?`.
elabTerm (← `(Finset.filter (fun $x:ident ↦ $p) $s)) expectedType?
| _, _ => throwUnsupportedSyntax
end Mathlib.Meta
namespace Finset
section Filter
variable (p q : α → Prop) [DecidablePred p] [DecidablePred q] {s t : Finset α}
@[simp]
theorem filter_val (s : Finset α) : (filter p s).1 = s.1.filter p :=
rfl
@[simp]
theorem filter_subset (s : Finset α) : s.filter p ⊆ s :=
Multiset.filter_subset _ _
variable {p}
@[simp, grind =]
theorem mem_filter {s : Finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a :=
Multiset.mem_filter
theorem mem_of_mem_filter {s : Finset α} (x : α) (h : x ∈ s.filter p) : x ∈ s :=
Multiset.mem_of_mem_filter h
theorem filter_ssubset {s : Finset α} : s.filter p ⊂ s ↔ ∃ x ∈ s, ¬p x := by grind
variable (p)
theorem filter_filter (s : Finset α) : (s.filter p).filter q = s.filter fun a => p a ∧ q a := by
grind
theorem filter_comm (s : Finset α) : (s.filter p).filter q = (s.filter q).filter p := by
grind
-- We can replace an application of filter where the decidability is inferred in "the wrong way".
theorem filter_congr_decidable (s : Finset α) (p : α → Prop) (h : DecidablePred p)
[DecidablePred p] : @filter α p h s = s.filter p := by congr
@[simp]
theorem filter_true {h} (s : Finset α) : @filter _ (fun _ => True) h s = s := by ext; simp
@[deprecated (since := "2025-08-24")] alias filter_True := filter_true
@[simp]
theorem filter_false {h} (s : Finset α) : @filter _ (fun _ => False) h s = ∅ := by ext; simp
@[deprecated (since := "2025-08-24")] alias filter_False := filter_false
variable {p q}
@[simp]
lemma filter_eq_self : s.filter p = s ↔ ∀ x ∈ s, p x := by simp [Finset.ext_iff]
@[simp]
theorem filter_eq_empty_iff : s.filter p = ∅ ↔ ∀ ⦃x⦄, x ∈ s → ¬p x := by simp [Finset.ext_iff]
theorem filter_nonempty_iff : (s.filter p).Nonempty ↔ ∃ a ∈ s, p a := by
simp only [nonempty_iff_ne_empty, Ne, filter_eq_empty_iff, Classical.not_not, not_forall,
exists_prop]
/-- If all elements of a `Finset` satisfy the predicate `p`, `s.filter p` is `s`. -/
theorem filter_true_of_mem (h : ∀ x ∈ s, p x) : s.filter p = s := filter_eq_self.2 h
/-- If all elements of a `Finset` fail to satisfy the predicate `p`, `s.filter p` is `∅`. -/
theorem filter_false_of_mem (h : ∀ x ∈ s, ¬p x) : s.filter p = ∅ := filter_eq_empty_iff.2 h
@[simp]
theorem filter_const (p : Prop) [Decidable p] (s : Finset α) :
(s.filter fun _a => p) = if p then s else ∅ := by split_ifs <;> simp [*]
theorem filter_congr {s : Finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s :=
eq_of_veq <| Multiset.filter_congr H
variable (p q)
@[simp]
theorem filter_empty : filter p ∅ = ∅ :=
subset_empty.1 <| filter_subset _ _
@[gcongr]
theorem filter_subset_filter {s t : Finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := fun _a ha =>
mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩
theorem monotone_filter_left : Monotone (filter p) := fun _ _ => filter_subset_filter p
@[gcongr]
theorem monotone_filter_right (s : Finset α) ⦃p q : α → Prop⦄ [DecidablePred p] [DecidablePred q]
(h : ∀ a ∈ s, p a → q a) : s.filter p ⊆ s.filter q := by simp +contextual [subset_iff, h]
@[simp, norm_cast]
theorem coe_filter (s : Finset α) : ↑(s.filter p) = ({ x ∈ ↑s | p x } : Set α) :=
Set.ext fun _ => mem_filter
theorem subset_coe_filter_of_subset_forall (s : Finset α) {t : Set α} (h₁ : t ⊆ s)
(h₂ : ∀ x ∈ t, p x) : t ⊆ s.filter p := fun x hx => (s.coe_filter p).symm ▸ ⟨h₁ hx, h₂ x hx⟩
theorem disjoint_filter_filter {s t : Finset α}
{p q : α → Prop} [DecidablePred p] [DecidablePred q] :
Disjoint s t → Disjoint (s.filter p) (t.filter q) :=
Disjoint.mono (filter_subset _ _) (filter_subset _ _)
lemma _root_.Set.pairwiseDisjoint_filter [DecidableEq β] (f : α → β) (s : Set β) (t : Finset α) :
s.PairwiseDisjoint fun x ↦ t.filter (f · = x) := by
rintro i - j - h u hi hj x hx
obtain ⟨-, rfl⟩ : x ∈ t ∧ f x = i := by simpa using hi hx
obtain ⟨-, rfl⟩ : x ∈ t ∧ f x = j := by simpa using hj hx
contradiction
theorem disjoint_filter_and_not_filter :
Disjoint (s.filter (fun x ↦ p x ∧ ¬q x)) (s.filter (fun x ↦ q x ∧ ¬p x)) := by
intro _ htp htq
simp only [bot_eq_empty, le_eq_subset, subset_empty, ← not_nonempty_iff_eq_empty]
rintro ⟨_, hx⟩
exact (mem_filter.mp (htq hx)).2.2 (mem_filter.mp (htp hx)).2.1
variable {p q}
lemma filter_inj : s.filter p = t.filter p ↔ ∀ ⦃a⦄, p a → (a ∈ s ↔ a ∈ t) := by
simp [Finset.ext_iff]
lemma filter_inj' : s.filter p = s.filter q ↔ ∀ ⦃a⦄, a ∈ s → (p a ↔ q a) := by
simp [Finset.ext_iff]
end Filter
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Defs.lean | import Aesop
import Mathlib.Data.Multiset.Defs
import Mathlib.Data.Set.Pairwise.Basic
import Mathlib.Data.SetLike.Basic
import Mathlib.Order.Hom.Basic
/-!
# Finite sets
Terms of type `Finset α` are one way of talking about finite subsets of `α` in Mathlib.
Below, `Finset α` is defined as a structure with 2 fields:
1. `val` is a `Multiset α` of elements;
2. `nodup` is a proof that `val` has no duplicates.
Finsets in Lean are constructive in that they have an underlying `List` that enumerates their
elements. In particular, any function that uses the data of the underlying list cannot depend on its
ordering. This is handled on the `Multiset` level by multiset API, so in most cases one needn't
worry about it explicitly.
Finsets give a basic foundation for defining finite sums and products over types:
1. `∑ i ∈ (s : Finset α), f i`;
2. `∏ i ∈ (s : Finset α), f i`.
Lean refers to these operations as big operators.
More information can be found in `Mathlib/Algebra/BigOperators/Group/Finset.lean`.
Finsets are directly used to define fintypes in Lean.
A `Fintype α` instance for a type `α` consists of a universal `Finset α` containing every term of
`α`, called `univ`. See `Mathlib/Data/Fintype/Basic.lean`.
`Finset.card`, the size of a finset is defined in `Mathlib/Data/Finset/Card.lean`.
This is then used to define `Fintype.card`, the size of a type.
## File structure
This file defines the `Finset` type and the membership and subset relations between finsets.
Most constructions involving `Finset`s have been split off to their own files.
## Main definitions
* `Finset`: Defines a type for the finite subsets of `α`.
Constructing a `Finset` requires two pieces of data: `val`, a `Multiset α` of elements,
and `nodup`, a proof that `val` has no duplicates.
* `Finset.instMembershipFinset`: Defines membership `a ∈ (s : Finset α)`.
* `Finset.instSetLike`: Provides a coercion `s : Finset α` to `s : Set α`.
* `Finset.instCoeSortFinsetType`: Coerce `s : Finset α` to the type of all `x ∈ s`.
## Tags
finite sets, finset
-/
-- Assert that we define `Finset` without the material on `List.sublists`.
-- Note that we cannot use `List.sublists` itself as that is defined very early.
assert_not_exists List.sublistsLen Multiset.powerset DirectedSystem CompleteLattice Monoid
open Multiset Subtype Function
universe u
variable {α : Type*} {β : Type*} {γ : Type*}
/-- `Finset α` is the type of finite sets of elements of `α`. It is implemented
as a multiset (a list up to permutation) which has no duplicate elements. -/
structure Finset (α : Type*) where
/-- The underlying multiset -/
val : Multiset α
/-- `val` contains no duplicates -/
nodup : Nodup val
instance Multiset.canLiftFinset {α} : CanLift (Multiset α) (Finset α) Finset.val Multiset.Nodup :=
⟨fun m hm => ⟨⟨m, hm⟩, rfl⟩⟩
namespace Finset
theorem eq_of_veq : ∀ {s t : Finset α}, s.1 = t.1 → s = t
| ⟨s, _⟩, ⟨t, _⟩, h => by cases h; rfl
theorem val_injective : Injective (val : Finset α → Multiset α) := fun _ _ => eq_of_veq
@[simp]
theorem val_inj {s t : Finset α} : s.1 = t.1 ↔ s = t :=
val_injective.eq_iff
instance decidableEq [DecidableEq α] : DecidableEq (Finset α)
| _, _ => decidable_of_iff _ val_inj
/-! ### membership -/
instance : Membership α (Finset α) :=
⟨fun s a => a ∈ s.1⟩
theorem mem_def {a : α} {s : Finset α} : a ∈ s ↔ a ∈ s.1 :=
Iff.rfl
-- If https://github.com/leanprover/lean4/issues/2678 is resolved-
-- this can be changed back to an `Iff`, but for now we would like `dsimp` to use it.
@[simp, grind =]
theorem mem_val {a : α} {s : Finset α} : (a ∈ s.1) = (a ∈ s) := rfl
@[simp, grind =]
theorem mem_mk {a : α} {s nd} : a ∈ @Finset.mk α s nd ↔ a ∈ s :=
Iff.rfl
instance decidableMem [_h : DecidableEq α] (a : α) (s : Finset α) : Decidable (a ∈ s) :=
Multiset.decidableMem _ _
@[simp] lemma forall_mem_not_eq {s : Finset α} {a : α} : (∀ b ∈ s, ¬ a = b) ↔ a ∉ s := by aesop
@[simp] lemma forall_mem_not_eq' {s : Finset α} {a : α} : (∀ b ∈ s, ¬ b = a) ↔ a ∉ s := by aesop
/-! ### set coercion -/
/-- Convert a finset to a set in the natural way. -/
instance : SetLike (Finset α) α where
coe s := {a | a ∈ s}
coe_injective' s₁ s₂ h := (val_inj.symm.trans <| s₁.nodup.ext s₂.nodup).2 <| Set.ext_iff.mp h
/-- Convert a finset to a set in the natural way. -/
@[deprecated SetLike.coe (since := "2025-10-22")]
abbrev toSet (s : Finset α) : Set α := s
@[norm_cast, grind =]
theorem mem_coe {a : α} {s : Finset α} : a ∈ (s : Set α) ↔ a ∈ (s : Finset α) :=
Iff.rfl
@[simp]
theorem setOf_mem {α} {s : Finset α} : { a | a ∈ s } = s :=
rfl
theorem coe_mem {s : Finset α} (x : (s : Set α)) : ↑x ∈ s :=
x.2
theorem mk_coe {s : Finset α} (x : (s : Set α)) {h} : (⟨x, h⟩ : (s : Set α)) = x :=
Subtype.coe_eta _ _
instance decidableMem' [DecidableEq α] (a : α) (s : Finset α) : Decidable (a ∈ (s : Set α)) :=
s.decidableMem _
/-! ### extensionality -/
@[ext, grind ext]
theorem ext {s₁ s₂ : Finset α} (h : ∀ a, a ∈ s₁ ↔ a ∈ s₂) : s₁ = s₂ :=
SetLike.ext h
@[norm_cast]
theorem coe_inj {s₁ s₂ : Finset α} : (s₁ : Set α) = s₂ ↔ s₁ = s₂ :=
SetLike.coe_set_eq
theorem coe_injective {α} : Injective ((↑) : Finset α → Set α) := fun _s _t => coe_inj.1
/-! ### type coercion -/
protected theorem forall_coe {α : Type*} (s : Finset α) (p : s → Prop) :
(∀ x : s, p x) ↔ ∀ (x : α) (h : x ∈ s), p ⟨x, h⟩ :=
Subtype.forall
protected theorem exists_coe {α : Type*} (s : Finset α) (p : s → Prop) :
(∃ x : s, p x) ↔ ∃ (x : α) (h : x ∈ s), p ⟨x, h⟩ :=
Subtype.exists
instance PiFinsetCoe.canLift (ι : Type*) (α : ι → Type*) [_ne : ∀ i, Nonempty (α i)]
(s : Finset ι) : CanLift (∀ i : s, α i) (∀ i, α i) (fun f i => f i) fun _ => True :=
PiSubtype.canLift ι α (· ∈ s)
instance PiFinsetCoe.canLift' (ι α : Type*) [_ne : Nonempty α] (s : Finset ι) :
CanLift (s → α) (ι → α) (fun f i => f i) fun _ => True :=
PiFinsetCoe.canLift ι (fun _ => α) s
instance FinsetCoe.canLift (s : Finset α) : CanLift α s (↑) fun a => a ∈ s where
prf a ha := ⟨⟨a, ha⟩, rfl⟩
@[norm_cast]
theorem coe_sort_coe (s : Finset α) : ((s : Set α) : Sort _) = s :=
rfl
/-! ### Subset and strict subset relations -/
section Subset
variable {s t : Finset α}
instance : HasSubset (Finset α) :=
⟨fun s t => ∀ ⦃a⦄, a ∈ s → a ∈ t⟩
instance : HasSSubset (Finset α) :=
⟨fun s t => s ⊆ t ∧ ¬t ⊆ s⟩
instance partialOrder : PartialOrder (Finset α) := inferInstance
theorem subset_of_le : s ≤ t → s ⊆ t := id
instance : IsRefl (Finset α) (· ⊆ ·) :=
inferInstanceAs <| IsRefl (Finset α) (· ≤ ·)
instance : IsTrans (Finset α) (· ⊆ ·) :=
inferInstanceAs <| IsTrans (Finset α) (· ≤ ·)
instance : IsAntisymm (Finset α) (· ⊆ ·) :=
inferInstanceAs <| IsAntisymm (Finset α) (· ≤ ·)
instance : IsIrrefl (Finset α) (· ⊂ ·) :=
inferInstanceAs <| IsIrrefl (Finset α) (· < ·)
instance : IsTrans (Finset α) (· ⊂ ·) :=
inferInstanceAs <| IsTrans (Finset α) (· < ·)
instance : IsAsymm (Finset α) (· ⊂ ·) :=
inferInstanceAs <| IsAsymm (Finset α) (· < ·)
instance : IsNonstrictStrictOrder (Finset α) (· ⊆ ·) (· ⊂ ·) :=
⟨fun _ _ => Iff.rfl⟩
theorem subset_def : s ⊆ t ↔ s.1 ⊆ t.1 :=
Iff.rfl
theorem ssubset_def : s ⊂ t ↔ s ⊆ t ∧ ¬t ⊆ s :=
Iff.rfl
theorem Subset.refl (s : Finset α) : s ⊆ s :=
Multiset.Subset.refl _
protected theorem Subset.rfl {s : Finset α} : s ⊆ s :=
Subset.refl _
protected theorem subset_of_eq {s t : Finset α} (h : s = t) : s ⊆ t :=
h ▸ Subset.refl _
theorem Subset.trans {s₁ s₂ s₃ : Finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ :=
Multiset.Subset.trans
theorem Superset.trans {s₁ s₂ s₃ : Finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ := fun h' h =>
Subset.trans h h'
@[gcongr]
theorem mem_of_subset {s₁ s₂ : Finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ :=
Multiset.mem_of_subset
theorem notMem_mono {s t : Finset α} (h : s ⊆ t) {a : α} : a ∉ t → a ∉ s :=
mt <| @h _
@[deprecated (since := "2025-05-23")] alias not_mem_mono := notMem_mono
alias not_mem_subset := not_mem_mono
theorem Subset.antisymm {s₁ s₂ : Finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ :=
ext fun a => ⟨@H₁ a, @H₂ a⟩
@[grind =]
theorem subset_iff {s₁ s₂ : Finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ :=
Iff.rfl
@[norm_cast]
theorem coe_subset {s₁ s₂ : Finset α} : (s₁ : Set α) ⊆ s₂ ↔ s₁ ⊆ s₂ :=
Iff.rfl
@[gcongr] protected alias ⟨_, GCongr.coe_subset_coe⟩ := coe_subset
@[simp]
theorem val_le_iff {s₁ s₂ : Finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ :=
le_iff_subset s₁.2
theorem Subset.antisymm_iff {s₁ s₂ : Finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ :=
le_antisymm_iff
theorem not_subset : ¬s ⊆ t ↔ ∃ x ∈ s, x ∉ t := by simp only [← coe_subset, Set.not_subset, mem_coe]
@[simp]
theorem le_eq_subset : ((· ≤ ·) : Finset α → Finset α → Prop) = (· ⊆ ·) :=
rfl
@[simp]
theorem lt_eq_subset : ((· < ·) : Finset α → Finset α → Prop) = (· ⊂ ·) :=
rfl
theorem le_iff_subset {s₁ s₂ : Finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ :=
Iff.rfl
theorem lt_iff_ssubset {s₁ s₂ : Finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ :=
Iff.rfl
@[norm_cast]
theorem coe_ssubset {s₁ s₂ : Finset α} : (s₁ : Set α) ⊂ s₂ ↔ s₁ ⊂ s₂ := by
simp
@[simp]
theorem val_lt_iff {s₁ s₂ : Finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ :=
and_congr val_le_iff <| not_congr val_le_iff
lemma val_strictMono : StrictMono (val : Finset α → Multiset α) := fun _ _ ↦ val_lt_iff.2
@[grind =]
theorem ssubset_iff_subset_ne {s t : Finset α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t :=
@lt_iff_le_and_ne _ _ s t
theorem ssubset_iff_of_subset {s₁ s₂ : Finset α} (h : s₁ ⊆ s₂) : s₁ ⊂ s₂ ↔ ∃ x ∈ s₂, x ∉ s₁ :=
Set.ssubset_iff_of_subset h
theorem ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : Finset α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) :
s₁ ⊂ s₃ :=
Set.ssubset_of_ssubset_of_subset hs₁s₂ hs₂s₃
theorem ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : Finset α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) :
s₁ ⊂ s₃ :=
Set.ssubset_of_subset_of_ssubset hs₁s₂ hs₂s₃
theorem exists_of_ssubset {s₁ s₂ : Finset α} (h : s₁ ⊂ s₂) : ∃ x ∈ s₂, x ∉ s₁ :=
Set.exists_of_ssubset h
instance isWellFounded_ssubset : IsWellFounded (Finset α) (· ⊂ ·) :=
Subrelation.isWellFounded (InvImage _ _) val_lt_iff.2
instance wellFoundedLT : WellFoundedLT (Finset α) :=
Finset.isWellFounded_ssubset
end Subset
-- TODO: these should be global attributes, but this will require fixing other files
attribute [local trans] Subset.trans Superset.trans
/-! ### Order embedding from `Finset α` to `Set α` -/
/-- Coercion to `Set α` as an `OrderEmbedding`. -/
def coeEmb : Finset α ↪o Set α :=
⟨⟨(↑), coe_injective⟩, coe_subset⟩
@[simp]
theorem coe_coeEmb : ⇑(coeEmb : Finset α ↪o Set α) = ((↑) : Finset α → Set α) :=
rfl
/-! ### Assorted results
These results can be defined using the current imports, but deserve to be given a nicer home.
-/
section DecidablePiExists
variable {s : Finset α}
instance decidableDforallFinset {p : ∀ a ∈ s, Prop} [_hp : ∀ (a) (h : a ∈ s), Decidable (p a h)] :
Decidable (∀ (a) (h : a ∈ s), p a h) :=
Multiset.decidableDforallMultiset
instance instDecidableRelSubset [DecidableEq α] : DecidableRel (α := Finset α) (· ⊆ ·) :=
fun _ _ ↦ decidableDforallFinset
instance instDecidableRelSSubset [DecidableEq α] : DecidableRel (α := Finset α) (· ⊂ ·) :=
fun _ _ ↦ instDecidableAnd
instance instDecidableLE [DecidableEq α] : DecidableLE (Finset α) :=
instDecidableRelSubset
instance instDecidableLT [DecidableEq α] : DecidableLT (Finset α) :=
instDecidableRelSSubset
instance decidableDExistsFinset {p : ∀ a ∈ s, Prop} [_hp : ∀ (a) (h : a ∈ s), Decidable (p a h)] :
Decidable (∃ (a : _) (h : a ∈ s), p a h) :=
Multiset.decidableDexistsMultiset
instance decidableExistsAndFinset {p : α → Prop} [_hp : ∀ (a), Decidable (p a)] :
Decidable (∃ a ∈ s, p a) :=
decidable_of_iff (∃ (a : _) (_ : a ∈ s), p a) (by simp)
instance decidableExistsAndFinsetCoe {p : α → Prop} [DecidablePred p] :
Decidable (∃ a ∈ (s : Set α), p a) := decidableExistsAndFinset
/-- decidable equality for functions whose domain is bounded by finsets -/
instance decidableEqPiFinset {β : α → Type*} [_h : ∀ a, DecidableEq (β a)] :
DecidableEq (∀ a ∈ s, β a) :=
Multiset.decidableEqPiMultiset
end DecidablePiExists
end Finset
namespace List
variable [DecidableEq α] {a : α} {f : α → β} {s : Finset α} {t : Set β} {t' : Finset β}
instance [DecidablePred (· ∈ t)] : Decidable (Set.MapsTo f s t) :=
inferInstanceAs (Decidable (∀ x ∈ s, f x ∈ t))
instance [DecidableEq β] : Decidable (Set.SurjOn f s t') :=
inferInstanceAs (Decidable (∀ x ∈ t', ∃ y ∈ s, f y = x))
end List
namespace Finset
section Pairwise
variable {s : Finset α}
theorem pairwise_subtype_iff_pairwise_finset' (r : β → β → Prop) (f : α → β) :
Pairwise (r on fun x : s => f x) ↔ (s : Set α).Pairwise (r on f) :=
pairwise_subtype_iff_pairwise_set (s : Set α) (r on f)
theorem pairwise_subtype_iff_pairwise_finset (r : α → α → Prop) :
Pairwise (r on fun x : s => x) ↔ (s : Set α).Pairwise r :=
pairwise_subtype_iff_pairwise_finset' r id
end Pairwise
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Finsupp.lean | import Mathlib.Algebra.BigOperators.Finsupp.Basic
import Mathlib.Data.Finsupp.Indicator
import Mathlib.Data.Fintype.BigOperators
import Mathlib.Algebra.Group.Pointwise.Finset.Basic
/-!
# Finitely supported product of finsets
This file defines the finitely supported product of finsets as a `Finset (ι →₀ α)`.
## Main declarations
* `Finset.finsupp`: Finitely supported product of finsets. `s.finset t` is the product of the `t i`
over all `i ∈ s`.
* `Finsupp.pi`: `f.pi` is the finset of `Finsupp`s whose `i`-th value lies in `f i`. This is the
special case of `Finset.finsupp` where we take the product of the `f i` over the support of `f`.
## Implementation notes
We make heavy use of the fact that `0 : Finset α` is `{0}`. This scalar actions convention turns out
to be precisely what we want here too.
-/
noncomputable section
open Finsupp
open Pointwise
variable {ι α : Type*} [Zero α] {s : Finset ι} {f : ι →₀ α}
namespace Finset
open scoped Classical in
/-- Finitely supported product of finsets. -/
protected def finsupp (s : Finset ι) (t : ι → Finset α) : Finset (ι →₀ α) :=
(s.pi t).map ⟨indicator s, indicator_injective s⟩
theorem mem_finsupp_iff {t : ι → Finset α} :
f ∈ s.finsupp t ↔ f.support ⊆ s ∧ ∀ i ∈ s, f i ∈ t i := by
classical
refine mem_map.trans ⟨?_, ?_⟩
· rintro ⟨f, hf, rfl⟩
refine ⟨support_indicator_subset _ _, fun i hi => ?_⟩
convert mem_pi.1 hf i hi
exact indicator_of_mem hi _
· refine fun h => ⟨fun i _ => f i, mem_pi.2 h.2, ?_⟩
ext i
exact ite_eq_left_iff.2 fun hi => (notMem_support_iff.1 fun H => hi <| h.1 H).symm
/-- When `t` is supported on `s`, `f ∈ s.finsupp t` precisely means that `f` is pointwise in `t`. -/
@[simp]
theorem mem_finsupp_iff_of_support_subset {t : ι →₀ Finset α} (ht : t.support ⊆ s) :
f ∈ s.finsupp t ↔ ∀ i, f i ∈ t i := by
refine
mem_finsupp_iff.trans
(forall_and.symm.trans <|
forall_congr' fun i =>
⟨fun h => ?_, fun h =>
⟨fun hi => ht <| mem_support_iff.2 fun H => mem_support_iff.1 hi ?_, fun _ => h⟩⟩)
· by_cases hi : i ∈ s
· exact h.2 hi
· rw [notMem_support_iff.1 (mt h.1 hi), notMem_support_iff.1 fun H => hi <| ht H]
exact zero_mem_zero
· rwa [H, mem_zero] at h
@[simp]
theorem card_finsupp (s : Finset ι) (t : ι → Finset α) : #(s.finsupp t) = ∏ i ∈ s, #(t i) := by
classical exact (card_map _).trans <| card_pi _ _
end Finset
open Finset
namespace Finsupp
/-- Given a finitely supported function `f : ι →₀ Finset α`, one can define the finset
`f.pi` of all finitely supported functions whose value at `i` is in `f i` for all `i`. -/
def pi (f : ι →₀ Finset α) : Finset (ι →₀ α) :=
f.support.finsupp f
@[simp]
theorem mem_pi {f : ι →₀ Finset α} {g : ι →₀ α} : g ∈ f.pi ↔ ∀ i, g i ∈ f i :=
mem_finsupp_iff_of_support_subset <| Subset.refl _
@[simp]
theorem card_pi (f : ι →₀ Finset α) : #f.pi = f.prod fun i ↦ #(f i) := by
rw [pi, card_finsupp]
exact Finset.prod_congr rfl fun i _ => by simp only [Pi.natCast_apply, Nat.cast_id]
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finset/Empty.lean | import Mathlib.Data.Finset.Defs
import Mathlib.Data.Multiset.ZeroCons
/-!
# Empty and nonempty finite sets
This file defines the empty finite set ∅ and a predicate for nonempty `Finset`s.
## Main declarations
* `Finset.Nonempty`: A finset is nonempty if it has elements. This is equivalent to saying `s ≠ ∅`.
* `Finset.empty`: Denoted by `∅`. The finset associated to any type consisting of no elements.
## Tags
finite sets, finset
-/
-- Assert that we define `Finset` without the material on `List.sublists`.
-- Note that we cannot use `List.sublists` itself as that is defined very early.
assert_not_exists List.sublistsLen Multiset.powerset CompleteLattice IsOrderedMonoid
open Multiset Subtype Function
universe u
variable {α : Type*} {β : Type*} {γ : Type*}
namespace Finset
/-! ### Nonempty -/
/-- The property `s.Nonempty` expresses the fact that the finset `s` is not empty. It should be used
in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks
to the dot notation. -/
protected def Nonempty (s : Finset α) : Prop := ∃ x : α, x ∈ s
@[grind =]
theorem nonempty_def {s : Finset α} : s.Nonempty ↔ ∃ x, x ∈ s := Iff.rfl
instance decidableNonempty {s : Finset α} : Decidable s.Nonempty :=
decidable_of_iff (∃ a ∈ s, true) <| by simp [Finset.Nonempty]
@[simp, norm_cast]
theorem coe_nonempty {s : Finset α} : (s : Set α).Nonempty ↔ s.Nonempty :=
Iff.rfl
-- Not `@[simp]` since `nonempty_subtype` already is.
theorem nonempty_coe_sort {s : Finset α} : Nonempty (s : Type _) ↔ s.Nonempty :=
nonempty_subtype
alias ⟨_, Nonempty.to_set⟩ := coe_nonempty
alias ⟨_, Nonempty.coe_sort⟩ := nonempty_coe_sort
theorem Nonempty.exists_mem {s : Finset α} (h : s.Nonempty) : ∃ x : α, x ∈ s :=
h
@[gcongr] theorem Nonempty.mono {s t : Finset α} (hst : s ⊆ t) (hs : s.Nonempty) : t.Nonempty :=
Set.Nonempty.mono hst hs
theorem Nonempty.forall_const {s : Finset α} (h : s.Nonempty) {p : Prop} : (∀ x ∈ s, p) ↔ p :=
let ⟨x, hx⟩ := h
⟨fun h => h x hx, fun h _ _ => h⟩
theorem Nonempty.to_subtype {s : Finset α} : s.Nonempty → Nonempty s :=
nonempty_coe_sort.2
theorem Nonempty.to_type {s : Finset α} : s.Nonempty → Nonempty α := fun ⟨x, _hx⟩ => ⟨x⟩
/-! ### empty -/
section Empty
variable {s : Finset α}
/-- The empty finset -/
protected def empty : Finset α :=
⟨0, nodup_zero⟩
instance : EmptyCollection (Finset α) :=
⟨Finset.empty⟩
instance inhabitedFinset : Inhabited (Finset α) :=
⟨∅⟩
@[simp]
theorem empty_val : (∅ : Finset α).1 = 0 :=
rfl
@[simp, grind ←]
theorem notMem_empty (a : α) : a ∉ (∅ : Finset α) := by
simp only [mem_def, empty_val, notMem_zero, not_false_iff]
@[deprecated (since := "2025-05-23")] alias not_mem_empty := notMem_empty
@[simp]
theorem not_nonempty_empty : ¬(∅ : Finset α).Nonempty := fun ⟨x, hx⟩ => notMem_empty x hx
@[simp]
theorem mk_zero : (⟨0, nodup_zero⟩ : Finset α) = ∅ :=
rfl
theorem ne_empty_of_mem {a : α} {s : Finset α} (h : a ∈ s) : s ≠ ∅ := fun e =>
notMem_empty a <| e ▸ h
theorem Nonempty.ne_empty {s : Finset α} (h : s.Nonempty) : s ≠ ∅ :=
(Exists.elim h) fun _a => ne_empty_of_mem
@[simp]
theorem empty_subset (s : Finset α) : ∅ ⊆ s :=
zero_subset _
theorem eq_empty_of_forall_notMem {s : Finset α} (H : ∀ x, x ∉ s) : s = ∅ :=
eq_of_veq (eq_zero_of_forall_notMem H)
@[deprecated (since := "2025-05-23")] alias eq_empty_of_forall_not_mem := eq_empty_of_forall_notMem
theorem eq_empty_iff_forall_notMem {s : Finset α} : s = ∅ ↔ ∀ x, x ∉ s := by grind
@[deprecated (since := "2025-05-23")]
alias eq_empty_iff_forall_not_mem := eq_empty_iff_forall_notMem
@[simp]
theorem val_eq_zero {s : Finset α} : s.1 = 0 ↔ s = ∅ :=
@val_inj _ s ∅
@[simp] lemma subset_empty : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero
@[simp]
theorem not_ssubset_empty (s : Finset α) : ¬s ⊂ ∅ := by grind
theorem nonempty_of_ne_empty {s : Finset α} (h : s ≠ ∅) : s.Nonempty :=
exists_mem_of_ne_zero (mt val_eq_zero.1 h)
theorem nonempty_iff_ne_empty {s : Finset α} : s.Nonempty ↔ s ≠ ∅ :=
⟨Nonempty.ne_empty, nonempty_of_ne_empty⟩
@[simp]
theorem not_nonempty_iff_eq_empty {s : Finset α} : ¬s.Nonempty ↔ s = ∅ :=
nonempty_iff_ne_empty.not.trans not_not
theorem eq_empty_or_nonempty (s : Finset α) : s = ∅ ∨ s.Nonempty :=
by_cases Or.inl fun h => Or.inr (nonempty_of_ne_empty h)
@[simp, norm_cast]
theorem coe_empty : ((∅ : Finset α) : Set α) = ∅ := by grind
@[simp, norm_cast]
theorem coe_eq_empty {s : Finset α} : (s : Set α) = ∅ ↔ s = ∅ := by grind
@[simp]
theorem isEmpty_coe_sort {s : Finset α} : IsEmpty (s : Type _) ↔ s = ∅ := by
simpa using @Set.isEmpty_coe_sort α s
instance instIsEmpty : IsEmpty (∅ : Finset α) :=
isEmpty_coe_sort.2 rfl
/-- A `Finset` for an empty type is empty. -/
theorem eq_empty_of_isEmpty [IsEmpty α] (s : Finset α) : s = ∅ :=
Finset.eq_empty_of_forall_notMem isEmptyElim
instance : OrderBot (Finset α) where
bot := ∅
bot_le := empty_subset
@[simp, grind =]
theorem bot_eq_empty : (⊥ : Finset α) = ∅ :=
rfl
@[simp]
theorem empty_ssubset : ∅ ⊂ s ↔ s.Nonempty :=
(@bot_lt_iff_ne_bot (Finset α) _ _ _).trans nonempty_iff_ne_empty.symm
alias ⟨_, Nonempty.empty_ssubset⟩ := empty_ssubset
-- useful rules for calculations with quantifiers
theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : Finset α) ∧ p x) ↔ False := by
grind
theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : Finset α) → p x) ↔ True := by
grind
end Empty
end Finset
namespace Mathlib.Meta
open Qq Lean Meta Finset
/-- Attempt to prove that a finset is nonempty using the `finsetNonempty` aesop rule-set.
You can add lemmas to the rule-set by tagging them with either:
* `aesop safe apply (rule_sets := [finsetNonempty])` if they are always a good idea to follow or
* `aesop unsafe apply (rule_sets := [finsetNonempty])` if they risk directing the search to a blind
alley.
TODO: should some of the lemmas be `aesop safe simp` instead?
-/
def proveFinsetNonempty {u : Level} {α : Q(Type u)} (s : Q(Finset $α)) :
MetaM (Option Q(Finset.Nonempty $s)) := do
-- Aesop expects to operate on goals, so we're going to make a new goal.
let goal ← Lean.Meta.mkFreshExprMVar q(Finset.Nonempty $s)
let mvar := goal.mvarId!
-- We want this to be fast, so use only the basic and `Finset.Nonempty`-specific rules.
let rulesets ← Aesop.Frontend.getGlobalRuleSets #[`builtin, `finsetNonempty]
let options : Aesop.Options' :=
{ terminal := true -- Fail if the new goal is not closed.
generateScript := false
useDefaultSimpSet := false -- Avoiding the whole simp set to speed up the tactic.
warnOnNonterminal := false -- Don't show a warning on failure, simply return `none`.
forwardMaxDepth? := none }
let rules ← Aesop.mkLocalRuleSet rulesets options
let (remainingGoals, _) ←
try Aesop.search (options := options.toOptions) mvar (.some rules)
catch _ => return none
-- Fail if there are open goals remaining, this serves as an extra check for the
-- Aesop configuration option `terminal := true`.
if remainingGoals.size > 0 then return none
Lean.getExprMVarAssignment? mvar
end Mathlib.Meta |
.lake/packages/mathlib/Mathlib/Data/Finset/SymmDiff.lean | import Mathlib.Data.Finset.Image
import Mathlib.Data.Set.SymmDiff
/-!
# Symmetric difference of finite sets
This file concerns the symmetric difference operator `s Δ t` on finite sets.
## Tags
finite sets, finset
-/
-- Assert that we define `Finset` without the material on `List.sublists`.
-- Note that we cannot use `List.sublists` itself as that is defined very early.
assert_not_exists List.sublistsLen Multiset.powerset CompleteLattice Monoid
open Multiset Subtype Function
universe u
variable {α : Type*} {β : Type*} {γ : Type*}
namespace Finset
/-! ### Symmetric difference -/
section SymmDiff
open scoped symmDiff
variable [DecidableEq α] {s t : Finset α} {a b : α}
theorem mem_symmDiff : a ∈ s ∆ t ↔ a ∈ s ∧ a ∉ t ∨ a ∈ t ∧ a ∉ s := by
simp_rw [symmDiff, sup_eq_union, mem_union, mem_sdiff]
@[simp, norm_cast]
theorem coe_symmDiff : (↑(s ∆ t) : Set α) = (s : Set α) ∆ t :=
Set.ext fun x => by simp [mem_symmDiff, Set.mem_symmDiff]
@[simp] lemma symmDiff_eq_empty : s ∆ t = ∅ ↔ s = t := symmDiff_eq_bot
@[simp] lemma symmDiff_nonempty : (s ∆ t).Nonempty ↔ s ≠ t :=
nonempty_iff_ne_empty.trans symmDiff_eq_empty.not
theorem image_symmDiff [DecidableEq β] {f : α → β} (s t : Finset α) (hf : Injective f) :
(s ∆ t).image f = s.image f ∆ t.image f :=
mod_cast Set.image_symmDiff hf s t
/-- See `symmDiff_subset_sdiff'` for the swapped version of this. -/
lemma symmDiff_subset_sdiff : s \ t ⊆ s ∆ t := subset_union_left
/-- See `symmDiff_subset_sdiff` for the swapped version of this. -/
lemma symmDiff_subset_sdiff' : t \ s ⊆ s ∆ t := subset_union_right
lemma symmDiff_subset_union : s ∆ t ⊆ s ∪ t := symmDiff_le_sup (α := Finset α)
lemma symmDiff_eq_union_iff (s t : Finset α) : s ∆ t = s ∪ t ↔ Disjoint s t := symmDiff_eq_sup s t
lemma symmDiff_eq_union (h : Disjoint s t) : s ∆ t = s ∪ t := Disjoint.symmDiff_eq_sup h
end SymmDiff
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Grade.lean | import Mathlib.Data.Set.Finite.Basic
import Mathlib.Order.Atoms
import Mathlib.Order.Grade
import Mathlib.Order.Nat
/-!
# Finsets and multisets form a graded order
This file characterises atoms, coatoms and the covering relation in finsets and multisets. It also
proves that they form a `ℕ`-graded order.
## Main declarations
* `Multiset.instGradeMinOrder_nat`: Multisets are `ℕ`-graded
* `Finset.instGradeMinOrder_nat`: Finsets are `ℕ`-graded
-/
open Order
variable {α : Type*}
namespace Multiset
variable {s t : Multiset α} {a : α}
@[simp] lemma covBy_cons (s : Multiset α) (a : α) : s ⋖ a ::ₘ s :=
⟨lt_cons_self _ _, fun t hst hts ↦ (covBy_succ _).2 (card_lt_card hst) <| by
simpa using card_lt_card hts⟩
lemma _root_.CovBy.exists_multiset_cons (h : s ⋖ t) : ∃ a, a ::ₘ s = t :=
(lt_iff_cons_le.1 h.lt).imp fun _a ha ↦ ha.eq_of_not_lt <| h.2 <| lt_cons_self _ _
lemma covBy_iff : s ⋖ t ↔ ∃ a, a ::ₘ s = t :=
⟨CovBy.exists_multiset_cons, by rintro ⟨a, rfl⟩; exact covBy_cons _ _⟩
lemma _root_.CovBy.card_multiset (h : s ⋖ t) : card s ⋖ card t := by
obtain ⟨a, rfl⟩ := h.exists_multiset_cons; rw [card_cons]; exact covBy_succ _
lemma isAtom_iff : IsAtom s ↔ ∃ a, s = {a} := by simp [← bot_covBy_iff, covBy_iff, eq_comm]
@[simp] lemma isAtom_singleton (a : α) : IsAtom ({a} : Multiset α) := isAtom_iff.2 ⟨_, rfl⟩
instance instGradeMinOrder : GradeMinOrder ℕ (Multiset α) where
grade := card
grade_strictMono := card_strictMono
covBy_grade _ _ := CovBy.card_multiset
isMin_grade s hs := by rw [isMin_iff_eq_bot.1 hs]; exact isMin_bot
@[simp] lemma grade_eq (m : Multiset α) : grade ℕ m = card m := rfl
end Multiset
namespace Finset
variable {s t : Finset α} {a : α}
/-- Finsets form an order-connected suborder of multisets. -/
lemma ordConnected_range_val : Set.OrdConnected (Set.range val : Set <| Multiset α) :=
⟨by rintro _ _ _ ⟨s, rfl⟩ t ht; exact ⟨⟨t, Multiset.nodup_of_le ht.2 s.2⟩, rfl⟩⟩
/-- Finsets form an order-connected suborder of sets. -/
lemma ordConnected_range_coe : Set.OrdConnected (Set.range ((↑) : Finset α → Set α)) :=
⟨by rintro _ _ _ ⟨s, rfl⟩ t ht; exact ⟨_, (s.finite_toSet.subset ht.2).coe_toFinset⟩⟩
@[simp] lemma val_wcovBy_val : s.1 ⩿ t.1 ↔ s ⩿ t :=
ordConnected_range_val.apply_wcovBy_apply_iff ⟨⟨_, val_injective⟩, val_le_iff⟩
@[simp] lemma val_covBy_val : s.1 ⋖ t.1 ↔ s ⋖ t :=
ordConnected_range_val.apply_covBy_apply_iff ⟨⟨_, val_injective⟩, val_le_iff⟩
@[simp] lemma coe_wcovBy_coe : (s : Set α) ⩿ t ↔ s ⩿ t :=
ordConnected_range_coe.apply_wcovBy_apply_iff ⟨⟨_, coe_injective⟩, coe_subset⟩
@[simp] lemma coe_covBy_coe : (s : Set α) ⋖ t ↔ s ⋖ t :=
ordConnected_range_coe.apply_covBy_apply_iff ⟨⟨_, coe_injective⟩, coe_subset⟩
alias ⟨_, _root_.WCovBy.finset_val⟩ := val_wcovBy_val
alias ⟨_, _root_.CovBy.finset_val⟩ := val_covBy_val
alias ⟨_, _root_.WCovBy.finset_coe⟩ := coe_wcovBy_coe
alias ⟨_, _root_.CovBy.finset_coe⟩ := coe_covBy_coe
@[simp] lemma covBy_cons (ha : a ∉ s) : s ⋖ s.cons a ha := by simp [← val_covBy_val]
lemma _root_.CovBy.exists_finset_cons (h : s ⋖ t) : ∃ a, ∃ ha : a ∉ s, s.cons a ha = t :=
let ⟨a, ha, hst⟩ := ssubset_iff_exists_cons_subset.1 h.lt
⟨a, ha, (hst.eq_of_not_ssuperset <| h.2 <| ssubset_cons _).symm⟩
lemma covBy_iff_exists_cons : s ⋖ t ↔ ∃ a, ∃ ha : a ∉ s, s.cons a ha = t :=
⟨CovBy.exists_finset_cons, by rintro ⟨a, ha, rfl⟩; exact covBy_cons _⟩
lemma _root_.CovBy.card_finset (h : s ⋖ t) : s.card ⋖ t.card := (val_covBy_val.2 h).card_multiset
section DecidableEq
variable [DecidableEq α]
@[simp] lemma wcovBy_insert (s : Finset α) (a : α) : s ⩿ insert a s := by simp [← coe_wcovBy_coe]
@[simp] lemma erase_wcovBy (s : Finset α) (a : α) : s.erase a ⩿ s := by simp [← coe_wcovBy_coe]
lemma covBy_insert (ha : a ∉ s) : s ⋖ insert a s :=
(wcovBy_insert _ _).covBy_of_lt <| ssubset_insert ha
@[simp] lemma empty_covBy_singleton (a : α) : ∅ ⋖ ({a} : Finset α) :=
insert_empty_eq (β := Finset α) a ▸ covBy_insert <| notMem_empty a
@[simp] lemma erase_covBy (ha : a ∈ s) : s.erase a ⋖ s := ⟨erase_ssubset ha, (erase_wcovBy _ _).2⟩
lemma _root_.CovBy.exists_finset_insert (h : s ⋖ t) : ∃ a ∉ s, insert a s = t := by
simpa using h.exists_finset_cons
lemma _root_.CovBy.exists_finset_erase (h : s ⋖ t) : ∃ a ∈ t, t.erase a = s := by
simpa only [← coe_inj, coe_erase] using h.finset_coe.exists_set_sdiff_singleton
lemma covBy_iff_exists_insert : s ⋖ t ↔ ∃ a ∉ s, insert a s = t := by
simp only [← coe_covBy_coe, Set.covBy_iff_exists_insert, ← coe_inj, coe_insert, mem_coe]
lemma covBy_iff_card_sdiff_eq_one : t ⋖ s ↔ t ⊆ s ∧ (s \ t).card = 1 := by
rw [covBy_iff_exists_insert]
constructor
· rintro ⟨a, ha, rfl⟩
simp [*]
· simp_rw [card_eq_one]
rintro ⟨hts, a, ha⟩
refine ⟨a, (mem_sdiff.1 <| superset_of_eq ha <| mem_singleton_self _).2, ?_⟩
rw [insert_eq, ← ha, sdiff_union_of_subset hts]
lemma covBy_iff_exists_erase : s ⋖ t ↔ ∃ a ∈ t, t.erase a = s := by
simp only [← coe_covBy_coe, Set.covBy_iff_exists_sdiff_singleton, ← coe_inj, coe_erase, mem_coe]
end DecidableEq
@[simp] lemma isAtom_singleton (a : α) : IsAtom ({a} : Finset α) :=
⟨singleton_ne_empty a, fun _ ↦ eq_empty_of_ssubset_singleton⟩
protected lemma isAtom_iff : IsAtom s ↔ ∃ a, s = {a} := by
simp [← bot_covBy_iff, covBy_iff_exists_cons, eq_comm]
section Fintype
variable [Fintype α] [DecidableEq α]
lemma isCoatom_compl_singleton (a : α) : IsCoatom ({a}ᶜ : Finset α) := (isAtom_singleton a).compl
protected lemma isCoatom_iff : IsCoatom s ↔ ∃ a, s = {a}ᶜ := by
simp_rw [← isAtom_compl, Finset.isAtom_iff, compl_eq_iff_isCompl, eq_compl_iff_isCompl]
end Fintype
/-- Finsets are multiset-graded. This is not very meaningful mathematically but rather a handy way
to record that the inclusion `Finset α ↪ Multiset α` preserves the covering relation. -/
instance instGradeMinOrder_multiset : GradeMinOrder (Multiset α) (Finset α) where
grade := val
grade_strictMono := val_strictMono
covBy_grade _ _ := CovBy.finset_val
isMin_grade s hs := by rw [isMin_iff_eq_bot.1 hs]; exact isMin_bot
@[simp] lemma grade_multiset_eq (s : Finset α) : grade (Multiset α) s = s.1 := rfl
instance instGradeMinOrder_nat : GradeMinOrder ℕ (Finset α) where
grade := card
grade_strictMono := card_strictMono
covBy_grade _ _ := CovBy.card_finset
isMin_grade s hs := by rw [isMin_iff_eq_bot.1 hs]; exact isMin_bot
@[simp] lemma grade_eq (s : Finset α) : grade ℕ s = s.card := rfl
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Fold.lean | import Mathlib.Data.Finset.Basic
import Mathlib.Data.Finset.Image
import Mathlib.Data.Multiset.Fold
import Mathlib.Data.Finset.Lattice.Lemmas
/-!
# The fold operation for a commutative associative operation over a finset.
-/
assert_not_exists Monoid
namespace Finset
open Multiset
variable {α β γ : Type*}
/-! ### fold -/
section Fold
variable (op : β → β → β) [hc : Std.Commutative op] [ha : Std.Associative op]
local notation a " * " b => op a b
/-- `fold op b f s` folds the commutative associative operation `op` over the
`f`-image of `s`, i.e. `fold (+) b f {1,2,3} = f 1 + f 2 + f 3 + b`. -/
def fold (b : β) (f : α → β) (s : Finset α) : β :=
(s.1.map f).fold op b
variable {op} {f : α → β} {b : β} {s : Finset α} {a : α}
@[simp]
theorem fold_empty : (∅ : Finset α).fold op b f = b :=
rfl
@[simp]
theorem fold_cons (h : a ∉ s) : (cons a s h).fold op b f = f a * s.fold op b f := by
dsimp only [fold]
rw [cons_val, Multiset.map_cons, fold_cons_left]
@[simp]
theorem fold_insert [DecidableEq α] (h : a ∉ s) :
(insert a s).fold op b f = f a * s.fold op b f := by
unfold fold
rw [insert_val, ndinsert_of_notMem h, Multiset.map_cons, fold_cons_left]
@[simp]
theorem fold_singleton : ({a} : Finset α).fold op b f = f a * b :=
rfl
@[simp]
theorem fold_map {g : γ ↪ α} {s : Finset γ} : (s.map g).fold op b f = s.fold op b (f ∘ g) := by
simp only [fold, map, Multiset.map_map]
@[simp]
theorem fold_image [DecidableEq α] {g : γ → α} {s : Finset γ}
(H : Set.InjOn g s) : (s.image g).fold op b f = s.fold op b (f ∘ g) := by
simp only [fold, image_val_of_injOn H, Multiset.map_map]
@[congr]
theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g := by
rw [fold, fold, map_congr rfl H]
theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} :
(s.fold op (b₁ * b₂) fun x => f x * g x) = s.fold op b₁ f * s.fold op b₂ g := by
simp only [fold, fold_distrib]
theorem fold_const [hd : Decidable (s = ∅)] (c : β) (h : op c (op b c) = op b c) :
Finset.fold op b (fun _ => c) s = if s = ∅ then b else op b c := by
classical
induction s using Finset.induction_on generalizing hd with
| empty => simp
| insert x s hx IH =>
simp only [Finset.fold_insert hx, IH, if_false, Finset.insert_ne_empty]
split_ifs
· rw [hc.comm]
· exact h
theorem fold_hom {op' : γ → γ → γ} [Std.Commutative op'] [Std.Associative op'] {m : β → γ}
(hm : ∀ x y, m (op x y) = op' (m x) (m y)) :
(s.fold op' (m b) fun x => m (f x)) = m (s.fold op b f) := by
rw [fold, fold, ← Multiset.fold_hom op hm, Multiset.map_map]
simp only [Function.comp_apply]
theorem fold_disjUnion {s₁ s₂ : Finset α} {b₁ b₂ : β} (h) :
(s₁.disjUnion s₂ h).fold op (b₁ * b₂) f = s₁.fold op b₁ f * s₂.fold op b₂ f :=
(congr_arg _ <| Multiset.map_add _ _ _).trans (Multiset.fold_add _ _ _ _ _)
theorem fold_union_inter [DecidableEq α] {s₁ s₂ : Finset α} {b₁ b₂ : β} :
((s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f) = s₁.fold op b₂ f * s₂.fold op b₁ f := by
unfold fold
rw [← fold_add op, ← Multiset.map_add, union_val, inter_val, union_add_inter, Multiset.map_add,
hc.comm, fold_add]
@[simp]
theorem fold_insert_idem [DecidableEq α] [hi : Std.IdempotentOp op] :
(insert a s).fold op b f = f a * s.fold op b f := by
by_cases h : a ∈ s
· rw [← insert_erase h]
simp [← ha.assoc, hi.idempotent]
· apply fold_insert h
theorem fold_image_idem [DecidableEq α] {g : γ → α} {s : Finset γ} [hi : Std.IdempotentOp op] :
(image g s).fold op b f = s.fold op b (f ∘ g) := by
induction s using Finset.cons_induction with
| empty => rw [fold_empty, image_empty, fold_empty]
| cons x xs hx ih =>
haveI := Classical.decEq γ
rw [fold_cons, cons_eq_insert, image_insert, fold_insert_idem, ih]
simp only [Function.comp_apply]
/-- A stronger version of `Finset.fold_ite`, but relies on
an explicit proof of idempotency on the seed element, rather
than relying on typeclass idempotency over the whole type. -/
theorem fold_ite' {g : α → β} (hb : op b b = b) (p : α → Prop) [DecidablePred p] :
Finset.fold op b (fun i => ite (p i) (f i) (g i)) s =
op (Finset.fold op b f (s.filter p)) (Finset.fold op b g (s.filter fun i => ¬p i)) := by
classical
induction s using Finset.induction_on with
| empty => simp [hb]
| insert x s hx IH =>
simp only [Finset.fold_insert hx]
split_ifs with h
· have : x ∉ Finset.filter p s := by simp [hx]
simp [Finset.filter_insert, h, Finset.fold_insert this, ha.assoc, IH]
· have : x ∉ Finset.filter (fun i => ¬ p i) s := by simp [hx]
simp [Finset.filter_insert, h, Finset.fold_insert this, IH, ← ha.assoc, hc.comm]
/-- A weaker version of `Finset.fold_ite'`,
relying on typeclass idempotency over the whole type,
instead of solely on the seed element.
However, this is easier to use because it does not generate side goals. -/
theorem fold_ite [Std.IdempotentOp op] {g : α → β} (p : α → Prop) [DecidablePred p] :
Finset.fold op b (fun i => ite (p i) (f i) (g i)) s =
op (Finset.fold op b f (s.filter p)) (Finset.fold op b g (s.filter fun i => ¬p i)) :=
fold_ite' (Std.IdempotentOp.idempotent _) _
theorem fold_op_rel_iff_and {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ r x y ∧ r x z)
{c : β} : r c (s.fold op b f) ↔ r c b ∧ ∀ x ∈ s, r c (f x) := by
classical
induction s using Finset.induction_on with
| empty => simp
| insert a s ha IH =>
rw [Finset.fold_insert ha, hr, IH, ← and_assoc, @and_comm (r c (f a)), and_assoc]
simp
theorem fold_op_rel_iff_or {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ r x y ∨ r x z)
{c : β} : r c (s.fold op b f) ↔ r c b ∨ ∃ x ∈ s, r c (f x) := by
classical
induction s using Finset.induction_on with
| empty => simp
| insert a s ha IH =>
rw [Finset.fold_insert ha, hr, IH, ← or_assoc, @or_comm (r c (f a)), or_assoc]
simp
@[simp]
theorem fold_union_empty_singleton [DecidableEq α] (s : Finset α) :
Finset.fold (· ∪ ·) ∅ singleton s = s := by
induction s using Finset.induction_on with
| empty => simp only [fold_empty]
| insert a s has ih => rw [fold_insert has, ih, insert_eq]
theorem fold_sup_bot_singleton [DecidableEq α] (s : Finset α) :
Finset.fold (· ⊔ ·) ⊥ singleton s = s :=
fold_union_empty_singleton s
section Order
variable [LinearOrder β] (c : β)
theorem le_fold_min : c ≤ s.fold min b f ↔ c ≤ b ∧ ∀ x ∈ s, c ≤ f x :=
fold_op_rel_iff_and le_min_iff
theorem fold_min_le : s.fold min b f ≤ c ↔ b ≤ c ∨ ∃ x ∈ s, f x ≤ c := by
change _ ≥ _ ↔ _
apply fold_op_rel_iff_or
intro x y z
change _ ≤ _ ↔ _
exact min_le_iff
theorem lt_fold_min : c < s.fold min b f ↔ c < b ∧ ∀ x ∈ s, c < f x :=
fold_op_rel_iff_and lt_min_iff
theorem fold_min_lt : s.fold min b f < c ↔ b < c ∨ ∃ x ∈ s, f x < c := by
change _ > _ ↔ _
apply fold_op_rel_iff_or
intro x y z
change _ < _ ↔ _
exact min_lt_iff
theorem fold_max_le : s.fold max b f ≤ c ↔ b ≤ c ∧ ∀ x ∈ s, f x ≤ c := by
change _ ≥ _ ↔ _
apply fold_op_rel_iff_and
intro x y z
change _ ≤ _ ↔ _
exact max_le_iff
theorem le_fold_max : c ≤ s.fold max b f ↔ c ≤ b ∨ ∃ x ∈ s, c ≤ f x :=
fold_op_rel_iff_or le_max_iff
theorem fold_max_lt : s.fold max b f < c ↔ b < c ∧ ∀ x ∈ s, f x < c := by
change _ > _ ↔ _
apply fold_op_rel_iff_and
intro x y z
change _ < _ ↔ _
exact max_lt_iff
theorem lt_fold_max : c < s.fold max b f ↔ c < b ∨ ∃ x ∈ s, c < f x :=
fold_op_rel_iff_or lt_max_iff
end Order
end Fold
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/MulAntidiagonal.lean | import Mathlib.Algebra.Order.Monoid.Defs
import Mathlib.Data.Set.MulAntidiagonal
import Mathlib.Algebra.Group.Pointwise.Set.Basic
/-! # Multiplication antidiagonal as a `Finset`.
We construct the `Finset` of all pairs
of an element in `s` and an element in `t` that multiply to `a`,
given that `s` and `t` are well-ordered. -/
namespace Set
open Pointwise
variable {α : Type*} {s t : Set α}
@[to_additive]
theorem IsPWO.mul [CommMonoid α] [PartialOrder α] [IsOrderedCancelMonoid α]
(hs : s.IsPWO) (ht : t.IsPWO) : IsPWO (s * t) := by
rw [← image_mul_prod]
exact (hs.prod ht).image_of_monotone (monotone_fst.mul' monotone_snd)
variable [CommMonoid α] [LinearOrder α] [IsOrderedCancelMonoid α]
@[to_additive]
theorem IsWF.mul (hs : s.IsWF) (ht : t.IsWF) : IsWF (s * t) :=
(hs.isPWO.mul ht.isPWO).isWF
@[to_additive]
theorem IsWF.min_mul (hs : s.IsWF) (ht : t.IsWF) (hsn : s.Nonempty) (htn : t.Nonempty) :
(hs.mul ht).min (hsn.mul htn) = hs.min hsn * ht.min htn := by
refine le_antisymm (IsWF.min_le _ _ (mem_mul.2 ⟨_, hs.min_mem _, _, ht.min_mem _, rfl⟩)) ?_
rw [IsWF.le_min_iff]
rintro _ ⟨x, hx, y, hy, rfl⟩
exact mul_le_mul' (hs.min_le _ hx) (ht.min_le _ hy)
end Set
namespace Finset
open Pointwise
variable {α : Type*}
variable [CommMonoid α] [PartialOrder α] [IsOrderedCancelMonoid α]
{s t : Set α} (hs : s.IsPWO) (ht : t.IsPWO) (a : α)
/-- `Finset.mulAntidiagonal hs ht a` is the set of all pairs of an element in `s` and an
element in `t` that multiply to `a`, but its construction requires proofs that `s` and `t` are
well-ordered. -/
@[to_additive /-- `Finset.addAntidiagonal hs ht a` is the set of all pairs of an element in
`s` and an element in `t` that add to `a`, but its construction requires proofs that `s` and `t` are
well-ordered. -/]
noncomputable def mulAntidiagonal : Finset (α × α) :=
(Set.MulAntidiagonal.finite_of_isPWO hs ht a).toFinset
variable {hs ht a} {u : Set α} {hu : u.IsPWO} {x : α × α}
@[to_additive (attr := simp)]
theorem mem_mulAntidiagonal : x ∈ mulAntidiagonal hs ht a ↔ x.1 ∈ s ∧ x.2 ∈ t ∧ x.1 * x.2 = a := by
simp only [mulAntidiagonal, Set.Finite.mem_toFinset, Set.mem_mulAntidiagonal]
@[to_additive]
theorem mulAntidiagonal_mono_left (h : u ⊆ s) : mulAntidiagonal hu ht a ⊆ mulAntidiagonal hs ht a :=
Set.Finite.toFinset_mono <| Set.mulAntidiagonal_mono_left h
@[to_additive]
theorem mulAntidiagonal_mono_right (h : u ⊆ t) :
mulAntidiagonal hs hu a ⊆ mulAntidiagonal hs ht a :=
Set.Finite.toFinset_mono <| Set.mulAntidiagonal_mono_right h
@[to_additive]
theorem swap_mem_mulAntidiagonal :
x.swap ∈ Finset.mulAntidiagonal hs ht a ↔ x ∈ Finset.mulAntidiagonal ht hs a := by
simp
@[to_additive]
theorem support_mulAntidiagonal_subset_mul : { a | (mulAntidiagonal hs ht a).Nonempty } ⊆ s * t :=
fun a ⟨b, hb⟩ => by
rw [mem_mulAntidiagonal] at hb
exact ⟨b.1, hb.1, b.2, hb.2⟩
@[to_additive]
theorem isPWO_support_mulAntidiagonal : { a | (mulAntidiagonal hs ht a).Nonempty }.IsPWO :=
(hs.mul ht).mono support_mulAntidiagonal_subset_mul
@[to_additive]
theorem mulAntidiagonal_min_mul_min {α} [CommMonoid α] [LinearOrder α] [IsOrderedCancelMonoid α]
{s t : Set α} (hs : s.IsWF) (ht : t.IsWF) (hns : s.Nonempty) (hnt : t.Nonempty) :
mulAntidiagonal hs.isPWO ht.isPWO (hs.min hns * ht.min hnt) = {(hs.min hns, ht.min hnt)} := by
ext ⟨a, b⟩
simp only [mem_mulAntidiagonal, mem_singleton, Prod.ext_iff]
constructor
· rintro ⟨has, hat, hst⟩
obtain rfl :=
(hs.min_le hns has).eq_of_not_lt fun hlt =>
(mul_lt_mul_of_lt_of_le hlt <| ht.min_le hnt hat).ne' hst
exact ⟨rfl, mul_left_cancel hst⟩
· rintro ⟨rfl, rfl⟩
exact ⟨hs.min_mem _, ht.min_mem _, rfl⟩
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Functor.lean | import Batteries.Control.AlternativeMonad
import Mathlib.Data.Finset.Lattice.Union
import Mathlib.Data.Finset.NAry
import Mathlib.Data.Multiset.Functor
/-!
# Functoriality of `Finset`
This file defines the functor structure of `Finset`.
## TODO
Currently, all instances are classical because the functor classes want to run over all types. If
instead we could state that a functor is lawful/applicative/traversable... between two given types,
then we could provide the instances for types with decidable equality.
-/
universe u
open Function
namespace Finset
/-! ### Functor -/
section Functor
variable {α β : Type u} [∀ P, Decidable P]
/-- Because `Finset.image` requires a `DecidableEq` instance for the target type, we can only
construct `Functor Finset` when working classically. -/
protected instance functor : Functor Finset where map f s := s.image f
instance lawfulFunctor : LawfulFunctor Finset where
id_map _ := image_id
comp_map _ _ _ := image_image.symm
map_const {α} {β} := by simp only [Functor.mapConst, Functor.map]
@[simp]
theorem fmap_def {s : Finset α} (f : α → β) : f <$> s = s.image f := rfl
end Functor
/-! ### Pure -/
protected instance pure : Pure Finset :=
⟨fun x => {x}⟩
@[simp]
theorem pure_def {α} : (pure : α → Finset α) = singleton := rfl
/-! ### Applicative functor -/
section Applicative
variable {α β : Type u} [∀ P, Decidable P]
protected instance applicative : Applicative Finset :=
{ Finset.functor, Finset.pure with
seq := fun t s => t.sup fun f => (s ()).image f
seqLeft := fun s t => if t () = ∅ then ∅ else s
seqRight := fun s t => if s = ∅ then ∅ else t () }
@[simp]
theorem seq_def (s : Finset α) (t : Finset (α → β)) : t <*> s = t.sup fun f => s.image f :=
rfl
@[simp]
theorem seqLeft_def (s : Finset α) (t : Finset β) : s <* t = if t = ∅ then ∅ else s :=
rfl
@[simp]
theorem seqRight_def (s : Finset α) (t : Finset β) : s *> t = if s = ∅ then ∅ else t :=
rfl
/-- `Finset.image₂` in terms of monadic operations. Note that this can't be taken as the definition
because of the lack of universe polymorphism. -/
theorem image₂_def {α β γ : Type u} (f : α → β → γ) (s : Finset α) (t : Finset β) :
image₂ f s t = f <$> s <*> t := by
ext
simp [mem_sup]
instance lawfulApplicative : LawfulApplicative Finset :=
{ Finset.lawfulFunctor with
seqLeft_eq := fun s t => by
rw [seq_def, fmap_def, seqLeft_def]
obtain rfl | ht := t.eq_empty_or_nonempty
· simp_rw [image_empty, if_true]
exact (sup_bot _).symm
· ext a
rw [if_neg ht.ne_empty, mem_sup]
refine ⟨fun ha => ⟨const _ a, mem_image_of_mem _ ha, mem_image_const_self.2 ht⟩, ?_⟩
rintro ⟨f, hf, ha⟩
rw [mem_image] at hf ha
obtain ⟨b, hb, rfl⟩ := hf
obtain ⟨_, _, rfl⟩ := ha
exact hb
seqRight_eq := fun s t => by
rw [seq_def, fmap_def, seqRight_def]
obtain rfl | hs := s.eq_empty_or_nonempty
· rw [if_pos rfl, image_empty, sup_empty, bot_eq_empty]
· ext a
rw [if_neg hs.ne_empty, mem_sup]
refine ⟨fun ha => ⟨id, mem_image_const_self.2 hs, by rwa [image_id]⟩, ?_⟩
rintro ⟨f, hf, ha⟩
rw [mem_image] at hf ha
obtain ⟨b, hb, rfl⟩ := ha
obtain ⟨_, _, rfl⟩ := hf
exact hb
pure_seq := fun f s => by simp only [pure_def, seq_def, sup_singleton, fmap_def]
map_pure := fun _ _ => image_singleton _ _
seq_pure := fun _ _ => sup_singleton_apply _ _
seq_assoc := fun s t u => by
ext a
simp_rw [seq_def, fmap_def]
simp only [mem_sup, mem_image]
constructor
· rintro ⟨g, hg, b, ⟨f, hf, a, ha, rfl⟩, rfl⟩
exact ⟨g ∘ f, ⟨comp g, ⟨g, hg, rfl⟩, f, hf, rfl⟩, a, ha, rfl⟩
· rintro ⟨c, ⟨_, ⟨g, hg, rfl⟩, f, hf, rfl⟩, a, ha, rfl⟩
exact ⟨g, hg, f a, ⟨f, hf, a, ha, rfl⟩, rfl⟩ }
instance commApplicative : CommApplicative Finset :=
{ Finset.lawfulApplicative with
commutative_prod := fun s t => by
simp_rw [seq_def, fmap_def, sup_image, sup_eq_biUnion]
change (s.biUnion fun a => t.image fun b => (a, b))
= t.biUnion fun b => s.image fun a => (a, b)
trans s ×ˢ t <;> [rw [product_eq_biUnion]; rw [product_eq_biUnion_right]] }
end Applicative
/-! ### Monad -/
section Monad
variable [∀ P, Decidable P]
instance : Monad Finset :=
{ Finset.applicative with bind := sup }
@[simp]
theorem bind_def {α β} : (· >>= ·) = sup (α := Finset α) (β := β) :=
rfl
instance : LawfulMonad Finset :=
{ Finset.lawfulApplicative with
bind_pure_comp := fun _ _ => sup_singleton_apply _ _
bind_map := fun _ _ => rfl
pure_bind := fun _ _ => sup_singleton
bind_assoc := fun s f g => by simp only [bind, sup_eq_biUnion, biUnion_biUnion] }
end Monad
/-! ### Alternative functor -/
section Alternative
variable [∀ P, Decidable P]
instance : AlternativeMonad Finset where
orElse s t := s ∪ t ()
failure := ∅
instance : LawfulAlternative Finset where
map_failure _ := Finset.image_empty _
failure_seq _ := Finset.sup_empty
orElse_failure _ := Finset.union_empty _
failure_orElse _ := Finset.empty_union _
orElse_assoc _ _ _ := Finset.union_assoc _ _ _ |>.symm
map_orElse _ _ _ := Finset.image_union _ _
end Alternative
/-! ### Traversable functor -/
section Traversable
variable {α β γ : Type u} {F G : Type u → Type u} [Applicative F] [Applicative G]
[CommApplicative F] [CommApplicative G]
/-- Traverse function for `Finset`. -/
def traverse [DecidableEq β] (f : α → F β) (s : Finset α) : F (Finset β) :=
Multiset.toFinset <$> Multiset.traverse f s.1
@[simp]
theorem id_traverse [DecidableEq α] (s : Finset α) : traverse (pure : α → Id α) s = pure s := by
rw [traverse, Multiset.id_traverse]
exact s.val_toFinset
open scoped Classical in
@[simp]
theorem map_comp_coe (h : α → β) :
Functor.map h ∘ Multiset.toFinset = Multiset.toFinset ∘ Functor.map h :=
funext fun _ => image_toFinset
open scoped Classical in
@[simp]
theorem map_comp_coe_apply (h : α → β) (s : Multiset α) :
s.toFinset.image h = (h <$> s).toFinset :=
congrFun (map_comp_coe h) s
open scoped Classical in
theorem map_traverse (g : α → G β) (h : β → γ) (s : Finset α) :
Functor.map h <$> traverse g s = traverse (Functor.map h ∘ g) s := by
unfold traverse
simp only [Functor.map_map, fmap_def, map_comp_coe_apply, Multiset.fmap_def, ←
Multiset.map_traverse]
end Traversable
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Range.lean | import Mathlib.Data.Finset.Insert
import Mathlib.Data.Multiset.Range
import Mathlib.Order.Interval.Set.Defs
/-!
# Finite sets made of a range of elements.
## Main declarations
### Finset constructions
* `Finset.range`: For any `n : ℕ`, `range n` is equal to `{0, 1, ..., n - 1} ⊆ ℕ`.
This convention is consistent with other languages and normalizes `card (range n) = n`.
Beware, `n` is not in `range n`.
## Tags
finite sets, finset
-/
-- Assert that we define `Finset` without the material on `List.sublists`.
-- Note that we cannot use `List.sublists` itself as that is defined very early.
assert_not_exists List.sublistsLen Multiset.powerset CompleteLattice IsOrderedMonoid
universe u
variable {α : Type*} {β : Type*} {γ : Type*}
namespace Finset
open Multiset Subtype Function
/-! ### range -/
section Range
open Nat
variable {n m l : ℕ}
/-- `range n` is the set of natural numbers less than `n`. -/
def range (n : ℕ) : Finset ℕ :=
⟨_, nodup_range n⟩
@[simp]
theorem range_val (n : ℕ) : (range n).1 = Multiset.range n :=
rfl
@[simp, grind =]
theorem mem_range : m ∈ range n ↔ m < n :=
Multiset.mem_range
@[simp, grind =, norm_cast]
theorem coe_range (n : ℕ) : (range n : Set ℕ) = Set.Iio n :=
Set.ext fun _ => mem_range
@[simp]
theorem range_zero : range 0 = ∅ :=
rfl
@[simp]
theorem range_one : range 1 = {0} :=
rfl
theorem range_add_one : range (n + 1) = insert n (range n) := by grind
@[deprecated range_add_one (since := "2025-09-08")]
theorem range_succ : range (succ n) = insert n (range n) := range_add_one
theorem notMem_range_self : n ∉ range n := by grind
@[deprecated (since := "2025-05-23")] alias not_mem_range_self := notMem_range_self
theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := by grind
@[grind =]
theorem range_subset {n s} : range n ⊆ s ↔ ∀ x, x < n → x ∈ s := by grind
theorem subset_range {s n} : s ⊆ range n ↔ ∀ x, x ∈ s → x < n := by grind
@[simp]
theorem range_subset_range {n m} : range n ⊆ range m ↔ n ≤ m := by grind
theorem range_mono : Monotone range := fun _ _ => range_subset_range.2
@[gcongr] alias ⟨_, _root_.GCongr.finset_range_subset_of_le⟩ := range_subset_range
theorem mem_range_succ_iff {a b : ℕ} : a ∈ range b.succ ↔ a ≤ b := by grind
theorem mem_range_le {n x : ℕ} (hx : x ∈ range n) : x ≤ n := by grind
theorem mem_range_sub_ne_zero {n x : ℕ} (hx : x ∈ range n) : n - x ≠ 0 := by grind
@[simp, grind =]
theorem nonempty_range_iff : (range n).Nonempty ↔ n ≠ 0 :=
⟨fun ⟨k, hk⟩ => by grind, fun h => ⟨0, by grind⟩⟩
@[aesop safe apply (rule_sets := [finsetNonempty])]
protected alias ⟨_, Aesop.range_nonempty⟩ := nonempty_range_iff
@[simp]
theorem range_eq_empty_iff : range n = ∅ ↔ n = 0 := by
grind [nonempty_range_iff]
@[aesop safe apply (rule_sets := [finsetNonempty])]
theorem nonempty_range_add_one : (range <| n + 1).Nonempty :=
nonempty_range_iff.2 n.succ_ne_zero
@[deprecated nonempty_range_add_one (since := "2025-09-08")]
alias nonempty_range_succ := nonempty_range_add_one
lemma range_nontrivial {n : ℕ} (hn : 1 < n) : (range n).Nontrivial := by
rw [Finset.Nontrivial, Finset.coe_range]
exact ⟨0, by grind, 1, hn, Nat.zero_ne_one⟩
theorem exists_nat_subset_range (s : Finset ℕ) : ∃ n : ℕ, s ⊆ range n :=
s.induction_on (by simp) fun a _ _ ⟨n, hn⟩ => ⟨max (a + 1) n, by grind⟩
end Range
end Finset
open Finset
/-- Equivalence between the set of natural numbers which are `≥ k` and `ℕ`, given by `n → n - k`. -/
def notMemRangeEquiv (k : ℕ) : { n // n ∉ range k } ≃ ℕ where
toFun i := i.1 - k
invFun j := ⟨j + k, by simp⟩
left_inv := by grind
right_inv := by grind
@[simp]
theorem coe_notMemRangeEquiv (k : ℕ) :
(notMemRangeEquiv k : { n // n ∉ range k } → ℕ) = fun (i : { n // n ∉ range k }) => i - k :=
rfl
@[simp]
theorem coe_notMemRangeEquiv_symm (k : ℕ) :
((notMemRangeEquiv k).symm : ℕ → { n // n ∉ range k }) = fun j => ⟨j + k, by simp⟩ :=
rfl |
.lake/packages/mathlib/Mathlib/Data/Finset/CastCard.lean | import Mathlib.Data.Finset.Card
import Mathlib.Data.Int.Cast.Basic
/-!
# Cardinality of a finite set and subtraction
This file contains results on the cardinality of a `Finset` and subtraction, by casting the
cardinality as element of an `AddGroupWithOne`.
## Main results
* `Finset.cast_card_erase_of_mem`: erasing an element of a finset decrements the cardinality
(avoiding `ℕ` subtraction).
* `Finset.cast_card_inter`, `Finset.cast_card_union`: inclusion/exclusion principle.
* `Finset.cast_card_sdiff`: cardinality of `t \ s` is the difference of cardinalities if `s ⊆ t`.
-/
assert_not_exists MonoidWithZero IsOrderedMonoid
open Nat
namespace Finset
variable {α R : Type*} {s t : Finset α} {a b : α}
variable [DecidableEq α] [AddGroupWithOne R]
/-- $\#(s \setminus \{a\}) = \#s - 1$ if $a \in s$.
This result is casted to any additive group with 1,
so that we don't have to work with `ℕ`-subtraction. -/
-- @[simp] -- removed because LHS is not in simp normal form
theorem cast_card_erase_of_mem (hs : a ∈ s) : (#(s.erase a) : R) = #s - 1 := by
rw [← card_erase_add_one hs, cast_add, cast_one, eq_sub_iff_add_eq]
lemma cast_card_inter : (#(s ∩ t) : R) = #s + #t - #(s ∪ t) := by
rw [eq_sub_iff_add_eq, ← cast_add, card_inter_add_card_union, cast_add]
lemma cast_card_union : (#(s ∪ t) : R) = #s + #t - #(s ∩ t) := by
rw [eq_sub_iff_add_eq, ← cast_add, card_union_add_card_inter, cast_add]
lemma cast_card_sdiff (h : s ⊆ t) : (#(t \ s) : R) = #t - #s := by
rw [card_sdiff_of_subset h, Nat.cast_sub (card_mono h)]
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Attach.lean | import Mathlib.Data.Finset.Defs
import Mathlib.Data.Multiset.MapFold
/-!
# Attaching a proof of membership to a finite set
## Main declarations
* `Finset.attach`: Given `s : Finset α`, `attach s` forms a finset of elements of the subtype
`{a // a ∈ s}`; in other words, it attaches elements to a proof of membership in the set.
## Tags
finite sets, finset
-/
-- Assert that we define `Finset` without the material on `List.sublists`.
-- Note that we cannot use `List.sublists` itself as that is defined very early.
assert_not_exists List.sublistsLen Multiset.powerset CompleteLattice IsOrderedMonoid
open Multiset Subtype Function
universe u
variable {α : Type*} {β : Type*} {γ : Type*}
namespace Finset
-- TODO: these should be global attributes, but this will require fixing other files
attribute [local trans] Subset.trans Superset.trans
/-! ### attach -/
/-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype
`{x // x ∈ s}`. -/
def attach (s : Finset α) : Finset { x // x ∈ s } :=
⟨Multiset.attach s.1, nodup_attach.2 s.2⟩
@[simp]
theorem attach_val (s : Finset α) : s.attach.1 = s.1.attach :=
rfl
@[simp, grind ←]
theorem mem_attach (s : Finset α) : ∀ x, x ∈ s.attach :=
Multiset.mem_attach _
@[simp, norm_cast]
theorem coe_attach (s : Finset α) : (s.attach : Set s) = Set.univ := by ext; simp
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/PiInduction.lean | import Mathlib.Data.Finset.Max
import Mathlib.Data.Finset.Sigma
import Mathlib.Data.Fintype.Basic
/-!
# Induction principles for `∀ i, Finset (α i)`
In this file we prove a few induction principles for functions `Π i : ι, Finset (α i)` defined on a
finite type.
* `Finset.induction_on_pi` is a generic lemma that requires only `[Finite ι]`, `[DecidableEq ι]`,
and `[∀ i, DecidableEq (α i)]`; this version can be seen as a direct generalization of
`Finset.induction_on`.
* `Finset.induction_on_pi_max` and `Finset.induction_on_pi_min`: generalizations of
`Finset.induction_on_max`; these versions require `∀ i, LinearOrder (α i)` but assume
`∀ y ∈ g i, y < x` and `∀ y ∈ g i, x < y` respectively in the induction step.
## Tags
finite set, finite type, induction, function
-/
open Function
variable {ι : Type*} {α : ι → Type*} [Finite ι] [DecidableEq ι] [∀ i, DecidableEq (α i)]
namespace Finset
/-- General theorem for `Finset.induction_on_pi`-style induction principles. -/
theorem induction_on_pi_of_choice (r : ∀ i, α i → Finset (α i) → Prop)
(H_ex : ∀ (i) (s : Finset (α i)), s.Nonempty → ∃ x ∈ s, r i x (s.erase x))
{p : (∀ i, Finset (α i)) → Prop} (f : ∀ i, Finset (α i)) (h0 : p fun _ ↦ ∅)
(step :
∀ (g : ∀ i, Finset (α i)) (i : ι) (x : α i),
r i x (g i) → p g → p (update g i (insert x (g i)))) :
p f := by
cases nonempty_fintype ι
induction hs : univ.sigma f using Finset.strongInductionOn generalizing f with | _ s ihs
subst s
rcases eq_empty_or_nonempty (univ.sigma f) with he | hne
· convert h0 using 1
simpa [funext_iff] using he
· rcases sigma_nonempty.1 hne with ⟨i, -, hi⟩
rcases H_ex i (f i) hi with ⟨x, x_mem, hr⟩
set g := update f i ((f i).erase x) with hg
clear_value g
have hx' : x ∉ g i := by
rw [hg, update_self]
apply notMem_erase
rw [show f = update g i (insert x (g i)) by
rw [hg, update_idem, update_self, insert_erase x_mem, update_eq_self]] at hr ihs ⊢
clear hg
rw [update_self, erase_insert hx'] at hr
refine step _ _ _ hr (ihs (univ.sigma g) ?_ _ rfl)
rw [ssubset_iff_of_subset (sigma_mono (Subset.refl _) _)]
exacts [⟨⟨i, x⟩, mem_sigma.2 ⟨mem_univ _, by simp⟩, by simp [hx']⟩,
(@le_update_iff _ _ _ _ g g i _).2 ⟨subset_insert _ _, fun _ _ ↦ le_rfl⟩]
/-- Given a predicate on functions `∀ i, Finset (α i)` defined on a finite type, it is true on all
maps provided that it is true on `fun _ ↦ ∅` and for any function `g : ∀ i, Finset (α i)`, an index
`i : ι`, and `x ∉ g i`, `p g` implies `p (update g i (insert x (g i)))`.
See also `Finset.induction_on_pi_max` and `Finset.induction_on_pi_min` for specialized versions
that require `∀ i, LinearOrder (α i)`. -/
theorem induction_on_pi {p : (∀ i, Finset (α i)) → Prop} (f : ∀ i, Finset (α i)) (h0 : p fun _ ↦ ∅)
(step : ∀ (g : ∀ i, Finset (α i)) (i : ι), ∀ x ∉ g i, p g → p (update g i (insert x (g i)))) :
p f :=
induction_on_pi_of_choice (fun _ x s ↦ x ∉ s) (fun _ s ⟨x, hx⟩ ↦ ⟨x, hx, notMem_erase x s⟩) f
h0 step
/-- Given a predicate on functions `∀ i, Finset (α i)` defined on a finite type, it is true on all
maps provided that it is true on `fun _ ↦ ∅` and for any function `g : ∀ i, Finset (α i)`, an index
`i : ι`, and an element`x : α i` that is strictly greater than all elements of `g i`, `p g` implies
`p (update g i (insert x (g i)))`.
This lemma requires `LinearOrder` instances on all `α i`. See also `Finset.induction_on_pi` for a
version that needs `x ∉ g i` and does not need `∀ i, LinearOrder (α i)`. -/
theorem induction_on_pi_max [∀ i, LinearOrder (α i)] {p : (∀ i, Finset (α i)) → Prop}
(f : ∀ i, Finset (α i)) (h0 : p fun _ ↦ ∅)
(step :
∀ (g : ∀ i, Finset (α i)) (i : ι) (x : α i),
(∀ y ∈ g i, y < x) → p g → p (update g i (insert x (g i)))) :
p f :=
induction_on_pi_of_choice (fun _ x s ↦ ∀ y ∈ s, y < x)
(fun _ s hs ↦ ⟨s.max' hs, s.max'_mem hs, fun _ ↦ s.lt_max'_of_mem_erase_max' _⟩) f h0 step
/-- Given a predicate on functions `∀ i, Finset (α i)` defined on a finite type, it is true on all
maps provided that it is true on `fun _ ↦ ∅` and for any function `g : ∀ i, Finset (α i)`, an index
`i : ι`, and an element`x : α i` that is strictly less than all elements of `g i`, `p g` implies
`p (update g i (insert x (g i)))`.
This lemma requires `LinearOrder` instances on all `α i`. See also `Finset.induction_on_pi` for a
version that needs `x ∉ g i` and does not need `∀ i, LinearOrder (α i)`. -/
theorem induction_on_pi_min [∀ i, LinearOrder (α i)] {p : (∀ i, Finset (α i)) → Prop}
(f : ∀ i, Finset (α i)) (h0 : p fun _ ↦ ∅)
(step :
∀ (g : ∀ i, Finset (α i)) (i : ι) (x : α i),
(∀ y ∈ g i, x < y) → p g → p (update g i (insert x (g i)))) :
p f :=
induction_on_pi_max (α := fun i ↦ (α i)ᵒᵈ) _ h0 step
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Slice.lean | import Mathlib.Data.Fintype.Powerset
import Mathlib.Order.Antichain
import Mathlib.Order.Interval.Finset.Nat
import Mathlib.Algebra.BigOperators.Group.Finset.Basic
/-!
# `r`-sets and slice
This file defines the `r`-th slice of a set family and provides a way to say that a set family is
made of `r`-sets.
An `r`-set is a finset of cardinality `r` (aka of *size* `r`). The `r`-th slice of a set family is
the set family made of its `r`-sets.
## Main declarations
* `Set.Sized`: `A.Sized r` means that `A` only contains `r`-sets.
* `Finset.slice`: `A.slice r` is the set of `r`-sets in `A`.
## Notation
`A # r` is notation for `A.slice r` in scope `finset_family`.
-/
open Finset Nat
variable {α : Type*} {ι : Sort*} {κ : ι → Sort*}
namespace Set
variable {A B : Set (Finset α)} {s : Finset α} {r : ℕ}
/-! ### Families of `r`-sets -/
/-- `Sized r A` means that every Finset in `A` has size `r`. -/
def Sized (r : ℕ) (A : Set (Finset α)) : Prop := ∀ ⦃x⦄, x ∈ A → #x = r
theorem Sized.mono (h : A ⊆ B) (hB : B.Sized r) : A.Sized r := fun _x hx => hB <| h hx
@[simp] lemma sized_empty : (∅ : Set (Finset α)).Sized r := by simp [Sized]
@[simp] lemma sized_singleton : ({s} : Set (Finset α)).Sized r ↔ #s = r := by simp [Sized]
theorem sized_union : (A ∪ B).Sized r ↔ A.Sized r ∧ B.Sized r :=
⟨fun hA => ⟨hA.mono subset_union_left, hA.mono subset_union_right⟩, fun hA _x hx =>
hx.elim (fun h => hA.1 h) fun h => hA.2 h⟩
alias ⟨_, sized.union⟩ := sized_union
--TODO: A `forall_iUnion` lemma would be handy here.
@[simp]
theorem sized_iUnion {f : ι → Set (Finset α)} : (⋃ i, f i).Sized r ↔ ∀ i, (f i).Sized r := by
simp_rw [Set.Sized, Set.mem_iUnion, forall_exists_index]
exact forall_swap
-- `simp` normal form is `sized_iUnion`.
theorem sized_iUnion₂ {f : ∀ i, κ i → Set (Finset α)} :
(⋃ (i) (j), f i j).Sized r ↔ ∀ i j, (f i j).Sized r := by
simp only [Set.sized_iUnion]
protected theorem Sized.isAntichain (hA : A.Sized r) : IsAntichain (· ⊆ ·) A :=
fun _s hs _t ht h hst => h <| Finset.eq_of_subset_of_card_le hst ((hA ht).trans (hA hs).symm).le
protected theorem Sized.subsingleton (hA : A.Sized 0) : A.Subsingleton :=
subsingleton_of_forall_eq ∅ fun _s hs => card_eq_zero.1 <| hA hs
theorem Sized.subsingleton' [Fintype α] (hA : A.Sized (Fintype.card α)) : A.Subsingleton :=
subsingleton_of_forall_eq Finset.univ fun s hs => s.card_eq_iff_eq_univ.1 <| hA hs
theorem Sized.empty_mem_iff (hA : A.Sized r) : ∅ ∈ A ↔ A = {∅} :=
hA.isAntichain.bot_mem_iff
theorem Sized.univ_mem_iff [Fintype α] (hA : A.Sized r) : Finset.univ ∈ A ↔ A = {Finset.univ} :=
hA.isAntichain.top_mem_iff
theorem sized_powersetCard (s : Finset α) (r : ℕ) : (powersetCard r s : Set (Finset α)).Sized r :=
fun _t ht => (mem_powersetCard.1 ht).2
end Set
namespace Finset
section Sized
variable [Fintype α] {𝒜 : Finset (Finset α)} {s : Finset α} {r : ℕ}
theorem subset_powersetCard_univ_iff : 𝒜 ⊆ powersetCard r univ ↔ (𝒜 : Set (Finset α)).Sized r :=
forall_congr' fun A => by rw [mem_powersetCard_univ, mem_coe]
alias ⟨_, _root_.Set.Sized.subset_powersetCard_univ⟩ := subset_powersetCard_univ_iff
theorem _root_.Set.Sized.card_le (h𝒜 : (𝒜 : Set (Finset α)).Sized r) :
#𝒜 ≤ (Fintype.card α).choose r := by
rw [Fintype.card, ← card_powersetCard]
exact card_le_card (subset_powersetCard_univ_iff.mpr h𝒜)
end Sized
/-! ### Slices -/
section Slice
variable {𝒜 : Finset (Finset α)} {A A₁ A₂ : Finset α} {r r₁ r₂ : ℕ}
/-- The `r`-th slice of a set family is the subset of its elements which have cardinality `r`. -/
def slice (𝒜 : Finset (Finset α)) (r : ℕ) : Finset (Finset α) := {A ∈ 𝒜 | #A = r}
@[inherit_doc]
scoped[Finset] infixl:90 " # " => Finset.slice
/-- `A` is in the `r`-th slice of `𝒜` iff it's in `𝒜` and has cardinality `r`. -/
theorem mem_slice : A ∈ 𝒜 # r ↔ A ∈ 𝒜 ∧ #A = r :=
mem_filter
/-- The `r`-th slice of `𝒜` is a subset of `𝒜`. -/
theorem slice_subset : 𝒜 # r ⊆ 𝒜 :=
filter_subset _ _
/-- Everything in the `r`-th slice of `𝒜` has size `r`. -/
theorem sized_slice : (𝒜 # r : Set (Finset α)).Sized r := fun _ => And.right ∘ mem_slice.mp
theorem eq_of_mem_slice (h₁ : A ∈ 𝒜 # r₁) (h₂ : A ∈ 𝒜 # r₂) : r₁ = r₂ :=
(sized_slice h₁).symm.trans <| sized_slice h₂
/-- Elements in distinct slices must be distinct. -/
theorem ne_of_mem_slice (h₁ : A₁ ∈ 𝒜 # r₁) (h₂ : A₂ ∈ 𝒜 # r₂) : r₁ ≠ r₂ → A₁ ≠ A₂ :=
mt fun h => (sized_slice h₁).symm.trans ((congr_arg card h).trans (sized_slice h₂))
theorem pairwiseDisjoint_slice : (Set.univ : Set ℕ).PairwiseDisjoint (slice 𝒜) := fun _ _ _ _ hmn =>
disjoint_filter.2 fun _s _hs hm hn => hmn <| hm.symm.trans hn
variable [Fintype α] (𝒜)
@[simp]
theorem biUnion_slice [DecidableEq α] : (Iic <| Fintype.card α).biUnion 𝒜.slice = 𝒜 :=
Subset.antisymm (biUnion_subset.2 fun _r _ => slice_subset) fun s hs =>
mem_biUnion.2 ⟨#s, mem_Iic.2 <| s.card_le_univ, mem_slice.2 <| ⟨hs, rfl⟩⟩
@[simp]
theorem sum_card_slice : ∑ r ∈ Iic (Fintype.card α), #(𝒜 # r) = #𝒜 := by
letI := Classical.decEq α
rw [← card_biUnion, biUnion_slice]
exact Finset.pairwiseDisjoint_slice.subset (Set.subset_univ _)
end Slice
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Max.lean | import Mathlib.Data.Finset.Card
import Mathlib.Data.Finset.Lattice.Fold
/-!
# Maximum and minimum of finite sets
-/
assert_not_exists IsOrderedMonoid MonoidWithZero
open Function Multiset OrderDual
variable {F α β γ ι κ : Type*}
namespace Finset
/-! ### max and min of finite sets -/
section MaxMin
variable [LinearOrder α]
/-- Let `s` be a finset in a linear order. Then `s.max` is the maximum of `s` if `s` is not empty,
and `⊥` otherwise. It belongs to `WithBot α`. If you want to get an element of `α`, see
`s.max'`. -/
protected def max (s : Finset α) : WithBot α :=
sup s (↑)
theorem max_eq_sup_coe {s : Finset α} : s.max = s.sup (↑) :=
rfl
theorem max_eq_sup_withBot (s : Finset α) : s.max = sup s (↑) :=
rfl
@[simp]
theorem max_empty : (∅ : Finset α).max = ⊥ :=
rfl
@[simp]
theorem max_insert {a : α} {s : Finset α} : (insert a s).max = max ↑a s.max :=
fold_insert_idem
@[simp]
theorem max_singleton {a : α} : Finset.max {a} = (a : WithBot α) := by
rw [← insert_empty_eq]
exact max_insert
lemma max_pair (a b : α) :
Finset.max {a, b} = max (↑a) (↑b) := by
simp
theorem max_of_mem {s : Finset α} {a : α} (h : a ∈ s) : ∃ b : α, s.max = b :=
let ⟨b, h, _⟩ := WithBot.le_iff_forall.1 (le_sup (α := WithBot α) h) _ rfl; ⟨b, h⟩
theorem max_of_nonempty {s : Finset α} (h : s.Nonempty) : ∃ a : α, s.max = a :=
let ⟨_, h⟩ := h
max_of_mem h
theorem max_eq_bot {s : Finset α} : s.max = ⊥ ↔ s = ∅ :=
⟨fun h ↦ s.eq_empty_or_nonempty.elim id fun H ↦ by
obtain ⟨a, ha⟩ := max_of_nonempty H
rw [h] at ha; cases ha; , -- the `;` is needed since the `cases` syntax allows `cases a, b`
fun h ↦ h.symm ▸ max_empty⟩
theorem mem_of_max {s : Finset α} : ∀ {a : α}, s.max = a → a ∈ s := by
induction s using Finset.induction_on with
| empty => intro _ H; cases H
| insert b s _ ih =>
intro a h
by_cases p : b = a
· induction p
exact mem_insert_self b s
· rcases max_choice (↑b) s.max with q | q <;> rw [max_insert, q] at h
· cases h
cases p rfl
· exact mem_insert_of_mem (ih h)
theorem le_max {a : α} {s : Finset α} (as : a ∈ s) : ↑a ≤ s.max :=
le_sup as
theorem notMem_of_max_lt_coe {a : α} {s : Finset α} (h : s.max < a) : a ∉ s :=
mt le_max h.not_ge
@[deprecated (since := "2025-05-23")] alias not_mem_of_max_lt_coe := notMem_of_max_lt_coe
theorem le_max_of_eq {s : Finset α} {a b : α} (h₁ : a ∈ s) (h₂ : s.max = b) : a ≤ b :=
WithBot.coe_le_coe.mp <| (le_max h₁).trans h₂.le
theorem notMem_of_max_lt {s : Finset α} {a b : α} (h₁ : b < a) (h₂ : s.max = ↑b) : a ∉ s :=
Finset.notMem_of_max_lt_coe <| h₂.trans_lt <| WithBot.coe_lt_coe.mpr h₁
@[deprecated (since := "2025-05-23")] alias not_mem_of_max_lt := notMem_of_max_lt
theorem max_union {s t : Finset α} : (s ∪ t).max = s.max ⊔ t.max := sup_union
@[gcongr]
theorem max_mono {s t : Finset α} (st : s ⊆ t) : s.max ≤ t.max :=
sup_mono st
protected theorem max_le {M : WithBot α} {s : Finset α} (st : ∀ a ∈ s, (a : WithBot α) ≤ M) :
s.max ≤ M :=
Finset.sup_le st
@[simp]
protected lemma max_le_iff {m : WithBot α} {s : Finset α} : s.max ≤ m ↔ ∀ a ∈ s, a ≤ m :=
Finset.sup_le_iff
@[simp]
protected lemma max_eq_top [OrderTop α] {s : Finset α} : s.max = ⊤ ↔ ⊤ ∈ s :=
Finset.sup_eq_top_iff.trans <| by simp
/-- Let `s` be a finset in a linear order. Then `s.min` is the minimum of `s` if `s` is not empty,
and `⊤` otherwise. It belongs to `WithTop α`. If you want to get an element of `α`, see
`s.min'`. -/
protected def min (s : Finset α) : WithTop α :=
inf s (↑)
theorem min_eq_inf_withTop (s : Finset α) : s.min = inf s (↑) :=
rfl
@[simp]
theorem min_empty : (∅ : Finset α).min = ⊤ :=
rfl
@[simp]
theorem min_insert {a : α} {s : Finset α} : (insert a s).min = min (↑a) s.min :=
fold_insert_idem
@[simp]
theorem min_singleton {a : α} : Finset.min {a} = (a : WithTop α) := by
rw [← insert_empty_eq]
exact min_insert
lemma min_pair (a b : α) :
Finset.min {a, b} = min (↑a) (↑b) := by
simp
theorem min_of_mem {s : Finset α} {a : α} (h : a ∈ s) : ∃ b : α, s.min = b :=
let ⟨b, h, _⟩ := WithTop.le_iff_forall.1 (inf_le (α := WithTop α) h) _ rfl; ⟨b, h⟩
theorem min_of_nonempty {s : Finset α} (h : s.Nonempty) : ∃ a : α, s.min = a :=
let ⟨_, h⟩ := h
min_of_mem h
@[simp]
theorem min_eq_top {s : Finset α} : s.min = ⊤ ↔ s = ∅ := by
simp [Finset.min, eq_empty_iff_forall_notMem]
theorem mem_of_min {s : Finset α} : ∀ {a : α}, s.min = a → a ∈ s :=
@mem_of_max αᵒᵈ _ s
theorem min_le {a : α} {s : Finset α} (as : a ∈ s) : s.min ≤ a :=
inf_le as
theorem notMem_of_coe_lt_min {a : α} {s : Finset α} (h : ↑a < s.min) : a ∉ s :=
mt min_le h.not_ge
@[deprecated (since := "2025-05-23")] alias not_mem_of_coe_lt_min := notMem_of_coe_lt_min
theorem min_le_of_eq {s : Finset α} {a b : α} (h₁ : b ∈ s) (h₂ : s.min = a) : a ≤ b :=
WithTop.coe_le_coe.mp <| h₂.ge.trans (min_le h₁)
theorem notMem_of_lt_min {s : Finset α} {a b : α} (h₁ : a < b) (h₂ : s.min = ↑b) : a ∉ s :=
Finset.notMem_of_coe_lt_min <| (WithTop.coe_lt_coe.mpr h₁).trans_eq h₂.symm
@[deprecated (since := "2025-05-23")] alias not_mem_of_lt_min := notMem_of_lt_min
theorem min_union {s t : Finset α} : (s ∪ t).min = s.min ⊓ t.min := inf_union
@[gcongr]
theorem min_mono {s t : Finset α} (st : s ⊆ t) : t.min ≤ s.min :=
inf_mono st
protected theorem le_min {m : WithTop α} {s : Finset α} (st : ∀ a : α, a ∈ s → m ≤ a) : m ≤ s.min :=
Finset.le_inf st
@[simp]
protected theorem le_min_iff {m : WithTop α} {s : Finset α} : m ≤ s.min ↔ ∀ a ∈ s, m ≤ a :=
Finset.le_inf_iff
@[simp]
protected theorem min_eq_bot [OrderBot α] {s : Finset α} : s.min = ⊥ ↔ ⊥ ∈ s :=
Finset.max_eq_top (α := αᵒᵈ)
/-- Given a nonempty finset `s` in a linear order `α`, then `s.min' H` is its minimum, as an
element of `α`, where `H` is a proof of nonemptiness. Without this assumption, use instead `s.min`,
taking values in `WithTop α`. -/
def min' (s : Finset α) (H : s.Nonempty) : α :=
inf' s H id
/-- Given a nonempty finset `s` in a linear order `α`, then `s.max' H` is its maximum, as an
element of `α`, where `H` is a proof of nonemptiness. Without this assumption, use instead `s.max`,
taking values in `WithBot α`. -/
def max' (s : Finset α) (H : s.Nonempty) : α :=
sup' s H id
variable (s : Finset α) (H : s.Nonempty) {x : α}
theorem min'_mem : s.min' H ∈ s :=
mem_of_min <| by simp only [Finset.min, min', id_eq, coe_inf', Function.comp_def]
theorem min'_le (x) (H2 : x ∈ s) : s.min' ⟨x, H2⟩ ≤ x :=
min_le_of_eq H2 (WithTop.coe_untop _ _).symm
theorem le_min' (x) (H2 : ∀ y ∈ s, x ≤ y) : x ≤ s.min' H :=
H2 _ <| min'_mem _ _
theorem isLeast_min' : IsLeast (↑s) (s.min' H) :=
⟨min'_mem _ _, min'_le _⟩
@[simp]
theorem le_min'_iff {x} : x ≤ s.min' H ↔ ∀ y ∈ s, x ≤ y :=
le_isGLB_iff (isLeast_min' s H).isGLB
/-- `{a}.min' _` is `a`. -/
@[simp]
theorem min'_singleton (a : α) : ({a} : Finset α).min' (singleton_nonempty _) = a := by simp [min']
theorem max'_mem : s.max' H ∈ s :=
mem_of_max <| by simp only [max', Finset.max, id_eq, coe_sup', Function.comp_def]
theorem le_max' (x) (H2 : x ∈ s) : x ≤ s.max' ⟨x, H2⟩ :=
le_max_of_eq H2 (WithBot.coe_unbot _ _).symm
theorem max'_le (x) (H2 : ∀ y ∈ s, y ≤ x) : s.max' H ≤ x :=
H2 _ <| max'_mem _ _
theorem isGreatest_max' : IsGreatest (↑s) (s.max' H) :=
⟨max'_mem _ _, le_max' _⟩
@[simp]
theorem max'_le_iff {x} : s.max' H ≤ x ↔ ∀ y ∈ s, y ≤ x :=
isLUB_le_iff (isGreatest_max' s H).isLUB
@[simp]
theorem max'_lt_iff {x} : s.max' H < x ↔ ∀ y ∈ s, y < x :=
⟨fun Hlt y hy => (s.le_max' y hy).trans_lt Hlt, fun H => H _ <| s.max'_mem _⟩
@[simp]
theorem lt_min'_iff : x < s.min' H ↔ ∀ y ∈ s, x < y :=
@max'_lt_iff αᵒᵈ _ _ H _
theorem max'_eq_sup' : s.max' H = s.sup' H id := rfl
theorem min'_eq_inf' : s.min' H = s.inf' H id := rfl
/-- `{a}.max' _` is `a`. -/
@[simp]
theorem max'_singleton (a : α) : ({a} : Finset α).max' (singleton_nonempty _) = a := by simp [max']
lemma min'_eq_iff (a : α) : s.min' H = a ↔ a ∈ s ∧ ∀ (b : α), b ∈ s → a ≤ b :=
⟨(· ▸ ⟨min'_mem _ _, min'_le _⟩), fun h ↦ le_antisymm (min'_le _ _ h.1) (le_min' _ _ _ h.2)⟩
lemma max'_eq_iff (a : α) : s.max' H = a ↔ a ∈ s ∧ ∀ (b : α), b ∈ s → b ≤ a :=
⟨(· ▸ ⟨max'_mem _ _, le_max' _⟩), fun h ↦ le_antisymm (max'_le _ _ _ h.2) (le_max' _ _ h.1)⟩
theorem min'_le_max' (hs : s.Nonempty) : s.min' hs ≤ s.max' hs := min'_le _ _ (max'_mem _ _)
theorem min'_lt_max' {i j} (H1 : i ∈ s) (H2 : j ∈ s) (H3 : i ≠ j) :
s.min' ⟨i, H1⟩ < s.max' ⟨i, H1⟩ :=
isGLB_lt_isLUB_of_ne (s.isLeast_min' _).isGLB (s.isGreatest_max' _).isLUB H1 H2 H3
/-- If there's more than 1 element, the min' is less than the max'. An alternate version of
`min'_lt_max'` which is sometimes more convenient.
-/
theorem min'_lt_max'_of_card (h₂ : 1 < card s) :
s.min' (Finset.card_pos.1 <| by cutsat) < s.max' (Finset.card_pos.1 <| by cutsat) := by
rcases one_lt_card.1 h₂ with ⟨a, ha, b, hb, hab⟩
exact s.min'_lt_max' ha hb hab
theorem max'_union {s₁ s₂ : Finset α} (h₁ : s₁.Nonempty) (h₂ : s₂.Nonempty) :
(s₁ ∪ s₂).max' (h₁.mono subset_union_left) = s₁.max' h₁ ⊔ s₂.max' h₂ := sup'_union h₁ h₂ id
theorem min'_union {s₁ s₂ : Finset α} (h₁ : s₁.Nonempty) (h₂ : s₂.Nonempty) :
(s₁ ∪ s₂).min' (h₁.mono subset_union_left) = s₁.min' h₁ ⊓ s₂.min' h₂ := inf'_union h₁ h₂ id
theorem map_ofDual_min (s : Finset αᵒᵈ) : s.min.map ofDual = (s.image ofDual).max := by
rw [max_eq_sup_withBot, sup_image]
exact congr_fun WithBot.map_id _
theorem map_ofDual_max (s : Finset αᵒᵈ) : s.max.map ofDual = (s.image ofDual).min := by
rw [min_eq_inf_withTop, inf_image]
exact congr_fun WithTop.map_id _
theorem map_toDual_min (s : Finset α) : s.min.map toDual = (s.image toDual).max := by
rw [max_eq_sup_withBot, sup_image]
exact congr_fun WithBot.map_id _
theorem map_toDual_max (s : Finset α) : s.max.map toDual = (s.image toDual).min := by
rw [min_eq_inf_withTop, inf_image]
exact congr_fun WithTop.map_id _
theorem ofDual_min' {s : Finset αᵒᵈ} (hs : s.Nonempty) :
ofDual (min' s hs) = max' (s.image ofDual) (hs.image _) := by
simp [min'_eq_inf', max'_eq_sup']
theorem ofDual_max' {s : Finset αᵒᵈ} (hs : s.Nonempty) :
ofDual (max' s hs) = min' (s.image ofDual) (hs.image _) := by
simp [min'_eq_inf', max'_eq_sup']
theorem toDual_min' {s : Finset α} (hs : s.Nonempty) :
toDual (min' s hs) = max' (s.image toDual) (hs.image _) := by
simp [min'_eq_inf', max'_eq_sup']
theorem toDual_max' {s : Finset α} (hs : s.Nonempty) :
toDual (max' s hs) = min' (s.image toDual) (hs.image _) := by
simp [min'_eq_inf', max'_eq_sup']
theorem max'_subset {s t : Finset α} (H : s.Nonempty) (hst : s ⊆ t) :
s.max' H ≤ t.max' (H.mono hst) :=
le_max' _ _ (hst (s.max'_mem H))
theorem min'_subset {s t : Finset α} (H : s.Nonempty) (hst : s ⊆ t) :
t.min' (H.mono hst) ≤ s.min' H :=
min'_le _ _ (hst (s.min'_mem H))
@[simp] theorem max'_insert (a : α) (s : Finset α) (H : s.Nonempty) :
(insert a s).max' (s.insert_nonempty a) = max a (s.max' H) :=
(isGreatest_max' _ _).unique <| by
rw [coe_insert]
exact (isGreatest_max' _ _).insert _
@[simp] theorem min'_insert (a : α) (s : Finset α) (H : s.Nonempty) :
(insert a s).min' (s.insert_nonempty a) = min a (s.min' H) :=
(isLeast_min' _ _).unique <| by
rw [coe_insert]
exact (isLeast_min' _ _).insert _
lemma min'_pair (a b : α) :
min' {a, b} (insert_nonempty _ _) = min a b := by
simp
lemma max'_pair (a b : α) :
max' {a, b} (insert_nonempty _ _) = max a b := by
simp
theorem lt_max'_of_mem_erase_max' [DecidableEq α] {a : α} (ha : a ∈ s.erase (s.max' H)) :
a < s.max' H :=
lt_of_le_of_ne (le_max' _ _ (mem_of_mem_erase ha)) <| ne_of_mem_of_not_mem ha <| notMem_erase _ _
theorem min'_lt_of_mem_erase_min' [DecidableEq α] {a : α} (ha : a ∈ s.erase (s.min' H)) :
s.min' H < a :=
@lt_max'_of_mem_erase_max' αᵒᵈ _ s H _ a ha
/-- To rewrite from right to left, use `Monotone.map_finset_max'`. -/
@[simp]
theorem max'_image [LinearOrder β] {f : α → β} (hf : Monotone f) (s : Finset α)
(h : (s.image f).Nonempty) : (s.image f).max' h = f (s.max' h.of_image) := by
simp only [max', sup'_image]
exact .symm <| comp_sup'_eq_sup'_comp _ _ fun _ _ ↦ hf.map_max
/-- A version of `Finset.max'_image` with LHS and RHS reversed.
Also, this version assumes that `s` is nonempty, not its image. -/
lemma _root_.Monotone.map_finset_max' [LinearOrder β] {f : α → β} (hf : Monotone f) {s : Finset α}
(h : s.Nonempty) : f (s.max' h) = (s.image f).max' (h.image f) :=
.symm <| max'_image hf ..
/-- To rewrite from right to left, use `Monotone.map_finset_min'`. -/
@[simp]
theorem min'_image [LinearOrder β] {f : α → β} (hf : Monotone f) (s : Finset α)
(h : (s.image f).Nonempty) : (s.image f).min' h = f (s.min' h.of_image) := by
simp only [min', inf'_image]
exact .symm <| comp_inf'_eq_inf'_comp _ _ fun _ _ ↦ hf.map_min
/-- A version of `Finset.min'_image` with LHS and RHS reversed.
Also, this version assumes that `s` is nonempty, not its image. -/
lemma _root_.Monotone.map_finset_min' [LinearOrder β] {f : α → β} (hf : Monotone f) {s : Finset α}
(h : s.Nonempty) : f (s.min' h) = (s.image f).min' (h.image f) :=
.symm <| min'_image hf ..
theorem coe_max' {s : Finset α} (hs : s.Nonempty) : ↑(s.max' hs) = s.max :=
coe_sup' hs id
theorem coe_min' {s : Finset α} (hs : s.Nonempty) : ↑(s.min' hs) = s.min :=
coe_inf' hs id
theorem max_mem_image_coe {s : Finset α} (hs : s.Nonempty) :
s.max ∈ (s.image (↑) : Finset (WithBot α)) :=
mem_image.2 ⟨max' s hs, max'_mem _ _, coe_max' hs⟩
theorem min_mem_image_coe {s : Finset α} (hs : s.Nonempty) :
s.min ∈ (s.image (↑) : Finset (WithTop α)) :=
mem_image.2 ⟨min' s hs, min'_mem _ _, coe_min' hs⟩
theorem max_mem_insert_bot_image_coe (s : Finset α) :
s.max ∈ (insert ⊥ (s.image (↑)) : Finset (WithBot α)) :=
mem_insert.2 <| s.eq_empty_or_nonempty.imp max_eq_bot.2 max_mem_image_coe
theorem min_mem_insert_top_image_coe (s : Finset α) :
s.min ∈ (insert ⊤ (s.image (↑)) : Finset (WithTop α)) :=
mem_insert.2 <| s.eq_empty_or_nonempty.imp min_eq_top.2 min_mem_image_coe
theorem max'_erase_ne_self {s : Finset α} (s0 : (s.erase x).Nonempty) : (s.erase x).max' s0 ≠ x :=
ne_of_mem_erase (max'_mem _ s0)
theorem min'_erase_ne_self {s : Finset α} (s0 : (s.erase x).Nonempty) : (s.erase x).min' s0 ≠ x :=
ne_of_mem_erase (min'_mem _ s0)
theorem max_erase_ne_self {s : Finset α} : (s.erase x).max ≠ x := by
by_cases s0 : (s.erase x).Nonempty
· refine ne_of_eq_of_ne (coe_max' s0).symm ?_
exact WithBot.coe_eq_coe.not.mpr (max'_erase_ne_self _)
· rw [not_nonempty_iff_eq_empty.mp s0, max_empty]
exact WithBot.bot_ne_coe
theorem min_erase_ne_self {s : Finset α} : (s.erase x).min ≠ x := by
apply mt (congr_arg (WithTop.map toDual))
rw [map_toDual_min, image_erase toDual.injective, WithTop.map_coe]
apply max_erase_ne_self
theorem exists_next_right {x : α} {s : Finset α} (h : ∃ y ∈ s, x < y) :
∃ y ∈ s, x < y ∧ ∀ z ∈ s, x < z → y ≤ z :=
have Hne : (s.filter (x < ·)).Nonempty := h.imp fun y hy => mem_filter.2 (by simpa)
have aux := mem_filter.1 (min'_mem _ Hne)
⟨min' _ Hne, aux.1, by simp, fun z hzs hz => min'_le _ _ <| mem_filter.2 ⟨hzs, by simpa⟩⟩
theorem exists_next_left {x : α} {s : Finset α} (h : ∃ y ∈ s, y < x) :
∃ y ∈ s, y < x ∧ ∀ z ∈ s, z < x → z ≤ y :=
@exists_next_right αᵒᵈ _ x s h
/-- If finsets `s` and `t` are interleaved, then `Finset.card s ≤ Finset.card t + 1`. -/
theorem card_le_of_interleaved {s t : Finset α}
(h : ∀ᵉ (x ∈ s) (y ∈ s),
x < y → (∀ z ∈ s, z ∉ Set.Ioo x y) → ∃ z ∈ t, x < z ∧ z < y) :
s.card ≤ t.card + 1 := by
replace h : ∀ᵉ (x ∈ s) (y ∈ s), x < y → ∃ z ∈ t, x < z ∧ z < y := by
intro x hx y hy hxy
rcases exists_next_right ⟨y, hy, hxy⟩ with ⟨a, has, hxa, ha⟩
rcases h x hx a has hxa fun z hzs hz => hz.2.not_ge <| ha _ hzs hz.1 with ⟨b, hbt, hxb, hba⟩
exact ⟨b, hbt, hxb, hba.trans_le <| ha _ hy hxy⟩
set f : α → WithTop α := fun x => (t.filter fun y => x < y).min
have f_mono : StrictMonoOn f s := by
intro x hx y hy hxy
rcases h x hx y hy hxy with ⟨a, hat, hxa, hay⟩
calc
f x ≤ a := min_le (mem_filter.2 ⟨hat, by simpa⟩)
_ < f y :=
(Finset.lt_inf_iff <| WithTop.coe_lt_top a).2 fun b hb =>
WithTop.coe_lt_coe.2 <| hay.trans (by simpa using (mem_filter.1 hb).2)
calc
s.card = (s.image f).card := (card_image_of_injOn f_mono.injOn).symm
_ ≤ (insert ⊤ (t.image (↑)) : Finset (WithTop α)).card :=
card_mono <| image_subset_iff.2 fun x _ =>
insert_subset_insert _ (image_subset_image <| filter_subset _ _)
(min_mem_insert_top_image_coe _)
_ ≤ t.card + 1 := (card_insert_le _ _).trans (Nat.add_le_add_right card_image_le _)
/-- If finsets `s` and `t` are interleaved, then `Finset.card s ≤ Finset.card (t \ s) + 1`. -/
theorem card_le_diff_of_interleaved {s t : Finset α}
(h :
∀ᵉ (x ∈ s) (y ∈ s),
x < y → (∀ z ∈ s, z ∉ Set.Ioo x y) → ∃ z ∈ t, x < z ∧ z < y) :
s.card ≤ (t \ s).card + 1 :=
card_le_of_interleaved fun x hx y hy hxy hs =>
let ⟨z, hzt, hxz, hzy⟩ := h x hx y hy hxy hs
⟨z, mem_sdiff.2 ⟨hzt, fun hzs => hs z hzs ⟨hxz, hzy⟩⟩, hxz, hzy⟩
/-- Induction principle for `Finset`s in a linearly ordered type: a predicate is true on all
`s : Finset α` provided that:
* it is true on the empty `Finset`,
* for every `s : Finset α` and an element `a` strictly greater than all elements of `s`, `p s`
implies `p (insert a s)`. -/
@[elab_as_elim]
theorem induction_on_max [DecidableEq α] {p : Finset α → Prop} (s : Finset α) (h0 : p ∅)
(step : ∀ a s, (∀ x ∈ s, x < a) → p s → p (insert a s)) : p s := by
induction s using Finset.eraseInduction with | _ s ih
rcases s.eq_empty_or_nonempty with (rfl | hne)
· exact h0
· have H : s.max' hne ∈ s := max'_mem s hne
rw [← insert_erase H]
exact step _ _ (fun x ↦ s.lt_max'_of_mem_erase_max' hne) (ih _ H)
/-- Induction principle for `Finset`s in a linearly ordered type: a predicate is true on all
`s : Finset α` provided that:
* it is true on the empty `Finset`,
* for every `s : Finset α` and an element `a` strictly less than all elements of `s`, `p s`
implies `p (insert a s)`. -/
@[elab_as_elim]
theorem induction_on_min [DecidableEq α] {p : Finset α → Prop} (s : Finset α) (h0 : p ∅)
(step : ∀ a s, (∀ x ∈ s, a < x) → p s → p (insert a s)) : p s :=
@induction_on_max αᵒᵈ _ _ _ s h0 step
end MaxMin
section MaxMinInductionValue
variable [LinearOrder α] [LinearOrder β]
/-- Induction principle for `Finset`s in any type from which a given function `f` maps to a linearly
ordered type : a predicate is true on all `s : Finset α` provided that:
* it is true on the empty `Finset`,
* for every `s : Finset α` and an element `a` such that for elements of `s` denoted by `x` we have
`f x ≤ f a`, `p s` implies `p (insert a s)`. -/
@[elab_as_elim]
theorem induction_on_max_value [DecidableEq ι] (f : ι → α) {p : Finset ι → Prop} (s : Finset ι)
(h0 : p ∅) (step : ∀ a s, a ∉ s → (∀ x ∈ s, f x ≤ f a) → p s → p (insert a s)) : p s := by
induction s using Finset.eraseInduction with | _ s ihs
rcases (s.image f).eq_empty_or_nonempty with (hne | hne)
· simp only [image_eq_empty] at hne
simp only [hne, h0]
· have H : (s.image f).max' hne ∈ s.image f := max'_mem (s.image f) hne
simp only [mem_image] at H
rcases H with ⟨a, has, hfa⟩
rw [← insert_erase has]
refine step _ _ (notMem_erase a s) (fun x hx => ?_) (ihs a has)
rw [hfa]
exact le_max' _ _ (mem_image_of_mem _ <| mem_of_mem_erase hx)
/-- Induction principle for `Finset`s in any type from which a given function `f` maps to a linearly
ordered type : a predicate is true on all `s : Finset α` provided that:
* it is true on the empty `Finset`,
* for every `s : Finset α` and an element `a` such that for elements of `s` denoted by `x` we have
`f a ≤ f x`, `p s` implies `p (insert a s)`. -/
@[elab_as_elim]
theorem induction_on_min_value [DecidableEq ι] (f : ι → α) {p : Finset ι → Prop} (s : Finset ι)
(h0 : p ∅) (step : ∀ a s, a ∉ s → (∀ x ∈ s, f a ≤ f x) → p s → p (insert a s)) : p s :=
@induction_on_max_value αᵒᵈ ι _ _ _ _ s h0 step
end MaxMinInductionValue
section ExistsMaxMin
variable [LinearOrder α]
theorem exists_max_image (s : Finset β) (f : β → α) (h : s.Nonempty) :
∃ x ∈ s, ∀ x' ∈ s, f x' ≤ f x := by
obtain ⟨y, hy⟩ := max_of_nonempty (h.image f)
rcases mem_image.mp (mem_of_max hy) with ⟨x, hx, rfl⟩
exact ⟨x, hx, fun x' hx' => le_max_of_eq (mem_image_of_mem f hx') hy⟩
theorem exists_min_image (s : Finset β) (f : β → α) (h : s.Nonempty) :
∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' :=
@exists_max_image αᵒᵈ β _ s f h
end ExistsMaxMin
theorem isGLB_iff_isLeast [LinearOrder α] (i : α) (s : Finset α) (hs : s.Nonempty) :
IsGLB (s : Set α) i ↔ IsLeast (↑s) i := by
refine ⟨fun his => ?_, IsLeast.isGLB⟩
suffices i = min' s hs by
rw [this]
exact isLeast_min' s hs
rw [IsGLB, IsGreatest, mem_lowerBounds, mem_upperBounds] at his
exact le_antisymm (his.1 (Finset.min' s hs) (Finset.min'_mem s hs)) (his.2 _ (Finset.min'_le s))
theorem isLUB_iff_isGreatest [LinearOrder α] (i : α) (s : Finset α) (hs : s.Nonempty) :
IsLUB (s : Set α) i ↔ IsGreatest (↑s) i :=
@isGLB_iff_isLeast αᵒᵈ _ i s hs
theorem isGLB_mem [LinearOrder α] {i : α} (s : Finset α) (his : IsGLB (s : Set α) i)
(hs : s.Nonempty) : i ∈ s := by
rw [← mem_coe]
exact ((isGLB_iff_isLeast i s hs).mp his).1
theorem isLUB_mem [LinearOrder α] {i : α} (s : Finset α) (his : IsLUB (s : Set α) i)
(hs : s.Nonempty) : i ∈ s :=
@isGLB_mem αᵒᵈ _ i s his hs
end Finset
theorem Multiset.exists_max_image {α R : Type*} [LinearOrder R] (f : α → R) {s : Multiset α}
(hs : s ≠ 0) : ∃ y ∈ s, ∀ z ∈ s, f z ≤ f y := by
classical
obtain ⟨y, hys, hy⟩ := Finset.exists_max_image s.toFinset f (toFinset_nonempty.mpr hs)
exact ⟨y, mem_toFinset.mp hys, fun _ hz ↦ hy _ (mem_toFinset.mpr hz)⟩
theorem Multiset.exists_min_image {α R : Type*} [LinearOrder R] (f : α → R) {s : Multiset α}
(hs : s ≠ 0) : ∃ y ∈ s, ∀ z ∈ s, f y ≤ f z :=
@exists_max_image α Rᵒᵈ _ f s hs |
.lake/packages/mathlib/Mathlib/Data/Finset/Erase.lean | import Mathlib.Data.Finset.Defs
import Mathlib.Data.Multiset.Filter
/-!
# Erasing an element from a finite set
## Main declarations
* `Finset.erase`: For any `a : α`, `erase s a` returns `s` with the element `a` removed.
## Tags
finite sets, finset
-/
-- Assert that we define `Finset` without the material on `List.sublists`.
-- Note that we cannot use `List.sublists` itself as that is defined very early.
assert_not_exists List.sublistsLen Multiset.powerset CompleteLattice IsOrderedMonoid
open Multiset Subtype Function
universe u
variable {α : Type*} {β : Type*} {γ : Type*}
namespace Finset
-- TODO: these should be global attributes, but this will require fixing other files
attribute [local trans] Subset.trans Superset.trans
/-! ### erase -/
section Erase
variable [DecidableEq α] {s t u v : Finset α} {a b : α}
/-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are
not equal to `a`. -/
def erase (s : Finset α) (a : α) : Finset α :=
⟨_, s.2.erase a⟩
@[simp]
theorem erase_val (s : Finset α) (a : α) : (erase s a).1 = s.1.erase a :=
rfl
@[simp, grind =]
theorem mem_erase {a b : α} {s : Finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s :=
s.2.mem_erase_iff
theorem notMem_erase (a : α) (s : Finset α) : a ∉ erase s a :=
s.2.notMem_erase
@[deprecated (since := "2025-05-23")] alias not_mem_erase := notMem_erase
theorem ne_of_mem_erase : b ∈ erase s a → b ≠ a := fun h => (mem_erase.1 h).1
theorem mem_of_mem_erase : b ∈ erase s a → b ∈ s :=
Multiset.mem_of_mem_erase
theorem mem_erase_of_ne_of_mem : a ≠ b → a ∈ s → a ∈ erase s b := by
simp only [mem_erase]; exact And.intro
/-- An element of `s` that is not an element of `erase s a` must be`a`. -/
theorem eq_of_mem_of_notMem_erase (hs : b ∈ s) (hsa : b ∉ s.erase a) : b = a := by grind
@[deprecated (since := "2025-05-23")] alias eq_of_mem_of_not_mem_erase := eq_of_mem_of_notMem_erase
@[simp]
theorem erase_eq_of_notMem {a : α} {s : Finset α} (h : a ∉ s) : erase s a = s :=
eq_of_veq <| erase_of_notMem h
@[deprecated (since := "2025-05-23")] alias erase_eq_of_not_mem := erase_eq_of_notMem
@[simp]
theorem erase_eq_self : s.erase a = s ↔ a ∉ s :=
⟨fun h => h ▸ notMem_erase _ _, erase_eq_of_notMem⟩
theorem erase_ne_self : s.erase a ≠ s ↔ a ∈ s :=
erase_eq_self.not_left
@[gcongr]
theorem erase_subset_erase (a : α) {s t : Finset α} (h : s ⊆ t) : erase s a ⊆ erase t a :=
val_le_iff.1 <| erase_le_erase _ <| val_le_iff.2 h
theorem erase_subset (a : α) (s : Finset α) : erase s a ⊆ s :=
Multiset.erase_subset _ _
theorem subset_erase {a : α} {s t : Finset α} : s ⊆ t.erase a ↔ s ⊆ t ∧ a ∉ s := by grind
@[simp, norm_cast]
theorem coe_erase (a : α) (s : Finset α) : ↑(erase s a) = (s \ {a} : Set α) := by grind
theorem erase_idem {a : α} {s : Finset α} : erase (erase s a) a = erase s a := by simp
theorem erase_right_comm {a b : α} {s : Finset α} : erase (erase s a) b = erase (erase s b) a := by
grind
theorem erase_inj {x y : α} (s : Finset α) (hx : x ∈ s) : s.erase x = s.erase y ↔ x = y := by
grind [eq_of_mem_of_notMem_erase]
theorem erase_injOn (s : Finset α) : Set.InjOn s.erase s := fun _ _ _ _ => (erase_inj s ‹_›).mp
end Erase
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/NatAntidiagonal.lean | import Mathlib.Algebra.Order.Antidiag.Prod
import Mathlib.Algebra.Order.Group.Nat
import Mathlib.Data.Multiset.NatAntidiagonal
/-!
# Antidiagonals in ℕ × ℕ as finsets
This file defines the antidiagonals of ℕ × ℕ as finsets: the `n`-th antidiagonal is the finset of
pairs `(i, j)` such that `i + j = n`. This is useful for polynomial multiplication and more
generally for sums going from `0` to `n`.
## Notes
This refines files `Data.List.NatAntidiagonal` and `Data.Multiset.NatAntidiagonal`, providing an
instance enabling `Finset.antidiagonal` on `Nat`.
-/
assert_not_exists Field
open Function
namespace Finset
namespace Nat
/-- The antidiagonal of a natural number `n` is
the finset of pairs `(i, j)` such that `i + j = n`. -/
instance instHasAntidiagonal : HasAntidiagonal ℕ where
antidiagonal n := ⟨Multiset.Nat.antidiagonal n, Multiset.Nat.nodup_antidiagonal n⟩
mem_antidiagonal {n} {xy} := by
rw [mem_def, Multiset.Nat.mem_antidiagonal]
lemma antidiagonal_eq_map (n : ℕ) :
antidiagonal n = (range (n + 1)).map ⟨fun i ↦ (i, n - i), fun _ _ h ↦ (Prod.ext_iff.1 h).1⟩ :=
rfl
lemma antidiagonal_eq_map' (n : ℕ) :
antidiagonal n =
(range (n + 1)).map ⟨fun i ↦ (n - i, i), fun _ _ h ↦ (Prod.ext_iff.1 h).2⟩ := by
rw [← map_swap_antidiagonal, antidiagonal_eq_map, map_map]; rfl
lemma antidiagonal_eq_image (n : ℕ) :
antidiagonal n = (range (n + 1)).image fun i ↦ (i, n - i) := by
simp only [antidiagonal_eq_map, map_eq_image, Function.Embedding.coeFn_mk]
lemma antidiagonal_eq_image' (n : ℕ) :
antidiagonal n = (range (n + 1)).image fun i ↦ (n - i, i) := by
simp only [antidiagonal_eq_map', map_eq_image, Function.Embedding.coeFn_mk]
/-- The cardinality of the antidiagonal of `n` is `n + 1`. -/
@[simp]
theorem card_antidiagonal (n : ℕ) : (antidiagonal n).card = n + 1 := by simp [antidiagonal]
/-- The antidiagonal of `0` is the list `[(0, 0)]` -/
@[simp]
theorem antidiagonal_zero : antidiagonal 0 = {(0, 0)} := rfl
theorem antidiagonal_succ (n : ℕ) :
antidiagonal (n + 1) =
cons (0, n + 1)
((antidiagonal n).map
(Embedding.prodMap ⟨Nat.succ, Nat.succ_injective⟩ (Embedding.refl _)))
(by simp) := by
apply eq_of_veq
rw [cons_val, map_val]
apply Multiset.Nat.antidiagonal_succ
theorem antidiagonal_succ' (n : ℕ) :
antidiagonal (n + 1) =
cons (n + 1, 0)
((antidiagonal n).map
(Embedding.prodMap (Embedding.refl _) ⟨Nat.succ, Nat.succ_injective⟩))
(by simp) := by
apply eq_of_veq
rw [cons_val, map_val]
exact Multiset.Nat.antidiagonal_succ'
theorem antidiagonal_succ_succ' {n : ℕ} :
antidiagonal (n + 2) =
cons (0, n + 2)
(cons (n + 2, 0)
((antidiagonal n).map
(Embedding.prodMap ⟨Nat.succ, Nat.succ_injective⟩
⟨Nat.succ, Nat.succ_injective⟩)) <|
by simp)
(by simp) := by
simp_rw [antidiagonal_succ (n + 1), antidiagonal_succ', Finset.map_cons, map_map]
rfl
theorem antidiagonal.fst_lt {n : ℕ} {kl : ℕ × ℕ} (hlk : kl ∈ antidiagonal n) : kl.1 < n + 1 :=
Nat.lt_succ_of_le <| antidiagonal.fst_le hlk
theorem antidiagonal.snd_lt {n : ℕ} {kl : ℕ × ℕ} (hlk : kl ∈ antidiagonal n) : kl.2 < n + 1 :=
Nat.lt_succ_of_le <| antidiagonal.snd_le hlk
@[simp] lemma antidiagonal_filter_snd_le_of_le {n k : ℕ} (h : k ≤ n) :
{a ∈ antidiagonal n | a.snd ≤ k} = (antidiagonal k).map
(Embedding.prodMap ⟨_, add_left_injective (n - k)⟩ (Embedding.refl ℕ)) := by
ext ⟨i, j⟩
suffices i + j = n ∧ j ≤ k ↔ ∃ a, a + j = k ∧ a + (n - k) = i by simpa
refine ⟨fun hi ↦ ⟨k - j, tsub_add_cancel_of_le hi.2, ?_⟩, ?_⟩
· rw [add_comm, tsub_add_eq_add_tsub h, ← hi.1, add_assoc, Nat.add_sub_of_le hi.2,
add_tsub_cancel_right]
· rintro ⟨l, hl, rfl⟩
refine ⟨?_, hl ▸ Nat.le_add_left j l⟩
rw [add_assoc, add_comm, add_assoc, add_comm j l, hl]
exact Nat.sub_add_cancel h
@[simp] lemma antidiagonal_filter_fst_le_of_le {n k : ℕ} (h : k ≤ n) :
{a ∈ antidiagonal n | a.fst ≤ k} = (antidiagonal k).map
(Embedding.prodMap (Embedding.refl ℕ) ⟨_, add_left_injective (n - k)⟩) := by
have aux₁ : fun a ↦ a.fst ≤ k = (fun a ↦ a.snd ≤ k) ∘ (Equiv.prodComm ℕ ℕ).symm := rfl
have aux₂ : ∀ i j, (∃ a b, a + b = k ∧ b = i ∧ a + (n - k) = j) ↔
∃ a b, a + b = k ∧ a = i ∧ b + (n - k) = j :=
fun i j ↦ by rw [exists_comm]; exact exists₂_congr (fun a b ↦ by rw [add_comm])
rw [← map_prodComm_antidiagonal]
simp_rw [aux₁, ← map_filter, antidiagonal_filter_snd_le_of_le h, map_map]
ext ⟨i, j⟩
simpa using aux₂ i j
@[simp] lemma antidiagonal_filter_le_fst_of_le {n k : ℕ} (h : k ≤ n) :
{a ∈ antidiagonal n | k ≤ a.fst} = (antidiagonal (n - k)).map
(Embedding.prodMap ⟨_, add_left_injective k⟩ (Embedding.refl ℕ)) := by
ext ⟨i, j⟩
suffices i + j = n ∧ k ≤ i ↔ ∃ a, a + j = n - k ∧ a + k = i by simpa
refine ⟨fun hi ↦ ⟨i - k, ?_, tsub_add_cancel_of_le hi.2⟩, ?_⟩
· rw [← Nat.sub_add_comm hi.2, hi.1]
· rintro ⟨l, hl, rfl⟩
refine ⟨?_, Nat.le_add_left k l⟩
rw [add_right_comm, hl]
exact tsub_add_cancel_of_le h
@[simp] lemma antidiagonal_filter_le_snd_of_le {n k : ℕ} (h : k ≤ n) :
{a ∈ antidiagonal n | k ≤ a.snd} = (antidiagonal (n - k)).map
(Embedding.prodMap (Embedding.refl ℕ) ⟨_, add_left_injective k⟩) := by
have aux₁ : fun a ↦ k ≤ a.snd = (fun a ↦ k ≤ a.fst) ∘ (Equiv.prodComm ℕ ℕ).symm := rfl
have aux₂ : ∀ i j, (∃ a b, a + b = n - k ∧ b = i ∧ a + k = j) ↔
∃ a b, a + b = n - k ∧ a = i ∧ b + k = j :=
fun i j ↦ by rw [exists_comm]; exact exists₂_congr (fun a b ↦ by rw [add_comm])
rw [← map_prodComm_antidiagonal]
simp_rw [aux₁, ← map_filter, antidiagonal_filter_le_fst_of_le h, map_map]
ext ⟨i, j⟩
simpa using aux₂ i j
/-- The set `antidiagonal n` is equivalent to `Fin (n+1)`, via the first projection. -/
@[simps]
def antidiagonalEquivFin (n : ℕ) : antidiagonal n ≃ Fin (n + 1) where
toFun := fun ⟨⟨i, _⟩, h⟩ ↦ ⟨i, antidiagonal.fst_lt h⟩
invFun := fun ⟨i, h⟩ ↦ ⟨⟨i, n - i⟩, by
rw [mem_antidiagonal, add_comm, Nat.sub_add_cancel]
exact Nat.le_of_lt_succ h⟩
end Nat
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Preimage.lean | import Mathlib.Data.Finset.Pi
import Mathlib.Data.Finset.Sigma
import Mathlib.Data.Finset.Sum
import Mathlib.Data.Set.Finite.Basic
/-!
# Preimage of a `Finset` under an injective map.
-/
assert_not_exists Finset.sum
open Set Function
universe u v w x
variable {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x}
namespace Finset
section Preimage
/-- Preimage of `s : Finset β` under a map `f` injective on `f ⁻¹' s` as a `Finset`. -/
noncomputable def preimage (s : Finset β) (f : α → β) (hf : Set.InjOn f (f ⁻¹' ↑s)) : Finset α :=
(s.finite_toSet.preimage hf).toFinset
@[simp]
theorem mem_preimage {f : α → β} {s : Finset β} {hf : Set.InjOn f (f ⁻¹' ↑s)} {x : α} :
x ∈ preimage s f hf ↔ f x ∈ s :=
Set.Finite.mem_toFinset _
@[simp, norm_cast]
theorem coe_preimage {f : α → β} (s : Finset β) (hf : Set.InjOn f (f ⁻¹' ↑s)) :
(↑(preimage s f hf) : Set α) = f ⁻¹' ↑s :=
Set.Finite.coe_toFinset _
@[simp]
theorem preimage_empty {f : α → β} : preimage ∅ f (by simp [InjOn]) = ∅ :=
Finset.coe_injective (by simp)
@[simp]
theorem preimage_univ {f : α → β} [Fintype α] [Fintype β] (hf) : preimage univ f hf = univ :=
Finset.coe_injective (by simp)
@[simp]
theorem preimage_inter [DecidableEq α] [DecidableEq β] {f : α → β} {s t : Finset β}
(hs : Set.InjOn f (f ⁻¹' ↑s)) (ht : Set.InjOn f (f ⁻¹' ↑t)) :
(preimage (s ∩ t) f fun _ hx₁ _ hx₂ =>
hs (mem_of_mem_inter_left hx₁) (mem_of_mem_inter_left hx₂)) =
preimage s f hs ∩ preimage t f ht :=
Finset.coe_injective (by simp)
@[simp]
theorem preimage_union [DecidableEq α] [DecidableEq β] {f : α → β} {s t : Finset β} (hst) :
preimage (s ∪ t) f hst =
(preimage s f fun _ hx₁ _ hx₂ => hst (mem_union_left _ hx₁) (mem_union_left _ hx₂)) ∪
preimage t f fun _ hx₁ _ hx₂ => hst (mem_union_right _ hx₁) (mem_union_right _ hx₂) :=
Finset.coe_injective (by simp)
@[simp]
theorem preimage_compl' [DecidableEq α] [DecidableEq β] [Fintype α] [Fintype β] {f : α → β}
(s : Finset β) (hfc : InjOn f (f ⁻¹' ↑sᶜ)) (hf : InjOn f (f ⁻¹' ↑s)) :
preimage sᶜ f hfc = (preimage s f hf)ᶜ :=
Finset.coe_injective (by simp)
-- Not `@[simp]` since `simp` can't figure out `hf`; `simp`-normal form is `preimage_compl'`.
theorem preimage_compl [DecidableEq α] [DecidableEq β] [Fintype α] [Fintype β] {f : α → β}
(s : Finset β) (hf : Function.Injective f) :
preimage sᶜ f hf.injOn = (preimage s f hf.injOn)ᶜ :=
preimage_compl' _ _ _
@[simp]
lemma preimage_map (f : α ↪ β) (s : Finset α) : (s.map f).preimage f f.injective.injOn = s :=
coe_injective <| by simp only [coe_preimage, coe_map, Set.preimage_image_eq _ f.injective]
theorem monotone_preimage {f : α → β} (h : Injective f) :
Monotone fun s => preimage s f h.injOn := fun _ _ H _ hx =>
mem_preimage.2 (H <| mem_preimage.1 hx)
theorem image_subset_iff_subset_preimage [DecidableEq β] {f : α → β} {s : Finset α} {t : Finset β}
(hf : Set.InjOn f (f ⁻¹' ↑t)) : s.image f ⊆ t ↔ s ⊆ t.preimage f hf :=
image_subset_iff.trans <| by simp only [subset_iff, mem_preimage]
theorem map_subset_iff_subset_preimage {f : α ↪ β} {s : Finset α} {t : Finset β} :
s.map f ⊆ t ↔ s ⊆ t.preimage f f.injective.injOn := by
classical rw [map_eq_image, image_subset_iff_subset_preimage]
lemma card_preimage (s : Finset β) (f : α → β) (hf) [DecidablePred (· ∈ Set.range f)] :
(s.preimage f hf).card = {x ∈ s | x ∈ Set.range f}.card :=
card_nbij f (by simp [Set.MapsTo]) (by simpa) (fun b hb ↦ by aesop)
theorem image_preimage [DecidableEq β] (f : α → β) (s : Finset β) [∀ x, Decidable (x ∈ Set.range f)]
(hf : Set.InjOn f (f ⁻¹' ↑s)) : image f (preimage s f hf) = {x ∈ s | x ∈ Set.range f} :=
Finset.coe_inj.1 <| by
simp only [coe_image, coe_preimage, coe_filter, Set.image_preimage_eq_inter_range,
← Set.sep_mem_eq]; rfl
theorem image_preimage_of_bij [DecidableEq β] (f : α → β) (s : Finset β)
(hf : Set.BijOn f (f ⁻¹' ↑s) ↑s) : image f (preimage s f hf.injOn) = s :=
Finset.coe_inj.1 <| by simpa using hf.image_eq
lemma preimage_subset_of_subset_image [DecidableEq β] {f : α → β} {s : Finset β} {t : Finset α}
(hs : s ⊆ t.image f) {hf} : s.preimage f hf ⊆ t := by
rw [← coe_subset, coe_preimage]; exact Set.preimage_subset (mod_cast hs) hf
theorem preimage_subset {f : α ↪ β} {s : Finset β} {t : Finset α} (hs : s ⊆ t.map f) :
s.preimage f f.injective.injOn ⊆ t := fun _ h => (mem_map' f).1 (hs (mem_preimage.1 h))
theorem subset_map_iff {f : α ↪ β} {s : Finset β} {t : Finset α} :
s ⊆ t.map f ↔ ∃ u ⊆ t, s = u.map f := by
classical
simp_rw [map_eq_image, subset_image_iff, eq_comm]
theorem sigma_preimage_mk {β : α → Type*} [DecidableEq α] (s : Finset (Σ a, β a)) (t : Finset α) :
t.sigma (fun a => s.preimage (Sigma.mk a) sigma_mk_injective.injOn) = {a ∈ s | a.1 ∈ t} := by
ext x
simp [and_comm]
theorem sigma_preimage_mk_of_subset {β : α → Type*} [DecidableEq α] (s : Finset (Σ a, β a))
{t : Finset α} (ht : s.image Sigma.fst ⊆ t) :
(t.sigma fun a => s.preimage (Sigma.mk a) sigma_mk_injective.injOn) = s := by
rw [sigma_preimage_mk, filter_true_of_mem <| image_subset_iff.1 ht]
theorem sigma_image_fst_preimage_mk {β : α → Type*} [DecidableEq α] (s : Finset (Σ a, β a)) :
((s.image Sigma.fst).sigma fun a => s.preimage (Sigma.mk a) sigma_mk_injective.injOn) =
s :=
s.sigma_preimage_mk_of_subset (Subset.refl _)
@[simp] lemma preimage_inl (s : Finset (α ⊕ β)) :
s.preimage Sum.inl Sum.inl_injective.injOn = s.toLeft := by
ext x; simp
@[simp] lemma preimage_inr (s : Finset (α ⊕ β)) :
s.preimage Sum.inr Sum.inr_injective.injOn = s.toRight := by
ext x; simp
end Preimage
end Finset
namespace Equiv
/-- Given an equivalence `e : α ≃ β` and `s : Finset β`, restrict `e` to an equivalence
from `e ⁻¹' s` to `s`. -/
@[simps]
def restrictPreimageFinset (e : α ≃ β) (s : Finset β) : (s.preimage e e.injective.injOn) ≃ s where
toFun a := ⟨e a, Finset.mem_preimage.1 a.2⟩
invFun b := ⟨e.symm b, by simp⟩
left_inv _ := by simp
right_inv _ := by simp
end Equiv
/-- Reindexing and then restricting to a `Finset` is the same as first restricting to the preimage
of this `Finset` and then reindexing. -/
lemma Finset.restrict_comp_piCongrLeft {π : β → Type*} (s : Finset β) (e : α ≃ β) :
s.restrict ∘ ⇑(e.piCongrLeft π) =
⇑((e.restrictPreimageFinset s).piCongrLeft (fun b : s ↦ (π b))) ∘
(s.preimage e e.injective.injOn).restrict := by
ext x b
simp only [comp_apply, restrict, Equiv.piCongrLeft_apply_eq_cast,
Equiv.restrictPreimageFinset_symm_apply_coe] |
.lake/packages/mathlib/Mathlib/Data/Finset/Sym.lean | import Mathlib.Data.Finset.Lattice.Fold
import Mathlib.Data.Fintype.Vector
import Mathlib.Data.Multiset.Sym
/-!
# Symmetric powers of a finset
This file defines the symmetric powers of a finset as `Finset (Sym α n)` and `Finset (Sym2 α)`.
## Main declarations
* `Finset.sym`: The symmetric power of a finset. `s.sym n` is all the multisets of cardinality `n`
whose elements are in `s`.
* `Finset.sym2`: The symmetric square of a finset. `s.sym2` is all the pairs whose elements are in
`s`.
* A `Fintype (Sym2 α)` instance that does not require `DecidableEq α`.
## TODO
`Finset.sym` forms a Galois connection between `Finset α` and `Finset (Sym α n)`. Similar for
`Finset.sym2`.
-/
namespace Finset
variable {α β : Type*}
/-- `s.sym2` is the finset of all unordered pairs of elements from `s`.
It is the image of `s ×ˢ s` under the quotient `α × α → Sym2 α`. -/
@[simps]
protected def sym2 (s : Finset α) : Finset (Sym2 α) := ⟨s.1.sym2, s.2.sym2⟩
section
variable {s t : Finset α} {a b : α}
theorem mk_mem_sym2_iff : s(a, b) ∈ s.sym2 ↔ a ∈ s ∧ b ∈ s := by
rw [mem_mk, sym2_val, Multiset.mk_mem_sym2_iff, mem_mk, mem_mk]
@[simp]
theorem mem_sym2_iff {m : Sym2 α} : m ∈ s.sym2 ↔ ∀ a ∈ m, a ∈ s := by
rw [mem_mk, sym2_val, Multiset.mem_sym2_iff]
simp only [mem_val]
@[simp] lemma coe_sym2 {m : Finset α} : (m.sym2 : Set (Sym2 α)) = (m : Set α).sym2 :=
Set.ext fun z ↦ z.ind fun a b => by simp
theorem sym2_cons (a : α) (s : Finset α) (ha : a ∉ s) :
(s.cons a ha).sym2 = ((s.cons a ha).map <| Sym2.mkEmbedding a).disjUnion s.sym2 (by
simp [Finset.disjoint_left, ha]) :=
val_injective <| Multiset.sym2_cons _ _
theorem sym2_insert [DecidableEq α] (a : α) (s : Finset α) :
(insert a s).sym2 = ((insert a s).image fun b => s(a, b)) ∪ s.sym2 := by
obtain ha | ha := Decidable.em (a ∈ s)
· simp only [insert_eq_of_mem ha, right_eq_union, image_subset_iff]
simp_all
· simpa [map_eq_image] using sym2_cons a s ha
theorem sym2_map (f : α ↪ β) (s : Finset α) : (s.map f).sym2 = s.sym2.map (.sym2Map f) :=
val_injective <| s.val.sym2_map _
theorem sym2_image [DecidableEq β] (f : α → β) (s : Finset α) :
(s.image f).sym2 = s.sym2.image (Sym2.map f) := by
apply val_injective
dsimp [Finset.sym2]
rw [← Multiset.dedup_sym2, Multiset.sym2_map]
instance _root_.Sym2.instFintype [Fintype α] : Fintype (Sym2 α) where
elems := Finset.univ.sym2
complete := fun x ↦ by rw [mem_sym2_iff]; exact (fun a _ ↦ mem_univ a)
-- Note(kmill): Using a default argument to make this simp lemma more general.
@[simp]
theorem sym2_univ [Fintype α] (inst : Fintype (Sym2 α) := Sym2.instFintype) :
(univ : Finset α).sym2 = univ := by
ext
simp only [mem_sym2_iff, mem_univ, implies_true]
@[simp, mono]
theorem sym2_mono (h : s ⊆ t) : s.sym2 ⊆ t.sym2 := by
rw [← val_le_iff, sym2_val, sym2_val]
apply Multiset.sym2_mono
rwa [val_le_iff]
theorem monotone_sym2 : Monotone (Finset.sym2 : Finset α → _) := fun _ _ => sym2_mono
theorem injective_sym2 : Function.Injective (Finset.sym2 : Finset α → _) := by
intro s t h
ext x
simpa using congr(s(x, x) ∈ $h)
theorem strictMono_sym2 : StrictMono (Finset.sym2 : Finset α → _) :=
monotone_sym2.strictMono_of_injective injective_sym2
theorem sym2_toFinset [DecidableEq α] (m : Multiset α) :
m.toFinset.sym2 = m.sym2.toFinset := by
ext z
refine z.ind fun x y ↦ ?_
simp only [mk_mem_sym2_iff, Multiset.mem_toFinset, Multiset.mk_mem_sym2_iff]
@[simp]
theorem sym2_empty : (∅ : Finset α).sym2 = ∅ := rfl
@[simp]
theorem sym2_eq_empty : s.sym2 = ∅ ↔ s = ∅ := by
rw [← val_eq_zero, sym2_val, Multiset.sym2_eq_zero_iff, val_eq_zero]
@[simp]
theorem sym2_nonempty : s.sym2.Nonempty ↔ s.Nonempty := by
rw [← not_iff_not]
simp_rw [not_nonempty_iff_eq_empty, sym2_eq_empty]
@[aesop safe apply (rule_sets := [finsetNonempty])]
protected alias ⟨_, Nonempty.sym2⟩ := sym2_nonempty
@[simp]
theorem sym2_singleton (a : α) : ({a} : Finset α).sym2 = {Sym2.diag a} := rfl
/-- Finset **stars and bars** for the case `n = 2`. -/
theorem card_sym2 (s : Finset α) : s.sym2.card = Nat.choose (s.card + 1) 2 := by
rw [card_def, sym2_val, Multiset.card_sym2, ← card_def]
end
variable {s t : Finset α} {a b : α}
section
variable [DecidableEq α]
theorem sym2_eq_image : s.sym2 = (s ×ˢ s).image Sym2.mk := by
ext z
refine z.ind fun x y ↦ ?_
rw [mk_mem_sym2_iff, mem_image]
constructor
· intro h
use (x, y)
simp only [mem_product, h, and_self]
· rintro ⟨⟨a, b⟩, h⟩
simp only [mem_product, Sym2.eq_iff] at h
obtain ⟨h, (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩)⟩ := h
<;> simp [h]
theorem isDiag_mk_of_mem_diag {a : α × α} (h : a ∈ s.diag) : (Sym2.mk a).IsDiag :=
(Sym2.isDiag_iff_proj_eq _).2 (mem_diag.1 h).2
theorem not_isDiag_mk_of_mem_offDiag {a : α × α} (h : a ∈ s.offDiag) :
¬ (Sym2.mk a).IsDiag := by
rw [Sym2.isDiag_iff_proj_eq]
exact (mem_offDiag.1 h).2.2
end
section Sym2
variable {m : Sym2 α}
@[simp]
theorem diag_mem_sym2_mem_iff : (∀ b, b ∈ Sym2.diag a → b ∈ s) ↔ a ∈ s := by
rw [← mem_sym2_iff]
exact mk_mem_sym2_iff.trans <| and_self_iff
theorem diag_mem_sym2_iff : Sym2.diag a ∈ s.sym2 ↔ a ∈ s := by simp [diag_mem_sym2_mem_iff]
theorem image_diag_union_image_offDiag [DecidableEq α] :
s.diag.image Sym2.mk ∪ s.offDiag.image Sym2.mk = s.sym2 := by
rw [← image_union, diag_union_offDiag, sym2_eq_image]
end Sym2
section Sym
variable [DecidableEq α] {n : ℕ}
/-- Lifts a finset to `Sym α n`. `s.sym n` is the finset of all unordered tuples of cardinality `n`
with elements in `s`. -/
protected def sym (s : Finset α) : ∀ n, Finset (Sym α n)
| 0 => {∅}
| n + 1 => s.sup fun a ↦ Finset.image (Sym.cons a) (s.sym n)
@[simp]
theorem sym_zero : s.sym 0 = {∅} := rfl
@[simp]
theorem sym_succ : s.sym (n + 1) = s.sup fun a ↦ (s.sym n).image <| Sym.cons a := rfl
@[simp]
theorem mem_sym_iff {m : Sym α n} : m ∈ s.sym n ↔ ∀ a ∈ m, a ∈ s := by
induction n with
| zero =>
refine mem_singleton.trans ⟨?_, fun _ ↦ Sym.eq_nil_of_card_zero _⟩
rintro rfl
exact fun a ha ↦ (Finset.notMem_empty _ ha).elim
| succ n ih => ?_
refine mem_sup.trans ⟨?_, fun h ↦ ?_⟩
· rintro ⟨a, ha, he⟩ b hb
rw [mem_image] at he
obtain ⟨m, he, rfl⟩ := he
rw [Sym.mem_cons] at hb
obtain rfl | hb := hb
· exact ha
· exact ih.1 he _ hb
· obtain ⟨a, m, rfl⟩ := m.exists_eq_cons_of_succ
exact
⟨a, h _ <| Sym.mem_cons_self _ _,
mem_image_of_mem _ <| ih.2 fun b hb ↦ h _ <| Sym.mem_cons_of_mem hb⟩
-- @[simp] /- adaption note for https://github.com/leanprover/lean4/pull/8419: the simpNF complained -/
theorem sym_empty (n : ℕ) : (∅ : Finset α).sym (n + 1) = ∅ := rfl
theorem replicate_mem_sym (ha : a ∈ s) (n : ℕ) : Sym.replicate n a ∈ s.sym n :=
mem_sym_iff.2 fun b hb ↦ by rwa [(Sym.mem_replicate.1 hb).2]
protected theorem Nonempty.sym (h : s.Nonempty) (n : ℕ) : (s.sym n).Nonempty :=
let ⟨_a, ha⟩ := h
⟨_, replicate_mem_sym ha n⟩
@[simp]
theorem sym_singleton (a : α) (n : ℕ) : ({a} : Finset α).sym n = {Sym.replicate n a} :=
eq_singleton_iff_unique_mem.2
⟨replicate_mem_sym (mem_singleton.2 rfl) _, fun _s hs ↦
Sym.eq_replicate_iff.2 fun _b hb ↦ eq_of_mem_singleton <| mem_sym_iff.1 hs _ hb⟩
theorem eq_empty_of_sym_eq_empty (h : s.sym n = ∅) : s = ∅ := by
rw [← not_nonempty_iff_eq_empty] at h ⊢
exact fun hs ↦ h (hs.sym _)
@[simp]
theorem sym_eq_empty : s.sym n = ∅ ↔ n ≠ 0 ∧ s = ∅ := by
cases n
· exact iff_of_false (singleton_ne_empty _) fun h ↦ (h.1 rfl).elim
· refine ⟨fun h ↦ ⟨Nat.succ_ne_zero _, eq_empty_of_sym_eq_empty h⟩, ?_⟩
rintro ⟨_, rfl⟩
exact sym_empty _
@[simp]
theorem sym_nonempty : (s.sym n).Nonempty ↔ n = 0 ∨ s.Nonempty := by
simp only [nonempty_iff_ne_empty, ne_eq, sym_eq_empty, not_and_or, not_ne_iff]
@[simp]
theorem sym_univ [Fintype α] (n : ℕ) : (univ : Finset α).sym n = univ :=
eq_univ_iff_forall.2 fun _s ↦ mem_sym_iff.2 fun _a _ ↦ mem_univ _
@[simp]
theorem sym_mono (h : s ⊆ t) (n : ℕ) : s.sym n ⊆ t.sym n := fun _m hm ↦
mem_sym_iff.2 fun _a ha ↦ h <| mem_sym_iff.1 hm _ ha
@[simp]
theorem sym_inter (s t : Finset α) (n : ℕ) : (s ∩ t).sym n = s.sym n ∩ t.sym n := by
ext m
simp only [mem_inter, mem_sym_iff, imp_and, forall_and]
@[simp]
theorem sym_union (s t : Finset α) (n : ℕ) : s.sym n ∪ t.sym n ⊆ (s ∪ t).sym n :=
union_subset (sym_mono subset_union_left n) (sym_mono subset_union_right n)
theorem sym_fill_mem (a : α) {i : Fin (n + 1)} {m : Sym α (n - i)} (h : m ∈ s.sym (n - i)) :
m.fill a i ∈ (insert a s).sym n :=
mem_sym_iff.2 fun b hb ↦
mem_insert.2 <| (Sym.mem_fill_iff.1 hb).imp And.right <| mem_sym_iff.1 h b
theorem sym_filterNe_mem {m : Sym α n} (a : α) (h : m ∈ s.sym n) :
(m.filterNe a).2 ∈ (Finset.erase s a).sym (n - (m.filterNe a).1) :=
mem_sym_iff.2 fun b H ↦
mem_erase.2 <| (Multiset.mem_filter.1 H).symm.imp Ne.symm <| mem_sym_iff.1 h b
/-- If `a` does not belong to the finset `s`, then the `n`th symmetric power of `{a} ∪ s` is
in 1-1 correspondence with the disjoint union of the `n - i`th symmetric powers of `s`,
for `0 ≤ i ≤ n`. -/
@[simps]
def symInsertEquiv (h : a ∉ s) : (insert a s).sym n ≃ Σ i : Fin (n + 1), s.sym (n - i) where
toFun m := ⟨_, (m.1.filterNe a).2, by convert sym_filterNe_mem a m.2; rw [erase_insert h]⟩
invFun m := ⟨m.2.1.fill a m.1, sym_fill_mem a m.2.2⟩
left_inv m := Subtype.ext <| m.1.fill_filterNe a
right_inv := fun ⟨i, m, hm⟩ ↦ by
refine Function.Injective.sigma_map (β₂ := ?_) (f₂ := ?_)
(Function.injective_id) (fun i ↦ ?_) ?_
· exact fun i ↦ Sym α (n - i)
swap
· exact Subtype.coe_injective
refine Eq.trans ?_ (Sym.filter_ne_fill a _ ?_)
exacts [rfl, h ∘ mem_sym_iff.1 hm a]
end Sym
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/NatDivisors.lean | import Mathlib.NumberTheory.Divisors
import Mathlib.Algebra.Group.Pointwise.Finset.Basic
/-!
# `Nat.divisors` as a multiplicative homomorpism
The main definition of this file is `Nat.divisorsHom : ℕ →* Finset ℕ`,
exhibiting `Nat.divisors` as a multiplicative homomorphism from `ℕ` to `Finset ℕ`.
-/
open Nat Finset
open scoped Pointwise
/-- The divisors of a product of natural numbers are the pointwise product of the divisors of the
factors. -/
lemma Nat.divisors_mul (m n : ℕ) : divisors (m * n) = divisors m * divisors n := by
ext k
simp_rw [mem_mul, mem_divisors, Nat.dvd_mul, mul_ne_zero_iff, ← exists_and_left,
← exists_and_right]
simp only [and_assoc, and_comm, and_left_comm]
/-- `Nat.divisors` as a `MonoidHom`. -/
@[simps]
def Nat.divisorsHom : ℕ →* Finset ℕ where
toFun := Nat.divisors
map_mul' := divisors_mul
map_one' := divisors_one
lemma Nat.Prime.divisors_sq {p : ℕ} (hp : p.Prime) : (p ^ 2).divisors = {p ^ 2, p, 1} := by
simp [divisors_prime_pow hp, range_add_one]
lemma List.nat_divisors_prod (l : List ℕ) : divisors l.prod = (l.map divisors).prod :=
map_list_prod Nat.divisorsHom l
lemma Multiset.nat_divisors_prod (s : Multiset ℕ) : divisors s.prod = (s.map divisors).prod :=
map_multiset_prod Nat.divisorsHom s
lemma Finset.nat_divisors_prod {ι : Type*} (s : Finset ι) (f : ι → ℕ) :
divisors (∏ i ∈ s, f i) = ∏ i ∈ s, divisors (f i) :=
map_prod Nat.divisorsHom f s |
.lake/packages/mathlib/Mathlib/Data/Finset/Lattice/Lemmas.lean | import Mathlib.Data.Finset.Insert
import Mathlib.Data.Finset.Lattice.Basic
/-!
# Lemmas about the lattice structure of finite sets
This file contains many results on the lattice structure of `Finset α`, in particular the
interaction between union, intersection, empty set and inserting elements.
## Tags
finite sets, finset
-/
-- Assert that we define `Finset` without the material on `List.sublists`.
-- Note that we cannot use `List.sublists` itself as that is defined very early.
assert_not_exists List.sublistsLen Multiset.powerset CompleteLattice Monoid
open Multiset Subtype Function
universe u
variable {α : Type*} {β : Type*} {γ : Type*}
namespace Finset
-- TODO: these should be global attributes, but this will require fixing other files
attribute [local trans] Subset.trans Superset.trans
/-! ### Lattice structure -/
section Lattice
variable [DecidableEq α] {s s₁ s₂ t t₁ t₂ u v : Finset α} {a b : α}
theorem disjoint_iff_inter_eq_empty : Disjoint s t ↔ s ∩ t = ∅ :=
disjoint_iff
/-! #### union -/
@[simp]
theorem union_empty (s : Finset α) : s ∪ ∅ = s :=
ext fun x => mem_union.trans <| by simp
@[simp]
theorem empty_union (s : Finset α) : ∅ ∪ s = s :=
ext fun x => mem_union.trans <| by simp
@[aesop unsafe apply (rule_sets := [finsetNonempty])]
theorem Nonempty.inl {s t : Finset α} (h : s.Nonempty) : (s ∪ t).Nonempty :=
h.mono subset_union_left
@[aesop unsafe apply (rule_sets := [finsetNonempty])]
theorem Nonempty.inr {s t : Finset α} (h : t.Nonempty) : (s ∪ t).Nonempty :=
h.mono subset_union_right
theorem insert_eq (a : α) (s : Finset α) : insert a s = {a} ∪ s :=
rfl
@[simp, grind =]
lemma singleton_union (x : α) (s : Finset α) : {x} ∪ s = insert x s :=
rfl
@[simp, grind =]
lemma union_singleton (x : α) (s : Finset α) : s ∪ {x} = insert x s := by
rw [Finset.union_comm, singleton_union]
@[simp, grind =]
theorem insert_union (a : α) (s t : Finset α) : insert a s ∪ t = insert a (s ∪ t) := by
simp only [insert_eq, union_assoc]
@[simp, grind =]
theorem union_insert (a : α) (s t : Finset α) : s ∪ insert a t = insert a (s ∪ t) := by
simp only [insert_eq, union_left_comm]
theorem insert_union_distrib (a : α) (s t : Finset α) :
insert a (s ∪ t) = insert a s ∪ insert a t := by
simp only [insert_union, union_insert, insert_idem]
/-- To prove a relation on pairs of `Finset X`, it suffices to show that it is
* symmetric,
* it holds when one of the `Finset`s is empty,
* it holds for pairs of singletons,
* if it holds for `[a, c]` and for `[b, c]`, then it holds for `[a ∪ b, c]`.
-/
theorem induction_on_union (P : Finset α → Finset α → Prop) (symm : ∀ {a b}, P a b → P b a)
(empty_right : ∀ {a}, P a ∅) (singletons : ∀ {a b}, P {a} {b})
(union_of : ∀ {a b c}, P a c → P b c → P (a ∪ b) c) : ∀ a b, P a b := by
intro a b
refine Finset.induction_on b empty_right fun x s _xs hi => symm ?_
rw [Finset.insert_eq]
apply union_of _ (symm hi)
refine Finset.induction_on a empty_right fun a t _ta hi => symm ?_
rw [Finset.insert_eq]
exact union_of singletons (symm hi)
/-! #### inter -/
@[simp]
theorem inter_empty (s : Finset α) : s ∩ ∅ = ∅ :=
ext fun _ => mem_inter.trans <| by simp
@[simp]
theorem empty_inter (s : Finset α) : ∅ ∩ s = ∅ :=
ext fun _ => mem_inter.trans <| by simp
@[simp]
theorem insert_inter_of_mem {s₁ s₂ : Finset α} {a : α} (h : a ∈ s₂) :
insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) :=
ext fun x => by
have : x = a ∨ x ∈ s₂ ↔ x ∈ s₂ := or_iff_right_of_imp <| by rintro rfl; exact h
simp only [mem_inter, mem_insert, or_and_left, this]
@[simp]
theorem inter_insert_of_mem {s₁ s₂ : Finset α} {a : α} (h : a ∈ s₁) :
s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm]
@[simp]
theorem insert_inter_of_notMem {s₁ s₂ : Finset α} {a : α} (h : a ∉ s₂) :
insert a s₁ ∩ s₂ = s₁ ∩ s₂ :=
ext fun x => by
have : ¬(x = a ∧ x ∈ s₂) := by rintro ⟨rfl, H⟩; exact h H
simp only [mem_inter, mem_insert, or_and_right, this, false_or]
@[deprecated (since := "2025-05-23")] alias insert_inter_of_not_mem := insert_inter_of_notMem
@[simp]
theorem inter_insert_of_notMem {s₁ s₂ : Finset α} {a : α} (h : a ∉ s₁) :
s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_notMem h, inter_comm]
@[deprecated (since := "2025-05-23")] alias inter_insert_of_not_mem := inter_insert_of_notMem
@[grind =]
theorem inter_insert {s₁ s₂ : Finset α} {a : α} :
insert a s₁ ∩ s₂ = if a ∈ s₂ then insert a (s₁ ∩ s₂) else s₁ ∩ s₂ := by
split_ifs <;> simp [*]
@[grind =]
theorem insert_inter {s₁ s₂ : Finset α} {a : α} :
s₁ ∩ insert a s₂ = if a ∈ s₁ then insert a (s₁ ∩ s₂) else s₁ ∩ s₂ := by
split_ifs <;> simp [*]
@[simp]
theorem singleton_inter_of_mem {a : α} {s : Finset α} (H : a ∈ s) : {a} ∩ s = {a} :=
show insert a ∅ ∩ s = insert a ∅ by rw [insert_inter_of_mem H, empty_inter]
@[simp]
theorem singleton_inter_of_notMem {a : α} {s : Finset α} (H : a ∉ s) : {a} ∩ s = ∅ :=
eq_empty_of_forall_notMem <| by
simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h
@[deprecated (since := "2025-05-23")] alias singleton_inter_of_not_mem := singleton_inter_of_notMem
@[grind =]
lemma singleton_inter {a : α} {s : Finset α} :
{a} ∩ s = if a ∈ s then {a} else ∅ := by
split_ifs with h <;> simp [h]
@[simp]
theorem inter_singleton_of_mem {a : α} {s : Finset α} (h : a ∈ s) : s ∩ {a} = {a} := by
rw [inter_comm, singleton_inter_of_mem h]
@[simp]
theorem inter_singleton_of_notMem {a : α} {s : Finset α} (h : a ∉ s) : s ∩ {a} = ∅ := by
rw [inter_comm, singleton_inter_of_notMem h]
@[deprecated (since := "2025-05-23")] alias inter_singleton_of_not_mem := inter_singleton_of_notMem
lemma inter_singleton {a : α} {s : Finset α} :
s ∩ {a} = if a ∈ s then {a} else ∅ := by
split_ifs with h <;> simp [h]
@[simp] lemma union_eq_empty : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := sup_eq_bot_iff
@[simp] lemma union_nonempty : (s ∪ t).Nonempty ↔ s.Nonempty ∨ t.Nonempty :=
mod_cast Set.union_nonempty (α := α) (s := s) (t := t)
theorem insert_union_comm (s t : Finset α) (a : α) : insert a s ∪ t = s ∪ insert a t := by
rw [insert_union, union_insert]
end Lattice
end Finset
namespace List
variable [DecidableEq α] {l l' : List α}
@[simp]
theorem toFinset_append : toFinset (l ++ l') = l.toFinset ∪ l'.toFinset := by
induction l with
| nil => simp
| cons hd tl hl => simp [hl]
end List |
.lake/packages/mathlib/Mathlib/Data/Finset/Lattice/Prod.lean | import Mathlib.Data.Finset.Lattice.Fold
import Mathlib.Data.Finset.Prod
/-!
# Lattice operations on finsets of products
This file is concerned with folding binary lattice operations over finsets.
-/
assert_not_exists IsOrderedMonoid MonoidWithZero
open Function Multiset OrderDual
variable {F α β γ ι κ : Type*}
namespace Finset
/-! ### sup -/
section Sup
-- TODO: define with just `[Bot α]` where some lemmas hold without requiring `[OrderBot α]`
variable [SemilatticeSup α] [OrderBot α]
/-- See also `Finset.product_biUnion`. -/
theorem sup_product_left (s : Finset β) (t : Finset γ) (f : β × γ → α) :
(s ×ˢ t).sup f = s.sup fun i => t.sup fun i' => f ⟨i, i'⟩ :=
eq_of_forall_ge_iff fun a => by simp [@forall_swap _ γ]
theorem sup_product_right (s : Finset β) (t : Finset γ) (f : β × γ → α) :
(s ×ˢ t).sup f = t.sup fun i' => s.sup fun i => f ⟨i, i'⟩ := by
rw [sup_product_left, Finset.sup_comm]
section Prod
variable {ι κ α β : Type*} [SemilatticeSup α] [SemilatticeSup β] [OrderBot α] [OrderBot β]
{s : Finset ι} {t : Finset κ}
@[simp] lemma sup_prodMap (hs : s.Nonempty) (ht : t.Nonempty) (f : ι → α) (g : κ → β) :
sup (s ×ˢ t) (Prod.map f g) = (sup s f, sup t g) :=
eq_of_forall_ge_iff fun i ↦ by
obtain ⟨a, ha⟩ := hs
obtain ⟨b, hb⟩ := ht
simp only [Prod.map, Finset.sup_le_iff, mem_product, and_imp, Prod.forall, Prod.le_def]
exact ⟨fun h ↦ ⟨fun i hi ↦ (h _ _ hi hb).1, fun j hj ↦ (h _ _ ha hj).2⟩, by simp_all⟩
end Prod
end Sup
/-! ### inf -/
section Inf
-- TODO: define with just `[Top α]` where some lemmas hold without requiring `[OrderTop α]`
variable [SemilatticeInf α] [OrderTop α]
theorem inf_product_left (s : Finset β) (t : Finset γ) (f : β × γ → α) :
(s ×ˢ t).inf f = s.inf fun i => t.inf fun i' => f ⟨i, i'⟩ :=
@sup_product_left αᵒᵈ _ _ _ _ _ _ _
theorem inf_product_right (s : Finset β) (t : Finset γ) (f : β × γ → α) :
(s ×ˢ t).inf f = t.inf fun i' => s.inf fun i => f ⟨i, i'⟩ :=
@sup_product_right αᵒᵈ _ _ _ _ _ _ _
section Prod
variable {ι κ α β : Type*} [SemilatticeInf α] [SemilatticeInf β] [OrderTop α] [OrderTop β]
{s : Finset ι} {t : Finset κ}
@[simp] lemma inf_prodMap (hs : s.Nonempty) (ht : t.Nonempty) (f : ι → α) (g : κ → β) :
inf (s ×ˢ t) (Prod.map f g) = (inf s f, inf t g) :=
sup_prodMap (α := αᵒᵈ) (β := βᵒᵈ) hs ht _ _
end Prod
end Inf
section DistribLattice
variable [DistribLattice α]
section OrderBot
variable [OrderBot α] {s : Finset ι} {t : Finset κ} {f : ι → α} {g : κ → α} {a : α}
theorem sup_inf_sup (s : Finset ι) (t : Finset κ) (f : ι → α) (g : κ → α) :
s.sup f ⊓ t.sup g = (s ×ˢ t).sup fun i => f i.1 ⊓ g i.2 := by
simp_rw [Finset.sup_inf_distrib_right, Finset.sup_inf_distrib_left, sup_product_left]
end OrderBot
section OrderTop
variable [OrderTop α] {f : ι → α} {g : κ → α} {s : Finset ι} {t : Finset κ} {a : α}
theorem inf_sup_inf (s : Finset ι) (t : Finset κ) (f : ι → α) (g : κ → α) :
s.inf f ⊔ t.inf g = (s ×ˢ t).inf fun i => f i.1 ⊔ g i.2 :=
@sup_inf_sup αᵒᵈ _ _ _ _ _ _ _ _
end OrderTop
end DistribLattice
section Sup'
variable [SemilatticeSup α]
variable {s : Finset β} (H : s.Nonempty) (f : β → α)
theorem sup'_product_left {t : Finset γ} (h : (s ×ˢ t).Nonempty) (f : β × γ → α) :
(s ×ˢ t).sup' h f = s.sup' h.fst fun i => t.sup' h.snd fun i' => f ⟨i, i'⟩ :=
eq_of_forall_ge_iff fun a => by simp [@forall_swap _ γ]
theorem sup'_product_right {t : Finset γ} (h : (s ×ˢ t).Nonempty) (f : β × γ → α) :
(s ×ˢ t).sup' h f = t.sup' h.snd fun i' => s.sup' h.fst fun i => f ⟨i, i'⟩ := by
rw [sup'_product_left, Finset.sup'_comm]
section Prod
variable {ι κ α β : Type*} [SemilatticeSup α] [SemilatticeSup β] {s : Finset ι} {t : Finset κ}
/-- See also `Finset.sup'_prodMap`. -/
lemma prodMk_sup'_sup' (hs : s.Nonempty) (ht : t.Nonempty) (f : ι → α) (g : κ → β) :
(sup' s hs f, sup' t ht g) = sup' (s ×ˢ t) (hs.product ht) (Prod.map f g) :=
eq_of_forall_ge_iff fun i ↦ by
obtain ⟨a, ha⟩ := hs
obtain ⟨b, hb⟩ := ht
simp only [Prod.map, sup'_le_iff, mem_product, and_imp, Prod.forall, Prod.le_def]
exact ⟨by simp_all, fun h ↦ ⟨fun i hi ↦ (h _ _ hi hb).1, fun j hj ↦ (h _ _ ha hj).2⟩⟩
/-- See also `Finset.prodMk_sup'_sup'`. -/
-- @[simp] -- TODO: Why does `Prod.map_apply` simplify the LHS?
lemma sup'_prodMap (hst : (s ×ˢ t).Nonempty) (f : ι → α) (g : κ → β) :
sup' (s ×ˢ t) hst (Prod.map f g) = (sup' s hst.fst f, sup' t hst.snd g) :=
(prodMk_sup'_sup' _ _ _ _).symm
end Prod
end Sup'
section Inf'
variable [SemilatticeInf α]
variable {s : Finset β} (H : s.Nonempty) (f : β → α)
theorem inf'_product_left {t : Finset γ} (h : (s ×ˢ t).Nonempty) (f : β × γ → α) :
(s ×ˢ t).inf' h f = s.inf' h.fst fun i => t.inf' h.snd fun i' => f ⟨i, i'⟩ :=
sup'_product_left (α := αᵒᵈ) h f
theorem inf'_product_right {t : Finset γ} (h : (s ×ˢ t).Nonempty) (f : β × γ → α) :
(s ×ˢ t).inf' h f = t.inf' h.snd fun i' => s.inf' h.fst fun i => f ⟨i, i'⟩ :=
sup'_product_right (α := αᵒᵈ) h f
section Prod
variable {ι κ α β : Type*} [SemilatticeInf α] [SemilatticeInf β] {s : Finset ι} {t : Finset κ}
/-- See also `Finset.inf'_prodMap`. -/
lemma prodMk_inf'_inf' (hs : s.Nonempty) (ht : t.Nonempty) (f : ι → α) (g : κ → β) :
(inf' s hs f, inf' t ht g) = inf' (s ×ˢ t) (hs.product ht) (Prod.map f g) :=
prodMk_sup'_sup' (α := αᵒᵈ) (β := βᵒᵈ) hs ht _ _
/-- See also `Finset.prodMk_inf'_inf'`. -/
-- @[simp] -- TODO: Why does `Prod.map_apply` simplify the LHS?
lemma inf'_prodMap (hst : (s ×ˢ t).Nonempty) (f : ι → α) (g : κ → β) :
inf' (s ×ˢ t) hst (Prod.map f g) = (inf' s hst.fst f, inf' t hst.snd g) :=
(prodMk_inf'_inf' _ _ _ _).symm
end Prod
end Inf'
section DistribLattice
variable [DistribLattice α] {s : Finset ι} {t : Finset κ} (hs : s.Nonempty) (ht : t.Nonempty)
{f : ι → α} {g : κ → α} {a : α}
theorem sup'_inf_sup' (f : ι → α) (g : κ → α) :
s.sup' hs f ⊓ t.sup' ht g = (s ×ˢ t).sup' (hs.product ht) fun i => f i.1 ⊓ g i.2 := by
simp_rw [Finset.sup'_inf_distrib_right, Finset.sup'_inf_distrib_left, sup'_product_left]
theorem inf'_sup_inf' (f : ι → α) (g : κ → α) :
s.inf' hs f ⊔ t.inf' ht g = (s ×ˢ t).inf' (hs.product ht) fun i => f i.1 ⊔ g i.2 :=
@sup'_inf_sup' αᵒᵈ _ _ _ _ _ hs ht _ _
end DistribLattice
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Lattice/Union.lean | import Mathlib.Data.Finset.Lattice.Fold
import Mathlib.Data.Finset.Union
/-!
# Relating `Finset.biUnion` with lattice operations
This file shows `Finset.biUnion` could alternatively be defined in terms of `Finset.sup`.
## TODO
Remove `Finset.biUnion` in favour of `Finset.sup`.
-/
open Function Multiset OrderDual
variable {F α β γ ι κ : Type*}
variable {s s₁ s₂ : Finset β} {f g : β → α} {a : α}
namespace Finset
section Sup
variable [SemilatticeSup α] [OrderBot α]
@[simp, grind =]
theorem sup_biUnion [DecidableEq β] (s : Finset γ) (t : γ → Finset β) :
(s.biUnion t).sup f = s.sup fun x => (t x).sup f :=
eq_of_forall_ge_iff fun c => by simp [@forall_swap _ β]
end Sup
section Inf
variable [SemilatticeInf α] [OrderTop α]
@[simp, grind =] theorem inf_biUnion [DecidableEq β] (s : Finset γ) (t : γ → Finset β) :
(s.biUnion t).inf f = s.inf fun x => (t x).inf f :=
@sup_biUnion αᵒᵈ _ _ _ _ _ _ _ _
end Inf
section Sup'
variable [SemilatticeSup α]
variable {s : Finset β} (H : s.Nonempty) (f : β → α)
theorem sup'_biUnion [DecidableEq β] {s : Finset γ} (Hs : s.Nonempty) {t : γ → Finset β}
(Ht : ∀ b, (t b).Nonempty) :
(s.biUnion t).sup' (Hs.biUnion fun b _ => Ht b) f = s.sup' Hs (fun b => (t b).sup' (Ht b) f) :=
eq_of_forall_ge_iff fun c => by simp [@forall_swap _ β]
end Sup'
section Inf'
variable [SemilatticeInf α]
variable {s : Finset β} (H : s.Nonempty) (f : β → α)
theorem inf'_biUnion [DecidableEq β] {s : Finset γ} (Hs : s.Nonempty) {t : γ → Finset β}
(Ht : ∀ b, (t b).Nonempty) :
(s.biUnion t).inf' (Hs.biUnion fun b _ => Ht b) f = s.inf' Hs (fun b => (t b).inf' (Ht b) f) :=
sup'_biUnion (α := αᵒᵈ) _ Hs Ht
end Inf'
variable [DecidableEq α] {s : Finset ι} {f : ι → Finset α} {a : α}
theorem sup_eq_biUnion {α β} [DecidableEq β] (s : Finset α) (t : α → Finset β) :
s.sup t = s.biUnion t := by
ext
rw [mem_sup, mem_biUnion]
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Lattice/Pi.lean | import Mathlib.Data.Finset.Lattice.Prod
import Mathlib.Data.Finset.Pi
/-!
# Lattice operations on finsets of functions
This file is concerned with folding binary lattice operations over finsets.
-/
assert_not_exists IsOrderedMonoid MonoidWithZero
variable {α ι : Type*}
namespace Finset
variable [DistribLattice α] [BoundedOrder α] [DecidableEq ι]
--TODO: Extract out the obvious isomorphism `(insert i s).pi t ≃ t i ×ˢ s.pi t` from this proof
theorem inf_sup {κ : ι → Type*} (s : Finset ι) (t : ∀ i, Finset (κ i)) (f : ∀ i, κ i → α) :
(s.inf fun i => (t i).sup (f i)) =
(s.pi t).sup fun g => s.attach.inf fun i => f _ <| g _ i.2 := by
induction s using Finset.induction with
| empty => simp
| insert i s hi ih => ?_
rw [inf_insert, ih, attach_insert, sup_inf_sup]
refine eq_of_forall_ge_iff fun c => ?_
simp only [Finset.sup_le_iff, mem_product, mem_pi, and_imp, Prod.forall,
inf_insert, inf_image]
refine
⟨fun h g hg =>
h (g i <| mem_insert_self _ _) (fun j hj => g j <| mem_insert_of_mem hj)
(hg _ <| mem_insert_self _ _) fun j hj => hg _ <| mem_insert_of_mem hj,
fun h a g ha hg => ?_⟩
-- TODO: This `have` must be named to prevent it being shadowed by the internal `this` in `simpa`
have aux : ∀ j : { x // x ∈ s }, ↑j ≠ i := fun j : s => ne_of_mem_of_not_mem j.2 hi
-- `simpa` doesn't support placeholders in proof terms
have := h (fun j hj => if hji : j = i then cast (congr_arg κ hji.symm) a
else g _ <| mem_of_mem_insert_of_ne hj hji) (fun j hj => ?_)
· simpa only [cast_eq, dif_pos, Function.comp_def, Subtype.coe_mk, dif_neg, aux] using this
rw [mem_insert] at hj
obtain (rfl | hj) := hj
· simpa
· simpa [ne_of_mem_of_not_mem hj hi] using hg _ _
theorem sup_inf {κ : ι → Type*} (s : Finset ι) (t : ∀ i, Finset (κ i)) (f : ∀ i, κ i → α) :
(s.sup fun i => (t i).inf (f i)) = (s.pi t).inf fun g => s.attach.sup fun i => f _ <| g _ i.2 :=
@inf_sup αᵒᵈ _ _ _ _ _ _ _ _
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Lattice/Basic.lean | import Mathlib.Data.Finset.Defs
import Mathlib.Data.Multiset.FinsetOps
/-!
# Lattice structure on finite sets
This file puts a lattice structure on finite sets using the union and intersection operators.
For `Finset α`, where `α` is a lattice, see also `Mathlib/Data/Finset/Lattice/Fold.lean`.
## Main declarations
There is a natural lattice structure on the subsets of a set.
In Lean, we use lattice notation to talk about things involving unions and intersections. See
`Mathlib/Order/Lattice.lean`. For the lattice structure on finsets, `⊥` is called `bot` with
`⊥ = ∅` and `⊤` is called `top` with `⊤ = univ`.
* `Finset.instHasSubsetFinset`: Lots of API about lattices, otherwise behaves as one would expect.
* `Finset.instUnionFinset`: Defines `s ∪ t` (or `s ⊔ t`) as the union of `s` and `t`.
See `Finset.sup`/`Finset.biUnion` for finite unions.
* `Finset.instInterFinset`: Defines `s ∩ t` (or `s ⊓ t`) as the intersection of `s` and `t`.
See `Finset.inf` for finite intersections.
### Operations on two or more finsets
* `Finset.instUnionFinset`: see "The lattice structure on subsets of finsets"
* `Finset.instInterFinset`: see "The lattice structure on subsets of finsets"
## Tags
finite sets, finset
-/
-- Assert that we define `Finset` without the material on `List.sublists`.
-- Note that we cannot use `List.sublists` itself as that is defined very early.
assert_not_exists List.sublistsLen Multiset.powerset CompleteLattice IsOrderedMonoid
open Multiset Subtype Function
universe u
variable {α : Type*}
namespace Finset
-- TODO: these should be global attributes, but this will require fixing other files
attribute [local trans] Subset.trans Superset.trans
/-! ### Lattice structure -/
section Lattice
variable [DecidableEq α] {s s₁ s₂ t t₁ t₂ u v : Finset α} {a : α}
/-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/
instance : Union (Finset α) :=
⟨fun s t => ⟨_, t.2.ndunion s.1⟩⟩
/-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/
instance : Inter (Finset α) :=
⟨fun s t => ⟨_, s.2.ndinter t.1⟩⟩
instance : Lattice (Finset α) :=
{ Finset.partialOrder with
sup := (· ∪ ·)
sup_le := fun _ _ _ hs ht _ ha => (mem_ndunion.1 ha).elim (fun h => hs h) fun h => ht h
le_sup_left := fun _ _ _ h => mem_ndunion.2 <| Or.inl h
le_sup_right := fun _ _ _ h => mem_ndunion.2 <| Or.inr h
inf := (· ∩ ·)
le_inf := fun _ _ _ ht hu _ h => mem_ndinter.2 ⟨ht h, hu h⟩
inf_le_left := fun _ _ _ h => (mem_ndinter.1 h).1
inf_le_right := fun _ _ _ h => (mem_ndinter.1 h).2 }
@[simp]
theorem sup_eq_union' : (Max.max : Finset α → Finset α → Finset α) = Union.union :=
rfl
@[grind =]
theorem sup_eq_union {s t : Finset α} : s ⊔ t = s ∪ t :=
rfl
@[simp]
theorem inf_eq_inter' : (Min.min : Finset α → Finset α → Finset α) = Inter.inter :=
rfl
@[grind =]
theorem inf_eq_inter {s t : Finset α} : s ⊓ t = s ∩ t :=
rfl
/-! #### union -/
theorem union_val_nd (s t : Finset α) : (s ∪ t).1 = ndunion s.1 t.1 :=
rfl
@[simp]
theorem union_val (s t : Finset α) : (s ∪ t).1 = s.1 ∪ t.1 :=
ndunion_eq_union s.2
@[simp, grind =]
theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t :=
mem_ndunion
theorem mem_union_left (t : Finset α) (h : a ∈ s) : a ∈ s ∪ t :=
mem_union.2 <| Or.inl h
theorem mem_union_right (s : Finset α) (h : a ∈ t) : a ∈ s ∪ t :=
mem_union.2 <| Or.inr h
theorem forall_mem_union {p : α → Prop} : (∀ a ∈ s ∪ t, p a) ↔ (∀ a ∈ s, p a) ∧ ∀ a ∈ t, p a := by
grind
theorem notMem_union : a ∉ s ∪ t ↔ a ∉ s ∧ a ∉ t := by rw [mem_union, not_or]
@[deprecated (since := "2025-05-23")] alias not_mem_union := notMem_union
@[simp, norm_cast]
theorem coe_union (s₁ s₂ : Finset α) : ↑(s₁ ∪ s₂) = (s₁ ∪ s₂ : Set α) :=
Set.ext fun _ => mem_union
theorem union_subset (hs : s ⊆ u) : t ⊆ u → s ∪ t ⊆ u :=
sup_le <| le_iff_subset.2 hs
@[simp] lemma subset_union_left : s₁ ⊆ s₁ ∪ s₂ := fun _ ↦ mem_union_left _
@[simp] lemma subset_union_right : s₂ ⊆ s₁ ∪ s₂ := fun _ ↦ mem_union_right _
@[gcongr]
theorem union_subset_union (hsu : s ⊆ u) (htv : t ⊆ v) : s ∪ t ⊆ u ∪ v :=
sup_le_sup (le_iff_subset.2 hsu) htv
theorem union_subset_union_left (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t :=
union_subset_union h Subset.rfl
theorem union_subset_union_right (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ :=
union_subset_union Subset.rfl h
theorem union_comm (s₁ s₂ : Finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := sup_comm _ _
instance : Std.Commutative (α := Finset α) (· ∪ ·) :=
⟨union_comm⟩
@[simp]
theorem union_assoc (s₁ s₂ s₃ : Finset α) : s₁ ∪ s₂ ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := sup_assoc _ _ _
instance : Std.Associative (α := Finset α) (· ∪ ·) :=
⟨union_assoc⟩
@[simp]
theorem union_idempotent (s : Finset α) : s ∪ s = s := sup_idem _
instance : Std.IdempotentOp (α := Finset α) (· ∪ ·) :=
⟨union_idempotent⟩
theorem union_subset_left (h : s ∪ t ⊆ u) : s ⊆ u :=
subset_union_left.trans h
theorem union_subset_right {s t u : Finset α} (h : s ∪ t ⊆ u) : t ⊆ u :=
Subset.trans subset_union_right h
theorem union_left_comm (s t u : Finset α) : s ∪ (t ∪ u) = t ∪ (s ∪ u) :=
ext fun _ => by simp only [mem_union, or_left_comm]
theorem union_right_comm (s t u : Finset α) : s ∪ t ∪ u = s ∪ u ∪ t :=
ext fun x => by simp only [mem_union, or_assoc, @or_comm (x ∈ t)]
theorem union_self (s : Finset α) : s ∪ s = s :=
union_idempotent s
@[simp] lemma union_eq_left : s ∪ t = s ↔ t ⊆ s := sup_eq_left
@[simp] lemma left_eq_union : s = s ∪ t ↔ t ⊆ s := by rw [eq_comm, union_eq_left]
@[simp] lemma union_eq_right : s ∪ t = t ↔ s ⊆ t := sup_eq_right
@[simp] lemma right_eq_union : s = t ∪ s ↔ t ⊆ s := by rw [eq_comm, union_eq_right]
theorem union_congr_left (ht : t ⊆ s ∪ u) (hu : u ⊆ s ∪ t) : s ∪ t = s ∪ u :=
sup_congr_left ht hu
theorem union_congr_right (hs : s ⊆ t ∪ u) (ht : t ⊆ s ∪ u) : s ∪ u = t ∪ u :=
sup_congr_right hs ht
theorem union_eq_union_iff_left : s ∪ t = s ∪ u ↔ t ⊆ s ∪ u ∧ u ⊆ s ∪ t :=
sup_eq_sup_iff_left
theorem union_eq_union_iff_right : s ∪ u = t ∪ u ↔ s ⊆ t ∪ u ∧ t ⊆ s ∪ u :=
sup_eq_sup_iff_right
theorem inter_val_nd (s₁ s₂ : Finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 :=
rfl
@[simp]
theorem inter_val (s₁ s₂ : Finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 :=
ndinter_eq_inter s₁.2
@[simp, grind =]
theorem mem_inter {a : α} {s₁ s₂ : Finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ :=
mem_ndinter
theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : Finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ :=
(mem_inter.1 h).1
theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : Finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ :=
(mem_inter.1 h).2
theorem mem_inter_of_mem {a : α} {s₁ s₂ : Finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ :=
and_imp.1 mem_inter.2
@[simp] lemma inter_subset_left : s₁ ∩ s₂ ⊆ s₁ := fun _ ↦ mem_of_mem_inter_left
@[simp] lemma inter_subset_right : s₁ ∩ s₂ ⊆ s₂ := fun _ ↦ mem_of_mem_inter_right
theorem subset_inter {s₁ s₂ u : Finset α} : s₁ ⊆ s₂ → s₁ ⊆ u → s₁ ⊆ s₂ ∩ u := by grind
@[simp, norm_cast]
theorem coe_inter (s₁ s₂ : Finset α) : ↑(s₁ ∩ s₂) = (s₁ ∩ s₂ : Set α) :=
Set.ext fun _ => mem_inter
@[simp]
theorem union_inter_cancel_left {s t : Finset α} : (s ∪ t) ∩ s = s := by grind
@[simp]
theorem union_inter_cancel_right {s t : Finset α} : (s ∪ t) ∩ t = t := by grind
theorem inter_comm (s₁ s₂ : Finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := by grind
@[simp]
theorem inter_assoc (s₁ s₂ s₃ : Finset α) : s₁ ∩ s₂ ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := by grind
theorem inter_left_comm (s₁ s₂ s₃ : Finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := by grind
theorem inter_right_comm (s₁ s₂ s₃ : Finset α) : s₁ ∩ s₂ ∩ s₃ = s₁ ∩ s₃ ∩ s₂ := by grind
@[simp]
theorem inter_self (s : Finset α) : s ∩ s = s :=
ext fun _ => mem_inter.trans <| and_self_iff
@[simp]
theorem inter_union_self (s t : Finset α) : s ∩ (t ∪ s) = s := by
rw [inter_comm, union_inter_cancel_right]
@[mono, gcongr]
theorem inter_subset_inter {x y s t : Finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := by grind
theorem inter_subset_inter_left (h : t ⊆ u) : s ∩ t ⊆ s ∩ u :=
inter_subset_inter Subset.rfl h
theorem inter_subset_inter_right (h : s ⊆ t) : s ∩ u ⊆ t ∩ u :=
inter_subset_inter h Subset.rfl
theorem inter_subset_union : s ∩ t ⊆ s ∪ t :=
le_iff_subset.1 inf_le_sup
instance : DistribLattice (Finset α) :=
{ le_sup_inf := fun a b c => by
simp +contextual only
[sup_eq_union, inf_eq_inter, le_eq_subset, subset_iff, mem_inter, mem_union, and_imp,
or_imp, true_or, imp_true_iff, true_and, or_true] }
@[simp]
theorem union_left_idem (s t : Finset α) : s ∪ (s ∪ t) = s ∪ t := sup_left_idem _ _
theorem union_right_idem (s t : Finset α) : s ∪ t ∪ t = s ∪ t := sup_right_idem _ _
@[simp]
theorem inter_left_idem (s t : Finset α) : s ∩ (s ∩ t) = s ∩ t := inf_left_idem _ _
theorem inter_right_idem (s t : Finset α) : s ∩ t ∩ t = s ∩ t := inf_right_idem _ _
theorem inter_union_distrib_left (s t u : Finset α) : s ∩ (t ∪ u) = s ∩ t ∪ s ∩ u :=
inf_sup_left _ _ _
theorem union_inter_distrib_right (s t u : Finset α) : (s ∪ t) ∩ u = s ∩ u ∪ t ∩ u :=
inf_sup_right _ _ _
theorem union_inter_distrib_left (s t u : Finset α) : s ∪ t ∩ u = (s ∪ t) ∩ (s ∪ u) :=
sup_inf_left _ _ _
theorem inter_union_distrib_right (s t u : Finset α) : s ∩ t ∪ u = (s ∪ u) ∩ (t ∪ u) :=
sup_inf_right _ _ _
theorem union_union_distrib_left (s t u : Finset α) : s ∪ (t ∪ u) = s ∪ t ∪ (s ∪ u) :=
sup_sup_distrib_left _ _ _
theorem union_union_distrib_right (s t u : Finset α) : s ∪ t ∪ u = s ∪ u ∪ (t ∪ u) :=
sup_sup_distrib_right _ _ _
theorem inter_inter_distrib_left (s t u : Finset α) : s ∩ (t ∩ u) = s ∩ t ∩ (s ∩ u) :=
inf_inf_distrib_left _ _ _
theorem inter_inter_distrib_right (s t u : Finset α) : s ∩ t ∩ u = s ∩ u ∩ (t ∩ u) :=
inf_inf_distrib_right _ _ _
theorem union_union_union_comm (s t u v : Finset α) : s ∪ t ∪ (u ∪ v) = s ∪ u ∪ (t ∪ v) :=
sup_sup_sup_comm _ _ _ _
theorem inter_inter_inter_comm (s t u v : Finset α) : s ∩ t ∩ (u ∩ v) = s ∩ u ∩ (t ∩ v) :=
inf_inf_inf_comm _ _ _ _
theorem union_subset_iff : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u :=
(sup_le_iff : s ⊔ t ≤ u ↔ s ≤ u ∧ t ≤ u)
theorem subset_inter_iff : s ⊆ t ∩ u ↔ s ⊆ t ∧ s ⊆ u :=
(le_inf_iff : s ≤ t ⊓ u ↔ s ≤ t ∧ s ≤ u)
@[simp] lemma inter_eq_left : s ∩ t = s ↔ s ⊆ t := inf_eq_left
@[simp] lemma inter_eq_right : t ∩ s = s ↔ s ⊆ t := inf_eq_right
theorem inter_congr_left (ht : s ∩ u ⊆ t) (hu : s ∩ t ⊆ u) : s ∩ t = s ∩ u :=
inf_congr_left ht hu
theorem inter_congr_right (hs : t ∩ u ⊆ s) (ht : s ∩ u ⊆ t) : s ∩ u = t ∩ u :=
inf_congr_right hs ht
theorem inter_eq_inter_iff_left : s ∩ t = s ∩ u ↔ s ∩ u ⊆ t ∧ s ∩ t ⊆ u :=
inf_eq_inf_iff_left
theorem inter_eq_inter_iff_right : s ∩ u = t ∩ u ↔ t ∩ u ⊆ s ∧ s ∩ u ⊆ t :=
inf_eq_inf_iff_right
theorem ite_subset_union (s s' : Finset α) (P : Prop) [Decidable P] : ite P s s' ⊆ s ∪ s' :=
ite_le_sup s s' P
theorem inter_subset_ite (s s' : Finset α) (P : Prop) [Decidable P] : s ∩ s' ⊆ ite P s s' :=
inf_le_ite s s' P
end Lattice
end Finset |
.lake/packages/mathlib/Mathlib/Data/Finset/Lattice/Fold.lean | import Mathlib.Data.Finset.Fold
import Mathlib.Data.Finset.Sum
import Mathlib.Data.Multiset.Lattice
import Mathlib.Data.Set.BooleanAlgebra
import Mathlib.Order.Hom.BoundedLattice
import Mathlib.Order.Nat
/-!
# Lattice operations on finsets
This file is concerned with folding binary lattice operations over finsets.
For the special case of maximum and minimum of a finset, see Max.lean.
See also `Mathlib/Order/CompleteLattice/Finset.lean`, which is instead concerned with how big
lattice or set operations behave when indexed by a finset.
-/
open Function Multiset OrderDual
variable {F α β γ ι κ : Type*}
namespace Finset
/-! ### sup -/
section Sup
-- TODO: define with just `[Bot α]` where some lemmas hold without requiring `[OrderBot α]`
variable [SemilatticeSup α] [OrderBot α]
/-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/
def sup (s : Finset β) (f : β → α) : α :=
s.fold (· ⊔ ·) ⊥ f
variable {s s₁ s₂ : Finset β} {f g : β → α} {a : α}
theorem sup_def : s.sup f = (s.1.map f).sup :=
rfl
@[simp]
theorem sup_empty : (∅ : Finset β).sup f = ⊥ :=
fold_empty
@[simp]
theorem sup_cons {b : β} (h : b ∉ s) : (cons b s h).sup f = f b ⊔ s.sup f :=
fold_cons h
@[simp, grind =]
theorem sup_insert [DecidableEq β] {b : β} : (insert b s : Finset β).sup f = f b ⊔ s.sup f :=
fold_insert_idem
@[simp]
theorem sup_image [DecidableEq β] (s : Finset γ) (f : γ → β) (g : β → α) :
(s.image f).sup g = s.sup (g ∘ f) :=
fold_image_idem
@[simp]
theorem sup_map (s : Finset γ) (f : γ ↪ β) (g : β → α) : (s.map f).sup g = s.sup (g ∘ f) :=
fold_map
@[simp]
theorem sup_singleton {b : β} : ({b} : Finset β).sup f = f b :=
Multiset.sup_singleton
theorem sup_sup : s.sup (f ⊔ g) = s.sup f ⊔ s.sup g := by
induction s using Finset.cons_induction with
| empty => rw [sup_empty, sup_empty, sup_empty, bot_sup_eq]
| cons _ _ _ ih =>
rw [sup_cons, sup_cons, sup_cons, ih]
exact sup_sup_sup_comm _ _ _ _
theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀ a ∈ s₂, f a = g a) :
s₁.sup f = s₂.sup g := by
subst hs
exact Finset.fold_congr hfg
@[simp]
theorem _root_.map_finset_sup [SemilatticeSup β] [OrderBot β]
[FunLike F α β] [SupBotHomClass F α β]
(f : F) (s : Finset ι) (g : ι → α) : f (s.sup g) = s.sup (f ∘ g) :=
Finset.cons_induction_on s (map_bot f) fun i s _ h => by
rw [sup_cons, sup_cons, map_sup, h, Function.comp_apply]
@[simp]
protected theorem sup_le_iff {a : α} : s.sup f ≤ a ↔ ∀ b ∈ s, f b ≤ a := by
apply Iff.trans Multiset.sup_le
simp only [Multiset.mem_map, and_imp, exists_imp]
exact ⟨fun k b hb => k _ _ hb rfl, fun k a' b hb h => h ▸ k _ hb⟩
protected alias ⟨_, sup_le⟩ := Finset.sup_le_iff
theorem sup_const_le : (s.sup fun _ => a) ≤ a :=
Finset.sup_le fun _ _ => le_rfl
theorem le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f :=
Finset.sup_le_iff.1 le_rfl _ hb
lemma isLUB_sup : IsLUB (f '' s) (s.sup f) := by
simp +contextual [IsLUB, IsLeast, upperBounds, lowerBounds, le_sup]
lemma isLUB_sup_id {s : Finset α} : IsLUB s (s.sup id) := by simpa using isLUB_sup (f := id)
theorem le_sup_of_le {b : β} (hb : b ∈ s) (h : a ≤ f b) : a ≤ s.sup f := h.trans <| le_sup hb
@[grind _=_]
theorem sup_union [DecidableEq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f :=
eq_of_forall_ge_iff fun c => by simp [or_imp, forall_and]
theorem sup_const {s : Finset β} (h : s.Nonempty) (c : α) : (s.sup fun _ => c) = c :=
eq_of_forall_ge_iff (fun _ => Finset.sup_le_iff.trans h.forall_const)
@[simp]
theorem sup_bot (s : Finset β) : (s.sup fun _ => ⊥) = (⊥ : α) := by
obtain rfl | hs := s.eq_empty_or_nonempty
· exact sup_empty
· exact sup_const hs _
theorem sup_ite (p : β → Prop) [DecidablePred p] :
(s.sup fun i => ite (p i) (f i) (g i)) = (s.filter p).sup f ⊔ (s.filter fun i => ¬p i).sup g :=
fold_ite _
@[gcongr, grind ←]
theorem sup_mono_fun {g : β → α} (h : ∀ b ∈ s, f b ≤ g b) : s.sup f ≤ s.sup g :=
Finset.sup_le fun b hb => le_trans (h b hb) (le_sup hb)
@[gcongr, grind ←]
theorem sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f :=
Finset.sup_le (fun _ hb => le_sup (h hb))
protected theorem sup_comm (s : Finset β) (t : Finset γ) (f : β → γ → α) :
(s.sup fun b => t.sup (f b)) = t.sup fun c => s.sup fun b => f b c :=
eq_of_forall_ge_iff fun a => by simpa using forall₂_swap
@[simp]
theorem sup_attach (s : Finset β) (f : β → α) : (s.attach.sup fun x => f x) = s.sup f :=
(s.attach.sup_map (Function.Embedding.subtype _) f).symm.trans <| congr_arg _ attach_map_val
@[simp]
theorem sup_erase_bot [DecidableEq α] (s : Finset α) : (s.erase ⊥).sup id = s.sup id := by
refine (sup_mono (s.erase_subset _)).antisymm (Finset.sup_le_iff.2 fun a ha => ?_)
obtain rfl | ha' := eq_or_ne a ⊥
· exact bot_le
· exact le_sup (mem_erase.2 ⟨ha', ha⟩)
theorem sup_sdiff_right {α β : Type*} [GeneralizedBooleanAlgebra α] (s : Finset β) (f : β → α)
(a : α) : (s.sup fun b => f b \ a) = s.sup f \ a := by
induction s using Finset.cons_induction with
| empty => rw [sup_empty, sup_empty, bot_sdiff]
| cons _ _ _ h => rw [sup_cons, sup_cons, h, sup_sdiff]
theorem comp_sup_eq_sup_comp [SemilatticeSup γ] [OrderBot γ] {s : Finset β} {f : β → α} (g : α → γ)
(g_sup : ∀ x y, g (x ⊔ y) = g x ⊔ g y) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) :=
Finset.cons_induction_on s bot fun c t hc ih => by
rw [sup_cons, sup_cons, g_sup, ih, Function.comp_apply]
/-- Computing `sup` in a subtype (closed under `sup`) is the same as computing it in `α`. -/
theorem sup_coe {P : α → Prop} {Pbot : P ⊥} {Psup : ∀ ⦃x y⦄, P x → P y → P (x ⊔ y)} (t : Finset β)
(f : β → { x : α // P x }) :
(@sup { x // P x } _ (Subtype.semilatticeSup Psup) (Subtype.orderBot Pbot) t f : α) =
t.sup fun x => ↑(f x) := by
letI := Subtype.semilatticeSup Psup
letI := Subtype.orderBot Pbot
apply comp_sup_eq_sup_comp Subtype.val <;> intros <;> rfl
@[simp]
theorem sup_toFinset {α β} [DecidableEq β] (s : Finset α) (f : α → Multiset β) :
(s.sup f).toFinset = s.sup fun x => (f x).toFinset :=
comp_sup_eq_sup_comp Multiset.toFinset toFinset_union rfl
theorem _root_.List.foldr_sup_eq_sup_toFinset [DecidableEq α] (l : List α) :
l.foldr (· ⊔ ·) ⊥ = l.toFinset.sup id := by
rw [← coe_fold_r, ← Multiset.fold_dedup_idem, sup_def, ← List.toFinset_coe, toFinset_val,
Multiset.map_id]
rfl
theorem subset_range_sup_succ (s : Finset ℕ) : s ⊆ range (s.sup id).succ := fun _ hn =>
mem_range.2 <| Nat.lt_succ_of_le <| @le_sup _ _ _ _ _ id _ hn
theorem sup_induction {p : α → Prop} (hb : p ⊥) (hp : ∀ a₁, p a₁ → ∀ a₂, p a₂ → p (a₁ ⊔ a₂))
(hs : ∀ b ∈ s, p (f b)) : p (s.sup f) := by
induction s using Finset.cons_induction with
| empty => exact hb
| cons _ _ _ ih =>
simp only [sup_cons, forall_mem_cons] at hs ⊢
exact hp _ hs.1 _ (ih hs.2)
theorem sup_le_of_le_directed {α : Type*} [SemilatticeSup α] [OrderBot α] (s : Set α)
(hs : s.Nonempty) (hdir : DirectedOn (· ≤ ·) s) (t : Finset α) :
(∀ x ∈ t, ∃ y ∈ s, x ≤ y) → ∃ x ∈ s, t.sup id ≤ x := by
classical
induction t using Finset.induction_on with
| empty =>
simpa only [forall_prop_of_true, and_true, forall_prop_of_false, bot_le, not_false_iff,
sup_empty, forall_true_iff, notMem_empty]
| insert a r _ ih =>
intro h
have incs : (r : Set α) ⊆ ↑(insert a r) := by
rw [Finset.coe_subset]
apply Finset.subset_insert
-- x ∈ s is above the sup of r
obtain ⟨x, ⟨hxs, hsx_sup⟩⟩ := ih fun x hx => h x <| incs hx
-- y ∈ s is above a
obtain ⟨y, hys, hay⟩ := h a (Finset.mem_insert_self a r)
-- z ∈ s is above x and y
obtain ⟨z, hzs, ⟨hxz, hyz⟩⟩ := hdir x hxs y hys
use z, hzs
rw [sup_insert, id, sup_le_iff]
exact ⟨le_trans hay hyz, le_trans hsx_sup hxz⟩
-- If we acquire sublattices
-- the hypotheses should be reformulated as `s : SubsemilatticeSupBot`
theorem sup_mem (s : Set α) (w₁ : ⊥ ∈ s) (w₂ : ∀ᵉ (x ∈ s) (y ∈ s), x ⊔ y ∈ s)
{ι : Type*} (t : Finset ι) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.sup p ∈ s :=
@sup_induction _ _ _ _ _ _ (· ∈ s) w₁ w₂ h
@[simp]
protected theorem sup_eq_bot_iff (f : β → α) (S : Finset β) : S.sup f = ⊥ ↔ ∀ s ∈ S, f s = ⊥ := by
classical induction S using Finset.induction <;> simp [*]
@[simp]
lemma sup_disjSum (s : Finset β) (t : Finset γ) (f : β ⊕ γ → α) :
(s.disjSum t).sup f = (s.sup fun x ↦ f (.inl x)) ⊔ (t.sup fun x ↦ f (.inr x)) :=
congr(fold _ $(bot_sup_eq _ |>.symm) _ _).trans (fold_disjSum _ _ _ _ _ _)
@[simp]
theorem sup_eq_bot_of_isEmpty [IsEmpty β] (f : β → α) (S : Finset β) : S.sup f = ⊥ := by
rw [Finset.sup_eq_bot_iff]
exact fun x _ => False.elim <| IsEmpty.false x
theorem le_sup_dite_pos (p : β → Prop) [DecidablePred p]
{f : (b : β) → p b → α} {g : (b : β) → ¬p b → α} {b : β} (h₀ : b ∈ s) (h₁ : p b) :
f b h₁ ≤ s.sup fun i ↦ if h : p i then f i h else g i h := by
have : f b h₁ = (fun i ↦ if h : p i then f i h else g i h) b := by simp [h₁]
rw [this]
apply le_sup h₀
theorem le_sup_dite_neg (p : β → Prop) [DecidablePred p]
{f : (b : β) → p b → α} {g : (b : β) → ¬p b → α} {b : β} (h₀ : b ∈ s) (h₁ : ¬p b) :
g b h₁ ≤ s.sup fun i ↦ if h : p i then f i h else g i h := by
have : g b h₁ = (fun i ↦ if h : p i then f i h else g i h) b := by simp [h₁]
rw [this]
apply le_sup h₀
end Sup
theorem sup_eq_iSup [CompleteLattice β] (s : Finset α) (f : α → β) : s.sup f = ⨆ a ∈ s, f a :=
le_antisymm
(Finset.sup_le (fun a ha => le_iSup_of_le a <| le_iSup (fun _ => f a) ha))
(iSup_le fun _ => iSup_le fun ha => le_sup ha)
theorem sup_id_eq_sSup [CompleteLattice α] (s : Finset α) : s.sup id = sSup s := by
simp [sSup_eq_iSup, sup_eq_iSup]
theorem sup_id_set_eq_sUnion (s : Finset (Set α)) : s.sup id = ⋃₀ ↑s :=
sup_id_eq_sSup _
@[simp]
theorem sup_set_eq_biUnion (s : Finset α) (f : α → Set β) : s.sup f = ⋃ x ∈ s, f x :=
sup_eq_iSup _ _
theorem sup_eq_sSup_image [CompleteLattice β] (s : Finset α) (f : α → β) :
s.sup f = sSup (f '' s) := by
classical rw [← Finset.coe_image, ← sup_id_eq_sSup, sup_image, Function.id_comp]
theorem exists_sup_ge [SemilatticeSup β] [OrderBot β] [WellFoundedGT β] (f : α → β) :
∃ t : Finset α, ∀ a, f a ≤ t.sup f := by
cases isEmpty_or_nonempty α
· exact ⟨⊥, isEmptyElim⟩
obtain ⟨_, ⟨t, rfl⟩, ht⟩ := wellFounded_gt.has_min _ (Set.range_nonempty (sup · f))
refine ⟨t, fun a ↦ ?_⟩
classical
have := ht (f a ⊔ t.sup f) ⟨insert a t, by simp⟩
rwa [GT.gt, right_lt_sup, not_not] at this
theorem exists_sup_eq_iSup [CompleteLattice β] [WellFoundedGT β] (f : α → β) :
∃ t : Finset α, t.sup f = ⨆ a, f a :=
have ⟨t, ht⟩ := exists_sup_ge f
⟨t, (Finset.sup_le fun _ _ ↦ le_iSup ..).antisymm <| iSup_le ht⟩
/-! ### inf -/
section Inf
-- TODO: define with just `[Top α]` where some lemmas hold without requiring `[OrderTop α]`
variable [SemilatticeInf α] [OrderTop α]
/-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/
def inf (s : Finset β) (f : β → α) : α :=
s.fold (· ⊓ ·) ⊤ f
variable {s s₁ s₂ : Finset β} {f g : β → α} {a : α}
theorem inf_def : s.inf f = (s.1.map f).inf :=
rfl
@[simp]
theorem inf_empty : (∅ : Finset β).inf f = ⊤ :=
rfl
@[simp]
theorem inf_cons {b : β} (h : b ∉ s) : (cons b s h).inf f = f b ⊓ s.inf f :=
@sup_cons αᵒᵈ _ _ _ _ _ _ h
@[simp]
theorem inf_insert [DecidableEq β] {b : β} : (insert b s : Finset β).inf f = f b ⊓ s.inf f :=
fold_insert_idem
@[simp]
theorem inf_image [DecidableEq β] (s : Finset γ) (f : γ → β) (g : β → α) :
(s.image f).inf g = s.inf (g ∘ f) :=
fold_image_idem
@[simp]
theorem inf_map (s : Finset γ) (f : γ ↪ β) (g : β → α) : (s.map f).inf g = s.inf (g ∘ f) :=
fold_map
@[simp]
theorem inf_singleton {b : β} : ({b} : Finset β).inf f = f b :=
Multiset.inf_singleton
theorem inf_inf : s.inf (f ⊓ g) = s.inf f ⊓ s.inf g :=
@sup_sup αᵒᵈ _ _ _ _ _ _
theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀ a ∈ s₂, f a = g a) :
s₁.inf f = s₂.inf g := by
subst hs
exact Finset.fold_congr hfg
@[simp]
theorem _root_.map_finset_inf [SemilatticeInf β] [OrderTop β]
[FunLike F α β] [InfTopHomClass F α β]
(f : F) (s : Finset ι) (g : ι → α) : f (s.inf g) = s.inf (f ∘ g) :=
Finset.cons_induction_on s (map_top f) fun i s _ h => by
rw [inf_cons, inf_cons, map_inf, h, Function.comp_apply]
@[simp] protected theorem le_inf_iff {a : α} : a ≤ s.inf f ↔ ∀ b ∈ s, a ≤ f b :=
@Finset.sup_le_iff αᵒᵈ _ _ _ _ _ _
protected alias ⟨_, le_inf⟩ := Finset.le_inf_iff
theorem le_inf_const_le : a ≤ s.inf fun _ => a :=
Finset.le_inf fun _ _ => le_rfl
theorem inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b :=
Finset.le_inf_iff.1 le_rfl _ hb
lemma isGLB_inf : IsGLB (f '' s) (s.inf f) := by
simp +contextual [IsGLB, IsGreatest, upperBounds, lowerBounds, inf_le]
lemma isGLB_inf_id {s : Finset α} : IsGLB s (s.inf id) := by simpa using isGLB_inf (f := id)
theorem inf_le_of_le {b : β} (hb : b ∈ s) (h : f b ≤ a) : s.inf f ≤ a := (inf_le hb).trans h
theorem inf_union [DecidableEq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f :=
eq_of_forall_le_iff fun c ↦ by simp [or_imp, forall_and]
theorem inf_const (h : s.Nonempty) (c : α) : (s.inf fun _ => c) = c := @sup_const αᵒᵈ _ _ _ _ h _
@[simp] theorem inf_top (s : Finset β) : (s.inf fun _ => ⊤) = (⊤ : α) := @sup_bot αᵒᵈ _ _ _ _
theorem inf_ite (p : β → Prop) [DecidablePred p] :
(s.inf fun i ↦ ite (p i) (f i) (g i)) = (s.filter p).inf f ⊓ (s.filter fun i ↦ ¬ p i).inf g :=
fold_ite _
@[gcongr]
theorem inf_mono_fun {g : β → α} (h : ∀ b ∈ s, f b ≤ g b) : s.inf f ≤ s.inf g :=
Finset.le_inf fun b hb => le_trans (inf_le hb) (h b hb)
@[gcongr]
theorem inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f :=
Finset.le_inf (fun _ hb => inf_le (h hb))
protected theorem inf_comm (s : Finset β) (t : Finset γ) (f : β → γ → α) :
(s.inf fun b => t.inf (f b)) = t.inf fun c => s.inf fun b => f b c :=
@Finset.sup_comm αᵒᵈ _ _ _ _ _ _ _
theorem inf_attach (s : Finset β) (f : β → α) : (s.attach.inf fun x => f x) = s.inf f :=
@sup_attach αᵒᵈ _ _ _ _ _
@[simp]
theorem inf_erase_top [DecidableEq α] (s : Finset α) : (s.erase ⊤).inf id = s.inf id :=
@sup_erase_bot αᵒᵈ _ _ _ _
theorem comp_inf_eq_inf_comp [SemilatticeInf γ] [OrderTop γ] {s : Finset β} {f : β → α} (g : α → γ)
(g_inf : ∀ x y, g (x ⊓ y) = g x ⊓ g y) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) :=
@comp_sup_eq_sup_comp αᵒᵈ _ γᵒᵈ _ _ _ _ _ _ _ g_inf top
/-- Computing `inf` in a subtype (closed under `inf`) is the same as computing it in `α`. -/
theorem inf_coe {P : α → Prop} {Ptop : P ⊤} {Pinf : ∀ ⦃x y⦄, P x → P y → P (x ⊓ y)} (t : Finset β)
(f : β → { x : α // P x }) :
(@inf { x // P x } _ (Subtype.semilatticeInf Pinf) (Subtype.orderTop Ptop) t f : α) =
t.inf fun x => ↑(f x) :=
@sup_coe αᵒᵈ _ _ _ _ Ptop Pinf t f
theorem _root_.List.foldr_inf_eq_inf_toFinset [DecidableEq α] (l : List α) :
l.foldr (· ⊓ ·) ⊤ = l.toFinset.inf id := by
rw [← coe_fold_r, ← Multiset.fold_dedup_idem, inf_def, ← List.toFinset_coe, toFinset_val,
Multiset.map_id]
rfl
theorem inf_induction {p : α → Prop} (ht : p ⊤) (hp : ∀ a₁, p a₁ → ∀ a₂, p a₂ → p (a₁ ⊓ a₂))
(hs : ∀ b ∈ s, p (f b)) : p (s.inf f) :=
@sup_induction αᵒᵈ _ _ _ _ _ _ ht hp hs
theorem inf_mem (s : Set α) (w₁ : ⊤ ∈ s) (w₂ : ∀ᵉ (x ∈ s) (y ∈ s), x ⊓ y ∈ s)
{ι : Type*} (t : Finset ι) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.inf p ∈ s :=
@inf_induction _ _ _ _ _ _ (· ∈ s) w₁ w₂ h
@[simp]
protected theorem inf_eq_top_iff (f : β → α) (S : Finset β) : S.inf f = ⊤ ↔ ∀ s ∈ S, f s = ⊤ :=
@Finset.sup_eq_bot_iff αᵒᵈ _ _ _ _ _
@[simp]
lemma inf_disjSum (s : Finset β) (t : Finset γ) (f : β ⊕ γ → α) :
(s.disjSum t).inf f = (s.inf fun x ↦ f (.inl x)) ⊓ (t.inf fun x ↦ f (.inr x)) :=
congr(fold _ $(top_inf_eq _ |>.symm) _ _).trans (fold_disjSum _ _ _ _ _ _)
theorem inf_dite_pos_le (p : β → Prop) [DecidablePred p]
{f : (b : β) → p b → α} {g : (b : β) → ¬p b → α} {b : β} (h₀ : b ∈ s) (h₁ : p b) :
(s.inf fun i ↦ if h : p i then f i h else g i h) ≤ f b h₁ := by
have : f b h₁ = (fun i ↦ if h : p i then f i h else g i h) b := by simp [h₁]
rw [this]
apply inf_le h₀
theorem inf_dite_neg_le (p : β → Prop) [DecidablePred p]
{f : (b : β) → p b → α} {g : (b : β) → ¬p b → α} {b : β} (h₀ : b ∈ s) (h₁ : ¬p b) :
(s.inf fun i ↦ if h : p i then f i h else g i h) ≤ g b h₁ := by
have : g b h₁ = (fun i ↦ if h : p i then f i h else g i h) b := by simp [h₁]
rw [this]
apply inf_le h₀
end Inf
@[simp]
theorem toDual_sup [SemilatticeSup α] [OrderBot α] (s : Finset β) (f : β → α) :
toDual (s.sup f) = s.inf (toDual ∘ f) :=
rfl
@[simp]
theorem toDual_inf [SemilatticeInf α] [OrderTop α] (s : Finset β) (f : β → α) :
toDual (s.inf f) = s.sup (toDual ∘ f) :=
rfl
@[simp]
theorem ofDual_sup [SemilatticeInf α] [OrderTop α] (s : Finset β) (f : β → αᵒᵈ) :
ofDual (s.sup f) = s.inf (ofDual ∘ f) :=
rfl
@[simp]
theorem ofDual_inf [SemilatticeSup α] [OrderBot α] (s : Finset β) (f : β → αᵒᵈ) :
ofDual (s.inf f) = s.sup (ofDual ∘ f) :=
rfl
section DistribLattice
variable [DistribLattice α]
section OrderBot
variable [OrderBot α] {s : Finset ι} {t : Finset κ} {f : ι → α} {g : κ → α} {a : α}
theorem sup_inf_distrib_left (s : Finset ι) (f : ι → α) (a : α) :
a ⊓ s.sup f = s.sup fun i => a ⊓ f i := by
induction s using Finset.cons_induction with
| empty => simp_rw [Finset.sup_empty, inf_bot_eq]
| cons _ _ _ h => rw [sup_cons, sup_cons, inf_sup_left, h]
theorem sup_inf_distrib_right (s : Finset ι) (f : ι → α) (a : α) :
s.sup f ⊓ a = s.sup fun i => f i ⊓ a := by
rw [_root_.inf_comm, s.sup_inf_distrib_left]
simp_rw [_root_.inf_comm]
protected theorem disjoint_sup_right : Disjoint a (s.sup f) ↔ ∀ ⦃i⦄, i ∈ s → Disjoint a (f i) := by
simp only [disjoint_iff, sup_inf_distrib_left, Finset.sup_eq_bot_iff]
protected theorem disjoint_sup_left : Disjoint (s.sup f) a ↔ ∀ ⦃i⦄, i ∈ s → Disjoint (f i) a := by
simp only [disjoint_iff, sup_inf_distrib_right, Finset.sup_eq_bot_iff]
end OrderBot
section OrderTop
variable [OrderTop α] {f : ι → α} {g : κ → α} {s : Finset ι} {t : Finset κ} {a : α}
theorem inf_sup_distrib_left (s : Finset ι) (f : ι → α) (a : α) :
a ⊔ s.inf f = s.inf fun i => a ⊔ f i :=
@sup_inf_distrib_left αᵒᵈ _ _ _ _ _ _
theorem inf_sup_distrib_right (s : Finset ι) (f : ι → α) (a : α) :
s.inf f ⊔ a = s.inf fun i => f i ⊔ a :=
@sup_inf_distrib_right αᵒᵈ _ _ _ _ _ _
protected theorem codisjoint_inf_right :
Codisjoint a (s.inf f) ↔ ∀ ⦃i⦄, i ∈ s → Codisjoint a (f i) :=
@Finset.disjoint_sup_right αᵒᵈ _ _ _ _ _ _
protected theorem codisjoint_inf_left :
Codisjoint (s.inf f) a ↔ ∀ ⦃i⦄, i ∈ s → Codisjoint (f i) a :=
@Finset.disjoint_sup_left αᵒᵈ _ _ _ _ _ _
end OrderTop
end DistribLattice
section BooleanAlgebra
variable [BooleanAlgebra α] {s : Finset ι}
theorem sup_sdiff_left (s : Finset ι) (f : ι → α) (a : α) :
(s.sup fun b => a \ f b) = a \ s.inf f := by
induction s using Finset.cons_induction with
| empty => rw [sup_empty, inf_empty, sdiff_top]
| cons _ _ _ h => rw [sup_cons, inf_cons, h, sdiff_inf]
theorem inf_sdiff_left (hs : s.Nonempty) (f : ι → α) (a : α) :
(s.inf fun b => a \ f b) = a \ s.sup f := by
induction hs using Finset.Nonempty.cons_induction with
| singleton => rw [sup_singleton, inf_singleton]
| cons _ _ _ _ ih => rw [sup_cons, inf_cons, ih, sdiff_sup]
theorem inf_sdiff_right (hs : s.Nonempty) (f : ι → α) (a : α) :
(s.inf fun b => f b \ a) = s.inf f \ a := by
induction hs using Finset.Nonempty.cons_induction with
| singleton => rw [inf_singleton, inf_singleton]
| cons _ _ _ _ ih => rw [inf_cons, inf_cons, ih, inf_sdiff]
theorem inf_himp_right (s : Finset ι) (f : ι → α) (a : α) :
(s.inf fun b => f b ⇨ a) = s.sup f ⇨ a :=
@sup_sdiff_left αᵒᵈ _ _ _ _ _
theorem sup_himp_right (hs : s.Nonempty) (f : ι → α) (a : α) :
(s.sup fun b => f b ⇨ a) = s.inf f ⇨ a :=
@inf_sdiff_left αᵒᵈ _ _ _ hs _ _
theorem sup_himp_left (hs : s.Nonempty) (f : ι → α) (a : α) :
(s.sup fun b => a ⇨ f b) = a ⇨ s.sup f :=
@inf_sdiff_right αᵒᵈ _ _ _ hs _ _
@[simp]
protected theorem compl_sup (s : Finset ι) (f : ι → α) : (s.sup f)ᶜ = s.inf fun i => (f i)ᶜ :=
map_finset_sup (OrderIso.compl α) _ _
@[simp]
protected theorem compl_inf (s : Finset ι) (f : ι → α) : (s.inf f)ᶜ = s.sup fun i => (f i)ᶜ :=
map_finset_inf (OrderIso.compl α) _ _
end BooleanAlgebra
section LinearOrder
variable [LinearOrder α]
section OrderBot
variable [OrderBot α] {s : Finset ι} {f : ι → α} {a : α}
theorem comp_sup_eq_sup_comp_of_is_total [SemilatticeSup β] [OrderBot β] (g : α → β)
(mono_g : Monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) :=
comp_sup_eq_sup_comp g mono_g.map_sup bot
@[simp]
protected theorem le_sup_iff (ha : ⊥ < a) : a ≤ s.sup f ↔ ∃ b ∈ s, a ≤ f b := by
apply Iff.intro
· induction s using cons_induction with
| empty => exact (absurd · (not_le_of_gt ha))
| cons c t hc ih =>
rw [sup_cons, le_sup_iff]
exact fun
| Or.inl h => ⟨c, mem_cons.2 (Or.inl rfl), h⟩
| Or.inr h => let ⟨b, hb, hle⟩ := ih h; ⟨b, mem_cons.2 (Or.inr hb), hle⟩
· exact fun ⟨b, hb, hle⟩ => le_trans hle (le_sup hb)
protected theorem sup_eq_top_iff {α : Type*} [LinearOrder α] [BoundedOrder α] [Nontrivial α]
{s : Finset ι} {f : ι → α} : s.sup f = ⊤ ↔ ∃ b ∈ s, f b = ⊤ := by
simp only [← top_le_iff]
exact Finset.le_sup_iff bot_lt_top
protected theorem Nonempty.sup_eq_top_iff {α : Type*} [LinearOrder α] [BoundedOrder α]
{s : Finset ι} {f : ι → α} (hs : s.Nonempty) : s.sup f = ⊤ ↔ ∃ b ∈ s, f b = ⊤ := by
cases subsingleton_or_nontrivial α
· simpa [Subsingleton.elim _ (⊤ : α)]
· exact Finset.sup_eq_top_iff
@[simp]
protected theorem lt_sup_iff : a < s.sup f ↔ ∃ b ∈ s, a < f b := by
apply Iff.intro
· induction s using cons_induction with
| empty => exact (absurd · not_lt_bot)
| cons c t hc ih =>
rw [sup_cons, lt_sup_iff]
exact fun
| Or.inl h => ⟨c, mem_cons.2 (Or.inl rfl), h⟩
| Or.inr h => let ⟨b, hb, hlt⟩ := ih h; ⟨b, mem_cons.2 (Or.inr hb), hlt⟩
· exact fun ⟨b, hb, hlt⟩ => lt_of_lt_of_le hlt (le_sup hb)
@[simp]
protected theorem sup_lt_iff (ha : ⊥ < a) : s.sup f < a ↔ ∀ b ∈ s, f b < a :=
⟨fun hs _ hb => lt_of_le_of_lt (le_sup hb) hs,
Finset.cons_induction_on s (fun _ => ha) fun c t hc => by
simpa only [sup_cons, sup_lt_iff, mem_cons, forall_eq_or_imp] using And.imp_right⟩
theorem sup_mem_of_nonempty (hs : s.Nonempty) : s.sup f ∈ f '' s := by
classical
induction s using Finset.induction with
| empty => simp only [Finset.not_nonempty_empty] at hs
| insert a s _ h =>
rw [Finset.sup_insert (b := a) (s := s) (f := f)]
cases s.eq_empty_or_nonempty with
| inl hs => simp [hs]
| inr hs =>
simp only [Finset.coe_insert]
rcases le_total (f a) (s.sup f) with (ha | ha)
· rw [sup_eq_right.mpr ha]
exact Set.image_mono (Set.subset_insert a s) (h hs)
· rw [sup_eq_left.mpr ha]
apply Set.mem_image_of_mem _ (Set.mem_insert a ↑s)
end OrderBot
section OrderTop
variable [OrderTop α] {s : Finset ι} {f : ι → α} {a : α}
theorem comp_inf_eq_inf_comp_of_is_total [SemilatticeInf β] [OrderTop β] (g : α → β)
(mono_g : Monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) :=
comp_inf_eq_inf_comp g mono_g.map_inf top
@[simp]
protected theorem inf_le_iff (ha : a < ⊤) : s.inf f ≤ a ↔ ∃ b ∈ s, f b ≤ a :=
@Finset.le_sup_iff αᵒᵈ _ _ _ _ _ _ ha
protected theorem inf_eq_bot_iff {α : Type*} [LinearOrder α] [BoundedOrder α] [Nontrivial α]
{s : Finset ι} {f : ι → α} : s.inf f = ⊥ ↔ ∃ b ∈ s, f b = ⊥ :=
Finset.sup_eq_top_iff (α := αᵒᵈ)
protected theorem Nonempty.inf_eq_bot_iff {α : Type*} [LinearOrder α] [BoundedOrder α]
{s : Finset ι} {f : ι → α} (h : s.Nonempty) : s.inf f = ⊥ ↔ ∃ b ∈ s, f b = ⊥ :=
h.sup_eq_top_iff (α := αᵒᵈ)
@[simp]
protected theorem inf_lt_iff : s.inf f < a ↔ ∃ b ∈ s, f b < a :=
@Finset.lt_sup_iff αᵒᵈ _ _ _ _ _ _
@[simp]
protected theorem lt_inf_iff (ha : a < ⊤) : a < s.inf f ↔ ∀ b ∈ s, a < f b :=
@Finset.sup_lt_iff αᵒᵈ _ _ _ _ _ _ ha
end OrderTop
end LinearOrder
theorem inf_eq_iInf [CompleteLattice β] (s : Finset α) (f : α → β) : s.inf f = ⨅ a ∈ s, f a :=
sup_eq_iSup (β := βᵒᵈ) ..
theorem inf_id_eq_sInf [CompleteLattice α] (s : Finset α) : s.inf id = sInf s :=
sup_id_eq_sSup (α := αᵒᵈ) _
theorem inf_id_set_eq_sInter (s : Finset (Set α)) : s.inf id = ⋂₀ ↑s :=
inf_id_eq_sInf _
@[simp]
theorem inf_set_eq_iInter (s : Finset α) (f : α → Set β) : s.inf f = ⋂ x ∈ s, f x :=
inf_eq_iInf _ _
theorem inf_eq_sInf_image [CompleteLattice β] (s : Finset α) (f : α → β) :
s.inf f = sInf (f '' s) :=
sup_eq_sSup_image (β := βᵒᵈ) ..
theorem exists_inf_le [SemilatticeInf β] [OrderTop β] [WellFoundedLT β] (f : α → β) :
∃ t : Finset α, ∀ a, t.inf f ≤ f a :=
exists_sup_ge (β := βᵒᵈ) _
theorem exists_inf_eq_iInf [CompleteLattice β] [WellFoundedLT β] (f : α → β) :
∃ t : Finset α, t.inf f = ⨅ a, f a :=
exists_sup_eq_iSup (β := βᵒᵈ) _
section Sup'
variable [SemilatticeSup α]
theorem sup_of_mem {s : Finset β} (f : β → α) {b : β} (h : b ∈ s) :
∃ a : α, s.sup ((↑) ∘ f : β → WithBot α) = ↑a :=
(WithBot.le_iff_forall.1 (le_sup (α := WithBot α) h) (f b) rfl).imp fun _ ↦ And.left
/-- Given nonempty finset `s` then `s.sup' H f` is the supremum of its image under `f` in (possibly
unbounded) join-semilattice `α`, where `H` is a proof of nonemptiness. If `α` has a bottom element
you may instead use `Finset.sup` which does not require `s` nonempty. -/
def sup' (s : Finset β) (H : s.Nonempty) (f : β → α) : α :=
WithBot.unbot (s.sup ((↑) ∘ f)) (by simpa using H)
variable {s : Finset β} (H : s.Nonempty) (f : β → α)
@[simp]
theorem coe_sup' : ((s.sup' H f : α) : WithBot α) = s.sup ((↑) ∘ f) := by
rw [sup', WithBot.coe_unbot]
@[simp]
theorem sup'_cons {b : β} {hb : b ∉ s} :
(cons b s hb).sup' (cons_nonempty hb) f = f b ⊔ s.sup' H f := by
rw [← WithBot.coe_eq_coe]
simp [WithBot.coe_sup]
@[simp]
theorem sup'_insert [DecidableEq β] {b : β} :
(insert b s).sup' (insert_nonempty _ _) f = f b ⊔ s.sup' H f := by
rw [← WithBot.coe_eq_coe]
simp [WithBot.coe_sup]
@[simp]
theorem sup'_singleton {b : β} : ({b} : Finset β).sup' (singleton_nonempty _) f = f b :=
rfl
@[simp]
theorem sup'_le_iff {a : α} : s.sup' H f ≤ a ↔ ∀ b ∈ s, f b ≤ a := by
simp_rw [← @WithBot.coe_le_coe α, coe_sup', Finset.sup_le_iff]; rfl
alias ⟨_, sup'_le⟩ := sup'_le_iff
theorem le_sup' {b : β} (h : b ∈ s) : f b ≤ s.sup' ⟨b, h⟩ f :=
(sup'_le_iff ⟨b, h⟩ f).1 le_rfl b h
set_option linter.docPrime false in
theorem isLUB_sup' {s : Finset α} (hs : s.Nonempty) : IsLUB s (sup' s hs id) :=
⟨fun x h => id_eq x ▸ le_sup' id h, fun _ h => Finset.sup'_le hs id h⟩
theorem le_sup'_of_le {a : α} {b : β} (hb : b ∈ s) (h : a ≤ f b) : a ≤ s.sup' ⟨b, hb⟩ f :=
h.trans <| le_sup' _ hb
lemma sup'_eq_of_forall {a : α} (h : ∀ b ∈ s, f b = a) : s.sup' H f = a :=
le_antisymm (sup'_le _ _ (fun _ hb ↦ (h _ hb).le))
(le_sup'_of_le _ H.choose_spec (h _ H.choose_spec).ge)
@[simp]
theorem sup'_const (a : α) : s.sup' H (fun _ => a) = a :=
sup'_eq_of_forall H (fun _ ↦ a) fun _ ↦ congrFun rfl
theorem sup'_union [DecidableEq β] {s₁ s₂ : Finset β} (h₁ : s₁.Nonempty) (h₂ : s₂.Nonempty)
(f : β → α) :
(s₁ ∪ s₂).sup' (h₁.mono subset_union_left) f = s₁.sup' h₁ f ⊔ s₂.sup' h₂ f :=
eq_of_forall_ge_iff fun a => by simp [or_imp, forall_and]
protected theorem sup'_comm {t : Finset γ} (hs : s.Nonempty) (ht : t.Nonempty) (f : β → γ → α) :
(s.sup' hs fun b => t.sup' ht (f b)) = t.sup' ht fun c => s.sup' hs fun b => f b c :=
eq_of_forall_ge_iff fun a => by simpa using forall₂_swap
theorem sup'_induction {p : α → Prop} (hp : ∀ a₁, p a₁ → ∀ a₂, p a₂ → p (a₁ ⊔ a₂))
(hs : ∀ b ∈ s, p (f b)) : p (s.sup' H f) := by
change @WithBot.recBotCoe α (fun _ => Prop) True p ↑(s.sup' H f)
rw [coe_sup']
refine sup_induction trivial (fun a₁ h₁ a₂ h₂ ↦ ?_) hs
match a₁, a₂ with
| ⊥, _ => rwa [bot_sup_eq]
| (a₁ : α), ⊥ => rwa [sup_bot_eq]
| (a₁ : α), (a₂ : α) => exact hp a₁ h₁ a₂ h₂
theorem sup'_mem (s : Set α) (w : ∀ᵉ (x ∈ s) (y ∈ s), x ⊔ y ∈ s) {ι : Type*}
(t : Finset ι) (H : t.Nonempty) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.sup' H p ∈ s :=
sup'_induction H p w h
@[congr]
theorem sup'_congr {t : Finset β} {f g : β → α} (h₁ : s = t) (h₂ : ∀ x ∈ s, f x = g x) :
s.sup' H f = t.sup' (h₁ ▸ H) g := by
subst s
refine eq_of_forall_ge_iff fun c => ?_
simp +contextual only [sup'_le_iff, h₂]
theorem comp_sup'_eq_sup'_comp [SemilatticeSup γ] {s : Finset β} (H : s.Nonempty) {f : β → α}
(g : α → γ) (g_sup : ∀ x y, g (x ⊔ y) = g x ⊔ g y) : g (s.sup' H f) = s.sup' H (g ∘ f) := by
refine H.cons_induction ?_ ?_ <;> intros <;> simp [*]
@[simp]
theorem _root_.map_finset_sup' [SemilatticeSup β] [FunLike F α β] [SupHomClass F α β]
(f : F) {s : Finset ι} (hs) (g : ι → α) :
f (s.sup' hs g) = s.sup' hs (f ∘ g) := by
refine hs.cons_induction ?_ ?_ <;> intros <;> simp [*]
/-- To rewrite from right to left, use `Finset.sup'_comp_eq_image`. -/
@[simp]
theorem sup'_image [DecidableEq β] {s : Finset γ} {f : γ → β} (hs : (s.image f).Nonempty)
(g : β → α) :
(s.image f).sup' hs g = s.sup' hs.of_image (g ∘ f) := by
rw [← WithBot.coe_eq_coe]; simp only [coe_sup', sup_image]; rfl
/-- A version of `Finset.sup'_image` with LHS and RHS reversed.
Also, this lemma assumes that `s` is nonempty instead of assuming that its image is nonempty. -/
lemma sup'_comp_eq_image [DecidableEq β] {s : Finset γ} {f : γ → β} (hs : s.Nonempty) (g : β → α) :
s.sup' hs (g ∘ f) = (s.image f).sup' (hs.image f) g :=
.symm <| sup'_image _ _
/-- To rewrite from right to left, use `Finset.sup'_comp_eq_map`. -/
@[simp]
theorem sup'_map {s : Finset γ} {f : γ ↪ β} (g : β → α) (hs : (s.map f).Nonempty) :
(s.map f).sup' hs g = s.sup' (map_nonempty.1 hs) (g ∘ f) := by
rw [← WithBot.coe_eq_coe, coe_sup', sup_map, coe_sup']
rfl
/-- A version of `Finset.sup'_map` with LHS and RHS reversed.
Also, this lemma assumes that `s` is nonempty instead of assuming that its image is nonempty. -/
lemma sup'_comp_eq_map {s : Finset γ} {f : γ ↪ β} (g : β → α) (hs : s.Nonempty) :
s.sup' hs (g ∘ f) = (s.map f).sup' (map_nonempty.2 hs) g :=
.symm <| sup'_map _ _
@[gcongr]
theorem sup'_mono {s₁ s₂ : Finset β} (h : s₁ ⊆ s₂) (h₁ : s₁.Nonempty) :
s₁.sup' h₁ f ≤ s₂.sup' (h₁.mono h) f :=
Finset.sup'_le h₁ _ (fun _ hb => le_sup' _ (h hb))
@[gcongr]
lemma sup'_mono_fun {hs : s.Nonempty} {f g : β → α} (h : ∀ b ∈ s, f b ≤ g b) :
s.sup' hs f ≤ s.sup' hs g := sup'_le _ _ fun b hb ↦ (h b hb).trans (le_sup' _ hb)
end Sup'
section Inf'
variable [SemilatticeInf α]
theorem inf_of_mem {s : Finset β} (f : β → α) {b : β} (h : b ∈ s) :
∃ a : α, s.inf ((↑) ∘ f : β → WithTop α) = ↑a :=
@sup_of_mem αᵒᵈ _ _ _ f _ h
/-- Given nonempty finset `s` then `s.inf' H f` is the infimum of its image under `f` in (possibly
unbounded) meet-semilattice `α`, where `H` is a proof of nonemptiness. If `α` has a top element you
may instead use `Finset.inf` which does not require `s` nonempty. -/
def inf' (s : Finset β) (H : s.Nonempty) (f : β → α) : α :=
WithTop.untop (s.inf ((↑) ∘ f)) (by simpa using H)
variable {s : Finset β} (H : s.Nonempty) (f : β → α)
@[simp]
theorem coe_inf' : ((s.inf' H f : α) : WithTop α) = s.inf ((↑) ∘ f) :=
@coe_sup' αᵒᵈ _ _ _ H f
@[simp]
theorem inf'_cons {b : β} {hb : b ∉ s} :
(cons b s hb).inf' (cons_nonempty hb) f = f b ⊓ s.inf' H f :=
@sup'_cons αᵒᵈ _ _ _ H f _ _
@[simp]
theorem inf'_insert [DecidableEq β] {b : β} :
(insert b s).inf' (insert_nonempty _ _) f = f b ⊓ s.inf' H f :=
@sup'_insert αᵒᵈ _ _ _ H f _ _
@[simp]
theorem inf'_singleton {b : β} : ({b} : Finset β).inf' (singleton_nonempty _) f = f b :=
rfl
@[simp]
theorem le_inf'_iff {a : α} : a ≤ s.inf' H f ↔ ∀ b ∈ s, a ≤ f b :=
sup'_le_iff (α := αᵒᵈ) H f
theorem le_inf' {a : α} (hs : ∀ b ∈ s, a ≤ f b) : a ≤ s.inf' H f :=
sup'_le (α := αᵒᵈ) H f hs
theorem inf'_le {b : β} (h : b ∈ s) : s.inf' ⟨b, h⟩ f ≤ f b :=
le_sup' (α := αᵒᵈ) f h
set_option linter.docPrime false in
theorem isGLB_inf' {s : Finset α} (hs : s.Nonempty) : IsGLB s (inf' s hs id) :=
⟨fun x h => id_eq x ▸ inf'_le id h, fun _ h => Finset.le_inf' hs id h⟩
theorem inf'_le_of_le {a : α} {b : β} (hb : b ∈ s) (h : f b ≤ a) :
s.inf' ⟨b, hb⟩ f ≤ a := (inf'_le _ hb).trans h
lemma inf'_eq_of_forall {a : α} (h : ∀ b ∈ s, f b = a) : s.inf' H f = a :=
sup'_eq_of_forall (α := αᵒᵈ) H f h
@[simp]
theorem inf'_const (a : α) : (s.inf' H fun _ => a) = a :=
sup'_const (α := αᵒᵈ) H a
theorem inf'_union [DecidableEq β] {s₁ s₂ : Finset β} (h₁ : s₁.Nonempty) (h₂ : s₂.Nonempty)
(f : β → α) :
(s₁ ∪ s₂).inf' (h₁.mono subset_union_left) f = s₁.inf' h₁ f ⊓ s₂.inf' h₂ f :=
@sup'_union αᵒᵈ _ _ _ _ _ h₁ h₂ _
protected theorem inf'_comm {t : Finset γ} (hs : s.Nonempty) (ht : t.Nonempty) (f : β → γ → α) :
(s.inf' hs fun b => t.inf' ht (f b)) = t.inf' ht fun c => s.inf' hs fun b => f b c :=
@Finset.sup'_comm αᵒᵈ _ _ _ _ _ hs ht _
theorem comp_inf'_eq_inf'_comp [SemilatticeInf γ] {s : Finset β} (H : s.Nonempty) {f : β → α}
(g : α → γ) (g_inf : ∀ x y, g (x ⊓ y) = g x ⊓ g y) : g (s.inf' H f) = s.inf' H (g ∘ f) :=
comp_sup'_eq_sup'_comp (α := αᵒᵈ) (γ := γᵒᵈ) H g g_inf
theorem inf'_induction {p : α → Prop} (hp : ∀ a₁, p a₁ → ∀ a₂, p a₂ → p (a₁ ⊓ a₂))
(hs : ∀ b ∈ s, p (f b)) : p (s.inf' H f) :=
sup'_induction (α := αᵒᵈ) H f hp hs
theorem inf'_mem (s : Set α) (w : ∀ᵉ (x ∈ s) (y ∈ s), x ⊓ y ∈ s) {ι : Type*}
(t : Finset ι) (H : t.Nonempty) (p : ι → α) (h : ∀ i ∈ t, p i ∈ s) : t.inf' H p ∈ s :=
inf'_induction H p w h
@[congr]
theorem inf'_congr {t : Finset β} {f g : β → α} (h₁ : s = t) (h₂ : ∀ x ∈ s, f x = g x) :
s.inf' H f = t.inf' (h₁ ▸ H) g :=
sup'_congr (α := αᵒᵈ) H h₁ h₂
@[simp]
theorem _root_.map_finset_inf' [SemilatticeInf β] [FunLike F α β] [InfHomClass F α β]
(f : F) {s : Finset ι} (hs) (g : ι → α) :
f (s.inf' hs g) = s.inf' hs (f ∘ g) := by
refine hs.cons_induction ?_ ?_ <;> intros <;> simp [*]
/-- To rewrite from right to left, use `Finset.inf'_comp_eq_image`. -/
@[simp]
theorem inf'_image [DecidableEq β] {s : Finset γ} {f : γ → β} (hs : (s.image f).Nonempty)
(g : β → α) :
(s.image f).inf' hs g = s.inf' hs.of_image (g ∘ f) :=
@sup'_image αᵒᵈ _ _ _ _ _ _ hs _
/-- A version of `Finset.inf'_image` with LHS and RHS reversed.
Also, this lemma assumes that `s` is nonempty instead of assuming that its image is nonempty. -/
lemma inf'_comp_eq_image [DecidableEq β] {s : Finset γ} {f : γ → β} (hs : s.Nonempty) (g : β → α) :
s.inf' hs (g ∘ f) = (s.image f).inf' (hs.image f) g :=
sup'_comp_eq_image (α := αᵒᵈ) hs g
/-- To rewrite from right to left, use `Finset.inf'_comp_eq_map`. -/
@[simp]
theorem inf'_map {s : Finset γ} {f : γ ↪ β} (g : β → α) (hs : (s.map f).Nonempty) :
(s.map f).inf' hs g = s.inf' (map_nonempty.1 hs) (g ∘ f) :=
sup'_map (α := αᵒᵈ) _ hs
/-- A version of `Finset.inf'_map` with LHS and RHS reversed.
Also, this lemma assumes that `s` is nonempty instead of assuming that its image is nonempty. -/
lemma inf'_comp_eq_map {s : Finset γ} {f : γ ↪ β} (g : β → α) (hs : s.Nonempty) :
s.inf' hs (g ∘ f) = (s.map f).inf' (map_nonempty.2 hs) g :=
sup'_comp_eq_map (α := αᵒᵈ) g hs
@[gcongr]
theorem inf'_mono {s₁ s₂ : Finset β} (h : s₁ ⊆ s₂) (h₁ : s₁.Nonempty) :
s₂.inf' (h₁.mono h) f ≤ s₁.inf' h₁ f :=
Finset.le_inf' h₁ _ (fun _ hb => inf'_le _ (h hb))
end Inf'
section Sup
variable [SemilatticeSup α] [OrderBot α]
theorem sup'_eq_sup {s : Finset β} (H : s.Nonempty) (f : β → α) : s.sup' H f = s.sup f :=
le_antisymm (sup'_le H f fun _ => le_sup) (Finset.sup_le fun _ => le_sup' f)
theorem coe_sup_of_nonempty {s : Finset β} (h : s.Nonempty) (f : β → α) :
(↑(s.sup f) : WithBot α) = s.sup ((↑) ∘ f) := by simp only [← sup'_eq_sup h, coe_sup' h]
end Sup
section Inf
variable [SemilatticeInf α] [OrderTop α]
theorem inf'_eq_inf {s : Finset β} (H : s.Nonempty) (f : β → α) : s.inf' H f = s.inf f :=
sup'_eq_sup (α := αᵒᵈ) H f
theorem coe_inf_of_nonempty {s : Finset β} (h : s.Nonempty) (f : β → α) :
(↑(s.inf f) : WithTop α) = s.inf ((↑) ∘ f) :=
coe_sup_of_nonempty (α := αᵒᵈ) h f
end Inf
@[simp]
protected theorem sup_apply {C : β → Type*} [∀ b : β, SemilatticeSup (C b)]
[∀ b : β, OrderBot (C b)] (s : Finset α) (f : α → ∀ b : β, C b) (b : β) :
s.sup f b = s.sup fun a => f a b :=
comp_sup_eq_sup_comp (fun x : ∀ b : β, C b => x b) (fun _ _ => rfl) rfl
@[simp]
protected theorem inf_apply {C : β → Type*} [∀ b : β, SemilatticeInf (C b)]
[∀ b : β, OrderTop (C b)] (s : Finset α) (f : α → ∀ b : β, C b) (b : β) :
s.inf f b = s.inf fun a => f a b :=
Finset.sup_apply (C := fun b => (C b)ᵒᵈ) s f b
@[simp]
protected theorem sup'_apply {C : β → Type*} [∀ b : β, SemilatticeSup (C b)]
{s : Finset α} (H : s.Nonempty) (f : α → ∀ b : β, C b) (b : β) :
s.sup' H f b = s.sup' H fun a => f a b :=
comp_sup'_eq_sup'_comp H (fun x : ∀ b : β, C b => x b) fun _ _ => rfl
@[simp]
protected theorem inf'_apply {C : β → Type*} [∀ b : β, SemilatticeInf (C b)]
{s : Finset α} (H : s.Nonempty) (f : α → ∀ b : β, C b) (b : β) :
s.inf' H f b = s.inf' H fun a => f a b :=
Finset.sup'_apply (C := fun b => (C b)ᵒᵈ) H f b
@[simp]
theorem toDual_sup' [SemilatticeSup α] {s : Finset ι} (hs : s.Nonempty) (f : ι → α) :
toDual (s.sup' hs f) = s.inf' hs (toDual ∘ f) :=
rfl
@[simp]
theorem toDual_inf' [SemilatticeInf α] {s : Finset ι} (hs : s.Nonempty) (f : ι → α) :
toDual (s.inf' hs f) = s.sup' hs (toDual ∘ f) :=
rfl
@[simp]
theorem ofDual_sup' [SemilatticeInf α] {s : Finset ι} (hs : s.Nonempty) (f : ι → αᵒᵈ) :
ofDual (s.sup' hs f) = s.inf' hs (ofDual ∘ f) :=
rfl
@[simp]
theorem ofDual_inf' [SemilatticeSup α] {s : Finset ι} (hs : s.Nonempty) (f : ι → αᵒᵈ) :
ofDual (s.inf' hs f) = s.sup' hs (ofDual ∘ f) :=
rfl
section DistribLattice
variable [DistribLattice α] {s : Finset ι} {t : Finset κ} (hs : s.Nonempty) (ht : t.Nonempty)
{f : ι → α} {g : κ → α} {a : α}
theorem sup'_inf_distrib_left (f : ι → α) (a : α) :
a ⊓ s.sup' hs f = s.sup' hs fun i ↦ a ⊓ f i := by
induction hs using Finset.Nonempty.cons_induction with
| singleton => simp
| cons _ _ _ hs ih => simp_rw [sup'_cons hs, inf_sup_left, ih]
theorem sup'_inf_distrib_right (f : ι → α) (a : α) :
s.sup' hs f ⊓ a = s.sup' hs fun i => f i ⊓ a := by
rw [inf_comm, sup'_inf_distrib_left]; simp_rw [inf_comm]
theorem inf'_sup_distrib_left (f : ι → α) (a : α) : a ⊔ s.inf' hs f = s.inf' hs fun i => a ⊔ f i :=
@sup'_inf_distrib_left αᵒᵈ _ _ _ hs _ _
theorem inf'_sup_distrib_right (f : ι → α) (a : α) : s.inf' hs f ⊔ a = s.inf' hs fun i => f i ⊔ a :=
@sup'_inf_distrib_right αᵒᵈ _ _ _ hs _ _
end DistribLattice
section LinearOrder
variable [LinearOrder α] {s : Finset ι} (H : s.Nonempty) {f : ι → α} {a : α}
theorem comp_sup_eq_sup_comp_of_nonempty [OrderBot α] [SemilatticeSup β] [OrderBot β]
{g : α → β} (mono_g : Monotone g) (H : s.Nonempty) : g (s.sup f) = s.sup (g ∘ f) := by
rw [← Finset.sup'_eq_sup H, ← Finset.sup'_eq_sup H]
exact Finset.comp_sup'_eq_sup'_comp H g (fun x y ↦ Monotone.map_sup mono_g x y)
@[simp]
theorem le_sup'_iff : a ≤ s.sup' H f ↔ ∃ b ∈ s, a ≤ f b := by
rw [← WithBot.coe_le_coe, coe_sup', Finset.le_sup_iff (WithBot.bot_lt_coe a)]
exact exists_congr (fun _ => and_congr_right' WithBot.coe_le_coe)
@[simp]
theorem lt_sup'_iff : a < s.sup' H f ↔ ∃ b ∈ s, a < f b := by
rw [← WithBot.coe_lt_coe, coe_sup', Finset.lt_sup_iff]
exact exists_congr (fun _ => and_congr_right' WithBot.coe_lt_coe)
@[simp]
theorem sup'_lt_iff : s.sup' H f < a ↔ ∀ i ∈ s, f i < a := by
rw [← WithBot.coe_lt_coe, coe_sup', Finset.sup_lt_iff (WithBot.bot_lt_coe a)]
exact forall₂_congr (fun _ _ => WithBot.coe_lt_coe)
@[simp]
theorem inf'_le_iff : s.inf' H f ≤ a ↔ ∃ i ∈ s, f i ≤ a :=
le_sup'_iff (α := αᵒᵈ) H
@[simp]
theorem inf'_lt_iff : s.inf' H f < a ↔ ∃ i ∈ s, f i < a :=
lt_sup'_iff (α := αᵒᵈ) H
@[simp]
theorem lt_inf'_iff : a < s.inf' H f ↔ ∀ i ∈ s, a < f i :=
sup'_lt_iff (α := αᵒᵈ) H
theorem exists_mem_eq_sup' (f : ι → α) : ∃ i, i ∈ s ∧ s.sup' H f = f i := by
induction H using Finset.Nonempty.cons_induction with
| singleton c => exact ⟨c, mem_singleton_self c, rfl⟩
| cons c s hcs hs ih =>
rcases ih with ⟨b, hb, h'⟩
rw [sup'_cons hs, h']
cases le_total (f b) (f c) with
| inl h => exact ⟨c, mem_cons.2 (Or.inl rfl), sup_eq_left.2 h⟩
| inr h => exact ⟨b, mem_cons.2 (Or.inr hb), sup_eq_right.2 h⟩
theorem exists_mem_eq_inf' (f : ι → α) : ∃ i, i ∈ s ∧ s.inf' H f = f i :=
exists_mem_eq_sup' (α := αᵒᵈ) H f
theorem exists_mem_eq_sup [OrderBot α] (s : Finset ι) (h : s.Nonempty) (f : ι → α) :
∃ i, i ∈ s ∧ s.sup f = f i :=
sup'_eq_sup h f ▸ exists_mem_eq_sup' h f
theorem exists_mem_eq_inf [OrderTop α] (s : Finset ι) (h : s.Nonempty) (f : ι → α) :
∃ i, i ∈ s ∧ s.inf f = f i :=
exists_mem_eq_sup (α := αᵒᵈ) s h f
end LinearOrder
end Finset
namespace Multiset
theorem map_finset_sup [DecidableEq α] [DecidableEq β] (s : Finset γ) (f : γ → Multiset β)
(g : β → α) (hg : Function.Injective g) : map g (s.sup f) = s.sup (map g ∘ f) :=
Finset.comp_sup_eq_sup_comp _ (fun _ _ => map_union hg) (map_zero _)
theorem count_finset_sup [DecidableEq β] (s : Finset α) (f : α → Multiset β) (b : β) :
count b (s.sup f) = s.sup fun a => count b (f a) := by
letI := Classical.decEq α
refine s.induction ?_ ?_
· exact count_zero _
· intro i s _ ih
rw [Finset.sup_insert, sup_eq_union, count_union, Finset.sup_insert, ih]
theorem mem_sup {α β} [DecidableEq β] {s : Finset α} {f : α → Multiset β} {x : β} :
x ∈ s.sup f ↔ ∃ v ∈ s, x ∈ f v := by
induction s using Finset.cons_induction <;> simp [*]
end Multiset
namespace Finset
variable [DecidableEq α] {s : Finset ι} {f : ι → Finset α} {a : α}
set_option linter.docPrime false in
@[simp] lemma mem_sup' (hs) : a ∈ s.sup' hs f ↔ ∃ i ∈ s, a ∈ f i := by
induction hs using Nonempty.cons_induction <;> simp [*]
set_option linter.docPrime false in
@[simp] lemma mem_inf' (hs) : a ∈ s.inf' hs f ↔ ∀ i ∈ s, a ∈ f i := by
induction hs using Nonempty.cons_induction <;> simp [*]
@[simp] lemma mem_sup : a ∈ s.sup f ↔ ∃ i ∈ s, a ∈ f i := by
induction s using cons_induction <;> simp [*]
@[simp]
theorem sup_singleton_apply (s : Finset β) (f : β → α) :
(s.sup fun b => {f b}) = s.image f := by
ext a
rw [mem_sup, mem_image]
simp only [mem_singleton, eq_comm]
@[deprecated (since := "2025-05-24")]
alias sup_singleton'' := sup_singleton_apply
@[simp]
theorem sup_singleton_eq_self (s : Finset α) : s.sup singleton = s :=
(s.sup_singleton_apply _).trans image_id
@[deprecated (since := "2025-05-24")]
alias sup_singleton' := sup_singleton_eq_self
end Finset |
.lake/packages/mathlib/Mathlib/Data/Fintype/Sum.lean | import Mathlib.Data.Finset.Sum
import Mathlib.Data.Fintype.EquivFin
import Mathlib.Logic.Embedding.Set
/-!
## Instances
We provide the `Fintype` instance for the sum of two fintypes.
-/
universe u v
variable {α β : Type*}
open Finset
instance (α : Type u) (β : Type v) [Fintype α] [Fintype β] : Fintype (α ⊕ β) where
elems := univ.disjSum univ
complete := by rintro (_ | _) <;> simp
namespace Finset
variable {α β : Type*} {u : Finset (α ⊕ β)} {s : Finset α} {t : Finset β}
section left
variable [Fintype α] {u : Finset (α ⊕ β)}
lemma toLeft_eq_univ : u.toLeft = univ ↔ univ.map .inl ⊆ u := by
simp [map_inl_subset_iff_subset_toLeft]
lemma toRight_eq_empty : u.toRight = ∅ ↔ u ⊆ univ.map .inl := by simp [subset_map_inl]
end left
section right
variable [Fintype β] {u : Finset (α ⊕ β)}
lemma toRight_eq_univ : u.toRight = univ ↔ univ.map .inr ⊆ u := by
simp [map_inr_subset_iff_subset_toRight]
lemma toLeft_eq_empty : u.toLeft = ∅ ↔ u ⊆ univ.map .inr := by simp [subset_map_inr]
end right
variable [Fintype α] [Fintype β]
@[simp] lemma univ_disjSum_univ : univ.disjSum univ = (univ : Finset (α ⊕ β)) := rfl
@[simp] lemma toLeft_univ : (univ : Finset (α ⊕ β)).toLeft = univ := by ext; simp
@[simp] lemma toRight_univ : (univ : Finset (α ⊕ β)).toRight = univ := by ext; simp
end Finset
@[simp]
theorem Fintype.card_sum [Fintype α] [Fintype β] :
Fintype.card (α ⊕ β) = Fintype.card α + Fintype.card β :=
card_disjSum _ _
/-- If the subtype of all-but-one elements is a `Fintype` then the type itself is a `Fintype`. -/
def fintypeOfFintypeNe (a : α) (_ : Fintype { b // b ≠ a }) : Fintype α :=
Fintype.ofBijective (Sum.elim ((↑) : { b // b = a } → α) ((↑) : { b // b ≠ a } → α)) <| by
classical exact (Equiv.sumCompl (· = a)).bijective
theorem image_subtype_ne_univ_eq_image_erase [Fintype α] [DecidableEq β] (k : β) (b : α → β) :
image (fun i : { a // b a ≠ k } => b ↑i) univ = (image b univ).erase k := by
apply subset_antisymm
· rw [image_subset_iff]
intro i _
apply mem_erase_of_ne_of_mem i.2 (mem_image_of_mem _ (mem_univ _))
· intro i hi
rw [mem_image]
rcases mem_image.1 (erase_subset _ _ hi) with ⟨a, _, ha⟩
subst ha
exact ⟨⟨a, ne_of_mem_erase hi⟩, mem_univ _, rfl⟩
theorem image_subtype_univ_ssubset_image_univ [Fintype α] [DecidableEq β] (k : β) (b : α → β)
(hk : k ∈ Finset.image b univ) (p : β → Prop) [DecidablePred p] (hp : ¬p k) :
image (fun i : { a // p (b a) } => b ↑i) univ ⊂ image b univ := by
grind
/-- Any injection from a finset `s` in a fintype `α` to a finset `t` of the same cardinality as `α`
can be extended to a bijection between `α` and `t`. -/
theorem Finset.exists_equiv_extend_of_card_eq [Fintype α] [DecidableEq β] {t : Finset β}
(hαt : Fintype.card α = #t) {s : Finset α} {f : α → β} (hfst : Finset.image f s ⊆ t)
(hfs : Set.InjOn f s) : ∃ g : α ≃ t, ∀ i ∈ s, (g i : β) = f i := by
classical
induction s using Finset.induction generalizing f with
| empty =>
obtain ⟨e⟩ : Nonempty (α ≃ ↥t) := by rwa [← Fintype.card_eq, Fintype.card_coe]
use e
simp
| insert a s has H => ?_
have hfst' : Finset.image f s ⊆ t := (Finset.image_mono _ (s.subset_insert a)).trans hfst
have hfs' : Set.InjOn f s := hfs.mono (s.subset_insert a)
obtain ⟨g', hg'⟩ := H hfst' hfs'
have hfat : f a ∈ t := hfst (mem_image_of_mem _ (s.mem_insert_self a))
use g'.trans (Equiv.swap (⟨f a, hfat⟩ : t) (g' a))
simp_rw [mem_insert]
rintro i (rfl | hi)
· simp
rw [Equiv.trans_apply, Equiv.swap_apply_of_ne_of_ne, hg' _ hi]
· exact
ne_of_apply_ne Subtype.val
(ne_of_eq_of_ne (hg' _ hi) <|
hfs.ne (subset_insert _ _ hi) (mem_insert_self _ _) <| ne_of_mem_of_not_mem hi has)
· exact g'.injective.ne (ne_of_mem_of_not_mem hi has)
/-- Any injection from a set `s` in a fintype `α` to a finset `t` of the same cardinality as `α`
can be extended to a bijection between `α` and `t`. -/
theorem Set.MapsTo.exists_equiv_extend_of_card_eq [Fintype α] {t : Finset β}
(hαt : Fintype.card α = #t) {s : Set α} {f : α → β} (hfst : s.MapsTo f t)
(hfs : Set.InjOn f s) : ∃ g : α ≃ t, ∀ i ∈ s, (g i : β) = f i := by
classical
let s' : Finset α := s.toFinset
have hfst' : s'.image f ⊆ t := by simpa [s', ← Finset.coe_subset] using hfst
have hfs' : Set.InjOn f s' := by simpa [s'] using hfs
obtain ⟨g, hg⟩ := Finset.exists_equiv_extend_of_card_eq hαt hfst' hfs'
refine ⟨g, fun i hi => ?_⟩
apply hg
simpa [s'] using hi
theorem Fintype.card_subtype_or (p q : α → Prop) [Fintype { x // p x }] [Fintype { x // q x }]
[Fintype { x // p x ∨ q x }] :
Fintype.card { x // p x ∨ q x } ≤ Fintype.card { x // p x } + Fintype.card { x // q x } := by
classical
convert Fintype.card_le_of_embedding (subtypeOrLeftEmbedding p q)
rw [Fintype.card_sum]
theorem Fintype.card_subtype_or_disjoint (p q : α → Prop) (h : Disjoint p q) [Fintype { x // p x }]
[Fintype { x // q x }] [Fintype { x // p x ∨ q x }] :
Fintype.card { x // p x ∨ q x } = Fintype.card { x // p x } + Fintype.card { x // q x } := by
classical
convert Fintype.card_congr (subtypeOrEquiv p q h)
simp
theorem Fintype.card_subtype_eq_or_eq_of_ne {α : Type*} [Fintype α] [DecidableEq α] {a b : α}
(h : a ≠ b) : Fintype.card { c : α // c = a ∨ c = b } = 2 :=
Fintype.card_subtype_or_disjoint _ _ fun _ ha hb _ hc ↦ ha _ hc ▸ hb _ hc ▸ h <| rfl
attribute [local instance] Fintype.ofFinite in
@[simp]
theorem infinite_sum : Infinite (α ⊕ β) ↔ Infinite α ∨ Infinite β := by
refine ⟨fun H => ?_, fun H => H.elim (@Sum.infinite_of_left α β) (@Sum.infinite_of_right α β)⟩
contrapose! H; cases H
infer_instance |
.lake/packages/mathlib/Mathlib/Data/Fintype/Fin.lean | import Mathlib.Order.Interval.Finset.Fin
import Mathlib.Data.Vector.Basic
/-!
# The structure of `Fintype (Fin n)`
This file contains some basic results about the `Fintype` instance for `Fin`,
especially properties of `Finset.univ : Finset (Fin n)`.
-/
open List (Vector)
open Finset
open Fintype
namespace Fin
variable {α β : Type*} {n : ℕ}
theorem map_valEmbedding_univ : (Finset.univ : Finset (Fin n)).map Fin.valEmbedding = Iio n := by
ext
simp [orderIsoSubtype.symm.surjective.exists, OrderIso.symm]
@[simp]
theorem Ioi_zero_eq_map : Ioi (0 : Fin n.succ) = univ.map (Fin.succEmb _) :=
coe_injective <| by ext; simp [pos_iff_ne_zero]
@[simp]
theorem Iio_last_eq_map : Iio (Fin.last n) = Finset.univ.map Fin.castSuccEmb :=
coe_injective <| by ext; simp [lt_def]
theorem Ioi_succ (i : Fin n) : Ioi i.succ = (Ioi i).map (Fin.succEmb _) := by simp
theorem Iio_castSucc (i : Fin n) : Iio (castSucc i) = (Iio i).map Fin.castSuccEmb := by simp
theorem card_filter_univ_succ (p : Fin (n + 1) → Prop) [DecidablePred p] :
#{x | p x} = if p 0 then #{x | p (.succ x)} + 1 else #{x | p (.succ x)} := by
rw [Fin.univ_succ, filter_cons, apply_ite Finset.card, card_cons, filter_map, card_map]; rfl
theorem card_filter_univ_succ' (p : Fin (n + 1) → Prop) [DecidablePred p] :
#{x | p x} = ite (p 0) 1 0 + #{x | p (.succ x)} := by
rw [card_filter_univ_succ]; split_ifs <;> simp [add_comm]
theorem card_filter_univ_eq_vector_get_eq_count [DecidableEq α] (a : α) (v : List.Vector α n) :
#{i | v.get i = a} = v.toList.count a := by
induction v with
| nil => simp
| @cons n x xs hxs =>
simp_rw [card_filter_univ_succ', Vector.get_cons_zero, Vector.toList_cons, Vector.get_cons_succ,
hxs, List.count_cons, add_comm (ite (x = a) 1 0), beq_iff_eq]
end Fin |
.lake/packages/mathlib/Mathlib/Data/Fintype/Card.lean | import Mathlib.Data.Finset.Card
import Mathlib.Data.Fintype.Basic
/-!
# Cardinalities of finite types
This file defines the cardinality `Fintype.card α` as the number of elements in `(univ : Finset α)`.
We also include some elementary results on the values of `Fintype.card` on specific types.
## Main declarations
* `Fintype.card α`: Cardinality of a fintype. Equal to `Finset.univ.card`.
* `Finite.surjective_of_injective`: an injective function from a finite type to
itself is also surjective.
-/
assert_not_exists Monoid
open Function
universe u v
variable {α β γ : Type*}
open Finset
namespace Fintype
/-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/
def card (α) [Fintype α] : ℕ :=
(@univ α _).card
theorem subtype_card {p : α → Prop} (s : Finset α) (H : ∀ x : α, x ∈ s ↔ p x) :
@card { x // p x } (Fintype.subtype s H) = #s :=
Multiset.card_pmap _ _ _
theorem card_of_subtype {p : α → Prop} (s : Finset α) (H : ∀ x : α, x ∈ s ↔ p x)
[Fintype { x // p x }] : card { x // p x } = #s := by
rw [← subtype_card s H]
congr!
@[simp]
theorem card_ofFinset {p : Set α} (s : Finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) :
@Fintype.card p (ofFinset s H) = #s :=
Fintype.subtype_card s H
theorem card_of_finset' {p : Set α} (s : Finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [Fintype p] :
Fintype.card p = #s := by rw [← card_ofFinset s H]; congr!
end Fintype
namespace Fintype
theorem ofEquiv_card [Fintype α] (f : α ≃ β) : @card β (ofEquiv α f) = card α :=
Multiset.card_map _ _
theorem card_congr {α β} [Fintype α] [Fintype β] (f : α ≃ β) : card α = card β := by
rw [← ofEquiv_card f]; congr!
@[congr]
theorem card_congr' {α β} [Fintype α] [Fintype β] (h : α = β) : card α = card β :=
card_congr (by rw [h])
/-- Note: this lemma is specifically about `Fintype.ofSubsingleton`. For a statement about
arbitrary `Fintype` instances, use either `Fintype.card_le_one_iff_subsingleton` or
`Fintype.card_unique`. -/
theorem card_ofSubsingleton (a : α) [Subsingleton α] : @Fintype.card _ (ofSubsingleton a) = 1 :=
rfl
@[simp]
theorem card_unique [Unique α] [h : Fintype α] : Fintype.card α = 1 :=
Subsingleton.elim (ofSubsingleton default) h ▸ card_ofSubsingleton _
/-- Note: this lemma is specifically about `Fintype.ofIsEmpty`. For a statement about
arbitrary `Fintype` instances, use `Fintype.card_eq_zero`. -/
theorem card_ofIsEmpty [IsEmpty α] : @Fintype.card α Fintype.ofIsEmpty = 0 :=
rfl
end Fintype
namespace Set
variable {s t : Set α}
-- We use an arbitrary `[Fintype s]` instance here,
-- not necessarily coming from a `[Fintype α]`.
@[simp]
theorem toFinset_card {α : Type*} (s : Set α) [Fintype s] : s.toFinset.card = Fintype.card s :=
Multiset.card_map Subtype.val Finset.univ.val
end Set
@[simp, grind =]
theorem Finset.card_univ [Fintype α] : #(univ : Finset α) = Fintype.card α := rfl
theorem Finset.eq_univ_of_card [Fintype α] (s : Finset α) (hs : #s = Fintype.card α) :
s = univ :=
eq_of_subset_of_card_le (subset_univ _) <| by rw [hs, Finset.card_univ]
theorem Finset.card_eq_iff_eq_univ [Fintype α] (s : Finset α) : #s = Fintype.card α ↔ s = univ :=
⟨s.eq_univ_of_card, by
rintro rfl
exact Finset.card_univ⟩
theorem Finset.card_le_univ [Fintype α] (s : Finset α) : #s ≤ Fintype.card α :=
card_le_card (subset_univ s)
theorem Finset.card_lt_univ_of_notMem [Fintype α] {s : Finset α} {x : α} (hx : x ∉ s) :
#s < Fintype.card α :=
card_lt_card ⟨subset_univ s, not_forall.2 ⟨x, fun hx' => hx (hx' <| mem_univ x)⟩⟩
@[deprecated (since := "2025-05-23")]
alias Finset.card_lt_univ_of_not_mem := Finset.card_lt_univ_of_notMem
theorem Finset.card_lt_iff_ne_univ [Fintype α] (s : Finset α) :
#s < Fintype.card α ↔ s ≠ Finset.univ :=
s.card_le_univ.lt_iff_ne.trans (not_congr s.card_eq_iff_eq_univ)
theorem Finset.card_compl_lt_iff_nonempty [Fintype α] [DecidableEq α] (s : Finset α) :
#sᶜ < Fintype.card α ↔ s.Nonempty :=
sᶜ.card_lt_iff_ne_univ.trans s.compl_ne_univ_iff_nonempty
theorem Finset.card_univ_diff [DecidableEq α] [Fintype α] (s : Finset α) :
#(univ \ s) = Fintype.card α - #s := by grind
theorem Finset.card_compl [DecidableEq α] [Fintype α] (s : Finset α) : #sᶜ = Fintype.card α - #s :=
Finset.card_univ_diff s
@[simp]
theorem Finset.card_add_card_compl [DecidableEq α] [Fintype α] (s : Finset α) :
#s + #sᶜ = Fintype.card α := by
rw [Finset.card_compl, ← Nat.add_sub_assoc (card_le_univ s), Nat.add_sub_cancel_left]
@[simp]
theorem Finset.card_compl_add_card [DecidableEq α] [Fintype α] (s : Finset α) :
#sᶜ + #s = Fintype.card α := by
rw [Nat.add_comm, card_add_card_compl]
theorem Fintype.card_compl_set [Fintype α] (s : Set α) [Fintype s] [Fintype (↥sᶜ : Sort _)] :
Fintype.card (↥sᶜ : Sort _) = Fintype.card α - Fintype.card s := by
classical rw [← Set.toFinset_card, ← Set.toFinset_card, ← Finset.card_compl, Set.toFinset_compl]
theorem Fintype.card_subtype_eq (y : α) [Fintype { x // x = y }] :
Fintype.card { x // x = y } = 1 :=
Fintype.card_unique
theorem Fintype.card_subtype_eq' (y : α) [Fintype { x // y = x }] :
Fintype.card { x // y = x } = 1 :=
Fintype.card_unique
theorem Fintype.card_empty : Fintype.card Empty = 0 :=
rfl
theorem Fintype.card_pempty : Fintype.card PEmpty = 0 :=
rfl
theorem Fintype.card_unit : Fintype.card Unit = 1 :=
rfl
@[simp]
theorem Fintype.card_punit : Fintype.card PUnit = 1 :=
rfl
@[simp]
theorem Fintype.card_bool : Fintype.card Bool = 2 :=
rfl
@[simp]
theorem Fintype.card_ulift (α : Type*) [Fintype α] : Fintype.card (ULift α) = Fintype.card α :=
Fintype.ofEquiv_card _
@[simp]
theorem Fintype.card_plift (α : Type*) [Fintype α] : Fintype.card (PLift α) = Fintype.card α :=
Fintype.ofEquiv_card _
@[simp]
theorem Fintype.card_orderDual (α : Type*) [Fintype α] : Fintype.card αᵒᵈ = Fintype.card α :=
rfl
@[simp]
theorem Fintype.card_lex (α : Type*) [Fintype α] : Fintype.card (Lex α) = Fintype.card α :=
rfl
-- Note: The extra hypothesis `h` is there so that the rewrite lemma applies,
-- no matter what instance of `Fintype (Set.univ : Set α)` is used.
@[simp]
theorem Fintype.card_setUniv [Fintype α] {h : Fintype (Set.univ : Set α)} :
Fintype.card (Set.univ : Set α) = Fintype.card α := by
apply Fintype.card_of_finset'
simp
@[simp]
theorem Fintype.card_subtype_true [Fintype α] {h : Fintype {_a : α // True}} :
@Fintype.card {_a // True} h = Fintype.card α := by
apply Fintype.card_of_subtype
simp
/-- Given that `α ⊕ β` is a fintype, `α` is also a fintype. This is non-computable as it uses
that `Sum.inl` is an injection, but there's no clear inverse if `α` is empty. -/
noncomputable def Fintype.sumLeft {α β} [Fintype (α ⊕ β)] : Fintype α :=
Fintype.ofInjective (Sum.inl : α → α ⊕ β) Sum.inl_injective
/-- Given that `α ⊕ β` is a fintype, `β` is also a fintype. This is non-computable as it uses
that `Sum.inr` is an injection, but there's no clear inverse if `β` is empty. -/
noncomputable def Fintype.sumRight {α β} [Fintype (α ⊕ β)] : Fintype β :=
Fintype.ofInjective (Sum.inr : β → α ⊕ β) Sum.inr_injective
theorem Finite.exists_univ_list (α) [Finite α] : ∃ l : List α, l.Nodup ∧ ∀ x : α, x ∈ l := by
cases nonempty_fintype α
obtain ⟨l, e⟩ := Quotient.exists_rep (@univ α _).1
have := And.intro (@univ α _).2 (@mem_univ_val α _)
exact ⟨_, by rwa [← e] at this⟩
theorem List.Nodup.length_le_card {α : Type*} [Fintype α] {l : List α} (h : l.Nodup) :
l.length ≤ Fintype.card α := by
classical exact List.toFinset_card_of_nodup h ▸ l.toFinset.card_le_univ
namespace Fintype
variable [Fintype α] [Fintype β]
theorem card_le_of_injective (f : α → β) (hf : Function.Injective f) : card α ≤ card β :=
Finset.card_le_card_of_injOn f (fun _ _ => Finset.mem_univ _) fun _ _ _ _ h => hf h
theorem card_le_of_embedding (f : α ↪ β) : card α ≤ card β :=
card_le_of_injective f f.2
theorem card_lt_of_injective_of_notMem (f : α → β) (h : Function.Injective f) {b : β}
(w : b ∉ Set.range f) : card α < card β :=
calc
card α = (univ.map ⟨f, h⟩).card := (card_map _).symm
_ < card β :=
Finset.card_lt_univ_of_notMem (x := b) <| by
rwa [← mem_coe, coe_map, coe_univ, Set.image_univ]
@[deprecated (since := "2025-05-23")]
alias card_lt_of_injective_of_not_mem := card_lt_of_injective_of_notMem
theorem card_lt_of_injective_not_surjective (f : α → β) (h : Function.Injective f)
(h' : ¬Function.Surjective f) : card α < card β :=
let ⟨_y, hy⟩ := not_forall.1 h'
card_lt_of_injective_of_notMem f h hy
theorem card_le_of_surjective (f : α → β) (h : Function.Surjective f) : card β ≤ card α :=
card_le_of_injective _ (Function.injective_surjInv h)
theorem card_range_le {α β : Type*} (f : α → β) [Fintype α] [Fintype (Set.range f)] :
Fintype.card (Set.range f) ≤ Fintype.card α :=
Fintype.card_le_of_surjective (fun a => ⟨f a, by simp⟩) fun ⟨_, a, ha⟩ => ⟨a, by simpa using ha⟩
theorem card_range {α β F : Type*} [FunLike F α β] [EmbeddingLike F α β] (f : F) [Fintype α]
[Fintype (Set.range f)] : Fintype.card (Set.range f) = Fintype.card α :=
Eq.symm <| Fintype.card_congr <| Equiv.ofInjective _ <| EmbeddingLike.injective f
theorem card_eq_zero_iff : card α = 0 ↔ IsEmpty α := by
rw [card, Finset.card_eq_zero, univ_eq_empty_iff]
@[simp] theorem card_eq_zero [IsEmpty α] : card α = 0 :=
card_eq_zero_iff.2 ‹_›
alias card_of_isEmpty := card_eq_zero
/-- A `Fintype` with cardinality zero is equivalent to `Empty`. -/
def cardEqZeroEquivEquivEmpty : card α = 0 ≃ (α ≃ Empty) :=
(Equiv.ofIff card_eq_zero_iff).trans (Equiv.equivEmptyEquiv α).symm
theorem card_pos_iff : 0 < card α ↔ Nonempty α :=
Nat.pos_iff_ne_zero.trans <| not_iff_comm.mp <| not_nonempty_iff.trans card_eq_zero_iff.symm
theorem card_pos [h : Nonempty α] : 0 < card α :=
card_pos_iff.mpr h
@[simp]
theorem card_ne_zero [Nonempty α] : card α ≠ 0 :=
_root_.ne_of_gt card_pos
instance [Nonempty α] : NeZero (card α) := ⟨card_ne_zero⟩
theorem existsUnique_iff_card_one {α} [Fintype α] (p : α → Prop) [DecidablePred p] :
(∃! a : α, p a) ↔ #{x | p x} = 1 := by
rw [Finset.card_eq_one]
refine exists_congr fun x => ?_
simp only [Subset.antisymm_iff, subset_singleton_iff', singleton_subset_iff, and_comm,
mem_filter_univ]
nonrec theorem two_lt_card_iff : 2 < card α ↔ ∃ a b c : α, a ≠ b ∧ a ≠ c ∧ b ≠ c := by
simp_rw [← Finset.card_univ, two_lt_card_iff, mem_univ, true_and]
theorem card_of_bijective {f : α → β} (hf : Bijective f) : card α = card β :=
card_congr (Equiv.ofBijective f hf)
end Fintype
namespace Finite
variable [Finite α]
theorem surjective_of_injective {f : α → α} (hinj : Injective f) : Surjective f := by
intro x
have := Classical.propDecidable
cases nonempty_fintype α
have h₁ : image f univ = univ :=
eq_of_subset_of_card_le (subset_univ _)
((card_image_of_injective univ hinj).symm ▸ le_rfl)
have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ x
obtain ⟨y, h⟩ := mem_image.1 h₂
exact ⟨y, h.2⟩
theorem injective_iff_surjective {f : α → α} : Injective f ↔ Surjective f :=
⟨surjective_of_injective, fun hsurj =>
HasLeftInverse.injective ⟨surjInv hsurj, leftInverse_of_surjective_of_rightInverse
(surjective_of_injective (injective_surjInv _))
(rightInverse_surjInv _)⟩⟩
theorem injective_iff_bijective {f : α → α} : Injective f ↔ Bijective f := by
simp [Bijective, injective_iff_surjective]
theorem surjective_iff_bijective {f : α → α} : Surjective f ↔ Bijective f := by
simp [Bijective, injective_iff_surjective]
theorem injective_iff_surjective_of_equiv {f : α → β} (e : α ≃ β) : Injective f ↔ Surjective f :=
have : Injective (e.symm ∘ f) ↔ Surjective (e.symm ∘ f) := injective_iff_surjective
⟨fun hinj => by
simpa [Function.comp] using e.surjective.comp (this.1 (e.symm.injective.comp hinj)),
fun hsurj => by
simpa [Function.comp] using e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩
alias ⟨_root_.Function.Injective.bijective_of_finite, _⟩ := injective_iff_bijective
alias ⟨_root_.Function.Surjective.bijective_of_finite, _⟩ := surjective_iff_bijective
alias ⟨_root_.Function.Injective.surjective_of_fintype,
_root_.Function.Surjective.injective_of_fintype⟩ :=
injective_iff_surjective_of_equiv
end Finite
@[simp]
theorem Fintype.card_coe (s : Finset α) [Fintype s] : Fintype.card s = #s :=
@Fintype.card_of_finset' _ _ _ (fun _ => Iff.rfl) (id _)
/-- We can inflate a set `s` to any bigger size. -/
lemma Finset.exists_superset_card_eq [Fintype α] {n : ℕ} {s : Finset α} (hsn : #s ≤ n)
(hnα : n ≤ Fintype.card α) :
∃ t, s ⊆ t ∧ #t = n := by simpa using exists_subsuperset_card_eq s.subset_univ hsn hnα
@[simp]
theorem Fintype.card_prop : Fintype.card Prop = 2 :=
rfl
theorem set_fintype_card_le_univ [Fintype α] (s : Set α) [Fintype s] :
Fintype.card s ≤ Fintype.card α :=
Fintype.card_le_of_embedding (Function.Embedding.subtype s)
theorem set_fintype_card_eq_univ_iff [Fintype α] (s : Set α) [Fintype s] :
Fintype.card s = Fintype.card α ↔ s = Set.univ := by
rw [← Set.toFinset_card, Finset.card_eq_iff_eq_univ, ← Set.toFinset_univ, Set.toFinset_inj]
theorem Fintype.card_subtype_le [Fintype α] (p : α → Prop) [Fintype {a // p a}] :
Fintype.card { x // p x } ≤ Fintype.card α :=
Fintype.card_le_of_embedding (Function.Embedding.subtype _)
lemma Fintype.card_subtype_lt [Fintype α] {p : α → Prop} [Fintype {a // p a}] {x : α} (hx : ¬p x) :
Fintype.card { x // p x } < Fintype.card α :=
Fintype.card_lt_of_injective_of_notMem (b := x) (↑) Subtype.coe_injective <| by
rwa [Subtype.range_coe_subtype]
theorem Fintype.card_subtype [Fintype α] (p : α → Prop) [Fintype {a // p a}] [DecidablePred p] :
Fintype.card { x // p x } = #{x | p x} := by
refine Fintype.card_of_subtype _ ?_
simp
@[simp]
theorem Fintype.card_subtype_compl [Fintype α] (p : α → Prop) [Fintype { x // p x }]
[Fintype { x // ¬p x }] :
Fintype.card { x // ¬p x } = Fintype.card α - Fintype.card { x // p x } := by
classical
rw [Fintype.card_of_subtype (Set.toFinset { x | p x }ᶜ), Set.toFinset_compl,
Finset.card_compl, Fintype.card_of_subtype] <;>
· intro
simp only [Set.mem_toFinset, Set.mem_compl_iff, Set.mem_setOf]
theorem Fintype.card_subtype_mono (p q : α → Prop) (h : p ≤ q) [Fintype { x // p x }]
[Fintype { x // q x }] : Fintype.card { x // p x } ≤ Fintype.card { x // q x } :=
Fintype.card_le_of_embedding (Subtype.impEmbedding _ _ h)
/-- If two subtypes of a fintype have equal cardinality, so do their complements. -/
theorem Fintype.card_compl_eq_card_compl [Finite α] (p q : α → Prop) [Fintype { x // p x }]
[Fintype { x // ¬p x }] [Fintype { x // q x }] [Fintype { x // ¬q x }]
(h : Fintype.card { x // p x } = Fintype.card { x // q x }) :
Fintype.card { x // ¬p x } = Fintype.card { x // ¬q x } := by
cases nonempty_fintype α
simp only [Fintype.card_subtype_compl, h]
theorem Fintype.card_quotient_le [Fintype α] (s : Setoid α)
[DecidableRel ((· ≈ ·) : α → α → Prop)] : Fintype.card (Quotient s) ≤ Fintype.card α :=
Fintype.card_le_of_surjective _ Quotient.mk'_surjective
theorem univ_eq_singleton_of_card_one {α} [Fintype α] (x : α) (h : Fintype.card α = 1) :
(univ : Finset α) = {x} := by
symm
apply eq_of_subset_of_card_le (subset_univ {x})
apply le_of_eq
simp [h, Finset.card_univ]
namespace Finite
variable [Finite α]
theorem wellFounded_of_trans_of_irrefl (r : α → α → Prop) [IsTrans α r] [IsIrrefl α r] :
WellFounded r := by
classical
cases nonempty_fintype α
have (x y) (hxy : r x y) : #{z | r z x} < #{z | r z y} :=
Finset.card_lt_card <| by
simp_rw [Finset.lt_iff_ssubset.symm, lt_iff_le_not_ge, Finset.le_iff_subset,
Finset.subset_iff, mem_filter_univ]
exact
⟨fun z hzx => _root_.trans hzx hxy,
not_forall_of_exists_not ⟨x, Classical.not_imp.2 ⟨hxy, irrefl x⟩⟩⟩
exact Subrelation.wf (this _ _) (measure _).wf
-- See note [lower instance priority]
instance (priority := 100) to_wellFoundedLT [Preorder α] : WellFoundedLT α :=
⟨wellFounded_of_trans_of_irrefl _⟩
-- See note [lower instance priority]
instance (priority := 100) to_wellFoundedGT [Preorder α] : WellFoundedGT α :=
⟨wellFounded_of_trans_of_irrefl _⟩
end Finite
-- Shortcut instances to make sure those are found even in the presence of other instances
-- See https://leanprover.zulipchat.com/#narrow/channel/287929-mathlib4/topic/WellFoundedLT.20Prop.20is.20not.20found.20when.20importing.20too.20much
instance Bool.instWellFoundedLT : WellFoundedLT Bool := inferInstance
instance Bool.instWellFoundedGT : WellFoundedGT Bool := inferInstance
instance Prop.instWellFoundedLT : WellFoundedLT Prop := inferInstance
instance Prop.instWellFoundedGT : WellFoundedGT Prop := inferInstance
section Trunc
/-- A `Fintype` with positive cardinality constructively contains an element.
-/
def truncOfCardPos {α} [Fintype α] (h : 0 < Fintype.card α) : Trunc α :=
letI := Fintype.card_pos_iff.mp h
truncOfNonemptyFintype α
end Trunc
/-- A custom induction principle for fintypes. The base case is a subsingleton type,
and the induction step is for non-trivial types, and one can assume the hypothesis for
smaller types (via `Fintype.card`).
The major premise is `Fintype α`, so to use this with the `induction` tactic you have to give a name
to that instance and use that name.
-/
@[elab_as_elim]
theorem Fintype.induction_subsingleton_or_nontrivial {P : ∀ (α) [Fintype α], Prop} (α : Type*)
[Fintype α] (hbase : ∀ (α) [Fintype α] [Subsingleton α], P α)
(hstep : ∀ (α) [Fintype α] [Nontrivial α],
(∀ (β) [Fintype β], Fintype.card β < Fintype.card α → P β) → P α) :
P α := by
obtain ⟨n, hn⟩ : ∃ n, Fintype.card α = n := ⟨Fintype.card α, rfl⟩
induction n using Nat.strong_induction_on generalizing α with | _ n ih
rcases subsingleton_or_nontrivial α with hsing | hnontriv
· apply hbase
· apply hstep
intro β _ hlt
rw [hn] at hlt
exact ih (Fintype.card β) hlt _ rfl
section Fin
@[simp]
theorem Fintype.card_fin (n : ℕ) : Fintype.card (Fin n) = n :=
List.length_finRange
theorem Fintype.card_fin_lt_of_le {m n : ℕ} (h : m ≤ n) :
Fintype.card {i : Fin n // i < m} = m := by
conv_rhs => rw [← Fintype.card_fin m]
apply Fintype.card_congr
exact { toFun := fun ⟨⟨i, _⟩, hi⟩ ↦ ⟨i, hi⟩
invFun := fun ⟨i, hi⟩ ↦ ⟨⟨i, lt_of_lt_of_le hi h⟩, hi⟩ }
theorem Finset.card_fin (n : ℕ) : #(univ : Finset (Fin n)) = n := by simp
/-- `Fin` as a map from `ℕ` to `Type` is injective. Note that since this is a statement about
equality of types, using it should be avoided if possible. -/
theorem fin_injective : Function.Injective Fin := fun m n h =>
(Fintype.card_fin m).symm.trans <| (Fintype.card_congr <| Equiv.cast h).trans (Fintype.card_fin n)
theorem Fin.val_eq_val_of_heq {k l : ℕ} {i : Fin k} {j : Fin l} (h : i ≍ j) :
(i : ℕ) = (j : ℕ) :=
(Fin.heq_ext_iff (fin_injective (type_eq_of_heq h))).1 h
/-- A reversed version of `Fin.cast_eq_cast` that is easier to rewrite with. -/
theorem Fin.cast_eq_cast' {n m : ℕ} (h : Fin n = Fin m) :
_root_.cast h = Fin.cast (fin_injective h) := by
cases fin_injective h
rfl
theorem card_finset_fin_le {n : ℕ} (s : Finset (Fin n)) : #s ≤ n := by
simpa only [Fintype.card_fin] using s.card_le_univ
end Fin |
.lake/packages/mathlib/Mathlib/Data/Fintype/Option.lean | import Mathlib.Data.Fintype.EquivFin
import Mathlib.Data.Finset.Option
/-!
# fintype instances for option
-/
assert_not_exists MonoidWithZero MulAction
open Function
open Nat
universe u v
variable {α β : Type*}
open Finset
instance {α : Type*} [Fintype α] : Fintype (Option α) :=
⟨Finset.insertNone univ, fun a => by simp⟩
instance {α : Type*} [Finite α] : Finite (Option α) :=
have := Fintype.ofFinite α
Finite.of_fintype _
theorem univ_option (α : Type*) [Fintype α] : (univ : Finset (Option α)) = insertNone univ :=
rfl
@[simp]
theorem Fintype.card_option {α : Type*} [Fintype α] :
Fintype.card (Option α) = Fintype.card α + 1 :=
(Finset.card_cons (by simp)).trans <| congr_arg₂ _ (card_map _) rfl
/-- If `Option α` is a `Fintype` then so is `α` -/
def fintypeOfOption {α : Type*} [Fintype (Option α)] : Fintype α :=
⟨Finset.eraseNone (Fintype.elems (α := Option α)), fun x =>
mem_eraseNone.mpr (Fintype.complete (some x))⟩
/-- A type is a `Fintype` if its successor (using `Option`) is a `Fintype`. -/
def fintypeOfOptionEquiv [Fintype α] (f : α ≃ Option β) : Fintype β :=
haveI := Fintype.ofEquiv _ f
fintypeOfOption
namespace Fintype
/-- A recursor principle for finite types, analogous to `Nat.rec`. It effectively says
that every `Fintype` is either `Empty` or `Option α`, up to an `Equiv`. -/
def truncRecEmptyOption {P : Type u → Sort v} (of_equiv : ∀ {α β}, α ≃ β → P α → P β)
(h_empty : P PEmpty) (h_option : ∀ {α} [Fintype α] [DecidableEq α], P α → P (Option α))
(α : Type u) [Fintype α] [DecidableEq α] : Trunc (P α) := by
suffices ∀ n : ℕ, Trunc (P (ULift <| Fin n)) by
apply Trunc.bind (this (Fintype.card α))
intro h
apply Trunc.map _ (Fintype.truncEquivFin α)
intro e
exact of_equiv (Equiv.ulift.trans e.symm) h
intro n
induction n with
| zero =>
have : card PEmpty = card (ULift (Fin 0)) := by
simp only [card_fin, card_pempty, card_ulift]
apply Trunc.bind (truncEquivOfCardEq this)
intro e
apply Trunc.mk
exact of_equiv e h_empty
| succ n ih =>
have : card (Option (ULift (Fin n))) = card (ULift (Fin n.succ)) := by
simp only [card_fin, card_option, card_ulift]
apply Trunc.bind (truncEquivOfCardEq this)
intro e
apply Trunc.map _ ih
intro ih
exact of_equiv e (h_option ih)
/-- An induction principle for finite types, analogous to `Nat.rec`. It effectively says
that every `Fintype` is either `Empty` or `Option α`, up to an `Equiv`. -/
@[elab_as_elim]
theorem induction_empty_option {P : ∀ (α : Type u) [Fintype α], Prop}
(of_equiv : ∀ (α β) [Fintype β] (e : α ≃ β), @P α (@Fintype.ofEquiv α β ‹_› e.symm) → @P β ‹_›)
(h_empty : P PEmpty) (h_option : ∀ (α) [Fintype α], P α → P (Option α)) (α : Type u)
[h_fintype : Fintype α] : P α := by
obtain ⟨p⟩ :=
let f_empty := fun i => by convert h_empty
let h_option : ∀ {α : Type u} [Fintype α] [DecidableEq α],
(∀ (h : Fintype α), P α) → ∀ (h : Fintype (Option α)), P (Option α) := by
rintro α hα - Pα hα'
convert h_option α (Pα _)
@truncRecEmptyOption (fun α => ∀ h, @P α h) (@fun α β e hα hβ => @of_equiv α β hβ e (hα _))
f_empty h_option α _ (Classical.decEq α)
exact p _
-- ·
end Fintype
/-- An induction principle for finite types, analogous to `Nat.rec`. It effectively says
that every `Fintype` is either `Empty` or `Option α`, up to an `Equiv`. -/
theorem Finite.induction_empty_option {P : Type u → Prop} (of_equiv : ∀ {α β}, α ≃ β → P α → P β)
(h_empty : P PEmpty) (h_option : ∀ {α} [Fintype α], P α → P (Option α)) (α : Type u)
[Finite α] : P α := by
cases nonempty_fintype α
refine Fintype.induction_empty_option ?_ ?_ ?_ α
exacts [fun α β _ => of_equiv, h_empty, @h_option] |
.lake/packages/mathlib/Mathlib/Data/Fintype/List.lean | import Mathlib.Data.Finset.Powerset
import Mathlib.Data.Fintype.Defs
import Mathlib.Data.List.Permutation
/-!
# Fintype instance for nodup lists
The subtype of `{l : List α // l.Nodup}` over a `[Fintype α]`
admits a `Fintype` instance.
## Implementation details
To construct the `Fintype` instance, a function lifting a `Multiset α`
to the `Multiset (List α)` is provided.
This function is applied to the `Finset.powerset` of `Finset.univ`.
-/
variable {α : Type*}
open List
namespace Multiset
/-- Given a `m : Multiset α`, we form the `Multiset` of `l : List α` with the property `⟦l⟧ = m`. -/
def lists : Multiset α → Multiset (List α) := fun s =>
Quotient.liftOn s (fun l => l.permutations) fun l l' (h : l ~ l') => by
simp only
refine coe_eq_coe.mpr ?_
exact Perm.permutations h
@[simp]
theorem lists_coe (l : List α) : lists (l : Multiset α) = l.permutations :=
rfl
@[simp]
theorem lists_nodup_finset (l : Finset α) : (lists (l.val)).Nodup := by
have h_nodup : l.val.Nodup := l.nodup
rw [← Finset.coe_toList l, Multiset.coe_nodup] at h_nodup
rw [← Finset.coe_toList l]
exact nodup_permutations l.val.toList (h_nodup)
@[simp]
theorem mem_lists_iff (s : Multiset α) (l : List α) : l ∈ lists s ↔ s = ⟦l⟧ := by
induction s using Quotient.inductionOn
simpa using perm_comm
end Multiset
instance fintypeNodupList [Fintype α] : Fintype { l : List α // l.Nodup } := by
refine Fintype.ofFinset ?_ ?_
· let univSubsets := ((Finset.univ : Finset α).powerset.1 : (Multiset (Finset α)))
let allPerms := Multiset.bind univSubsets (fun s => (Multiset.lists s.1))
refine ⟨allPerms, Multiset.nodup_bind.mpr ?_⟩
simp only [Multiset.lists_nodup_finset, implies_true, true_and]
unfold Multiset.Pairwise
use ((Finset.univ : Finset α).powerset.toList : (List (Finset α)))
constructor
· simp only [Finset.coe_toList]
rfl
· convert Finset.nodup_toList (Finset.univ.powerset : Finset (Finset α))
ext l
unfold Nodup
refine Pairwise.iff ?_
intro m n
simp only [_root_.Disjoint]
rw [← m.coe_toList, ← n.coe_toList, Multiset.lists_coe, Multiset.lists_coe]
have := Multiset.coe_disjoint m.toList.permutations n.toList.permutations
rw [_root_.Disjoint] at this
rw [this]
simp only [ne_eq]
rw [List.disjoint_iff_ne]
constructor
· intro h
by_contra hc
rw [hc] at h
contrapose! h
use n.toList
simp
· intro h
simp only [mem_permutations]
intro a ha b hb
by_contra hab
absurd h
rw [hab] at ha
exact Finset.perm_toList.mp <| Perm.trans ha.symm hb
· intro l
simp only [Finset.mem_mk, Multiset.mem_bind, Finset.mem_val, Finset.mem_powerset,
Finset.subset_univ, Multiset.mem_lists_iff, Multiset.quot_mk_to_coe, true_and]
constructor
· intro h
rcases h with ⟨f, hf⟩
convert f.nodup
rw [hf]
rfl
· intro h
exact CanLift.prf _ h |
.lake/packages/mathlib/Mathlib/Data/Fintype/Sigma.lean | import Mathlib.Data.Finset.Sigma
import Mathlib.Data.Fintype.OfMap
/-!
# fintype instances for sigma types
-/
open Function
open Nat
universe u v
variable {ι α : Type*} {κ : ι → Type*} [Π i, Fintype (κ i)]
open Finset
lemma Set.biUnion_finsetSigma_univ (s : Finset ι) (f : Sigma κ → Set α) :
⋃ ij ∈ s.sigma fun _ ↦ Finset.univ, f ij = ⋃ i ∈ s, ⋃ j, f ⟨i, j⟩ := by aesop
lemma Set.biUnion_finsetSigma_univ' (s : Finset ι) (f : Π i, κ i → Set α) :
⋃ i ∈ s, ⋃ j, f i j = ⋃ ij ∈ s.sigma fun _ ↦ Finset.univ, f ij.1 ij.2 := by aesop
lemma Set.biInter_finsetSigma_univ (s : Finset ι) (f : Sigma κ → Set α) :
⋂ ij ∈ s.sigma fun _ ↦ Finset.univ, f ij = ⋂ i ∈ s, ⋂ j, f ⟨i, j⟩ := by aesop
attribute [local simp] Sigma.forall in
lemma Set.biInter_finsetSigma_univ' (s : Finset ι) (f : Π i, κ i → Set α) :
⋂ i ∈ s, ⋂ j, f i j = ⋂ ij ∈ s.sigma fun _ ↦ Finset.univ, f ij.1 ij.2 := by aesop
variable [Fintype ι]
instance Sigma.instFintype : Fintype (Σ i, κ i) := ⟨univ.sigma fun _ ↦ univ, by simp⟩
instance PSigma.instFintype : Fintype (Σ' i, κ i) := .ofEquiv _ (Equiv.psigmaEquivSigma _).symm
@[simp] lemma Finset.univ_sigma_univ : univ.sigma (fun _ ↦ univ) = (univ : Finset (Σ i, κ i)) := rfl |
.lake/packages/mathlib/Mathlib/Data/Fintype/OfMap.lean | import Mathlib.Data.Fintype.Defs
import Mathlib.Data.Finset.Image
/-!
# Constructors for `Fintype`
This file contains basic constructors for `Fintype` instances,
given maps from/to finite types.
## Main results
* `Fintype.ofBijective`, `Fintype.ofInjective`, `Fintype.ofSurjective`:
a type is finite if there is a bi/in/surjection from/to a finite type.
-/
assert_not_exists Monoid
open Function
open Nat
universe u v
variable {α β γ : Type*}
open Finset
namespace Fintype
/-- Construct a proof of `Fintype α` from a universal multiset -/
def ofMultiset [DecidableEq α] (s : Multiset α) (H : ∀ x : α, x ∈ s) : Fintype α :=
⟨s.toFinset, by simpa using H⟩
/-- Construct a proof of `Fintype α` from a universal list -/
def ofList [DecidableEq α] (l : List α) (H : ∀ x : α, x ∈ l) : Fintype α :=
⟨l.toFinset, by simpa using H⟩
/-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/
def ofBijective [Fintype α] (f : α → β) (H : Function.Bijective f) : Fintype β :=
⟨univ.map ⟨f, H.1⟩, fun b =>
let ⟨_, e⟩ := H.2 b
e ▸ mem_map_of_mem _ (mem_univ _)⟩
/-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/
def ofSurjective [DecidableEq β] [Fintype α] (f : α → β) (H : Function.Surjective f) : Fintype β :=
⟨univ.image f, fun b =>
let ⟨_, e⟩ := H b
e ▸ mem_image_of_mem _ (mem_univ _)⟩
/-- Given an injective function to a fintype, the domain is also a
fintype. This is noncomputable because injectivity alone cannot be
used to construct preimages. -/
noncomputable def ofInjective [Fintype β] (f : α → β) (H : Function.Injective f) : Fintype α :=
letI := Classical.dec
if hα : Nonempty α then
letI := Classical.inhabited_of_nonempty hα
ofSurjective (invFun f) (invFun_surjective H)
else ⟨∅, fun x => (hα ⟨x⟩).elim⟩
/-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/
def ofEquiv (α : Type*) [Fintype α] (f : α ≃ β) : Fintype β :=
ofBijective _ f.bijective
/-- Any subsingleton type with a witness is a fintype (with one term). -/
def ofSubsingleton (a : α) [Subsingleton α] : Fintype α :=
⟨{a}, fun _ => Finset.mem_singleton.2 (Subsingleton.elim _ _)⟩
-- In principle, this could be a `simp` theorem but it applies to any occurrence of `univ` and
-- required unification of the (possibly very complex) `Fintype` instances.
theorem univ_ofSubsingleton (a : α) [Subsingleton α] : @univ _ (ofSubsingleton a) = {a} :=
rfl
/-- An empty type is a fintype. Not registered as an instance, to make sure that there aren't two
conflicting `Fintype ι` instances around when casing over whether a fintype `ι` is empty or not. -/
def ofIsEmpty [IsEmpty α] : Fintype α :=
⟨∅, isEmptyElim⟩
/-- Note: this lemma is specifically about `Fintype.ofIsEmpty`. For a statement about
arbitrary `Fintype` instances, use `Finset.univ_eq_empty`. -/
theorem univ_ofIsEmpty [IsEmpty α] : @univ α Fintype.ofIsEmpty = ∅ :=
rfl
instance : Fintype Empty := Fintype.ofIsEmpty
instance : Fintype PEmpty := Fintype.ofIsEmpty
end Fintype |
.lake/packages/mathlib/Mathlib/Data/Fintype/Prod.lean | import Mathlib.Data.Finset.Prod
import Mathlib.Data.Fintype.EquivFin
/-!
# fintype instance for the product of two fintypes.
-/
open Function
universe u v
variable {α β γ : Type*}
open Finset
namespace Set
variable {s t : Set α}
theorem toFinset_prod (s : Set α) (t : Set β) [Fintype s] [Fintype t] [Fintype (s ×ˢ t)] :
(s ×ˢ t).toFinset = s.toFinset ×ˢ t.toFinset := by
ext
simp
theorem toFinset_off_diag {s : Set α} [DecidableEq α] [Fintype s] [Fintype s.offDiag] :
s.offDiag.toFinset = s.toFinset.offDiag :=
Finset.ext <| by simp
end Set
instance instFintypeProd (α β : Type*) [Fintype α] [Fintype β] : Fintype (α × β) :=
⟨univ ×ˢ univ, fun ⟨a, b⟩ => by simp⟩
namespace Finset
variable [Fintype α] [Fintype β] {s : Finset α} {t : Finset β}
@[simp] lemma univ_product_univ : univ ×ˢ univ = (univ : Finset (α × β)) := rfl
@[simp] lemma product_eq_univ [Nonempty α] [Nonempty β] : s ×ˢ t = univ ↔ s = univ ∧ t = univ := by
simp [eq_univ_iff_forall, forall_and]
end Finset
@[simp]
theorem Fintype.card_prod (α β : Type*) [Fintype α] [Fintype β] :
Fintype.card (α × β) = Fintype.card α * Fintype.card β :=
card_product _ _
section
attribute [local instance] Fintype.ofFinite in
@[simp]
theorem infinite_prod : Infinite (α × β) ↔ Infinite α ∧ Nonempty β ∨ Nonempty α ∧ Infinite β := by
refine
⟨fun H => ?_, fun H =>
H.elim (and_imp.2 <| @Prod.infinite_of_left α β) (and_imp.2 <| @Prod.infinite_of_right α β)⟩
rw [and_comm]
rcases Infinite.nonempty (α × β) with ⟨a, b⟩
contrapose! H; haveI := H.1 ⟨b⟩; haveI := H.2 ⟨a⟩
infer_instance
instance Pi.infinite_of_left {ι : Sort*} {π : ι → Type*} [∀ i, Nontrivial <| π i] [Infinite ι] :
Infinite (∀ i : ι, π i) := by
classical
choose m n hm using fun i => exists_pair_ne (π i)
refine Infinite.of_injective (fun i => update m i (n i)) fun x y h => of_not_not fun hne => ?_
simp_rw [update_eq_iff, update_of_ne hne] at h
exact (hm x h.1.symm).elim
/-- If at least one `π i` is infinite and the rest nonempty, the pi type of all `π` is infinite. -/
theorem Pi.infinite_of_exists_right {ι : Sort*} {π : ι → Sort*} (i : ι) [Infinite <| π i]
[∀ i, Nonempty <| π i] : Infinite (∀ i : ι, π i) := by
classical
let ⟨m⟩ := @Pi.instNonempty ι π _
exact Infinite.of_injective _ (update_injective m i)
/-- See `Pi.infinite_of_exists_right` for the case that only one `π i` is infinite. -/
instance Pi.infinite_of_right {ι : Sort*} {π : ι → Type*} [∀ i, Infinite <| π i] [Nonempty ι] :
Infinite (∀ i : ι, π i) :=
Pi.infinite_of_exists_right (Classical.arbitrary ι)
/-- Non-dependent version of `Pi.infinite_of_left`. -/
instance Function.infinite_of_left {ι : Sort*} {π : Type*} [Nontrivial π] [Infinite ι] :
Infinite (ι → π) :=
Pi.infinite_of_left
/-- Non-dependent version of `Pi.infinite_of_exists_right` and `Pi.infinite_of_right`. -/
instance Function.infinite_of_right {ι : Sort*} {π : Type*} [Infinite π] [Nonempty ι] :
Infinite (ι → π) :=
Pi.infinite_of_right
end |
.lake/packages/mathlib/Mathlib/Data/Fintype/EquivFin.lean | import Mathlib.Data.Fintype.Card
import Mathlib.Data.List.NodupEquivFin
/-!
# Equivalences between `Fintype`, `Fin` and `Finite`
This file defines the bijection between a `Fintype α` and `Fin (Fintype.card α)`, and uses this to
relate `Fintype` with `Finite`. From that we can derive properties of `Finite` and `Infinite`,
and show some instances of `Infinite`.
## Main declarations
* `Fintype.truncEquivFin`: A fintype `α` is computably equivalent to `Fin (card α)`. The
`Trunc`-free, noncomputable version is `Fintype.equivFin`.
* `Fintype.truncEquivOfCardEq` `Fintype.equivOfCardEq`: Two fintypes of same cardinality are
equivalent. See above.
* `Fin.equiv_iff_eq`: `Fin m ≃ Fin n` iff `m = n`.
* `Infinite.natEmbedding`: An embedding of `ℕ` into an infinite type.
Types which have an injection from/a surjection to an `Infinite` type are themselves `Infinite`.
See `Infinite.of_injective` and `Infinite.of_surjective`.
## Instances
We provide `Infinite` instances for
* specific types: `ℕ`, `ℤ`, `String`
* type constructors: `Multiset α`, `List α`
-/
assert_not_exists Monoid
open Function
universe u v
variable {α β γ : Type*}
open Finset
namespace Fintype
/-- There is (computably) an equivalence between `α` and `Fin (card α)`.
Since it is not unique and depends on which permutation
of the universe list is used, the equivalence is wrapped in `Trunc` to
preserve computability.
See `Fintype.equivFin` for the noncomputable version,
and `Fintype.truncEquivFinOfCardEq` and `Fintype.equivFinOfCardEq`
for an equiv `α ≃ Fin n` given `Fintype.card α = n`.
See `Fintype.truncFinBijection` for a version without `[DecidableEq α]`.
-/
def truncEquivFin (α) [DecidableEq α] [Fintype α] : Trunc (α ≃ Fin (card α)) := by
unfold card Finset.card
exact
Quot.recOnSubsingleton
(motive := fun s : Multiset α =>
(∀ x : α, x ∈ s) → s.Nodup → Trunc (α ≃ Fin (Multiset.card s)))
univ.val
(fun l (h : ∀ x : α, x ∈ l) (nd : l.Nodup) => Trunc.mk (nd.getEquivOfForallMemList _ h).symm)
mem_univ_val univ.2
/-- There is (noncomputably) an equivalence between `α` and `Fin (card α)`.
See `Fintype.truncEquivFin` for the computable version,
and `Fintype.truncEquivFinOfCardEq` and `Fintype.equivFinOfCardEq`
for an equiv `α ≃ Fin n` given `Fintype.card α = n`.
-/
noncomputable def equivFin (α) [Fintype α] : α ≃ Fin (card α) :=
letI := Classical.decEq α
(truncEquivFin α).out
/-- There is (computably) a bijection between `Fin (card α)` and `α`.
Since it is not unique and depends on which permutation
of the universe list is used, the bijection is wrapped in `Trunc` to
preserve computability.
See `Fintype.truncEquivFin` for a version that gives an equivalence
given `[DecidableEq α]`.
-/
def truncFinBijection (α) [Fintype α] : Trunc { f : Fin (card α) → α // Bijective f } := by
unfold card Finset.card
refine
Quot.recOnSubsingleton
(motive := fun s : Multiset α =>
(∀ x : α, x ∈ s) → s.Nodup → Trunc {f : Fin (Multiset.card s) → α // Bijective f})
univ.val
(fun l (h : ∀ x : α, x ∈ l) (nd : l.Nodup) => Trunc.mk (nd.getBijectionOfForallMemList _ h))
mem_univ_val univ.2
end Fintype
namespace Fintype
section
variable [Fintype α] [Fintype β]
/-- If the cardinality of `α` is `n`, there is computably a bijection between `α` and `Fin n`.
See `Fintype.equivFinOfCardEq` for the noncomputable definition,
and `Fintype.truncEquivFin` and `Fintype.equivFin` for the bijection `α ≃ Fin (card α)`.
-/
def truncEquivFinOfCardEq [DecidableEq α] {n : ℕ} (h : Fintype.card α = n) : Trunc (α ≃ Fin n) :=
(truncEquivFin α).map fun e => e.trans (finCongr h)
/-- If the cardinality of `α` is `n`, there is noncomputably a bijection between `α` and `Fin n`.
See `Fintype.truncEquivFinOfCardEq` for the computable definition,
and `Fintype.truncEquivFin` and `Fintype.equivFin` for the bijection `α ≃ Fin (card α)`.
-/
noncomputable def equivFinOfCardEq {n : ℕ} (h : Fintype.card α = n) : α ≃ Fin n :=
letI := Classical.decEq α
(truncEquivFinOfCardEq h).out
/-- Two `Fintype`s with the same cardinality are (computably) in bijection.
See `Fintype.equivOfCardEq` for the noncomputable version,
and `Fintype.truncEquivFinOfCardEq` and `Fintype.equivFinOfCardEq` for
the specialization to `Fin`.
-/
def truncEquivOfCardEq [DecidableEq α] [DecidableEq β] (h : card α = card β) : Trunc (α ≃ β) :=
(truncEquivFinOfCardEq h).bind fun e => (truncEquivFin β).map fun e' => e.trans e'.symm
/-- Two `Fintype`s with the same cardinality are (noncomputably) in bijection.
See `Fintype.truncEquivOfCardEq` for the computable version,
and `Fintype.truncEquivFinOfCardEq` and `Fintype.equivFinOfCardEq` for
the specialization to `Fin`.
-/
noncomputable def equivOfCardEq (h : card α = card β) : α ≃ β := by
letI := Classical.decEq α
letI := Classical.decEq β
exact (truncEquivOfCardEq h).out
end
theorem card_eq {α β} [_F : Fintype α] [_G : Fintype β] : card α = card β ↔ Nonempty (α ≃ β) :=
⟨fun h =>
haveI := Classical.propDecidable
(truncEquivOfCardEq h).nonempty,
fun ⟨f⟩ => card_congr f⟩
end Fintype
/-!
### Relation to `Finite`
In this section we prove that `α : Type*` is `Finite` if and only if `Fintype α` is nonempty.
-/
protected theorem Fintype.finite {α : Type*} (_inst : Fintype α) : Finite α :=
⟨Fintype.equivFin α⟩
/-- For efficiency reasons, we want `Finite` instances to have higher
priority than ones coming from `Fintype` instances. -/
instance (priority := 900) Finite.of_fintype (α : Type*) [Fintype α] : Finite α :=
Fintype.finite ‹_›
theorem finite_iff_nonempty_fintype (α : Type*) : Finite α ↔ Nonempty (Fintype α) :=
⟨fun _ => nonempty_fintype α, fun ⟨_⟩ => inferInstance⟩
/-- Noncomputably get a `Fintype` instance from a `Finite` instance. This is not an
instance because we want `Fintype` instances to be useful for computations. -/
noncomputable def Fintype.ofFinite (α : Type*) [Finite α] : Fintype α :=
(nonempty_fintype α).some
theorem Finite.of_injective {α β : Sort*} [Finite β] (f : α → β) (H : Injective f) : Finite α := by
rcases Finite.exists_equiv_fin β with ⟨n, ⟨e⟩⟩
classical exact .of_equiv (Set.range (e ∘ f)) (Equiv.ofInjective _ (e.injective.comp H)).symm
-- see Note [lower instance priority]
instance (priority := 100) Finite.of_subsingleton {α : Sort*} [Subsingleton α] : Finite α :=
Finite.of_injective (Function.const α ()) <| Function.injective_of_subsingleton _
-- Higher priority for `Prop`s
instance instFiniteProp (p : Prop) : Finite p :=
Finite.of_subsingleton
/-- This instance also provides `[Finite s]` for `s : Set α`. -/
instance Subtype.finite {α : Sort*} [Finite α] {p : α → Prop} : Finite { x // p x } :=
Finite.of_injective Subtype.val Subtype.coe_injective
theorem Finite.of_surjective {α β : Sort*} [Finite α] (f : α → β) (H : Surjective f) : Finite β :=
Finite.of_injective _ <| injective_surjInv H
instance Quot.finite {α : Sort*} [Finite α] (r : α → α → Prop) : Finite (Quot r) :=
Finite.of_surjective _ Quot.mk_surjective
instance Quotient.finite {α : Sort*} [Finite α] (s : Setoid α) : Finite (Quotient s) :=
Quot.finite _
namespace Fintype
variable [Fintype α] [Fintype β]
theorem card_eq_one_iff : card α = 1 ↔ ∃ x : α, ∀ y, y = x := by
rw [← card_unit, card_eq]
exact
⟨fun ⟨a⟩ => ⟨a.symm (), fun y => a.injective (Subsingleton.elim _ _)⟩,
fun ⟨x, hx⟩ =>
⟨⟨fun _ => (), fun _ => x, fun _ => (hx _).trans (hx _).symm, fun _ =>
Subsingleton.elim _ _⟩⟩⟩
theorem card_eq_one_iff_nonempty_unique : card α = 1 ↔ Nonempty (Unique α) :=
⟨fun h =>
let ⟨d, h⟩ := Fintype.card_eq_one_iff.mp h
⟨{ default := d
uniq := h }⟩,
fun ⟨_h⟩ => Fintype.card_unique⟩
theorem card_le_one_iff : card α ≤ 1 ↔ ∀ a b : α, a = b :=
let n := card α
have hn : n = card α := rfl
match n, hn with
| 0, ha =>
⟨fun _h => fun a => (card_eq_zero_iff.1 ha.symm).elim a, fun _ => ha ▸ Nat.le_succ _⟩
| 1, ha =>
⟨fun _h => fun a b => by
let ⟨x, hx⟩ := card_eq_one_iff.1 ha.symm
rw [hx a, hx b], fun _ => ha ▸ le_rfl⟩
| n + 2, ha =>
⟨fun h => False.elim <| by rw [← ha] at h; cases h with | step h => cases h; , fun h =>
card_unit ▸ card_le_of_injective (fun _ => ()) fun _ _ _ => h _ _⟩
theorem card_le_one_iff_subsingleton : card α ≤ 1 ↔ Subsingleton α :=
card_le_one_iff.trans subsingleton_iff.symm
theorem one_lt_card_iff_nontrivial : 1 < card α ↔ Nontrivial α := by
rw [← not_iff_not, not_lt, not_nontrivial_iff_subsingleton, card_le_one_iff_subsingleton]
theorem exists_ne_of_one_lt_card (h : 1 < card α) (a : α) : ∃ b : α, b ≠ a :=
haveI : Nontrivial α := one_lt_card_iff_nontrivial.1 h
exists_ne a
theorem exists_pair_of_one_lt_card (h : 1 < card α) : ∃ a b : α, a ≠ b :=
haveI : Nontrivial α := one_lt_card_iff_nontrivial.1 h
exists_pair_ne α
theorem card_eq_one_of_forall_eq {i : α} (h : ∀ j, j = i) : card α = 1 :=
Fintype.card_eq_one_iff.2 ⟨i, h⟩
theorem one_lt_card [h : Nontrivial α] : 1 < Fintype.card α :=
Fintype.one_lt_card_iff_nontrivial.mpr h
theorem one_lt_card_iff : 1 < card α ↔ ∃ a b : α, a ≠ b :=
one_lt_card_iff_nontrivial.trans nontrivial_iff
end Fintype
namespace Fintype
variable [Fintype α] [Fintype β]
theorem bijective_iff_injective_and_card (f : α → β) :
Bijective f ↔ Injective f ∧ card α = card β :=
⟨fun h => ⟨h.1, card_of_bijective h⟩, fun h =>
⟨h.1, h.1.surjective_of_fintype <| equivOfCardEq h.2⟩⟩
theorem bijective_iff_surjective_and_card (f : α → β) :
Bijective f ↔ Surjective f ∧ card α = card β :=
⟨fun h => ⟨h.2, card_of_bijective h⟩, fun h =>
⟨h.1.injective_of_fintype <| equivOfCardEq h.2, h.1⟩⟩
theorem _root_.Function.LeftInverse.rightInverse_of_card_le {f : α → β} {g : β → α}
(hfg : LeftInverse f g) (hcard : card α ≤ card β) : RightInverse f g :=
have hsurj : Surjective f := surjective_iff_hasRightInverse.2 ⟨g, hfg⟩
rightInverse_of_injective_of_leftInverse
((bijective_iff_surjective_and_card _).2
⟨hsurj, le_antisymm hcard (card_le_of_surjective f hsurj)⟩).1
hfg
theorem _root_.Function.RightInverse.leftInverse_of_card_le {f : α → β} {g : β → α}
(hfg : RightInverse f g) (hcard : card β ≤ card α) : LeftInverse f g :=
Function.LeftInverse.rightInverse_of_card_le hfg hcard
end Fintype
namespace Equiv
variable [Fintype α] [Fintype β]
open Fintype
/-- Construct an equivalence from functions that are inverse to each other. -/
@[simps]
def ofLeftInverseOfCardLE (hβα : card β ≤ card α) (f : α → β) (g : β → α) (h : LeftInverse g f) :
α ≃ β where
toFun := f
invFun := g
left_inv := h
right_inv := h.rightInverse_of_card_le hβα
/-- Construct an equivalence from functions that are inverse to each other. -/
@[simps]
def ofRightInverseOfCardLE (hαβ : card α ≤ card β) (f : α → β) (g : β → α) (h : RightInverse g f) :
α ≃ β where
toFun := f
invFun := g
left_inv := h.leftInverse_of_card_le hαβ
right_inv := h
end Equiv
/-- Noncomputable equivalence between a finset `s` coerced to a type and `Fin #s`. -/
noncomputable def Finset.equivFin (s : Finset α) : s ≃ Fin #s :=
Fintype.equivFinOfCardEq (Fintype.card_coe _)
/-- Noncomputable equivalence between a finset `s` as a fintype and `Fin n`, when there is a
proof that `#s = n`. -/
noncomputable def Finset.equivFinOfCardEq {s : Finset α} {n : ℕ} (h : #s = n) : s ≃ Fin n :=
Fintype.equivFinOfCardEq ((Fintype.card_coe _).trans h)
theorem Finset.card_eq_of_equiv_fin {s : Finset α} {n : ℕ} (i : s ≃ Fin n) : #s = n :=
Fin.equiv_iff_eq.1 ⟨s.equivFin.symm.trans i⟩
theorem Finset.card_eq_of_equiv_fintype {s : Finset α} [Fintype β] (i : s ≃ β) :
#s = Fintype.card β := card_eq_of_equiv_fin <| i.trans <| Fintype.equivFin β
/-- Noncomputable equivalence between two finsets `s` and `t` as fintypes when there is a proof
that `#s = #t`. -/
noncomputable def Finset.equivOfCardEq {s : Finset α} {t : Finset β} (h : #s = #t) :
s ≃ t := Fintype.equivOfCardEq ((Fintype.card_coe _).trans (h.trans (Fintype.card_coe _).symm))
theorem Finset.card_eq_of_equiv {s : Finset α} {t : Finset β} (i : s ≃ t) : #s = #t :=
(card_eq_of_equiv_fintype i).trans (Fintype.card_coe _)
namespace Function.Embedding
/-- An embedding from a `Fintype` to itself can be promoted to an equivalence. -/
noncomputable def equivOfFiniteSelfEmbedding [Finite α] (e : α ↪ α) : α ≃ α :=
Equiv.ofBijective e e.2.bijective_of_finite
@[simp]
theorem toEmbedding_equivOfFiniteSelfEmbedding [Finite α] (e : α ↪ α) :
e.equivOfFiniteSelfEmbedding.toEmbedding = e := by
ext
rfl
/-- On a finite type, equivalence between the self-embeddings and the bijections. -/
@[simps] noncomputable def _root_.Equiv.embeddingEquivOfFinite (α : Type*) [Finite α] :
(α ↪ α) ≃ (α ≃ α) where
toFun e := e.equivOfFiniteSelfEmbedding
invFun e := e.toEmbedding
/-- A constructive embedding of a fintype `α` in another fintype `β` when `card α ≤ card β`. -/
def truncOfCardLE [Fintype α] [Fintype β] [DecidableEq α] [DecidableEq β]
(h : Fintype.card α ≤ Fintype.card β) : Trunc (α ↪ β) :=
(Fintype.truncEquivFin α).bind fun ea =>
(Fintype.truncEquivFin β).map fun eb =>
ea.toEmbedding.trans ((Fin.castLEEmb h).trans eb.symm.toEmbedding)
theorem nonempty_of_card_le [Fintype α] [Fintype β] (h : Fintype.card α ≤ Fintype.card β) :
Nonempty (α ↪ β) := by classical exact (truncOfCardLE h).nonempty
theorem nonempty_iff_card_le [Fintype α] [Fintype β] :
Nonempty (α ↪ β) ↔ Fintype.card α ≤ Fintype.card β :=
⟨fun ⟨e⟩ => Fintype.card_le_of_embedding e, nonempty_of_card_le⟩
theorem exists_of_card_le_finset [Fintype α] {s : Finset β} (h : Fintype.card α ≤ #s) :
∃ f : α ↪ β, Set.range f ⊆ s := by
rw [← Fintype.card_coe] at h
rcases nonempty_of_card_le h with ⟨f⟩
exact ⟨f.trans (Embedding.subtype _), by simp [Set.range_subset_iff]⟩
end Function.Embedding
@[simp]
theorem Finset.univ_map_embedding {α : Type*} [Fintype α] (e : α ↪ α) : univ.map e = univ := by
rw [← e.toEmbedding_equivOfFiniteSelfEmbedding, univ_map_equiv_to_embedding]
namespace Fintype
theorem card_lt_of_surjective_not_injective [Fintype α] [Fintype β] (f : α → β)
(h : Function.Surjective f) (h' : ¬Function.Injective f) : card β < card α :=
card_lt_of_injective_not_surjective _ (Function.injective_surjInv h) fun hg =>
have w : Function.Bijective (Function.surjInv h) := ⟨Function.injective_surjInv h, hg⟩
h' <| h.injective_of_fintype (Equiv.ofBijective _ w).symm
end Fintype
protected theorem Fintype.false [Infinite α] (_h : Fintype α) : False :=
not_finite α
@[simp]
theorem isEmpty_fintype {α : Type*} : IsEmpty (Fintype α) ↔ Infinite α :=
⟨fun ⟨h⟩ => ⟨fun h' => (@nonempty_fintype α h').elim h⟩, fun ⟨h⟩ => ⟨fun h' => h h'.finite⟩⟩
/-- A non-infinite type is a fintype. -/
noncomputable def fintypeOfNotInfinite {α : Type*} (h : ¬Infinite α) : Fintype α :=
@Fintype.ofFinite _ (not_infinite_iff_finite.mp h)
section
open scoped Classical in
/-- Any type is (classically) either a `Fintype`, or `Infinite`.
One can obtain the relevant typeclasses via `cases fintypeOrInfinite α`.
-/
noncomputable def fintypeOrInfinite (α : Type*) : Fintype α ⊕' Infinite α :=
if h : Infinite α then PSum.inr h else PSum.inl (fintypeOfNotInfinite h)
end
namespace Infinite
theorem of_not_fintype (h : Fintype α → False) : Infinite α :=
isEmpty_fintype.mp ⟨h⟩
/-- If `s : Set α` is a proper subset of `α` and `f : α → s` is injective, then `α` is infinite. -/
theorem of_injective_to_set {s : Set α} (hs : s ≠ Set.univ) {f : α → s} (hf : Injective f) :
Infinite α :=
of_not_fintype fun h => by
classical
refine lt_irrefl (Fintype.card α) ?_
calc
Fintype.card α ≤ Fintype.card s := Fintype.card_le_of_injective f hf
_ = #s.toFinset := s.toFinset_card.symm
_ < Fintype.card α :=
Finset.card_lt_card <| by rwa [Set.toFinset_ssubset_univ, Set.ssubset_univ_iff]
/-- If `s : Set α` is a proper subset of `α` and `f : s → α` is surjective, then `α` is infinite. -/
theorem of_surjective_from_set {s : Set α} (hs : s ≠ Set.univ) {f : s → α} (hf : Surjective f) :
Infinite α :=
of_injective_to_set hs (injective_surjInv hf)
theorem exists_notMem_finset [Infinite α] (s : Finset α) : ∃ x, x ∉ s :=
not_forall.1 fun h => Fintype.false ⟨s, h⟩
@[deprecated (since := "2025-05-23")] alias exists_not_mem_finset := exists_notMem_finset
-- see Note [lower instance priority]
instance (priority := 100) (α : Type*) [Infinite α] : Nontrivial α :=
⟨let ⟨x, _hx⟩ := exists_notMem_finset (∅ : Finset α)
let ⟨y, hy⟩ := exists_notMem_finset ({x} : Finset α)
⟨y, x, by simpa only [mem_singleton] using hy⟩⟩
protected theorem nonempty (α : Type*) [Infinite α] : Nonempty α := by infer_instance
theorem of_injective {α β} [Infinite β] (f : β → α) (hf : Injective f) : Infinite α :=
⟨fun _I => (Finite.of_injective f hf).false⟩
theorem of_surjective {α β} [Infinite β] (f : α → β) (hf : Surjective f) : Infinite α :=
⟨fun _I => (Finite.of_surjective f hf).false⟩
instance {β : α → Type*} [Infinite α] [∀ a, Nonempty (β a)] : Infinite ((a : α) × β a) :=
Infinite.of_surjective Sigma.fst Sigma.fst_surjective
theorem sigma_of_right {β : α → Type*} {a : α} [Infinite (β a)] :
Infinite ((a : α) × β a) :=
Infinite.of_injective (f := fun x ↦ ⟨a,x⟩) fun _ _ ↦ by simp
instance {β : α → Type*} [Nonempty α] [∀ a, Infinite (β a)] : Infinite ((a : α) × β a) :=
Infinite.sigma_of_right (a := Classical.arbitrary α)
end Infinite
instance : Infinite ℕ :=
Infinite.of_not_fintype <| by
intro h
exact (Finset.range _).card_le_univ.not_gt ((Nat.lt_succ_self _).trans_eq (card_range _).symm)
instance Int.infinite : Infinite ℤ :=
Infinite.of_injective Int.ofNat fun _ _ => Int.ofNat.inj
instance [Nonempty α] : Infinite (Multiset α) :=
let ⟨x⟩ := ‹Nonempty α›
Infinite.of_injective (fun n => Multiset.replicate n x) (Multiset.replicate_left_injective _)
instance [Nonempty α] : Infinite (List α) :=
Infinite.of_surjective ((↑) : List α → Multiset α) Quot.mk_surjective
instance String.infinite : Infinite String :=
Infinite.of_injective List.asString (fun _ _ => List.asString_injective)
instance Infinite.set [Infinite α] : Infinite (Set α) :=
Infinite.of_injective singleton Set.singleton_injective
instance [Infinite α] : Infinite (Finset α) :=
Infinite.of_injective singleton Finset.singleton_injective
instance [Infinite α] : Infinite (Option α) :=
Infinite.of_injective some (Option.some_injective α)
instance Sum.infinite_of_left [Infinite α] : Infinite (α ⊕ β) :=
Infinite.of_injective Sum.inl Sum.inl_injective
instance Sum.infinite_of_right [Infinite β] : Infinite (α ⊕ β) :=
Infinite.of_injective Sum.inr Sum.inr_injective
instance Prod.infinite_of_right [Nonempty α] [Infinite β] : Infinite (α × β) :=
Infinite.of_surjective Prod.snd Prod.snd_surjective
instance Prod.infinite_of_left [Infinite α] [Nonempty β] : Infinite (α × β) :=
Infinite.of_surjective Prod.fst Prod.fst_surjective
namespace Infinite
private noncomputable def natEmbeddingAux (α : Type*) [Infinite α] : ℕ → α
| n =>
letI := Classical.decEq α
Classical.choose
(exists_notMem_finset
((Multiset.range n).pmap (fun m (_ : m < n) => natEmbeddingAux _ m) fun _ =>
Multiset.mem_range.1).toFinset)
private theorem natEmbeddingAux_injective (α : Type*) [Infinite α] :
Function.Injective (natEmbeddingAux α) := by
rintro m n h
letI := Classical.decEq α
wlog hmlen : m ≤ n generalizing m n
· exact (this h.symm <| le_of_not_ge hmlen).symm
by_contra hmn
have hmn : m < n := lt_of_le_of_ne hmlen hmn
refine (Classical.choose_spec (exists_notMem_finset
((Multiset.range n).pmap (fun m (_ : m < n) ↦ natEmbeddingAux α m)
(fun _ ↦ Multiset.mem_range.1)).toFinset)) ?_
refine Multiset.mem_toFinset.2 (Multiset.mem_pmap.2 ⟨m, Multiset.mem_range.2 hmn, ?_⟩)
rw [h, natEmbeddingAux]
/-- Embedding of `ℕ` into an infinite type. -/
noncomputable def natEmbedding (α : Type*) [Infinite α] : ℕ ↪ α :=
⟨_, natEmbeddingAux_injective α⟩
/-- See `Infinite.exists_superset_card_eq` for a version that, for an `s : Finset α`,
provides a superset `t : Finset α`, `s ⊆ t` such that `#t` is fixed. -/
theorem exists_subset_card_eq (α : Type*) [Infinite α] (n : ℕ) : ∃ s : Finset α, #s = n :=
⟨(range n).map (natEmbedding α), by rw [card_map, card_range]⟩
/-- See `Infinite.exists_subset_card_eq` for a version that provides an arbitrary
`s : Finset α` for any cardinality. -/
theorem exists_superset_card_eq [Infinite α] (s : Finset α) (n : ℕ) (hn : #s ≤ n) :
∃ t : Finset α, s ⊆ t ∧ #t = n := by
induction n generalizing s with
| zero => exact ⟨s, subset_rfl, Nat.eq_zero_of_le_zero hn⟩
| succ n IH =>
rcases hn.eq_or_lt with hn' | hn'
· exact ⟨s, subset_rfl, hn'⟩
obtain ⟨t, hs, ht⟩ := IH _ (Nat.le_of_lt_succ hn')
obtain ⟨x, hx⟩ := exists_notMem_finset t
refine ⟨Finset.cons x t hx, hs.trans (Finset.subset_cons _), ?_⟩
simp [ht]
end Infinite
/-- If every finset in a type has bounded cardinality, that type is finite. -/
noncomputable def fintypeOfFinsetCardLe {ι : Type*} (n : ℕ) (w : ∀ s : Finset ι, #s ≤ n) :
Fintype ι := by
apply fintypeOfNotInfinite
intro i
obtain ⟨s, c⟩ := Infinite.exists_subset_card_eq ι (n + 1)
specialize w s
rw [c] at w
exact Nat.not_succ_le_self n w
theorem not_injective_infinite_finite {α β} [Infinite α] [Finite β] (f : α → β) : ¬Injective f :=
fun hf => (Finite.of_injective f hf).false
instance Function.Embedding.is_empty {α β} [Infinite α] [Finite β] : IsEmpty (α ↪ β) :=
⟨fun f => not_injective_infinite_finite f f.2⟩
theorem not_surjective_finite_infinite {α β} [Finite α] [Infinite β] (f : α → β) : ¬Surjective f :=
fun hf => (Infinite.of_surjective f hf).not_finite ‹_› |
.lake/packages/mathlib/Mathlib/Data/Fintype/Perm.lean | import Mathlib.Algebra.BigOperators.Group.List.Defs
import Mathlib.Algebra.Group.End
import Mathlib.Algebra.Group.Nat.Defs
import Mathlib.Data.Fintype.EquivFin
import Mathlib.Data.Nat.Factorial.Basic
/-!
# `Fintype` instances for `Equiv` and `Perm`
Main declarations:
* `permsOfFinset s`: The finset of permutations of the finset `s`.
-/
assert_not_exists MonoidWithZero
open Function
open Nat
universe u v
variable {α β γ : Type*}
open Finset List Equiv Equiv.Perm
variable [DecidableEq α] [DecidableEq β]
/-- Given a list, produce a list of all permutations of its elements. -/
def permsOfList : List α → List (Perm α)
| [] => [1]
| a :: l => permsOfList l ++ l.flatMap fun b => (permsOfList l).map fun f => Equiv.swap a b * f
theorem length_permsOfList : ∀ l : List α, length (permsOfList l) = l.length !
| [] => rfl
| a :: l => by
simp [Nat.factorial_succ, permsOfList, length_permsOfList, succ_mul, add_comm]
theorem mem_permsOfList_of_mem {l : List α} {f : Perm α} (h : ∀ x, f x ≠ x → x ∈ l) :
f ∈ permsOfList l := by
induction l generalizing f with
| nil =>
simp only [not_mem_nil] at h
exact List.mem_singleton.2 (Equiv.ext fun x => Decidable.byContradiction <| h x)
| cons a l IH =>
by_cases hfa : f a = a
· refine mem_append_left _ (IH fun x hx => mem_of_ne_of_mem ?_ (h x hx))
rintro rfl
exact hx hfa
have hfa' : f (f a) ≠ f a := mt (fun h => f.injective h) hfa
have : ∀ x : α, (Equiv.swap a (f a) * f) x ≠ x → x ∈ l := by
intro x hx
have hxa : x ≠ a := by
rintro rfl
apply hx
simp only [mul_apply, swap_apply_right]
refine List.mem_of_ne_of_mem hxa (h x fun h => ?_)
simp only [mul_apply, swap_apply_def, mul_apply, Ne, apply_eq_iff_eq] at hx
split_ifs at hx with h_1
exacts [hxa (h.symm.trans h_1), hx h]
suffices f ∈ permsOfList l ∨ ∃ b ∈ l, ∃ g ∈ permsOfList l, Equiv.swap a b * g = f by
simpa only [permsOfList, exists_prop, List.mem_map, mem_append, List.mem_flatMap]
refine or_iff_not_imp_left.2 fun _hfl => ⟨f a, ?_, Equiv.swap a (f a) * f, IH this, ?_⟩
· exact mem_of_ne_of_mem hfa (h _ hfa')
· rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← Perm.one_def, one_mul]
theorem mem_of_mem_permsOfList :
∀ {l : List α} {f : Perm α}, f ∈ permsOfList l → {x : α} → f x ≠ x → x ∈ l
| [], f, h, heq_iff_eq => by
have : f = 1 := by simpa [permsOfList] using h
rw [this]; simp
| a :: l, f, h, x =>
(mem_append.1 h).elim (fun h hx => mem_cons_of_mem _ (mem_of_mem_permsOfList h hx))
fun h hx =>
let ⟨y, hy, hy'⟩ := List.mem_flatMap.1 h
let ⟨g, hg₁, hg₂⟩ := List.mem_map.1 hy'
if hxa : x = a then by simp [hxa]
else
if hxy : x = y then mem_cons_of_mem _ <| by rwa [hxy]
else mem_cons_of_mem a <| mem_of_mem_permsOfList hg₁ <| by
rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]
split_ifs <;> [exact Ne.symm hxy; exact Ne.symm hxa; exact hx]
theorem mem_permsOfList_iff {l : List α} {f : Perm α} :
f ∈ permsOfList l ↔ ∀ {x}, f x ≠ x → x ∈ l :=
⟨mem_of_mem_permsOfList, mem_permsOfList_of_mem⟩
theorem nodup_permsOfList : ∀ {l : List α}, l.Nodup → (permsOfList l).Nodup
| [], _ => by simp [permsOfList]
| a :: l, hl => by
have hl' : l.Nodup := hl.of_cons
have hln' : (permsOfList l).Nodup := nodup_permsOfList hl'
have hmeml : ∀ {f : Perm α}, f ∈ permsOfList l → f a = a := fun {f} hf =>
not_not.1 (mt (mem_of_mem_permsOfList hf) (nodup_cons.1 hl).1)
rw [permsOfList, List.nodup_append', List.nodup_flatMap, pairwise_iff_getElem]
refine ⟨?_, ⟨⟨?_,?_ ⟩, ?_⟩⟩
· exact hln'
· exact fun _ _ => hln'.map fun _ _ => mul_left_cancel
· intro i j hi hj hij x hx₁ hx₂
let ⟨f, hf⟩ := List.mem_map.1 hx₁
let ⟨g, hg⟩ := List.mem_map.1 hx₂
have hix : x a = l[i] := by
rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left]
have hiy : x a = l[j] := by
rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left]
have hieqj : i = j := hl'.getElem_inj_iff.1 (hix.symm.trans hiy)
exact absurd hieqj (_root_.ne_of_lt hij)
· intro f hf₁ hf₂
let ⟨x, hx, hx'⟩ := List.mem_flatMap.1 hf₂
let ⟨g, hg⟩ := List.mem_map.1 hx'
obtain rfl : g⁻¹ x = a := f.injective <| by rw [hmeml hf₁, ← hg.2]; simp
have hxa : x ≠ g⁻¹ x := fun h => (List.nodup_cons.1 hl).1 (h ▸ hx)
exact (List.nodup_cons.1 hl).1 <| mem_of_mem_permsOfList hg.1 (by simpa using hxa)
/-- Given a finset, produce the finset of all permutations of its elements. -/
def permsOfFinset (s : Finset α) : Finset (Perm α) :=
Quotient.hrecOn s.1 (fun l hl => ⟨permsOfList l, nodup_permsOfList hl⟩)
(fun a b hab =>
hfunext (congr_arg _ (Quotient.sound hab)) fun ha hb _ =>
heq_of_eq <| Finset.ext <| by simp [mem_permsOfList_iff, hab.mem_iff])
s.2
theorem mem_perms_of_finset_iff :
∀ {s : Finset α} {f : Perm α}, f ∈ permsOfFinset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by
rintro ⟨⟨l⟩, hs⟩ f; exact mem_permsOfList_iff
theorem card_perms_of_finset : ∀ s : Finset α, #(permsOfFinset s) = (#s)! := by
rintro ⟨⟨l⟩, hs⟩; exact length_permsOfList l
/-- The collection of permutations of a fintype is a fintype. -/
def fintypePerm [Fintype α] : Fintype (Perm α) :=
⟨permsOfFinset (@Finset.univ α _), by simp [mem_perms_of_finset_iff]⟩
instance Equiv.instFintype [Fintype α] [Fintype β] : Fintype (α ≃ β) :=
if h : Fintype.card β = Fintype.card α then
Trunc.recOnSubsingleton (Fintype.truncEquivFin α) fun eα =>
Trunc.recOnSubsingleton (Fintype.truncEquivFin β) fun eβ =>
@Fintype.ofEquiv _ (Perm α) fintypePerm
(equivCongr (Equiv.refl α) (eα.trans (Eq.recOn h eβ.symm)) : α ≃ α ≃ (α ≃ β))
else ⟨∅, fun x => False.elim (h (Fintype.card_eq.2 ⟨x.symm⟩))⟩
@[to_additive]
instance MulEquiv.instFintype
{α β : Type*} [Mul α] [Mul β] [DecidableEq α] [DecidableEq β] [Fintype α] [Fintype β] :
Fintype (α ≃* β) where
elems := Equiv.instFintype.elems.filterMap
(fun e => if h : ∀ a b : α, e (a * b) = e a * e b then (⟨e, h⟩ : α ≃* β) else none) (by aesop)
complete me := (Finset.mem_filterMap ..).mpr ⟨me.toEquiv, Finset.mem_univ _, by {simp; rfl}⟩
theorem Fintype.card_perm [Fintype α] : Fintype.card (Perm α) = (Fintype.card α)! :=
Subsingleton.elim (@fintypePerm α _ _) (@Equiv.instFintype α α _ _ _ _) ▸ card_perms_of_finset _
theorem Fintype.card_equiv [Fintype α] [Fintype β] (e : α ≃ β) :
Fintype.card (α ≃ β) = (Fintype.card α)! :=
Fintype.card_congr (equivCongr (Equiv.refl α) e) ▸ Fintype.card_perm |
.lake/packages/mathlib/Mathlib/Data/Fintype/Sets.lean | import Mathlib.Data.Finset.BooleanAlgebra
import Mathlib.Data.Finset.SymmDiff
import Mathlib.Data.Fintype.OfMap
/-!
# Subsets of finite types
In a `Fintype`, all `Set`s are automatically `Finset`s, and there are only finitely many of them.
## Main results
* `Set.toFinset`: convert a subset of a finite type to a `Finset`
* `Finset.fintypeCoeSort`: `((s : Finset α) : Type*)` is a finite type
* `Fintype.finsetEquivSet`: `Finset α` and `Set α` are equivalent if `α` is a `Fintype`
-/
assert_not_exists Monoid
open Function
open Nat
universe u v
variable {α β γ : Type*}
open Finset
namespace Set
variable {s t : Set α}
/-- Construct a finset enumerating a set `s`, given a `Fintype` instance. -/
def toFinset (s : Set α) [Fintype s] : Finset α :=
(@Finset.univ s _).map <| Function.Embedding.subtype _
@[congr]
theorem toFinset_congr {s t : Set α} [Fintype s] [Fintype t] (h : s = t) :
toFinset s = toFinset t := by subst h; congr!
@[simp]
theorem mem_toFinset {s : Set α} [Fintype s] {a : α} : a ∈ s.toFinset ↔ a ∈ s := by
simp [toFinset]
/-- Many `Fintype` instances for sets are defined using an extensionally equal `Finset`.
Rewriting `s.toFinset` with `Set.toFinset_ofFinset` replaces the term with such a `Finset`. -/
theorem toFinset_ofFinset {p : Set α} (s : Finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) :
@Set.toFinset _ p (Fintype.ofFinset s H) = s :=
Finset.ext fun x => by rw [@mem_toFinset _ _ (id _), H]
/-- Membership of a set with a `Fintype` instance is decidable.
Using this as an instance leads to potential loops with `Subtype.fintype` under certain decidability
assumptions, so it should only be declared a local instance. -/
def decidableMemOfFintype [DecidableEq α] (s : Set α) [Fintype s] (a) : Decidable (a ∈ s) :=
decidable_of_iff _ mem_toFinset
@[simp]
theorem coe_toFinset (s : Set α) [Fintype s] : (↑s.toFinset : Set α) = s :=
Set.ext fun _ => mem_toFinset
@[simp]
theorem toFinset_nonempty {s : Set α} [Fintype s] : s.toFinset.Nonempty ↔ s.Nonempty := by
rw [← Finset.coe_nonempty, coe_toFinset]
@[aesop safe apply (rule_sets := [finsetNonempty])]
alias ⟨_, Aesop.toFinset_nonempty_of_nonempty⟩ := toFinset_nonempty
@[simp]
theorem toFinset_inj {s t : Set α} [Fintype s] [Fintype t] : s.toFinset = t.toFinset ↔ s = t :=
⟨fun h => by rw [← s.coe_toFinset, h, t.coe_toFinset], fun h => by simp [h]⟩
@[mono]
theorem toFinset_subset_toFinset [Fintype s] [Fintype t] : s.toFinset ⊆ t.toFinset ↔ s ⊆ t := by
simp [Finset.subset_iff, Set.subset_def]
@[simp]
theorem toFinset_ssubset [Fintype s] {t : Finset α} : s.toFinset ⊂ t ↔ s ⊂ t := by
rw [← Finset.coe_ssubset, coe_toFinset]
@[simp]
theorem subset_toFinset {s : Finset α} [Fintype t] : s ⊆ t.toFinset ↔ ↑s ⊆ t := by
rw [← Finset.coe_subset, coe_toFinset]
@[simp]
theorem ssubset_toFinset {s : Finset α} [Fintype t] : s ⊂ t.toFinset ↔ ↑s ⊂ t := by
rw [← Finset.coe_ssubset, coe_toFinset]
@[mono]
theorem toFinset_ssubset_toFinset [Fintype s] [Fintype t] : s.toFinset ⊂ t.toFinset ↔ s ⊂ t := by
simp only [Finset.ssubset_def, toFinset_subset_toFinset, ssubset_def]
@[simp]
theorem toFinset_subset [Fintype s] {t : Finset α} : s.toFinset ⊆ t ↔ s ⊆ t := by
rw [← Finset.coe_subset, coe_toFinset]
@[gcongr]
alias ⟨_, toFinset_mono⟩ := toFinset_subset_toFinset
@[deprecated (since := "2025-10-25")] alias toFinset_subset_toFinset_of_subset := toFinset_mono
alias ⟨_, toFinset_strict_mono⟩ := toFinset_ssubset_toFinset
@[simp]
theorem disjoint_toFinset [Fintype s] [Fintype t] :
Disjoint s.toFinset t.toFinset ↔ Disjoint s t := by simp only [← disjoint_coe, coe_toFinset]
@[simp]
theorem toFinset_nontrivial [Fintype s] : s.toFinset.Nontrivial ↔ s.Nontrivial := by
rw [Finset.Nontrivial, coe_toFinset]
section DecidableEq
variable [DecidableEq α] (s t) [Fintype s] [Fintype t]
@[simp]
theorem toFinset_inter [Fintype (s ∩ t : Set _)] : (s ∩ t).toFinset = s.toFinset ∩ t.toFinset := by
ext
simp
@[simp]
theorem toFinset_union [Fintype (s ∪ t : Set _)] : (s ∪ t).toFinset = s.toFinset ∪ t.toFinset := by
ext
simp
@[simp]
theorem toFinset_diff [Fintype (s \ t : Set _)] : (s \ t).toFinset = s.toFinset \ t.toFinset := by
ext
simp
open scoped symmDiff in
@[simp]
theorem toFinset_symmDiff [Fintype (s ∆ t : Set _)] :
(s ∆ t).toFinset = s.toFinset ∆ t.toFinset := by
ext
simp [mem_symmDiff, Finset.mem_symmDiff]
@[simp]
theorem toFinset_compl [Fintype α] [Fintype (sᶜ : Set _)] : sᶜ.toFinset = s.toFinsetᶜ := by
ext
simp
end DecidableEq
-- TODO The `↥` circumvents an elaboration bug. See comment on `Set.toFinset_univ`.
@[simp]
theorem toFinset_empty [Fintype (∅ : Set α)] : (∅ : Set α).toFinset = ∅ := by
ext
simp
/- TODO Without the coercion arrow (`↥`) there is an elaboration bug in the following two;
it essentially infers `Fintype.{v} (Set.univ.{u} : Set α)` with `v` and `u` distinct.
Reported in https://github.com/leanprover-community/lean/issues/672 -/
@[simp]
theorem toFinset_univ [Fintype α] [Fintype (Set.univ : Set α)] :
(Set.univ : Set α).toFinset = Finset.univ := by
ext
simp
@[simp]
theorem toFinset_eq_empty [Fintype s] : s.toFinset = ∅ ↔ s = ∅ := by
let A : Fintype (∅ : Set α) := Fintype.ofIsEmpty
rw [← toFinset_empty, toFinset_inj]
@[simp]
theorem toFinset_eq_univ [Fintype α] [Fintype s] : s.toFinset = Finset.univ ↔ s = univ := by
rw [← coe_inj, coe_toFinset, coe_univ]
@[simp]
theorem toFinset_setOf [Fintype α] (p : α → Prop) [DecidablePred p] [Fintype { x | p x }] :
Set.toFinset {x | p x} = Finset.univ.filter p := by
ext
simp
theorem toFinset_ssubset_univ [Fintype α] {s : Set α} [Fintype s] :
s.toFinset ⊂ Finset.univ ↔ s ⊂ univ := by simp
@[simp]
theorem toFinset_image [DecidableEq β] (f : α → β) (s : Set α) [Fintype s] [Fintype (f '' s)] :
(f '' s).toFinset = s.toFinset.image f :=
Finset.coe_injective <| by simp
@[simp]
theorem toFinset_range [DecidableEq α] [Fintype β] (f : β → α) [Fintype (Set.range f)] :
(Set.range f).toFinset = Finset.univ.image f := by
ext
simp
@[simp]
theorem toFinset_singleton (a : α) [Fintype ({a} : Set α)] : ({a} : Set α).toFinset = {a} := by
ext
simp
@[simp]
theorem toFinset_insert [DecidableEq α] {a : α} {s : Set α} [Fintype (insert a s : Set α)]
[Fintype s] : (insert a s).toFinset = insert a s.toFinset := by
ext
simp
theorem filter_mem_univ_eq_toFinset [Fintype α] (s : Set α) [Fintype s] [DecidablePred (· ∈ s)] :
Finset.univ.filter (· ∈ s) = s.toFinset := by
ext
rw [mem_filter_univ, mem_toFinset]
end Set
@[simp]
theorem Finset.toFinset_coe (s : Finset α) [Fintype (s : Set α)] : (s : Set α).toFinset = s :=
ext fun _ => Set.mem_toFinset
section Finset
/-! ### `Fintype (s : Finset α)` -/
instance Finset.fintypeCoeSort {α : Type u} (s : Finset α) : Fintype s :=
⟨s.attach, s.mem_attach⟩
@[simp]
theorem Finset.univ_eq_attach {α : Type u} (s : Finset α) : (univ : Finset s) = s.attach :=
rfl
end Finset
theorem Fintype.coe_image_univ [Fintype α] [DecidableEq β] {f : α → β} :
↑(Finset.image f Finset.univ) = Set.range f := by
simp
instance List.Subtype.fintype [DecidableEq α] (l : List α) : Fintype { x // x ∈ l } :=
Fintype.ofList l.attach l.mem_attach
instance Multiset.Subtype.fintype [DecidableEq α] (s : Multiset α) : Fintype { x // x ∈ s } :=
Fintype.ofMultiset s.attach s.mem_attach
instance Finset.Subtype.fintype (s : Finset α) : Fintype { x // x ∈ s } :=
⟨s.attach, s.mem_attach⟩
instance FinsetCoe.fintype (s : Finset α) : Fintype (↑s : Set α) :=
Finset.Subtype.fintype s
theorem Finset.attach_eq_univ {s : Finset α} : s.attach = Finset.univ :=
rfl
instance Prop.fintype : Fintype Prop :=
⟨⟨{True, False}, by simp⟩, by simpa using em⟩
@[simp]
theorem Fintype.univ_Prop : (Finset.univ : Finset Prop) = {True, False} :=
Finset.eq_of_veq <| by simp; rfl
instance Subtype.fintype (p : α → Prop) [DecidablePred p] [Fintype α] : Fintype { x // p x } :=
Fintype.subtype (univ.filter p) (by simp)
/-- A set on a fintype, when coerced to a type, is a fintype. -/
def setFintype [Fintype α] (s : Set α) [DecidablePred (· ∈ s)] : Fintype s :=
Subtype.fintype fun x => x ∈ s
namespace Fintype
variable [Fintype α]
/-- Given `Fintype α`, `finsetEquivSet` is the equiv between `Finset α` and `Set α`. (All
sets on a finite type are finite.) -/
noncomputable def finsetEquivSet : Finset α ≃ Set α where
toFun := (↑)
invFun := by classical exact fun s => s.toFinset
left_inv s := by convert Finset.toFinset_coe s
right_inv s := by classical exact s.coe_toFinset
@[simp, norm_cast] lemma coe_finsetEquivSet : ⇑finsetEquivSet = ((↑) : Finset α → Set α) := rfl
@[simp] lemma finsetEquivSet_apply (s : Finset α) : finsetEquivSet s = s := rfl
@[simp] lemma finsetEquivSet_symm_apply (s : Set α) [Fintype s] :
finsetEquivSet.symm s = s.toFinset := by simp [finsetEquivSet]
/-- Given a fintype `α`, `finsetOrderIsoSet` is the order isomorphism between `Finset α` and `Set α`
(all sets on a finite type are finite). -/
@[simps toEquiv]
noncomputable def finsetOrderIsoSet : Finset α ≃o Set α where
toEquiv := finsetEquivSet
map_rel_iff' := Finset.coe_subset
@[simp, norm_cast]
lemma coe_finsetOrderIsoSet : ⇑finsetOrderIsoSet = ((↑) : Finset α → Set α) := rfl
@[simp] lemma coe_finsetOrderIsoSet_symm :
⇑(finsetOrderIsoSet : Finset α ≃o Set α).symm = ⇑finsetEquivSet.symm := rfl
end Fintype
theorem mem_image_univ_iff_mem_range {α β : Type*} [Fintype α] [DecidableEq β] {f : α → β}
{b : β} : b ∈ univ.image f ↔ b ∈ Set.range f := by simp
open Batteries.ExtendedBinder Lean Meta
/-- `finset% t` elaborates `t` as a `Finset`.
If `t` is a `Set`, then inserts `Set.toFinset`.
Does not make use of the expected type; useful for big operators over finsets.
```
#check finset% Finset.range 2 -- Finset Nat
#check finset% (Set.univ : Set Bool) -- Finset Bool
```
-/
elab (name := finsetStx) "finset% " t:term : term => do
let u ← mkFreshLevelMVar
let ty ← mkFreshExprMVar (mkSort (.succ u))
let x ← Elab.Term.elabTerm t (mkApp (.const ``Finset [u]) ty)
let xty ← whnfR (← inferType x)
if xty.isAppOfArity ``Set 1 then
Elab.Term.elabAppArgs (.const ``Set.toFinset [u]) #[] #[.expr x] none false false
else
return x
open Lean.Elab.Term.Quotation in
/-- `quot_precheck` for the `finset%` syntax. -/
@[quot_precheck finsetStx] def precheckFinsetStx : Precheck
| `(finset% $t) => precheck t
| _ => Elab.throwUnsupportedSyntax |
.lake/packages/mathlib/Mathlib/Data/Fintype/Order.lean | import Mathlib.Data.Finset.Lattice.Fold
import Mathlib.Data.Finset.Order
import Mathlib.Data.Set.Finite.Basic
import Mathlib.Data.Set.Finite.Range
import Mathlib.Order.Atoms
/-!
# Order structures on finite types
This file provides order instances on fintypes.
## Computable instances
On a `Fintype`, we can construct
* an `OrderBot` from `SemilatticeInf`.
* an `OrderTop` from `SemilatticeSup`.
* a `BoundedOrder` from `Lattice`.
Those are marked as `def` to avoid defeqness issues.
## Completion instances
Those instances are noncomputable because the definitions of `sSup` and `sInf` use `Set.toFinset`
and set membership is undecidable in general.
On a `Fintype`, we can promote:
* a `Lattice` to a `CompleteLattice`.
* a `DistribLattice` to a `CompleteDistribLattice`.
* a `LinearOrder` to a `CompleteLinearOrder`.
* a `BooleanAlgebra` to a `CompleteAtomicBooleanAlgebra`.
Those are marked as `def` to avoid typeclass loops.
## Concrete instances
We provide a few instances for concrete types:
* `Fin.completeLinearOrder`
* `Bool.completeLinearOrder`
* `Bool.completeBooleanAlgebra`
-/
open Finset
namespace Fintype
variable {ι α : Type*} [Fintype ι] [Fintype α]
section Nonempty
variable (α) [Nonempty α]
-- See note [reducible non-instances]
/-- Constructs the `⊥` of a finite nonempty `SemilatticeInf`. -/
abbrev toOrderBot [SemilatticeInf α] : OrderBot α where
bot := univ.inf' univ_nonempty id
bot_le a := inf'_le _ <| mem_univ a
-- See note [reducible non-instances]
/-- Constructs the `⊤` of a finite nonempty `SemilatticeSup` -/
abbrev toOrderTop [SemilatticeSup α] : OrderTop α where
top := univ.sup' univ_nonempty id
le_top a := le_sup' id <| mem_univ a
-- See note [reducible non-instances]
/-- Constructs the `⊤` and `⊥` of a finite nonempty `Lattice`. -/
abbrev toBoundedOrder [Lattice α] : BoundedOrder α :=
{ toOrderBot α, toOrderTop α with }
end Nonempty
section BoundedOrder
variable (α)
open scoped Classical in
-- See note [reducible non-instances]
/-- A finite bounded lattice is complete. -/
noncomputable abbrev toCompleteLattice [Lattice α] [BoundedOrder α] : CompleteLattice α where
__ := ‹Lattice α›
__ := ‹BoundedOrder α›
sSup := fun s => s.toFinset.sup id
sInf := fun s => s.toFinset.inf id
le_sSup := fun _ _ ha => Finset.le_sup (f := id) (Set.mem_toFinset.mpr ha)
sSup_le := fun _ _ ha => Finset.sup_le fun _ hb => ha _ <| Set.mem_toFinset.mp hb
sInf_le := fun _ _ ha => Finset.inf_le (Set.mem_toFinset.mpr ha)
le_sInf := fun _ _ ha => Finset.le_inf fun _ hb => ha _ <| Set.mem_toFinset.mp hb
-- See note [reducible non-instances]
/-- A finite bounded distributive lattice is completely distributive. -/
noncomputable abbrev toCompleteDistribLatticeMinimalAxioms [DistribLattice α] [BoundedOrder α] :
CompleteDistribLattice.MinimalAxioms α where
__ := toCompleteLattice α
iInf_sup_le_sup_sInf := fun a s => by
convert (Finset.inf_sup_distrib_left s.toFinset id a).ge using 1
rw [Finset.inf_eq_iInf]
simp_rw [Set.mem_toFinset]
rfl
inf_sSup_le_iSup_inf := fun a s => by
convert (Finset.sup_inf_distrib_left s.toFinset id a).le using 1
rw [Finset.sup_eq_iSup]
simp_rw [Set.mem_toFinset]
rfl
-- See note [reducible non-instances]
/-- A finite bounded distributive lattice is completely distributive. -/
noncomputable abbrev toCompleteDistribLattice [DistribLattice α] [BoundedOrder α] :
CompleteDistribLattice α := .ofMinimalAxioms (toCompleteDistribLatticeMinimalAxioms _)
-- See note [reducible non-instances]
/-- A finite bounded linear order is complete.
If the `α` is already a `BiheytingAlgebra`, then prefer to construct this instance manually using
`Fintype.toCompleteLattice` instead, to avoid creating a diamond with
`LinearOrder.toBiheytingAlgebra`. -/
noncomputable abbrev toCompleteLinearOrder
[LinearOrder α] [BoundedOrder α] : CompleteLinearOrder α :=
{ toCompleteLattice α, ‹LinearOrder α›, LinearOrder.toBiheytingAlgebra _ with }
-- See note [reducible non-instances]
/-- A finite Boolean algebra is complete. -/
noncomputable abbrev toCompleteBooleanAlgebra [BooleanAlgebra α] : CompleteBooleanAlgebra α where
__ := ‹BooleanAlgebra α›
__ := Fintype.toCompleteDistribLattice α
-- See note [reducible non-instances]
/-- A finite Boolean algebra is complete and atomic. -/
noncomputable abbrev toCompleteAtomicBooleanAlgebra [BooleanAlgebra α] :
CompleteAtomicBooleanAlgebra α :=
(toCompleteBooleanAlgebra α).toCompleteAtomicBooleanAlgebra
end BoundedOrder
section Nonempty
variable (α) [Nonempty α]
-- See note [reducible non-instances]
/-- A nonempty finite lattice is complete. If the lattice is already a `BoundedOrder`, then use
`Fintype.toCompleteLattice` instead, as this gives definitional equality for `⊥` and `⊤`. -/
noncomputable abbrev toCompleteLatticeOfNonempty [Lattice α] : CompleteLattice α :=
@toCompleteLattice _ _ _ <| toBoundedOrder α
-- See note [reducible non-instances]
/-- A nonempty finite linear order is complete. If the linear order is already a `BoundedOrder`,
then use `Fintype.toCompleteLinearOrder` instead, as this gives definitional equality for `⊥` and
`⊤`. -/
noncomputable abbrev toCompleteLinearOrderOfNonempty [LinearOrder α] : CompleteLinearOrder α :=
@toCompleteLinearOrder _ _ _ <| toBoundedOrder α
end Nonempty
end Fintype
/-! ### Concrete instances -/
noncomputable instance Fin.completeLinearOrder {n : ℕ} [NeZero n] : CompleteLinearOrder (Fin n) :=
Fintype.toCompleteLinearOrder _
noncomputable instance Bool.completeBooleanAlgebra : CompleteBooleanAlgebra Bool :=
Fintype.toCompleteBooleanAlgebra _
noncomputable instance Bool.completeLinearOrder : CompleteLinearOrder Bool where
__ := Fintype.toCompleteLattice _
__ : BiheytingAlgebra Bool := inferInstance
__ : LinearOrder Bool := inferInstance
noncomputable instance Bool.completeAtomicBooleanAlgebra : CompleteAtomicBooleanAlgebra Bool :=
Fintype.toCompleteAtomicBooleanAlgebra _
/-! ### Directed Orders -/
variable {α : Type*} {r : α → α → Prop} [IsTrans α r] {β γ : Type*} [Nonempty γ] {f : γ → α}
[Finite β]
theorem Directed.finite_set_le (D : Directed r f) {s : Set γ} (hs : s.Finite) :
∃ z, ∀ i ∈ s, r (f i) (f z) := by
convert D.finset_le hs.toFinset using 3; rw [Set.Finite.mem_toFinset]
theorem Directed.finite_le (D : Directed r f) (g : β → γ) : ∃ z, ∀ i, r (f (g i)) (f z) := by
classical
obtain ⟨z, hz⟩ := D.finite_set_le (Set.finite_range g)
exact ⟨z, fun i => hz (g i) ⟨i, rfl⟩⟩
variable [Nonempty α] [Preorder α]
theorem Finite.exists_le [IsDirected α (· ≤ ·)] (f : β → α) : ∃ M, ∀ i, f i ≤ M :=
directed_id.finite_le _
theorem Finite.exists_ge [IsDirected α (· ≥ ·)] (f : β → α) : ∃ M, ∀ i, M ≤ f i :=
directed_id.finite_le (r := (· ≥ ·)) _
theorem Set.Finite.exists_le [IsDirected α (· ≤ ·)] {s : Set α} (hs : s.Finite) :
∃ M, ∀ i ∈ s, i ≤ M :=
directed_id.finite_set_le hs
theorem Set.Finite.exists_ge [IsDirected α (· ≥ ·)] {s : Set α} (hs : s.Finite) :
∃ M, ∀ i ∈ s, M ≤ i :=
directed_id.finite_set_le (r := (· ≥ ·)) hs
@[simp]
theorem Finite.bddAbove_range [IsDirected α (· ≤ ·)] (f : β → α) : BddAbove (Set.range f) := by
obtain ⟨M, hM⟩ := Finite.exists_le f
refine ⟨M, fun a ha => ?_⟩
obtain ⟨b, rfl⟩ := ha
exact hM b
@[simp]
theorem Finite.bddBelow_range [IsDirected α (· ≥ ·)] (f : β → α) : BddBelow (Set.range f) := by
obtain ⟨M, hM⟩ := Finite.exists_ge f
refine ⟨M, fun a ha => ?_⟩
obtain ⟨b, rfl⟩ := ha
exact hM b |
.lake/packages/mathlib/Mathlib/Data/Fintype/Pi.lean | import Mathlib.Data.Finset.Pi
import Mathlib.Data.Fintype.Basic
import Mathlib.Data.Set.Finite.Basic
/-!
# Fintype instances for pi types
-/
assert_not_exists IsOrderedRing MonoidWithZero
open Finset Function
variable {α β : Type*}
namespace Fintype
variable [DecidableEq α] [Fintype α] {γ δ : α → Type*} {s : ∀ a, Finset (γ a)}
/-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the
finset `Fintype.piFinset t` of all functions taking values in `t a` for all `a`. This is the
analogue of `Finset.pi` where the base finset is `univ` (but formally they are not the same, as
there is an additional condition `i ∈ Finset.univ` in the `Finset.pi` definition). -/
def piFinset (t : ∀ a, Finset (δ a)) : Finset (∀ a, δ a) :=
(Finset.univ.pi t).map ⟨fun f a => f a (mem_univ a), fun _ _ =>
by simp +contextual [funext_iff]⟩
@[simp]
theorem mem_piFinset {t : ∀ a, Finset (δ a)} {f : ∀ a, δ a} : f ∈ piFinset t ↔ ∀ a, f a ∈ t a := by
constructor
· simp only [piFinset, mem_map, and_imp, forall_prop_of_true, mem_univ, exists_imp,
mem_pi]
rintro g hg hgf a
rw [← hgf]
exact hg a
· simp only [piFinset, mem_map, forall_prop_of_true, mem_univ, mem_pi]
exact fun hf => ⟨fun a _ => f a, hf, rfl⟩
@[simp]
theorem coe_piFinset (t : ∀ a, Finset (δ a)) :
(piFinset t : Set (∀ a, δ a)) = Set.pi Set.univ fun a => t a :=
Set.ext fun x => by
rw [Set.mem_univ_pi]
exact Fintype.mem_piFinset
theorem piFinset_subset (t₁ t₂ : ∀ a, Finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) :
piFinset t₁ ⊆ piFinset t₂ := fun _ hg => mem_piFinset.2 fun a => h a <| mem_piFinset.1 hg a
@[simp]
theorem piFinset_eq_empty : piFinset s = ∅ ↔ ∃ i, s i = ∅ := by simp [piFinset]
@[simp]
theorem piFinset_empty [Nonempty α] : piFinset (fun _ => ∅ : ∀ i, Finset (δ i)) = ∅ := by simp
@[simp]
lemma piFinset_nonempty : (piFinset s).Nonempty ↔ ∀ a, (s a).Nonempty := by simp [piFinset]
@[aesop safe apply (rule_sets := [finsetNonempty])]
alias ⟨_, Aesop.piFinset_nonempty_of_forall_nonempty⟩ := piFinset_nonempty
lemma _root_.Finset.Nonempty.piFinset_const {ι : Type*} [Fintype ι] [DecidableEq ι] {s : Finset β}
(hs : s.Nonempty) : (piFinset fun _ : ι ↦ s).Nonempty := piFinset_nonempty.2 fun _ ↦ hs
@[simp]
lemma piFinset_of_isEmpty [IsEmpty α] (s : ∀ a, Finset (γ a)) : piFinset s = univ :=
eq_univ_of_forall fun _ ↦ by simp
@[simp]
theorem piFinset_singleton (f : ∀ i, δ i) : piFinset (fun i => {f i} : ∀ i, Finset (δ i)) = {f} :=
ext fun _ => by simp only [funext_iff, Fintype.mem_piFinset, mem_singleton]
theorem piFinset_subsingleton {f : ∀ i, Finset (δ i)} (hf : ∀ i, (f i : Set (δ i)).Subsingleton) :
(Fintype.piFinset f : Set (∀ i, δ i)).Subsingleton := fun _ ha _ hb =>
funext fun _ => hf _ (mem_piFinset.1 ha _) (mem_piFinset.1 hb _)
theorem piFinset_disjoint_of_disjoint (t₁ t₂ : ∀ a, Finset (δ a)) {a : α}
(h : Disjoint (t₁ a) (t₂ a)) : Disjoint (piFinset t₁) (piFinset t₂) :=
disjoint_iff_ne.2 fun f₁ hf₁ f₂ hf₂ eq₁₂ =>
disjoint_iff_ne.1 h (f₁ a) (mem_piFinset.1 hf₁ a) (f₂ a) (mem_piFinset.1 hf₂ a)
(congr_fun eq₁₂ a)
lemma piFinset_image [∀ a, DecidableEq (δ a)] (f : ∀ a, γ a → δ a) (s : ∀ a, Finset (γ a)) :
piFinset (fun a ↦ (s a).image (f a)) = (piFinset s).image fun b a ↦ f _ (b a) := by
ext; simp only [mem_piFinset, mem_image, Classical.skolem, forall_and, funext_iff]
lemma eval_image_piFinset_subset (t : ∀ a, Finset (δ a)) (a : α) [DecidableEq (δ a)] :
((piFinset t).image fun f ↦ f a) ⊆ t a := image_subset_iff.2 fun _x hx ↦ mem_piFinset.1 hx _
lemma eval_image_piFinset (t : ∀ a, Finset (δ a)) (a : α) [DecidableEq (δ a)]
(ht : ∀ b, a ≠ b → (t b).Nonempty) : ((piFinset t).image fun f ↦ f a) = t a := by
refine (eval_image_piFinset_subset _ _).antisymm fun x h ↦ mem_image.2 ?_
choose f hf using ht
exact ⟨fun b ↦ if h : a = b then h ▸ x else f _ h, by aesop, by simp⟩
lemma eval_image_piFinset_const {β} [DecidableEq β] (t : Finset β) (a : α) :
((piFinset fun _i : α ↦ t).image fun f ↦ f a) = t := by
obtain rfl | ht := t.eq_empty_or_nonempty
· haveI : Nonempty α := ⟨a⟩
simp
· exact eval_image_piFinset (fun _ ↦ t) a fun _ _ ↦ ht
variable [∀ a, DecidableEq (δ a)]
lemma filter_piFinset_of_notMem (t : ∀ a, Finset (δ a)) (a : α) (x : δ a) (hx : x ∉ t a) :
{f ∈ piFinset t | f a = x} = ∅ := by
simp only [filter_eq_empty_iff, mem_piFinset]; rintro f hf rfl; exact hx (hf _)
@[deprecated (since := "2025-05-23")] alias filter_piFinset_of_not_mem := filter_piFinset_of_notMem
-- TODO: This proof looks like a good example of something that `aesop` can't do but should
lemma piFinset_update_eq_filter_piFinset_mem (s : ∀ i, Finset (δ i)) (i : α) {t : Finset (δ i)}
(hts : t ⊆ s i) : piFinset (Function.update s i t) = {f ∈ piFinset s | f i ∈ t} := by
ext f
simp only [mem_piFinset, mem_filter]
refine ⟨fun h ↦ ?_, fun h j ↦ ?_⟩
· have := by simpa using h i
refine ⟨fun j ↦ ?_, this⟩
obtain rfl | hji := eq_or_ne j i
· exact hts this
· simpa [hji] using h j
· obtain rfl | hji := eq_or_ne j i
· simpa using h.2
· simpa [hji] using h.1 j
lemma piFinset_update_singleton_eq_filter_piFinset_eq (s : ∀ i, Finset (δ i)) (i : α) {a : δ i}
(ha : a ∈ s i) :
piFinset (Function.update s i {a}) = {f ∈ piFinset s | f i = a} := by
simp [piFinset_update_eq_filter_piFinset_mem, ha]
end Fintype
/-! ### pi -/
/-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/
instance Pi.instFintype {α : Type*} {β : α → Type*} [DecidableEq α] [Fintype α]
[∀ a, Fintype (β a)] : Fintype (∀ a, β a) :=
⟨Fintype.piFinset fun _ => univ, by simp⟩
@[simp]
theorem Fintype.piFinset_univ {α : Type*} {β : α → Type*} [DecidableEq α] [Fintype α]
[∀ a, Fintype (β a)] :
(Fintype.piFinset fun a : α => (Finset.univ : Finset (β a))) =
(Finset.univ : Finset (∀ a, β a)) :=
rfl
/-- There are finitely many embeddings between finite types.
This instance used to be computable (using `DecidableEq` arguments), but
it makes things a lot harder to work with here.
-/
noncomputable instance _root_.Function.Embedding.fintype {α β} [Fintype α] [Fintype β] :
Fintype (α ↪ β) := by
classical exact Fintype.ofEquiv _ (Equiv.subtypeInjectiveEquivEmbedding α β)
instance RelHom.instFintype {α β} [Fintype α] [Fintype β] [DecidableEq α] {r : α → α → Prop}
{s : β → β → Prop} [DecidableRel r] [DecidableRel s] : Fintype (r →r s) :=
Fintype.ofEquiv {f : α → β // ∀ {x y}, r x y → s (f x) (f y)} <| Equiv.mk
(fun f ↦ ⟨f.1, f.2⟩) (fun f ↦ ⟨f.1, f.2⟩) (fun _ ↦ rfl) (fun _ ↦ rfl)
noncomputable instance RelEmbedding.instFintype {α β} [Fintype α] [Fintype β]
{r : α → α → Prop} {s : β → β → Prop} : Fintype (r ↪r s) :=
Fintype.ofInjective _ RelEmbedding.toEmbedding_injective
@[simp]
theorem Finset.univ_pi_univ {α : Type*} {β : α → Type*} [DecidableEq α] [Fintype α]
[∀ a, Fintype (β a)] :
(Finset.univ.pi fun a : α => (Finset.univ : Finset (β a))) = Finset.univ := by
ext; simp
/-! ### Diagonal -/
namespace Finset
variable {ι : Type*} [DecidableEq (ι → α)] {s : Finset α} {f : ι → α}
lemma piFinset_filter_const [DecidableEq ι] [Fintype ι] :
{f ∈ Fintype.piFinset fun _ : ι ↦ s | ∃ a ∈ s, const ι a = f} = s.piDiag ι := by aesop
lemma piDiag_subset_piFinset [DecidableEq ι] [Fintype ι] :
s.piDiag ι ⊆ Fintype.piFinset fun _ ↦ s := by simp [← piFinset_filter_const]
end Finset
namespace Set
/-! ### Constructors for `Set.Finite`
Every constructor here should have a corresponding `Fintype` instance in the previous section
(or in the `Fintype` module).
The implementation of these constructors ideally should be no more than `Set.toFinite`,
after possibly setting up some `Fintype` and classical `Decidable` instances.
-/
section SetFiniteConstructors
section Pi
variable {ι : Type*} [Finite ι] {κ : ι → Type*} {t : ∀ i, Set (κ i)}
/-- Finite product of finite sets is finite -/
theorem Finite.pi (ht : ∀ i, (t i).Finite) : (pi univ t).Finite := by
cases nonempty_fintype ι
lift t to ∀ d, Finset (κ d) using ht
classical
rw [← Fintype.coe_piFinset]
apply Finset.finite_toSet
/-- Finite product of finite sets is finite. Note this is a variant of `Set.Finite.pi` without the
extra `i ∈ univ` binder. -/
lemma Finite.pi' (ht : ∀ i, (t i).Finite) : {f : ∀ i, κ i | ∀ i, f i ∈ t i}.Finite := by
simpa [Set.pi] using Finite.pi ht
end Pi
end SetFiniteConstructors
theorem forall_finite_image_eval_iff {δ : Type*} [Finite δ] {κ : δ → Type*} {s : Set (∀ d, κ d)} :
(∀ d, (eval d '' s).Finite) ↔ s.Finite :=
⟨fun h => (Finite.pi h).subset <| subset_pi_eval_image _ _, fun h _ => h.image _⟩
end Set |
.lake/packages/mathlib/Mathlib/Data/Fintype/Basic.lean | import Mathlib.Data.Finite.Defs
import Mathlib.Data.Finset.BooleanAlgebra
import Mathlib.Data.Finset.Image
import Mathlib.Data.Fintype.Defs
import Mathlib.Data.Fintype.OfMap
import Mathlib.Data.Fintype.Sets
import Mathlib.Data.List.FinRange
/-!
# Instances for finite types
This file is a collection of basic `Fintype` instances for types such as `Fin`, `Prod` and pi types.
-/
assert_not_exists Monoid
open Function
open Nat
universe u v
variable {α β γ : Type*}
open Finset
instance Fin.fintype (n : ℕ) : Fintype (Fin n) :=
⟨⟨List.finRange n, List.nodup_finRange n⟩, List.mem_finRange⟩
theorem Fin.univ_def (n : ℕ) : (univ : Finset (Fin n)) = ⟨List.finRange n, List.nodup_finRange n⟩ :=
rfl
theorem Finset.val_univ_fin (n : ℕ) : (Finset.univ : Finset (Fin n)).val = List.finRange n := rfl
/-- See also `nonempty_encodable`, `nonempty_denumerable`. -/
theorem nonempty_fintype (α : Type*) [Finite α] : Nonempty (Fintype α) := by
rcases Finite.exists_equiv_fin α with ⟨n, ⟨e⟩⟩
exact ⟨.ofEquiv _ e.symm⟩
@[simp] theorem List.toFinset_finRange (n : ℕ) : (List.finRange n).toFinset = Finset.univ := by
ext; simp
@[simp] theorem Fin.univ_val_map {n : ℕ} (f : Fin n → α) :
Finset.univ.val.map f = List.ofFn f := by
simp [List.ofFn_eq_map, univ_def]
theorem Fin.univ_image_def {n : ℕ} [DecidableEq α] (f : Fin n → α) :
Finset.univ.image f = (List.ofFn f).toFinset := by
simp [Finset.image]
theorem Fin.univ_map_def {n : ℕ} (f : Fin n ↪ α) :
Finset.univ.map f = ⟨List.ofFn f, List.nodup_ofFn.mpr f.injective⟩ := by
simp [Finset.map]
@[simp]
theorem Fin.image_succAbove_univ {n : ℕ} (i : Fin (n + 1)) : univ.image i.succAbove = {i}ᶜ := by
ext m
simp
@[simp]
theorem Fin.image_succ_univ (n : ℕ) : (univ : Finset (Fin n)).image Fin.succ = {0}ᶜ := by
rw [← Fin.succAbove_zero, Fin.image_succAbove_univ]
@[simp]
theorem Fin.image_castSucc (n : ℕ) :
(univ : Finset (Fin n)).image Fin.castSucc = {Fin.last n}ᶜ := by
rw [← Fin.succAbove_last, Fin.image_succAbove_univ]
/- The following three lemmas use `Finset.cons` instead of `insert` and `Finset.map` instead of
`Finset.image` to reduce proof obligations downstream. -/
/-- Embed `Fin n` into `Fin (n + 1)` by prepending zero to the `univ` -/
theorem Fin.univ_succ (n : ℕ) :
(univ : Finset (Fin (n + 1))) =
Finset.cons 0 (univ.map ⟨Fin.succ, Fin.succ_injective _⟩) (by simp [map_eq_image]) := by
simp [map_eq_image]
/-- Embed `Fin n` into `Fin (n + 1)` by appending a new `Fin.last n` to the `univ` -/
theorem Fin.univ_castSuccEmb (n : ℕ) :
(univ : Finset (Fin (n + 1))) =
Finset.cons (Fin.last n) (univ.map Fin.castSuccEmb) (by simp [map_eq_image]) := by
simp [map_eq_image]
/-- Embed `Fin n` into `Fin (n + 1)` by inserting
around a specified pivot `p : Fin (n + 1)` into the `univ` -/
theorem Fin.univ_succAbove (n : ℕ) (p : Fin (n + 1)) :
(univ : Finset (Fin (n + 1))) = Finset.cons p (univ.map <| Fin.succAboveEmb p) (by simp) := by
simp [map_eq_image]
@[simp] theorem Fin.univ_image_get [DecidableEq α] (l : List α) :
Finset.univ.image l.get = l.toFinset := by
simp [univ_image_def]
@[simp] theorem Fin.univ_image_getElem' [DecidableEq β] (l : List α) (f : α → β) :
Finset.univ.image (fun i : Fin l.length => f <| l[(i : Nat)]) = (l.map f).toFinset := by
simp only [univ_image_def, List.ofFn_getElem_eq_map]
theorem Fin.univ_image_get' [DecidableEq β] (l : List α) (f : α → β) :
Finset.univ.image (f <| l.get ·) = (l.map f).toFinset := by
simp
@[instance]
def Unique.fintype {α : Type*} [Unique α] : Fintype α :=
Fintype.ofSubsingleton default
/-- Short-circuit instance to decrease search for `Unique.fintype`,
since that relies on a subsingleton elimination for `Unique`. -/
instance Fintype.subtypeEq (y : α) : Fintype { x // x = y } :=
Fintype.subtype {y} (by simp)
/-- Short-circuit instance to decrease search for `Unique.fintype`,
since that relies on a subsingleton elimination for `Unique`. -/
instance Fintype.subtypeEq' (y : α) : Fintype { x // y = x } :=
Fintype.subtype {y} (by simp [eq_comm])
theorem Fintype.univ_empty : @univ Empty _ = ∅ :=
rfl
theorem Fintype.univ_pempty : @univ PEmpty _ = ∅ :=
rfl
instance Unit.fintype : Fintype Unit :=
Fintype.ofSubsingleton ()
theorem Fintype.univ_unit : @univ Unit _ = {()} :=
rfl
instance PUnit.fintype : Fintype PUnit :=
Fintype.ofSubsingleton PUnit.unit
theorem Fintype.univ_punit : @univ PUnit _ = {PUnit.unit} :=
rfl
@[simp]
theorem Fintype.univ_bool : @univ Bool _ = {true, false} :=
rfl
/-- Given that `α × β` is a fintype, `α` is also a fintype. -/
def Fintype.prodLeft {α β} [DecidableEq α] [Fintype (α × β)] [Nonempty β] : Fintype α :=
⟨(@univ (α × β) _).image Prod.fst, fun a => by simp⟩
/-- Given that `α × β` is a fintype, `β` is also a fintype. -/
def Fintype.prodRight {α β} [DecidableEq β] [Fintype (α × β)] [Nonempty α] : Fintype β :=
⟨(@univ (α × β) _).image Prod.snd, fun b => by simp⟩
instance ULift.fintype (α : Type*) [Fintype α] : Fintype (ULift α) :=
Fintype.ofEquiv _ Equiv.ulift.symm
instance PLift.fintype (α : Type*) [Fintype α] : Fintype (PLift α) :=
Fintype.ofEquiv _ Equiv.plift.symm
instance PLift.fintypeProp (p : Prop) [Decidable p] : Fintype (PLift p) :=
⟨if h : p then {⟨h⟩} else ∅, fun ⟨h⟩ => by simp [h]⟩
instance Quotient.fintype [Fintype α] (s : Setoid α) [DecidableRel ((· ≈ ·) : α → α → Prop)] :
Fintype (Quotient s) :=
Fintype.ofSurjective Quotient.mk'' Quotient.mk''_surjective
instance PSigma.fintypePropLeft {α : Prop} {β : α → Type*} [Decidable α] [∀ a, Fintype (β a)] :
Fintype (Σ' a, β a) :=
if h : α then Fintype.ofEquiv (β h) ⟨fun x => ⟨h, x⟩, PSigma.snd, fun _ => rfl, fun ⟨_, _⟩ => rfl⟩
else ⟨∅, fun x => (h x.1).elim⟩
instance PSigma.fintypePropRight {α : Type*} {β : α → Prop} [∀ a, Decidable (β a)] [Fintype α] :
Fintype (Σ' a, β a) :=
Fintype.ofEquiv { a // β a }
⟨fun ⟨x, y⟩ => ⟨x, y⟩, fun ⟨x, y⟩ => ⟨x, y⟩, fun ⟨_, _⟩ => rfl, fun ⟨_, _⟩ => rfl⟩
instance PSigma.fintypePropProp {α : Prop} {β : α → Prop} [Decidable α] [∀ a, Decidable (β a)] :
Fintype (Σ' a, β a) :=
if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, fun ⟨_, _⟩ => by simp⟩ else ⟨∅, fun ⟨x, y⟩ =>
(h ⟨x, y⟩).elim⟩
instance pfunFintype (p : Prop) [Decidable p] (α : p → Type*) [∀ hp, Fintype (α hp)] :
Fintype (∀ hp : p, α hp) :=
if hp : p then Fintype.ofEquiv (α hp) ⟨fun a _ => a, fun f => f hp, fun _ => rfl, fun _ => rfl⟩
else ⟨singleton fun h => (hp h).elim, fun h => mem_singleton.2
(funext fun x => by contradiction)⟩
section Trunc
/-- For `s : Multiset α`, we can lift the existential statement that `∃ x, x ∈ s` to a `Trunc α`.
-/
def truncOfMultisetExistsMem {α} (s : Multiset α) : (∃ x, x ∈ s) → Trunc α :=
Quotient.recOnSubsingleton s fun l h =>
match l, h with
| [], _ => False.elim (by tauto)
| a :: _, _ => Trunc.mk a
/-- A `Nonempty` `Fintype` constructively contains an element.
-/
def truncOfNonemptyFintype (α) [Nonempty α] [Fintype α] : Trunc α :=
truncOfMultisetExistsMem Finset.univ.val (by simp)
/-- By iterating over the elements of a fintype, we can lift an existential statement `∃ a, P a`
to `Trunc (Σ' a, P a)`, containing data.
-/
def truncSigmaOfExists {α} [Fintype α] {P : α → Prop} [DecidablePred P] (h : ∃ a, P a) :
Trunc (Σ' a, P a) :=
@truncOfNonemptyFintype (Σ' a, P a) ((Exists.elim h) fun a ha => ⟨⟨a, ha⟩⟩) _
end Trunc
namespace Multiset
variable [Fintype α] [Fintype β]
@[simp]
theorem count_univ [DecidableEq α] (a : α) : count a Finset.univ.val = 1 :=
count_eq_one_of_mem Finset.univ.nodup (Finset.mem_univ _)
@[simp]
theorem map_univ_val_equiv (e : α ≃ β) :
map e univ.val = univ.val := by
rw [← congr_arg Finset.val (Finset.map_univ_equiv e), Finset.map_val, Equiv.coe_toEmbedding]
/-- For functions on finite sets, they are bijections iff they map universes into universes. -/
@[simp]
theorem bijective_iff_map_univ_eq_univ (f : α → β) :
f.Bijective ↔ map f (Finset.univ : Finset α).val = univ.val :=
⟨fun bij ↦ congr_arg (·.val) (map_univ_equiv <| Equiv.ofBijective f bij),
fun eq ↦ ⟨
fun a₁ a₂ ↦ inj_on_of_nodup_map (eq.symm ▸ univ.nodup) _ (mem_univ a₁) _ (mem_univ a₂),
fun b ↦ have ⟨a, _, h⟩ := mem_map.mp (eq.symm ▸ mem_univ_val b); ⟨a, h⟩⟩⟩
end Multiset
/-- Auxiliary definition to show `exists_seq_of_forall_finset_exists`. -/
noncomputable def seqOfForallFinsetExistsAux {α : Type*} [DecidableEq α] (P : α → Prop)
(r : α → α → Prop) (h : ∀ s : Finset α, ∃ y, (∀ x ∈ s, P x) → P y ∧ ∀ x ∈ s, r x y) : ℕ → α
| n =>
Classical.choose
(h
(Finset.image (fun i : Fin n => seqOfForallFinsetExistsAux P r h i)
(Finset.univ : Finset (Fin n))))
/-- Induction principle to build a sequence, by adding one point at a time satisfying a given
relation with respect to all the previously chosen points.
More precisely, Assume that, for any finite set `s`, one can find another point satisfying
some relation `r` with respect to all the points in `s`. Then one may construct a
function `f : ℕ → α` such that `r (f m) (f n)` holds whenever `m < n`.
We also ensure that all constructed points satisfy a given predicate `P`. -/
theorem exists_seq_of_forall_finset_exists {α : Type*} (P : α → Prop) (r : α → α → Prop)
(h : ∀ s : Finset α, (∀ x ∈ s, P x) → ∃ y, P y ∧ ∀ x ∈ s, r x y) :
∃ f : ℕ → α, (∀ n, P (f n)) ∧ ∀ m n, m < n → r (f m) (f n) := by
classical
have : Nonempty α := by
rcases h ∅ (by simp) with ⟨y, _⟩
exact ⟨y⟩
choose! F hF using h
have h' : ∀ s : Finset α, ∃ y, (∀ x ∈ s, P x) → P y ∧ ∀ x ∈ s, r x y := fun s => ⟨F s, hF s⟩
set f := seqOfForallFinsetExistsAux P r h' with hf
have A : ∀ n : ℕ, P (f n) := by
intro n
induction n using Nat.strong_induction_on with | _ n IH
have IH' : ∀ x : Fin n, P (f x) := fun n => IH n.1 n.2
rw [hf, seqOfForallFinsetExistsAux]
exact
(Classical.choose_spec
(h' (Finset.image (fun i : Fin n => f i) (Finset.univ : Finset (Fin n))))
(by simp [IH'])).1
refine ⟨f, A, fun m n hmn => ?_⟩
conv_rhs => rw [hf]
rw [seqOfForallFinsetExistsAux]
apply
(Classical.choose_spec
(h' (Finset.image (fun i : Fin n => f i) (Finset.univ : Finset (Fin n)))) (by simp [A])).2
exact Finset.mem_image.2 ⟨⟨m, hmn⟩, Finset.mem_univ _, rfl⟩
/-- Induction principle to build a sequence, by adding one point at a time satisfying a given
symmetric relation with respect to all the previously chosen points.
More precisely, Assume that, for any finite set `s`, one can find another point satisfying
some relation `r` with respect to all the points in `s`. Then one may construct a
function `f : ℕ → α` such that `r (f m) (f n)` holds whenever `m ≠ n`.
We also ensure that all constructed points satisfy a given predicate `P`. -/
theorem exists_seq_of_forall_finset_exists' {α : Type*} (P : α → Prop) (r : α → α → Prop)
[IsSymm α r] (h : ∀ s : Finset α, (∀ x ∈ s, P x) → ∃ y, P y ∧ ∀ x ∈ s, r x y) :
∃ f : ℕ → α, (∀ n, P (f n)) ∧ Pairwise (r on f) := by
rcases exists_seq_of_forall_finset_exists P r h with ⟨f, hf, hf'⟩
refine ⟨f, hf, fun m n hmn => ?_⟩
rcases lt_trichotomy m n with (h | rfl | h)
· exact hf' m n h
· exact (hmn rfl).elim
· unfold Function.onFun
apply symm
exact hf' n m h |
.lake/packages/mathlib/Mathlib/Data/Fintype/Sort.lean | import Mathlib.Data.Finset.Sort
import Mathlib.Data.Fintype.Basic
/-!
# Sorting a finite type
This file provides two equivalences for linearly ordered fintypes:
* `monoEquivOfFin`: Order isomorphism between `α` and `Fin (card α)`.
* `finSumEquivOfFinset`: Equivalence between `α` and `Fin m ⊕ Fin n` where `m` and `n` are
respectively the cardinalities of some `Finset α` and its complement.
-/
open Finset
/-- Given a linearly ordered fintype `α` of cardinal `k`, the order isomorphism
`monoEquivOfFin α h` is the increasing bijection between `Fin k` and `α`. Here, `h` is a proof
that the cardinality of `α` is `k`. We use this instead of an isomorphism `Fin (card α) ≃o α` to
avoid casting issues in further uses of this function. -/
def monoEquivOfFin (α : Type*) [Fintype α] [LinearOrder α] {k : ℕ} (h : Fintype.card α = k) :
Fin k ≃o α :=
(univ.orderIsoOfFin h).trans <| (OrderIso.setCongr _ _ coe_univ).trans OrderIso.Set.univ
variable {α : Type*} [DecidableEq α] [Fintype α] [LinearOrder α] {m n : ℕ} {s : Finset α}
/-- If `α` is a linearly ordered fintype, `s : Finset α` has cardinality `m` and its complement has
cardinality `n`, then `Fin m ⊕ Fin n ≃ α`. The equivalence sends elements of `Fin m` to
elements of `s` and elements of `Fin n` to elements of `sᶜ` while preserving order on each
"half" of `Fin m ⊕ Fin n` (using `Set.orderIsoOfFin`). -/
def finSumEquivOfFinset (hm : #s = m) (hn : #sᶜ = n) : Fin m ⊕ Fin n ≃ α :=
calc
Fin m ⊕ Fin n ≃ (s : Set α) ⊕ (sᶜ : Set α) :=
Equiv.sumCongr (s.orderIsoOfFin hm).toEquiv <|
(sᶜ.orderIsoOfFin hn).toEquiv.trans <| Equiv.setCongr s.coe_compl
_ ≃ α := Equiv.Set.sumCompl _
@[simp]
theorem finSumEquivOfFinset_inl (hm : #s = m) (hn : #sᶜ = n) (i : Fin m) :
finSumEquivOfFinset hm hn (Sum.inl i) = s.orderEmbOfFin hm i :=
rfl
@[simp]
theorem finSumEquivOfFinset_inr (hm : #s = m) (hn : #sᶜ = n) (i : Fin n) :
finSumEquivOfFinset hm hn (Sum.inr i) = sᶜ.orderEmbOfFin hn i :=
rfl |
.lake/packages/mathlib/Mathlib/Data/Fintype/Quotient.lean | import Mathlib.Data.List.Pi
import Mathlib.Data.Fintype.Defs
/-!
# Quotients of families indexed by a finite type
This file proves some basic facts and defines lifting and recursion principle for quotients indexed
by a finite type.
## Main definitions
* `Quotient.finChoice`: Given a function `f : Π i, Quotient (S i)` on a fintype `ι`, returns the
class of functions `Π i, α i` sending each `i` to an element of the class `f i`.
* `Quotient.finChoiceEquiv`: A finite family of quotients is equivalent to a quotient of
finite families.
* `Quotient.finLiftOn`: Given a fintype `ι`. A function on `Π i, α i` which respects
setoid `S i` for each `i` can be lifted to a function on `Π i, Quotient (S i)`.
* `Quotient.finRecOn`: Recursion principle for quotients indexed by a finite type. It is the
dependent version of `Quotient.finLiftOn`.
-/
namespace Quotient
section List
variable {ι : Type*} [DecidableEq ι] {α : ι → Sort*} {S : ∀ i, Setoid (α i)} {β : Sort*}
/-- Given a collection of setoids indexed by a type `ι`, a list `l` of indices, and a function that
for each `i ∈ l` gives a term of the corresponding quotient type, then there is a corresponding
term in the quotient of the product of the setoids indexed by `l`. -/
def listChoice {l : List ι} (q : ∀ i ∈ l, Quotient (S i)) : @Quotient (∀ i ∈ l, α i) piSetoid :=
match l with
| [] => ⟦nofun⟧
| i :: _ => Quotient.liftOn₂ (List.Pi.head (i := i) q)
(listChoice (List.Pi.tail q))
(⟦List.Pi.cons _ _ · ·⟧)
(fun _ _ _ _ ha hl ↦ Quotient.sound (List.Pi.forall_rel_cons_ext ha hl))
theorem listChoice_mk {l : List ι} (a : ∀ i ∈ l, α i) : listChoice (S := S) (⟦a · ·⟧) = ⟦a⟧ :=
match l with
| [] => Quotient.sound nofun
| i :: l => by
unfold listChoice List.Pi.tail
rw [listChoice_mk]
exact congrArg (⟦·⟧) (List.Pi.cons_eta a)
/-- Choice-free induction principle for quotients indexed by a `List`. -/
@[elab_as_elim]
lemma list_ind {l : List ι} {C : (∀ i ∈ l, Quotient (S i)) → Prop}
(f : ∀ a : ∀ i ∈ l, α i, C (⟦a · ·⟧)) (q : ∀ i ∈ l, Quotient (S i)) : C q :=
match l with
| [] => cast (congr_arg _ (funext₂ nofun)) (f nofun)
| i :: l => by
rw [← List.Pi.cons_eta q]
induction List.Pi.head q using Quotient.ind with | _ a
refine @list_ind _ (fun q ↦ C (List.Pi.cons _ _ ⟦a⟧ q)) ?_ (List.Pi.tail q)
intro as
rw [List.Pi.cons_map a as (fun i ↦ Quotient.mk (S i))]
exact f _
end List
section Fintype
variable {ι : Type*} [Fintype ι] [DecidableEq ι] {α : ι → Sort*} {S : ∀ i, Setoid (α i)} {β : Sort*}
/-- Choice-free induction principle for quotients indexed by a finite type.
See `Quotient.induction_on_pi` for the general version assuming `Classical.choice`. -/
@[elab_as_elim]
lemma ind_fintype_pi {C : (∀ i, Quotient (S i)) → Prop}
(f : ∀ a : ∀ i, α i, C (⟦a ·⟧)) (q : ∀ i, Quotient (S i)) : C q := by
have {m : Multiset ι} (C : (∀ i ∈ m, Quotient (S i)) → Prop) :
∀ (_ : ∀ a : ∀ i ∈ m, α i, C (⟦a · ·⟧)) (q : ∀ i ∈ m, Quotient (S i)), C q := by
induction m using Quotient.ind
exact list_ind
exact this (fun q ↦ C (q · (Finset.mem_univ _))) (fun _ ↦ f _) (fun i _ ↦ q i)
/-- Choice-free induction principle for quotients indexed by a finite type.
See `Quotient.induction_on_pi` for the general version assuming `Classical.choice`. -/
@[elab_as_elim]
lemma induction_on_fintype_pi {C : (∀ i, Quotient (S i)) → Prop}
(q : ∀ i, Quotient (S i)) (f : ∀ a : ∀ i, α i, C (⟦a ·⟧)) : C q :=
ind_fintype_pi f q
/-- Given a collection of setoids indexed by a fintype `ι` and a function that for each `i : ι`
gives a term of the corresponding quotient type, then there is corresponding term in the quotient
of the product of the setoids.
See `Quotient.choice` for the noncomputable general version. -/
def finChoice (q : ∀ i, Quotient (S i)) :
@Quotient (∀ i, α i) piSetoid := by
let e := Equiv.subtypeQuotientEquivQuotientSubtype (fun l : List ι ↦ ∀ i, i ∈ l)
(fun s : Multiset ι ↦ ∀ i, i ∈ s) (fun i ↦ Iff.rfl) (fun _ _ ↦ Iff.rfl) ⟨_, Finset.mem_univ⟩
refine e.liftOn
(fun l ↦ (listChoice fun i _ ↦ q i).map (fun a i ↦ a i (l.2 i)) ?_) ?_
· exact fun _ _ h i ↦ h i _
intro _ _ _
refine ind_fintype_pi (fun a ↦ ?_) q
simp_rw [listChoice_mk, Quotient.map_mk]
theorem finChoice_eq (a : ∀ i, α i) :
finChoice (S := S) (⟦a ·⟧) = ⟦a⟧ := by
dsimp [finChoice]
obtain ⟨l, hl⟩ := (Finset.univ.val : Multiset ι).exists_rep
simp_rw [← hl, Equiv.subtypeQuotientEquivQuotientSubtype, listChoice_mk]
rfl
lemma eval_finChoice (f : ∀ i, Quotient (S i)) :
eval (finChoice f) = f :=
induction_on_fintype_pi f (fun a ↦ by rw [finChoice_eq]; rfl)
/-- Lift a function on `∀ i, α i` to a function on `∀ i, Quotient (S i)`. -/
def finLiftOn (q : ∀ i, Quotient (S i)) (f : (∀ i, α i) → β)
(h : ∀ (a b : ∀ i, α i), (∀ i, a i ≈ b i) → f a = f b) : β :=
(finChoice q).liftOn f h
@[simp]
lemma finLiftOn_empty [e : IsEmpty ι] (q : ∀ i, Quotient (S i)) :
finLiftOn (β := β) q = fun f _ ↦ f e.elim := by
ext f h
dsimp [finLiftOn]
induction finChoice q using Quotient.ind
exact h _ _ e.elim
@[simp]
lemma finLiftOn_mk (a : ∀ i, α i) :
finLiftOn (S := S) (β := β) (⟦a ·⟧) = fun f _ ↦ f a := by
ext f h
dsimp [finLiftOn]
rw [finChoice_eq]
rfl
/-- `Quotient.finChoice` as an equivalence. -/
@[simps]
def finChoiceEquiv :
(∀ i, Quotient (S i)) ≃ @Quotient (∀ i, α i) piSetoid where
toFun := finChoice
invFun := eval
left_inv q := by
refine induction_on_fintype_pi q (fun a ↦ ?_)
rw [finChoice_eq]
rfl
right_inv q := by
induction q using Quotient.ind
exact finChoice_eq _
/-- Recursion principle for quotients indexed by a finite type. -/
@[elab_as_elim]
def finHRecOn {C : (∀ i, Quotient (S i)) → Sort*}
(q : ∀ i, Quotient (S i))
(f : ∀ a : ∀ i, α i, C (⟦a ·⟧))
(h : ∀ (a b : ∀ i, α i), (∀ i, a i ≈ b i) → f a ≍ f b) :
C q :=
eval_finChoice q ▸ (finChoice q).hrecOn f h
/-- Recursion principle for quotients indexed by a finite type. -/
@[elab_as_elim]
def finRecOn {C : (∀ i, Quotient (S i)) → Sort*}
(q : ∀ i, Quotient (S i))
(f : ∀ a : ∀ i, α i, C (⟦a ·⟧))
(h : ∀ (a b : ∀ i, α i) (h : ∀ i, a i ≈ b i),
Eq.ndrec (f a) (funext fun i ↦ Quotient.sound (h i)) = f b) :
C q :=
finHRecOn q f (eqRec_heq_iff_heq.mp <| heq_of_eq <| h · · ·)
@[simp]
lemma finHRecOn_mk {C : (∀ i, Quotient (S i)) → Sort*}
(a : ∀ i, α i) :
finHRecOn (C := C) (⟦a ·⟧) = fun f _ ↦ f a := by
ext f h
refine eq_of_heq ((eqRec_heq _ _).trans ?_)
rw [finChoice_eq]
rfl
@[simp]
lemma finRecOn_mk {C : (∀ i, Quotient (S i)) → Sort*}
(a : ∀ i, α i) :
finRecOn (C := C) (⟦a ·⟧) = fun f _ ↦ f a := by
unfold finRecOn
simp
end Fintype
end Quotient
namespace Trunc
variable {ι : Type*} [DecidableEq ι] [Fintype ι] {α : ι → Sort*} {β : Sort*}
/-- Given a function that for each `i : ι` gives a term of the corresponding
truncation type, then there is corresponding term in the truncation of the product. -/
def finChoice (q : ∀ i, Trunc (α i)) : Trunc (∀ i, α i) :=
Quotient.map' id (fun _ _ _ => trivial) (Quotient.finChoice q)
theorem finChoice_eq (f : ∀ i, α i) : (Trunc.finChoice fun i => Trunc.mk (f i)) = Trunc.mk f :=
Subsingleton.elim _ _
/-- Lift a function on `∀ i, α i` to a function on `∀ i, Trunc (α i)`. -/
def finLiftOn (q : ∀ i, Trunc (α i)) (f : (∀ i, α i) → β) (h : ∀ (a b : ∀ i, α i), f a = f b) : β :=
Quotient.finLiftOn q f (fun _ _ _ ↦ h _ _)
@[simp]
lemma finLiftOn_empty [e : IsEmpty ι] (q : ∀ i, Trunc (α i)) :
finLiftOn (β := β) q = fun f _ ↦ f e.elim :=
funext₂ fun _ _ ↦ congrFun₂ (Quotient.finLiftOn_empty q) _ _
@[simp]
lemma finLiftOn_mk (a : ∀ i, α i) :
finLiftOn (β := β) (⟦a ·⟧) = fun f _ ↦ f a :=
funext₂ fun _ _ ↦ congrFun₂ (Quotient.finLiftOn_mk a) _ _
/-- `Trunc.finChoice` as an equivalence. -/
@[simps]
def finChoiceEquiv : (∀ i, Trunc (α i)) ≃ Trunc (∀ i, α i) where
toFun := finChoice
invFun q i := q.map (· i)
left_inv _ := Subsingleton.elim _ _
right_inv _ := Subsingleton.elim _ _
/-- Recursion principle for `Trunc`s indexed by a finite type. -/
@[elab_as_elim]
def finRecOn {C : (∀ i, Trunc (α i)) → Sort*}
(q : ∀ i, Trunc (α i))
(f : ∀ a : ∀ i, α i, C (mk <| a ·))
(h : ∀ (a b : ∀ i, α i), (Eq.ndrec (f a) (funext fun _ ↦ Trunc.eq _ _)) = f b) :
C q :=
Quotient.finRecOn q (f ·) (fun _ _ _ ↦ h _ _)
@[simp]
lemma finRecOn_mk {C : (∀ i, Trunc (α i)) → Sort*}
(a : ∀ i, α i) :
finRecOn (C := C) (⟦a ·⟧) = fun f _ ↦ f a := by
unfold finRecOn
simp
end Trunc |
.lake/packages/mathlib/Mathlib/Data/Fintype/Vector.lean | import Mathlib.Data.Fintype.Pi
import Mathlib.Data.Sym.Basic
/-!
# `Vector α n` and `Sym α n` are fintypes when `α` is.
-/
open List (Vector)
variable {α : Type*}
instance Vector.fintype [Fintype α] {n : ℕ} : Fintype (List.Vector α n) :=
Fintype.ofEquiv _ (Equiv.vectorEquivFin _ _).symm
instance [DecidableEq α] [Fintype α] {n : ℕ} : Fintype (Sym.Sym' α n) :=
Quotient.fintype _
instance [DecidableEq α] [Fintype α] {n : ℕ} : Fintype (Sym α n) :=
Fintype.ofEquiv _ Sym.symEquivSym'.symm |
.lake/packages/mathlib/Mathlib/Data/Fintype/Powerset.lean | import Mathlib.Data.Finset.Powerset
import Mathlib.Data.Fintype.EquivFin
/-!
# fintype instance for `Set α`, when `α` is a fintype
-/
variable {α : Type*}
open Finset
instance Finset.fintype [Fintype α] : Fintype (Finset α) :=
⟨univ.powerset, fun _ => Finset.mem_powerset.2 (Finset.subset_univ _)⟩
@[simp]
theorem Fintype.card_finset [Fintype α] : Fintype.card (Finset α) = 2 ^ Fintype.card α :=
Finset.card_powerset Finset.univ
namespace Finset
variable [Fintype α] {s : Finset α} {k : ℕ}
@[simp] lemma powerset_univ : (univ : Finset α).powerset = univ :=
coe_injective <| by simp [-coe_eq_univ]
lemma filter_subset_univ [DecidableEq α] (s : Finset α) :
({t | t ⊆ s} : Finset _) = powerset s := by ext; simp
@[simp] lemma powerset_eq_univ : s.powerset = univ ↔ s = univ := by
rw [← Finset.powerset_univ, powerset_inj]
lemma mem_powersetCard_univ : s ∈ powersetCard k (univ : Finset α) ↔ #s = k :=
mem_powersetCard.trans <| and_iff_right <| subset_univ _
variable (α)
@[simp] lemma univ_filter_card_eq (k : ℕ) :
({s | #s = k} : Finset (Finset α)) = univ.powersetCard k := by ext; simp
end Finset
@[simp]
theorem Fintype.card_finset_len [Fintype α] (k : ℕ) :
Fintype.card { s : Finset α // #s = k } = Nat.choose (Fintype.card α) k := by
simp [Fintype.subtype_card, Finset.card_univ]
instance Set.fintype [Fintype α] : Fintype (Set α) :=
⟨(@Finset.univ (Finset α) _).map coeEmb.1, fun s => by
classical
refine mem_map.2 ⟨({a | a ∈ s} : Finset _), Finset.mem_univ _, (coe_filter _ _).trans ?_⟩
simp⟩
-- Not to be confused with `Set.Finite`, the predicate
instance Set.instFinite [Finite α] : Finite (Set α) := by
cases nonempty_fintype α
infer_instance
@[simp]
theorem Fintype.card_set [Fintype α] : Fintype.card (Set α) = 2 ^ Fintype.card α :=
(Finset.card_map _).trans (Finset.card_powerset _) |
.lake/packages/mathlib/Mathlib/Data/Fintype/CardEmbedding.lean | import Mathlib.Data.Nat.Factorial.Basic
import Mathlib.Data.Fintype.BigOperators
import Mathlib.Data.Set.Finite.Range
import Mathlib.Logic.Equiv.Embedding
/-!
# Number of embeddings
This file establishes the cardinality of `α ↪ β` in full generality.
-/
local notation "|" x "|" => Finset.card x
local notation "‖" x "‖" => Fintype.card x
open Function
open Nat
namespace Fintype
theorem card_embedding_eq_of_unique {α β : Type*} [Unique α] [Fintype β] [Fintype (α ↪ β)] :
‖α ↪ β‖ = ‖β‖ :=
card_congr Equiv.uniqueEmbeddingEquivResult
-- Establishes the cardinality of the type of all injections between two finite types.
-- Porting note: `induction α using Fintype.induction_empty_option` can't work with the `Fintype α`
-- instance so instead we make an ugly refine and `dsimp` a lot.
@[simp]
theorem card_embedding_eq {α β : Type*} [Fintype α] [Fintype β] [emb : Fintype (α ↪ β)] :
‖α ↪ β‖ = ‖β‖.descFactorial ‖α‖ := by
rw [Subsingleton.elim emb Embedding.fintype]
refine Fintype.induction_empty_option (P := fun t ↦ ‖t ↪ β‖ = ‖β‖.descFactorial ‖t‖)
(fun α₁ α₂ h₂ e ih ↦ ?_) (?_) (fun γ h ih ↦ ?_) α <;> dsimp only at * <;> clear! α
· letI := Fintype.ofEquiv _ e.symm
rw [← card_congr (Equiv.embeddingCongr e (Equiv.refl β)), ih, card_congr e]
· rw [card_pempty, Nat.descFactorial_zero, card_eq_one_iff]
exact ⟨Embedding.ofIsEmpty, fun x ↦ DFunLike.ext _ _ isEmptyElim⟩
· classical
rw [card_option, Nat.descFactorial_succ, card_congr (Embedding.optionEmbeddingEquiv γ β),
card_sigma, ← ih]
simp only [Fintype.card_compl_set, Fintype.card_range, Finset.sum_const, Finset.card_univ,
Nat.nsmul_eq_mul, mul_comm]
/-- The cardinality of embeddings from an infinite type to a finite type is zero.
This is a re-statement of the pigeonhole principle. -/
theorem card_embedding_eq_of_infinite {α β : Type*} [Infinite α] [Finite β] [Fintype (α ↪ β)] :
‖α ↪ β‖ = 0 :=
card_eq_zero
end Fintype |
.lake/packages/mathlib/Mathlib/Data/Fintype/Pigeonhole.lean | import Mathlib.Data.Finset.Union
import Mathlib.Data.Fintype.EquivFin
/-!
# Pigeonhole principles in finite types
## Main declarations
We provide the following versions of the pigeonholes principle.
* `Fintype.exists_ne_map_eq_of_card_lt` and `isEmpty_of_card_lt`: Finitely many pigeons and
pigeonholes. Weak formulation.
* `Finite.exists_ne_map_eq_of_infinite`: Infinitely many pigeons in finitely many pigeonholes.
Weak formulation.
* `Finite.exists_infinite_fiber`: Infinitely many pigeons in finitely many pigeonholes. Strong
formulation.
Some more pigeonhole-like statements can be found in `Data.Fintype.CardEmbedding`.
-/
assert_not_exists MonoidWithZero MulAction
open Function
universe u v
variable {α β γ : Type*}
open Finset
namespace Fintype
variable [Fintype α] [Fintype β]
/-- The pigeonhole principle for finitely many pigeons and pigeonholes.
This is the `Fintype` version of `Finset.exists_ne_map_eq_of_card_lt_of_maps_to`.
-/
theorem exists_ne_map_eq_of_card_lt (f : α → β) (h : Fintype.card β < Fintype.card α) :
∃ x y, x ≠ y ∧ f x = f y :=
let ⟨x, _, y, _, h⟩ := Finset.exists_ne_map_eq_of_card_lt_of_maps_to h fun x _ => mem_univ (f x)
⟨x, y, h⟩
end Fintype
namespace Function.Embedding
/-- If `‖β‖ < ‖α‖` there are no embeddings `α ↪ β`.
This is a formulation of the pigeonhole principle.
Note this cannot be an instance as it needs `h`. -/
@[simp]
theorem isEmpty_of_card_lt [Fintype α] [Fintype β] (h : Fintype.card β < Fintype.card α) :
IsEmpty (α ↪ β) :=
⟨fun f =>
let ⟨_x, _y, ne, feq⟩ := Fintype.exists_ne_map_eq_of_card_lt f h
ne <| f.injective feq⟩
end Function.Embedding
/-- The pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are
infinitely many pigeons in finitely many pigeonholes, then there are at least two pigeons in the
same pigeonhole.
See also: `Fintype.exists_ne_map_eq_of_card_lt`, `Finite.exists_infinite_fiber`.
-/
theorem Finite.exists_ne_map_eq_of_infinite {α β} [Infinite α] [Finite β] (f : α → β) :
∃ x y : α, x ≠ y ∧ f x = f y := by
simpa [Injective, and_comm] using not_injective_infinite_finite f
attribute [local instance] Fintype.ofFinite in
/-- The strong pigeonhole principle for infinitely many pigeons in
finitely many pigeonholes. If there are infinitely many pigeons in
finitely many pigeonholes, then there is a pigeonhole with infinitely
many pigeons.
See also: `Finite.exists_ne_map_eq_of_infinite`
-/
theorem Finite.exists_infinite_fiber [Infinite α] [Finite β] (f : α → β) :
∃ y : β, Infinite (f ⁻¹' {y}) := by
classical
by_contra! hf
cases nonempty_fintype β
let key : Fintype α :=
{ elems := univ.biUnion fun y : β => (f ⁻¹' {y}).toFinset
complete := by simp }
exact key.false |
.lake/packages/mathlib/Mathlib/Data/Fintype/Defs.lean | import Mathlib.Data.Finset.Filter
import Mathlib.Data.Finite.Defs
/-!
# Finite types
This file defines a typeclass to state that a type is finite.
## Main declarations
* `Fintype α`: Typeclass saying that a type is finite. It takes as fields a `Finset` and a proof
that all terms of type `α` are in it.
* `Finset.univ`: The finset of all elements of a fintype.
See `Data.Fintype.Basic` for elementary results,
`Data.Fintype.Card` for the cardinality of a fintype,
the equivalence with `Fin (Fintype.card α)`, and pigeonhole principles.
## Instances
Instances for `Fintype` for
* `{x // p x}` are in this file as `Fintype.subtype`
* `Option α` are in `Data.Fintype.Option`
* `α × β` are in `Data.Fintype.Prod`
* `α ⊕ β` are in `Data.Fintype.Sum`
* `Σ (a : α), β a` are in `Data.Fintype.Sigma`
These files also contain appropriate `Infinite` instances for these types.
`Infinite` instances for `ℕ`, `ℤ`, `Multiset α`, and `List α` are in `Data.Fintype.Lattice`.
-/
assert_not_exists Monoid
open Function
open Nat
universe u v
variable {α β γ : Type*}
/-- `Fintype α` means that `α` is finite, i.e. there are only
finitely many distinct elements of type `α`. The evidence of this
is a finset `elems` (a list up to permutation without duplicates),
together with a proof that everything of type `α` is in the list. -/
class Fintype (α : Type*) where
/-- The `Finset` containing all elements of a `Fintype` -/
elems : Finset α
/-- A proof that `elems` contains every element of the type -/
complete : ∀ x : α, x ∈ elems
/-! ### Preparatory lemmas -/
namespace Finset
theorem nodup_map_iff_injOn {f : α → β} {s : Finset α} :
(Multiset.map f s.val).Nodup ↔ Set.InjOn f s := by
simp [Multiset.nodup_map_iff_inj_on s.nodup, Set.InjOn]
end Finset
namespace List
variable [DecidableEq α] {a : α} {f : α → β} {s : Finset α} {t : Set β} {t' : Finset β}
instance [DecidableEq β] : Decidable (Set.InjOn f s) :=
-- Use custom implementation for better performance.
decidable_of_iff ((Multiset.map f s.val).Nodup) Finset.nodup_map_iff_injOn
instance [DecidableEq β] : Decidable (Set.BijOn f s t') :=
inferInstanceAs (Decidable (_ ∧ _ ∧ _))
end List
namespace Finset
variable [Fintype α] {s t : Finset α}
/-- `univ` is the universal finite set of type `Finset α` implied from
the assumption `Fintype α`. -/
def univ : Finset α :=
@Fintype.elems α _
@[simp, grind ←]
theorem mem_univ (x : α) : x ∈ (univ : Finset α) :=
Fintype.complete x
theorem mem_univ_val : ∀ x, x ∈ (univ : Finset α).1 := by simp
theorem eq_univ_iff_forall : s = univ ↔ ∀ x, x ∈ s := by simp [Finset.ext_iff]
theorem eq_univ_of_forall : (∀ x, x ∈ s) → s = univ :=
eq_univ_iff_forall.2
@[simp, norm_cast]
theorem coe_univ : ↑(univ : Finset α) = (Set.univ : Set α) := by ext; simp
@[simp, norm_cast]
theorem coe_eq_univ : (s : Set α) = Set.univ ↔ s = univ := by rw [← coe_univ, coe_inj]
@[simp]
theorem subset_univ (s : Finset α) : s ⊆ univ := fun a _ => mem_univ a
theorem mem_filter_univ {p : α → Prop} [DecidablePred p] : ∀ x, x ∈ univ.filter p ↔ p x := by simp
end Finset
namespace Mathlib.Meta
open Lean Elab Term Meta Batteries.ExtendedBinder Parser.Term PrettyPrinter.Delaborator SubExpr
/-- Elaborate set builder notation for `Finset`.
* `{x | p x}` is elaborated as `Finset.filter (fun x ↦ p x) Finset.univ` if the expected type is
`Finset ?α`.
* `{x : α | p x}` is elaborated as `Finset.filter (fun x : α ↦ p x) Finset.univ` if the expected
type is `Finset ?α`.
* `{x ∉ s | p x}` is elaborated as `Finset.filter (fun x ↦ p x) sᶜ` if either the expected type is
`Finset ?α` or the expected type is not `Set ?α` and `s` has expected type `Finset ?α`.
* `{x ≠ a | p x}` is elaborated as `Finset.filter (fun x ↦ p x) {a}ᶜ` if the expected type is
`Finset ?α`.
See also
* `Data.Set.Defs` for the `Set` builder notation elaborator that this elaborator partly overrides.
* `Data.Finset.Basic` for the `Finset` builder notation elaborator partly overriding this one for
syntax of the form `{x ∈ s | p x}`.
* `Data.Fintype.Basic` for the `Finset` builder notation elaborator handling syntax of the form
`{x | p x}`, `{x : α | p x}`, `{x ∉ s | p x}`, `{x ≠ a | p x}`.
* `Order.LocallyFinite.Basic` for the `Finset` builder notation elaborator handling syntax of the
form `{x ≤ a | p x}`, `{x ≥ a | p x}`, `{x < a | p x}`, `{x > a | p x}`.
-/
@[term_elab setBuilder]
def elabFinsetBuilderSetOf : TermElab
| `({ $x:ident | $p }), expectedType? => do
-- If the expected type is not known to be `Finset ?α`, give up.
unless ← knownToBeFinsetNotSet expectedType? do throwUnsupportedSyntax
elabTerm (← `(Finset.filter (fun $x:ident ↦ $p) Finset.univ)) expectedType?
| `({ $x:ident : $t | $p }), expectedType? => do
-- If the expected type is not known to be `Finset ?α`, give up.
unless ← knownToBeFinsetNotSet expectedType? do throwUnsupportedSyntax
elabTerm (← `(Finset.filter (fun $x:ident : $t ↦ $p) Finset.univ)) expectedType?
| `({ $x:ident ∉ $s:term | $p }), expectedType? => do
-- If the expected type is known to be `Set ?α`, give up. If it is not known to be `Set ?α` or
-- `Finset ?α`, check the expected type of `s`.
unless ← knownToBeFinsetNotSet expectedType? do
let ty ← try whnfR (← inferType (← elabTerm s none)) catch _ => throwUnsupportedSyntax
-- If the expected type of `s` is not known to be `Finset ?α`, give up.
match_expr ty with
| Finset _ => pure ()
| _ => throwUnsupportedSyntax
-- Finally, we can elaborate the syntax as a finset.
-- TODO: Seems a bit wasteful to have computed the expected type but still use `expectedType?`.
elabTerm (← `(Finset.filter (fun $x:ident ↦ $p) $sᶜ)) expectedType?
| `({ $x:ident ≠ $a | $p }), expectedType? => do
-- If the expected type is not known to be `Finset ?α`, give up.
unless ← knownToBeFinsetNotSet expectedType? do throwUnsupportedSyntax
elabTerm (← `(Finset.filter (fun $x:ident ↦ $p) (singleton $a)ᶜ)) expectedType?
| _, _ => throwUnsupportedSyntax
/-- Delaborator for `Finset.filter`. The `pp.funBinderTypes` option controls whether
to show the domain type when the filter is over `Finset.univ`. -/
@[app_delab Finset.filter] def delabFinsetFilter : Delab :=
whenPPOption getPPNotation do
let #[_, p, _, t] := (← getExpr).getAppArgs | failure
guard p.isLambda
let i ← withNaryArg 1 <| withBindingBodyUnusedName (pure ⟨·⟩)
let p ← withNaryArg 1 <| withBindingBody i.getId delab
if t.isAppOfArity ``Finset.univ 2 then
if ← getPPOption getPPFunBinderTypes then
let ty ← withNaryArg 0 delab
`({$i:ident : $ty | $p})
else
`({$i:ident | $p})
-- check if `t` is of the form `s₀ᶜ`, in which case we display `x ∉ s₀` instead
else if t.isAppOfArity ``HasCompl.compl 3 then
let #[_, _, s₀] := t.getAppArgs | failure
-- if `s₀` is a singleton, we can even use the notation `x ≠ a`
if s₀.isAppOfArity ``Singleton.singleton 4 then
let t ← withNaryArg 3 <| withNaryArg 2 <| withNaryArg 3 delab
`({$i:ident ≠ $t | $p})
else
let t ← withNaryArg 3 <| withNaryArg 2 delab
`({$i:ident ∉ $t | $p})
else
let t ← withNaryArg 3 delab
`({$i:ident ∈ $t | $p})
end Mathlib.Meta
open Finset
namespace Fintype
instance decidablePiFintype {α} {β : α → Type*} [∀ a, DecidableEq (β a)] [Fintype α] :
DecidableEq (∀ a, β a) := fun f g =>
decidable_of_iff (∀ a ∈ @univ α _, f a = g a)
(by simp [funext_iff])
instance decidableForallFintype {p : α → Prop} [DecidablePred p] [Fintype α] :
Decidable (∀ a, p a) :=
decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp)
instance decidableExistsFintype {p : α → Prop} [DecidablePred p] [Fintype α] :
Decidable (∃ a, p a) :=
decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp)
instance decidableMemRangeFintype [Fintype α] [DecidableEq β] (f : α → β) :
DecidablePred (· ∈ Set.range f) := fun _ => Fintype.decidableExistsFintype
instance decidableSubsingleton [Fintype α] [DecidableEq α] {s : Set α} [DecidablePred (· ∈ s)] :
Decidable s.Subsingleton := decidable_of_iff (∀ a ∈ s, ∀ b ∈ s, a = b) Iff.rfl
section BundledHoms
instance decidableEqEquivFintype [DecidableEq β] [Fintype α] : DecidableEq (α ≃ β) := fun a b =>
decidable_of_iff (a.1 = b.1) Equiv.coe_fn_injective.eq_iff
instance decidableEqEmbeddingFintype [DecidableEq β] [Fintype α] : DecidableEq (α ↪ β) := fun a b =>
decidable_of_iff ((a : α → β) = b) Function.Embedding.coe_injective.eq_iff
end BundledHoms
theorem nodup_map_univ_iff_injective [Fintype α] {f : α → β} :
(Multiset.map f univ.val).Nodup ↔ Function.Injective f := by
rw [nodup_map_iff_injOn, coe_univ, Set.injOn_univ]
instance decidableInjectiveFintype [DecidableEq β] [Fintype α] :
DecidablePred (Injective : (α → β) → Prop) :=
-- Use custom implementation for better performance.
fun f => decidable_of_iff ((Multiset.map f univ.val).Nodup) nodup_map_univ_iff_injective
instance decidableSurjectiveFintype [DecidableEq β] [Fintype α] [Fintype β] :
DecidablePred (Surjective : (α → β) → Prop) := fun x => by unfold Surjective; infer_instance
instance decidableBijectiveFintype [DecidableEq β] [Fintype α] [Fintype β] :
DecidablePred (Bijective : (α → β) → Prop) := fun x => by unfold Bijective; infer_instance
instance decidableRightInverseFintype [DecidableEq α] [Fintype α] (f : α → β) (g : β → α) :
Decidable (Function.RightInverse f g) :=
show Decidable (∀ x, g (f x) = x) by infer_instance
instance decidableLeftInverseFintype [DecidableEq β] [Fintype β] (f : α → β) (g : β → α) :
Decidable (Function.LeftInverse f g) :=
show Decidable (∀ x, f (g x) = x) by infer_instance
instance subsingleton (α : Type*) : Subsingleton (Fintype α) :=
⟨fun ⟨s₁, h₁⟩ ⟨s₂, h₂⟩ => by congr; simp [Finset.ext_iff, h₁, h₂]⟩
instance (α : Type*) : Lean.Meta.FastSubsingleton (Fintype α) := {}
/-- Given a predicate that can be represented by a finset, the subtype
associated to the predicate is a fintype. -/
protected def subtype {p : α → Prop} (s : Finset α) (H : ∀ x : α, x ∈ s ↔ p x) :
Fintype { x // p x } :=
⟨⟨s.1.pmap Subtype.mk fun x => (H x).1, s.nodup.pmap fun _ _ _ _ => congr_arg Subtype.val⟩,
fun ⟨x, px⟩ => Multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩
/-- Construct a fintype from a finset with the same elements. -/
def ofFinset {p : Set α} (s : Finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : Fintype p :=
Fintype.subtype s H
end Fintype
instance Bool.fintype : Fintype Bool :=
⟨⟨{true, false}, by simp⟩, fun x => by cases x <;> simp⟩
instance Ordering.fintype : Fintype Ordering :=
⟨⟨{.lt, .eq, .gt}, by simp⟩, fun x => by cases x <;> simp⟩
instance OrderDual.fintype (α : Type*) [Fintype α] : Fintype αᵒᵈ :=
‹Fintype α›
instance OrderDual.finite (α : Type*) [Finite α] : Finite αᵒᵈ :=
‹Finite α›
instance Lex.fintype (α : Type*) [Fintype α] : Fintype (Lex α) :=
‹Fintype α› |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.