path stringlengths 11 71 | content stringlengths 75 124k |
|---|---|
Data\Int\Cast\Lemmas.lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Algebra.Ring.Hom.Basic
import Mathlib.Algebra.Ring.Int
/-!
# Cast of integers (additional theorems)
This file proves additional properties about the *canonical* homomorphism from
the integers into an additive group with a one (`Int.cast`),
particularly results involving algebraic homomorphisms or the order structure on `ℤ`
which were not available in the import dependencies of `Data.Int.Cast.Basic`.
## Main declarations
* `castAddHom`: `cast` bundled as an `AddMonoidHom`.
* `castRingHom`: `cast` bundled as a `RingHom`.
-/
assert_not_exists OrderedCommMonoid
open Additive Function Multiplicative Nat
variable {F ι α β : Type*}
namespace Int
/-- Coercion `ℕ → ℤ` as a `RingHom`. -/
def ofNatHom : ℕ →+* ℤ :=
Nat.castRingHom ℤ
section cast
@[simp, norm_cast]
theorem cast_ite [AddGroupWithOne α] (P : Prop) [Decidable P] (m n : ℤ) :
((ite P m n : ℤ) : α) = ite P (m : α) (n : α) :=
apply_ite _ _ _ _
/-- `coe : ℤ → α` as an `AddMonoidHom`. -/
def castAddHom (α : Type*) [AddGroupWithOne α] : ℤ →+ α where
toFun := Int.cast
map_zero' := cast_zero
map_add' := cast_add
section AddGroupWithOne
variable [AddGroupWithOne α]
@[simp] lemma coe_castAddHom : ⇑(castAddHom α) = fun x : ℤ => (x : α) := rfl
lemma _root_.Even.intCast {n : ℤ} (h : Even n) : Even (n : α) := h.map (castAddHom α)
variable [CharZero α] {m n : ℤ}
@[simp] lemma cast_eq_zero : (n : α) = 0 ↔ n = 0 where
mp h := by
cases n
· erw [Int.cast_natCast] at h
exact congr_arg _ (Nat.cast_eq_zero.1 h)
· rw [cast_negSucc, neg_eq_zero, Nat.cast_eq_zero] at h
contradiction
mpr h := by rw [h, cast_zero]
@[simp, norm_cast]
lemma cast_inj : (m : α) = n ↔ m = n := by rw [← sub_eq_zero, ← cast_sub, cast_eq_zero, sub_eq_zero]
lemma cast_injective : Injective (Int.cast : ℤ → α) := fun _ _ ↦ cast_inj.1
lemma cast_ne_zero : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero
@[simp] lemma cast_eq_one : (n : α) = 1 ↔ n = 1 := by rw [← cast_one, cast_inj]
lemma cast_ne_one : (n : α) ≠ 1 ↔ n ≠ 1 := cast_eq_one.not
end AddGroupWithOne
section NonAssocRing
variable [NonAssocRing α] {a b : α} {n : ℤ}
variable (α) in
/-- `coe : ℤ → α` as a `RingHom`. -/
def castRingHom : ℤ →+* α where
toFun := Int.cast
map_zero' := cast_zero
map_add' := cast_add
map_one' := cast_one
map_mul' := cast_mul
@[simp] lemma coe_castRingHom : ⇑(castRingHom α) = fun x : ℤ ↦ (x : α) := rfl
lemma cast_commute : ∀ (n : ℤ) (a : α), Commute ↑n a
| (n : ℕ), x => by simpa using n.cast_commute x
| -[n+1], x => by
simpa only [cast_negSucc, Commute.neg_left_iff, Commute.neg_right_iff] using
(n + 1).cast_commute (-x)
lemma cast_comm (n : ℤ) (x : α) : n * x = x * n := (cast_commute ..).eq
lemma commute_cast (a : α) (n : ℤ) : Commute a n := (cast_commute ..).symm
@[simp] lemma _root_.zsmul_eq_mul (a : α) : ∀ n : ℤ, n • a = n * a
| (n : ℕ) => by rw [natCast_zsmul, nsmul_eq_mul, Int.cast_natCast]
| -[n+1] => by simp [Nat.cast_succ, neg_add_rev, Int.cast_negSucc, add_mul]
lemma _root_.zsmul_eq_mul' (a : α) (n : ℤ) : n • a = a * n := by
rw [zsmul_eq_mul, (n.cast_commute a).eq]
end NonAssocRing
section Ring
variable [Ring α] {n : ℤ}
lemma _root_.Odd.intCast (hn : Odd n) : Odd (n : α) := hn.map (castRingHom α)
end Ring
theorem cast_dvd_cast [CommRing α] (m n : ℤ) (h : m ∣ n) : (m : α) ∣ (n : α) :=
RingHom.map_dvd (Int.castRingHom α) h
@[deprecated (since := "2024-05-25")] alias coe_int_dvd := cast_dvd_cast
end cast
end Int
open Int
namespace SemiconjBy
variable [Ring α] {a x y : α}
@[simp] lemma intCast_mul_right (h : SemiconjBy a x y) (n : ℤ) : SemiconjBy a (n * x) (n * y) :=
SemiconjBy.mul_right (Int.commute_cast _ _) h
@[simp] lemma intCast_mul_left (h : SemiconjBy a x y) (n : ℤ) : SemiconjBy (n * a) x y :=
SemiconjBy.mul_left (Int.cast_commute _ _) h
@[simp] lemma intCast_mul_intCast_mul (h : SemiconjBy a x y) (m n : ℤ) :
SemiconjBy (m * a) (n * x) (n * y) := (h.intCast_mul_left m).intCast_mul_right n
@[deprecated (since := "2024-05-27")] alias cast_int_mul_right := intCast_mul_right
@[deprecated (since := "2024-05-27")] alias cast_int_mul_left := intCast_mul_left
@[deprecated (since := "2024-05-27")] alias cast_int_mul_cast_int_mul := intCast_mul_intCast_mul
end SemiconjBy
namespace Commute
section NonAssocRing
variable [NonAssocRing α] {a b : α} {n : ℤ}
@[simp] lemma intCast_left : Commute (n : α) a := Int.cast_commute _ _
@[simp] lemma intCast_right : Commute a n := Int.commute_cast _ _
@[deprecated (since := "2024-05-27")] alias cast_int_right := intCast_right
@[deprecated (since := "2024-05-27")] alias cast_int_left := intCast_left
end NonAssocRing
section Ring
variable [Ring α] {a b : α} {n : ℤ}
@[simp] lemma intCast_mul_right (h : Commute a b) (m : ℤ) : Commute a (m * b) :=
SemiconjBy.intCast_mul_right h m
@[simp] lemma intCast_mul_left (h : Commute a b) (m : ℤ) : Commute (m * a) b :=
SemiconjBy.intCast_mul_left h m
lemma intCast_mul_intCast_mul (h : Commute a b) (m n : ℤ) : Commute (m * a) (n * b) :=
SemiconjBy.intCast_mul_intCast_mul h m n
variable (a) (m n : ℤ)
/- Porting note (#10618): `simp` attribute removed as linter reports:
simp can prove this:
by simp only [Commute.cast_int_right, Commute.refl, Commute.mul_right]
-/
-- @[simp]
lemma self_intCast_mul : Commute a (n * a : α) := (Commute.refl a).intCast_mul_right n
/- Porting note (#10618): `simp` attribute removed as linter reports:
simp can prove this:
by simp only [Commute.cast_int_left, Commute.refl, Commute.mul_left]
-/
-- @[simp]
lemma intCast_mul_self : Commute ((n : α) * a) a := (Commute.refl a).intCast_mul_left n
lemma self_intCast_mul_intCast_mul : Commute (m * a : α) (n * a : α) :=
(Commute.refl a).intCast_mul_intCast_mul m n
@[deprecated (since := "2024-05-27")] alias cast_int_mul_right := intCast_mul_right
@[deprecated (since := "2024-05-27")] alias cast_int_mul_left := intCast_mul_left
@[deprecated (since := "2024-05-27")] alias cast_int_mul_cast_int_mul := intCast_mul_intCast_mul
@[deprecated (since := "2024-05-27")] alias self_cast_int_mul := self_intCast_mul
@[deprecated (since := "2024-05-27")] alias cast_int_mul_self := intCast_mul_self
@[deprecated (since := "2024-05-27")]
alias self_cast_int_mul_cast_int_mul := self_intCast_mul_intCast_mul
end Ring
end Commute
namespace AddMonoidHom
variable {A : Type*}
/-- Two additive monoid homomorphisms `f`, `g` from `ℤ` to an additive monoid are equal
if `f 1 = g 1`. -/
@[ext high]
theorem ext_int [AddMonoid A] {f g : ℤ →+ A} (h1 : f 1 = g 1) : f = g :=
have : f.comp (Int.ofNatHom : ℕ →+ ℤ) = g.comp (Int.ofNatHom : ℕ →+ ℤ) := ext_nat' _ _ h1
have this' : ∀ n : ℕ, f n = g n := DFunLike.ext_iff.1 this
ext fun n => match n with
| (n : ℕ) => this' n
| .negSucc n => eq_on_neg _ _ (this' <| n + 1)
variable [AddGroupWithOne A]
theorem eq_intCastAddHom (f : ℤ →+ A) (h1 : f 1 = 1) : f = Int.castAddHom A :=
ext_int <| by simp [h1]
@[deprecated (since := "2024-04-17")]
alias eq_int_castAddHom := eq_intCastAddHom
end AddMonoidHom
theorem eq_intCast' [AddGroupWithOne α] [FunLike F ℤ α] [AddMonoidHomClass F ℤ α]
(f : F) (h₁ : f 1 = 1) :
∀ n : ℤ, f n = n :=
DFunLike.ext_iff.1 <| (f : ℤ →+ α).eq_intCastAddHom h₁
@[simp] lemma zsmul_one [AddGroupWithOne α] (n : ℤ) : n • (1 : α) = n := by cases n <;> simp
@[simp]
theorem Int.castAddHom_int : Int.castAddHom ℤ = AddMonoidHom.id ℤ :=
((AddMonoidHom.id ℤ).eq_intCastAddHom rfl).symm
namespace MonoidHom
variable {M : Type*} [Monoid M]
open Multiplicative
@[ext]
theorem ext_mint {f g : Multiplicative ℤ →* M} (h1 : f (ofAdd 1) = g (ofAdd 1)) : f = g :=
MonoidHom.toAdditive''.injective <| AddMonoidHom.ext_int <| Additive.toMul.injective h1
/-- If two `MonoidHom`s agree on `-1` and the naturals then they are equal. -/
@[ext]
theorem ext_int {f g : ℤ →* M} (h_neg_one : f (-1) = g (-1))
(h_nat : f.comp Int.ofNatHom.toMonoidHom = g.comp Int.ofNatHom.toMonoidHom) : f = g := by
ext (x | x)
· exact (DFunLike.congr_fun h_nat x : _)
· rw [Int.negSucc_eq, ← neg_one_mul, f.map_mul, g.map_mul]
congr 1
exact mod_cast (DFunLike.congr_fun h_nat (x + 1) : _)
end MonoidHom
namespace MonoidWithZeroHom
variable {M : Type*} [MonoidWithZero M]
/-- If two `MonoidWithZeroHom`s agree on `-1` and the naturals then they are equal. -/
@[ext]
theorem ext_int {f g : ℤ →*₀ M} (h_neg_one : f (-1) = g (-1))
(h_nat : f.comp Int.ofNatHom.toMonoidWithZeroHom = g.comp Int.ofNatHom.toMonoidWithZeroHom) :
f = g :=
toMonoidHom_injective <| MonoidHom.ext_int h_neg_one <|
MonoidHom.ext (DFunLike.congr_fun h_nat : _)
end MonoidWithZeroHom
/-- If two `MonoidWithZeroHom`s agree on `-1` and the _positive_ naturals then they are equal. -/
theorem ext_int' [MonoidWithZero α] [FunLike F ℤ α] [MonoidWithZeroHomClass F ℤ α] {f g : F}
(h_neg_one : f (-1) = g (-1)) (h_pos : ∀ n : ℕ, 0 < n → f n = g n) : f = g :=
(DFunLike.ext _ _) fun n =>
haveI :=
DFunLike.congr_fun
(@MonoidWithZeroHom.ext_int _ _ (f : ℤ →*₀ α) (g : ℤ →*₀ α) h_neg_one <|
MonoidWithZeroHom.ext_nat (h_pos _))
n
this
section Group
variable (α) [Group α] (β) [AddGroup β]
/-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/
def zmultiplesHom : β ≃ (ℤ →+ β) where
toFun x :=
{ toFun := fun n => n • x
map_zero' := zero_zsmul x
map_add' := fun _ _ => add_zsmul _ _ _ }
invFun f := f 1
left_inv := one_zsmul
right_inv f := AddMonoidHom.ext_int <| one_zsmul (f 1)
/-- Monoid homomorphisms from `Multiplicative ℤ` are defined by the image
of `Multiplicative.ofAdd 1`. -/
@[to_additive existing]
def zpowersHom : α ≃ (Multiplicative ℤ →* α) :=
ofMul.trans <| (zmultiplesHom _).trans <| AddMonoidHom.toMultiplicative''
lemma zmultiplesHom_apply (x : β) (n : ℤ) : zmultiplesHom β x n = n • x := rfl
lemma zmultiplesHom_symm_apply (f : ℤ →+ β) : (zmultiplesHom β).symm f = f 1 := rfl
@[to_additive existing (attr := simp)]
lemma zpowersHom_apply (x : α) (n : Multiplicative ℤ) : zpowersHom α x n = x ^ toAdd n := rfl
@[to_additive existing (attr := simp)]
lemma zpowersHom_symm_apply (f : Multiplicative ℤ →* α) :
(zpowersHom α).symm f = f (ofAdd 1) := rfl
lemma MonoidHom.apply_mint (f : Multiplicative ℤ →* α) (n : Multiplicative ℤ) :
f n = f (ofAdd 1) ^ (toAdd n) := by
rw [← zpowersHom_symm_apply, ← zpowersHom_apply, Equiv.apply_symm_apply]
lemma AddMonoidHom.apply_int (f : ℤ →+ β) (n : ℤ) : f n = n • f 1 := by
rw [← zmultiplesHom_symm_apply, ← zmultiplesHom_apply, Equiv.apply_symm_apply]
end Group
section CommGroup
variable (α) [CommGroup α] (β) [AddCommGroup β]
/-- If `α` is commutative, `zmultiplesHom` is an additive equivalence. -/
def zmultiplesAddHom : β ≃+ (ℤ →+ β) :=
{ zmultiplesHom β with map_add' := fun a b => AddMonoidHom.ext fun n => by simp [zsmul_add] }
/-- If `α` is commutative, `zpowersHom` is a multiplicative equivalence. -/
def zpowersMulHom : α ≃* (Multiplicative ℤ →* α) :=
{ zpowersHom α with map_mul' := fun a b => MonoidHom.ext fun n => by simp [mul_zpow] }
variable {α}
@[simp]
lemma zpowersMulHom_apply (x : α) (n : Multiplicative ℤ) : zpowersMulHom α x n = x ^ toAdd n := rfl
@[simp]
lemma zpowersMulHom_symm_apply (f : Multiplicative ℤ →* α) :
(zpowersMulHom α).symm f = f (ofAdd 1) := rfl
@[simp] lemma zmultiplesAddHom_apply (x : β) (n : ℤ) : zmultiplesAddHom β x n = n • x := rfl
@[simp] lemma zmultiplesAddHom_symm_apply (f : ℤ →+ β) : (zmultiplesAddHom β).symm f = f 1 := rfl
end CommGroup
section NonAssocRing
variable [NonAssocRing α] [NonAssocRing β]
@[simp]
theorem eq_intCast [FunLike F ℤ α] [RingHomClass F ℤ α] (f : F) (n : ℤ) : f n = n :=
eq_intCast' f (map_one _) n
@[simp]
theorem map_intCast [FunLike F α β] [RingHomClass F α β] (f : F) (n : ℤ) : f n = n :=
eq_intCast ((f : α →+* β).comp (Int.castRingHom α)) n
namespace RingHom
theorem eq_intCast' (f : ℤ →+* α) : f = Int.castRingHom α :=
RingHom.ext <| eq_intCast f
theorem ext_int {R : Type*} [NonAssocSemiring R] (f g : ℤ →+* R) : f = g :=
coe_addMonoidHom_injective <| AddMonoidHom.ext_int <| f.map_one.trans g.map_one.symm
instance Int.subsingleton_ringHom {R : Type*} [NonAssocSemiring R] : Subsingleton (ℤ →+* R) :=
⟨RingHom.ext_int⟩
end RingHom
end NonAssocRing
@[simp]
theorem Int.castRingHom_int : Int.castRingHom ℤ = RingHom.id ℤ :=
(RingHom.id ℤ).eq_intCast'.symm
namespace Pi
variable {π : ι → Type*} [∀ i, IntCast (π i)]
instance instIntCast : IntCast (∀ i, π i) where intCast n _ := n
theorem intCast_apply (n : ℤ) (i : ι) : (n : ∀ i, π i) i = n :=
rfl
@[simp]
theorem intCast_def (n : ℤ) : (n : ∀ i, π i) = fun _ => ↑n :=
rfl
@[deprecated (since := "2024-04-05")] alias int_apply := intCast_apply
@[deprecated (since := "2024-04-05")] alias coe_int := intCast_def
end Pi
theorem Sum.elim_intCast_intCast {α β γ : Type*} [IntCast γ] (n : ℤ) :
Sum.elim (n : α → γ) (n : β → γ) = n :=
Sum.elim_lam_const_lam_const (γ := γ) n
|
Data\Int\Cast\Prod.lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.Nat.Cast.Prod
/-!
# The product of two `AddGroupWithOne`s.
-/
namespace Prod
variable {α β : Type*} [AddGroupWithOne α] [AddGroupWithOne β]
instance : AddGroupWithOne (α × β) :=
{ Prod.instAddMonoidWithOne, Prod.instAddGroup with
intCast := fun n => (n, n)
intCast_ofNat := fun _ => by ext <;> simp
intCast_negSucc := fun _ => by ext <;> simp }
@[simp]
theorem fst_intCast (n : ℤ) : (n : α × β).fst = n :=
rfl
@[simp]
theorem snd_intCast (n : ℤ) : (n : α × β).snd = n :=
rfl
end Prod
|
Data\Int\Order\Lemmas.lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import Mathlib.Algebra.Order.Ring.Abs
/-!
# Further lemmas about the integers
The distinction between this file and `Data.Int.Order.Basic` is not particularly clear.
They are separated by now to minimize the porting requirements for tactics during the transition to
mathlib4. Please feel free to reorganize these two files.
-/
open Function Nat
namespace Int
/-! ### nat abs -/
variable {a b : ℤ} {n : ℕ}
theorem natAbs_eq_iff_mul_self_eq {a b : ℤ} : a.natAbs = b.natAbs ↔ a * a = b * b := by
rw [← abs_eq_iff_mul_self_eq, abs_eq_natAbs, abs_eq_natAbs]
exact Int.natCast_inj.symm
theorem natAbs_lt_iff_mul_self_lt {a b : ℤ} : a.natAbs < b.natAbs ↔ a * a < b * b := by
rw [← abs_lt_iff_mul_self_lt, abs_eq_natAbs, abs_eq_natAbs]
exact Int.ofNat_lt.symm
theorem natAbs_le_iff_mul_self_le {a b : ℤ} : a.natAbs ≤ b.natAbs ↔ a * a ≤ b * b := by
rw [← abs_le_iff_mul_self_le, abs_eq_natAbs, abs_eq_natAbs]
exact Int.ofNat_le.symm
/-! ### units -/
theorem eq_zero_of_abs_lt_dvd {m x : ℤ} (h1 : m ∣ x) (h2 : |x| < m) : x = 0 := by
obtain rfl | hm := eq_or_ne m 0
· exact Int.zero_dvd.1 h1
rcases h1 with ⟨d, rfl⟩
apply mul_eq_zero_of_right
rw [← abs_lt_one_iff, ← mul_lt_iff_lt_one_right (abs_pos.mpr hm), ← abs_mul]
exact lt_of_lt_of_le h2 (le_abs_self m)
end Int
|
Data\Int\Order\Units.lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import Mathlib.Algebra.Order.Ring.Abs
/-!
# Lemmas about units in `ℤ`, which interact with the order structure.
-/
namespace Int
theorem isUnit_iff_abs_eq {x : ℤ} : IsUnit x ↔ abs x = 1 := by
rw [isUnit_iff_natAbs_eq, abs_eq_natAbs, ← Int.ofNat_one, natCast_inj]
theorem isUnit_sq {a : ℤ} (ha : IsUnit a) : a ^ 2 = 1 := by rw [sq, isUnit_mul_self ha]
@[simp]
theorem units_sq (u : ℤˣ) : u ^ 2 = 1 := by
rw [Units.ext_iff, Units.val_pow_eq_pow_val, Units.val_one, isUnit_sq u.isUnit]
alias units_pow_two := units_sq
@[simp]
theorem units_mul_self (u : ℤˣ) : u * u = 1 := by rw [← sq, units_sq]
@[simp]
theorem units_inv_eq_self (u : ℤˣ) : u⁻¹ = u := by rw [inv_eq_iff_mul_eq_one, units_mul_self]
theorem units_div_eq_mul (u₁ u₂ : ℤˣ) : u₁ / u₂ = u₁ * u₂ := by
rw [div_eq_mul_inv, units_inv_eq_self]
-- `Units.val_mul` is a "wrong turn" for the simplifier, this undoes it and simplifies further
@[simp]
theorem units_coe_mul_self (u : ℤˣ) : (u * u : ℤ) = 1 := by
rw [← Units.val_mul, units_mul_self, Units.val_one]
theorem neg_one_pow_ne_zero {n : ℕ} : (-1 : ℤ) ^ n ≠ 0 := by simp
theorem sq_eq_one_of_sq_lt_four {x : ℤ} (h1 : x ^ 2 < 4) (h2 : x ≠ 0) : x ^ 2 = 1 :=
sq_eq_one_iff.mpr
((abs_eq (zero_le_one' ℤ)).mp
(le_antisymm (lt_add_one_iff.mp (abs_lt_of_sq_lt_sq h1 zero_le_two))
(sub_one_lt_iff.mp (abs_pos.mpr h2))))
theorem sq_eq_one_of_sq_le_three {x : ℤ} (h1 : x ^ 2 ≤ 3) (h2 : x ≠ 0) : x ^ 2 = 1 :=
sq_eq_one_of_sq_lt_four (lt_of_le_of_lt h1 (lt_add_one (3 : ℤ))) h2
theorem units_pow_eq_pow_mod_two (u : ℤˣ) (n : ℕ) : u ^ n = u ^ (n % 2) := by
conv =>
lhs
rw [← Nat.mod_add_div n 2]
rw [pow_add, pow_mul, units_sq, one_pow, mul_one]
end Int
|
Data\LazyList\Basic.lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import Mathlib.Control.Traversable.Equiv
import Mathlib.Control.Traversable.Instances
import Batteries.Data.LazyList
import Mathlib.Lean.Thunk
/-!
## Definitions on lazy lists
This file is entirely deprecated, and contains various definitions and proofs on lazy lists.
-/
-- The whole file is full of deprecations about LazyList
set_option linter.deprecated false
universe u
namespace LazyList
open Function
/-- Isomorphism between strict and lazy lists. -/
@[deprecated (since := "2024-07-22")]
def listEquivLazyList (α : Type*) : List α ≃ LazyList α where
toFun := LazyList.ofList
invFun := LazyList.toList
right_inv := by
intro xs
induction xs using toList.induct
· simp [toList, ofList]
· simp [toList, ofList, *]; rfl
left_inv := by
intro xs
induction xs
· simp [toList, ofList]
· simpa [ofList, toList]
@[deprecated (since := "2024-07-22")]
instance : Traversable LazyList where
map := @LazyList.traverse Id _
traverse := @LazyList.traverse
@[deprecated (since := "2024-07-22")]
instance : LawfulTraversable LazyList := by
apply Equiv.isLawfulTraversable' listEquivLazyList <;> intros <;> ext <;> rename_i f xs
· induction' xs using LazyList.rec with _ _ _ _ ih
· simp only [Functor.map, LazyList.traverse, pure, Equiv.map, listEquivLazyList,
Equiv.coe_fn_symm_mk, toList, Equiv.coe_fn_mk, ofList]
· simpa only [Equiv.map, Functor.map, listEquivLazyList, Equiv.coe_fn_symm_mk, Equiv.coe_fn_mk,
LazyList.traverse, Seq.seq, toList, ofList, cons.injEq, true_and]
· ext; apply ih
· simp only [Equiv.map, listEquivLazyList, Equiv.coe_fn_symm_mk, Equiv.coe_fn_mk, comp,
Functor.mapConst]
induction' xs using LazyList.rec with _ _ _ _ ih
· simp only [LazyList.traverse, pure, Functor.map, toList, ofList]
· simpa only [toList, ofList, LazyList.traverse, Seq.seq, Functor.map, cons.injEq, true_and]
· congr; apply ih
· simp only [traverse, Equiv.traverse, listEquivLazyList, Equiv.coe_fn_mk, Equiv.coe_fn_symm_mk]
induction' xs using LazyList.rec with _ tl ih _ ih
· simp only [LazyList.traverse, toList, List.traverse, map_pure, ofList]
· replace ih : tl.get.traverse f = ofList <$> tl.get.toList.traverse f := ih
simp [traverse.eq_2, ih, Functor.map_map, seq_map_assoc, toList, List.traverse, map_seq,
Function.comp, Thunk.pure, ofList]
· apply ih
@[deprecated (since := "2024-07-22"), simp]
theorem bind_singleton {α} (x : LazyList α) : x.bind singleton = x := by
induction x using LazyList.rec (motive_2 := fun xs => xs.get.bind singleton = xs.get) with
| nil => simp [LazyList.bind]
| cons h t ih =>
simp only [LazyList.bind, singleton, append, Thunk.get_pure, Thunk.get_mk, cons.injEq, true_and]
ext
simp [ih]
| mk f ih => simp_all
@[deprecated (since := "2024-07-22")]
instance : LawfulMonad LazyList := LawfulMonad.mk'
(id_map := by
intro α xs
induction xs using LazyList.rec (motive_2 := fun xs => id <$> xs.get = xs) with
| nil => simp only [Functor.map, comp_id, LazyList.bind]
| cons h t _ => simp only [Functor.map, comp_id, bind_singleton]
| mk f _ => ext; simp_all)
(pure_bind := by
intros
simp only [bind, pure, singleton, LazyList.bind, append, Thunk.pure, Thunk.get]
apply append_nil)
(bind_assoc := by
intro _ _ _ xs _ _
induction' xs using LazyList.rec with _ _ _ _ ih
· simp only [bind, LazyList.bind]
· simp only [bind, LazyList.bind, append_bind]; congr
· congr; funext; apply ih)
(bind_pure_comp := by
intro _ _ f xs
simp only [bind, Functor.map, pure, singleton]
induction xs using LazyList.traverse.induct (m := @Id) (f := f) with
| case1 =>
simp only [Thunk.pure, LazyList.bind, LazyList.traverse, Id.pure_eq]
| case2 _ _ ih =>
simp only [Thunk.pure, LazyList.bind, append, Thunk.get_mk, comp_apply, ← ih]
simp only [Thunk.get, append, singleton, Thunk.pure])
end LazyList
|
Data\List\AList.lean | /-
Copyright (c) 2018 Sean Leather. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sean Leather, Mario Carneiro
-/
import Mathlib.Data.List.Sigma
/-!
# Association Lists
This file defines association lists. An association list is a list where every element consists of
a key and a value, and no two entries have the same key. The type of the value is allowed to be
dependent on the type of the key.
This type dependence is implemented using `Sigma`: The elements of the list are of type `Sigma β`,
for some type index `β`.
## Main definitions
Association lists are represented by the `AList` structure. This file defines this structure and
provides ways to access, modify, and combine `AList`s.
* `AList.keys` returns a list of keys of the alist.
* `AList.membership` returns membership in the set of keys.
* `AList.erase` removes a certain key.
* `AList.insert` adds a key-value mapping to the list.
* `AList.union` combines two association lists.
## References
* <https://en.wikipedia.org/wiki/Association_list>
-/
universe u v w
open List
variable {α : Type u} {β : α → Type v}
/-- `AList β` is a key-value map stored as a `List` (i.e. a linked list).
It is a wrapper around certain `List` functions with the added constraint
that the list have unique keys. -/
structure AList (β : α → Type v) : Type max u v where
/-- The underlying `List` of an `AList` -/
entries : List (Sigma β)
/-- There are no duplicate keys in `entries` -/
nodupKeys : entries.NodupKeys
/-- Given `l : List (Sigma β)`, create a term of type `AList β` by removing
entries with duplicate keys. -/
def List.toAList [DecidableEq α] {β : α → Type v} (l : List (Sigma β)) : AList β where
entries := _
nodupKeys := nodupKeys_dedupKeys l
namespace AList
@[ext]
theorem ext : ∀ {s t : AList β}, s.entries = t.entries → s = t
| ⟨l₁, h₁⟩, ⟨l₂, _⟩, H => by congr
instance [DecidableEq α] [∀ a, DecidableEq (β a)] : DecidableEq (AList β) := fun xs ys => by
rw [AList.ext_iff]; infer_instance
/-! ### keys -/
/-- The list of keys of an association list. -/
def keys (s : AList β) : List α :=
s.entries.keys
theorem keys_nodup (s : AList β) : s.keys.Nodup :=
s.nodupKeys
/-! ### mem -/
/-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/
instance : Membership α (AList β) :=
⟨fun a s => a ∈ s.keys⟩
theorem mem_keys {a : α} {s : AList β} : a ∈ s ↔ a ∈ s.keys :=
Iff.rfl
theorem mem_of_perm {a : α} {s₁ s₂ : AList β} (p : s₁.entries ~ s₂.entries) : a ∈ s₁ ↔ a ∈ s₂ :=
(p.map Sigma.fst).mem_iff
/-! ### empty -/
/-- The empty association list. -/
instance : EmptyCollection (AList β) :=
⟨⟨[], nodupKeys_nil⟩⟩
instance : Inhabited (AList β) :=
⟨∅⟩
@[simp]
theorem not_mem_empty (a : α) : a ∉ (∅ : AList β) :=
not_mem_nil a
@[simp]
theorem empty_entries : (∅ : AList β).entries = [] :=
rfl
@[simp]
theorem keys_empty : (∅ : AList β).keys = [] :=
rfl
/-! ### singleton -/
/-- The singleton association list. -/
def singleton (a : α) (b : β a) : AList β :=
⟨[⟨a, b⟩], nodupKeys_singleton _⟩
@[simp]
theorem singleton_entries (a : α) (b : β a) : (singleton a b).entries = [Sigma.mk a b] :=
rfl
@[simp]
theorem keys_singleton (a : α) (b : β a) : (singleton a b).keys = [a] :=
rfl
/-! ### lookup -/
section
variable [DecidableEq α]
/-- Look up the value associated to a key in an association list. -/
def lookup (a : α) (s : AList β) : Option (β a) :=
s.entries.dlookup a
@[simp]
theorem lookup_empty (a) : lookup a (∅ : AList β) = none :=
rfl
theorem lookup_isSome {a : α} {s : AList β} : (s.lookup a).isSome ↔ a ∈ s :=
dlookup_isSome
theorem lookup_eq_none {a : α} {s : AList β} : lookup a s = none ↔ a ∉ s :=
dlookup_eq_none
theorem mem_lookup_iff {a : α} {b : β a} {s : AList β} :
b ∈ lookup a s ↔ Sigma.mk a b ∈ s.entries :=
mem_dlookup_iff s.nodupKeys
theorem perm_lookup {a : α} {s₁ s₂ : AList β} (p : s₁.entries ~ s₂.entries) :
s₁.lookup a = s₂.lookup a :=
perm_dlookup _ s₁.nodupKeys s₂.nodupKeys p
instance (a : α) (s : AList β) : Decidable (a ∈ s) :=
decidable_of_iff _ lookup_isSome
end
theorem keys_subset_keys_of_entries_subset_entries
{s₁ s₂ : AList β} (h : s₁.entries ⊆ s₂.entries) : s₁.keys ⊆ s₂.keys := by
intro k hk
letI : DecidableEq α := Classical.decEq α
have := h (mem_lookup_iff.1 (Option.get_mem (lookup_isSome.2 hk)))
rw [← mem_lookup_iff, Option.mem_def] at this
rw [← mem_keys, ← lookup_isSome, this]
exact Option.isSome_some
/-! ### replace -/
section
variable [DecidableEq α]
/-- Replace a key with a given value in an association list.
If the key is not present it does nothing. -/
def replace (a : α) (b : β a) (s : AList β) : AList β :=
⟨kreplace a b s.entries, (kreplace_nodupKeys a b).2 s.nodupKeys⟩
@[simp]
theorem keys_replace (a : α) (b : β a) (s : AList β) : (replace a b s).keys = s.keys :=
keys_kreplace _ _ _
@[simp]
theorem mem_replace {a a' : α} {b : β a} {s : AList β} : a' ∈ replace a b s ↔ a' ∈ s := by
rw [mem_keys, keys_replace, ← mem_keys]
theorem perm_replace {a : α} {b : β a} {s₁ s₂ : AList β} :
s₁.entries ~ s₂.entries → (replace a b s₁).entries ~ (replace a b s₂).entries :=
Perm.kreplace s₁.nodupKeys
end
/-- Fold a function over the key-value pairs in the map. -/
def foldl {δ : Type w} (f : δ → ∀ a, β a → δ) (d : δ) (m : AList β) : δ :=
m.entries.foldl (fun r a => f r a.1 a.2) d
/-! ### erase -/
section
variable [DecidableEq α]
/-- Erase a key from the map. If the key is not present, do nothing. -/
def erase (a : α) (s : AList β) : AList β :=
⟨s.entries.kerase a, s.nodupKeys.kerase a⟩
@[simp]
theorem keys_erase (a : α) (s : AList β) : (erase a s).keys = s.keys.erase a :=
keys_kerase
@[simp]
theorem mem_erase {a a' : α} {s : AList β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s := by
rw [mem_keys, keys_erase, s.keys_nodup.mem_erase_iff, ← mem_keys]
theorem perm_erase {a : α} {s₁ s₂ : AList β} :
s₁.entries ~ s₂.entries → (erase a s₁).entries ~ (erase a s₂).entries :=
Perm.kerase s₁.nodupKeys
@[simp]
theorem lookup_erase (a) (s : AList β) : lookup a (erase a s) = none :=
dlookup_kerase a s.nodupKeys
@[simp]
theorem lookup_erase_ne {a a'} {s : AList β} (h : a ≠ a') : lookup a (erase a' s) = lookup a s :=
dlookup_kerase_ne h
theorem erase_erase (a a' : α) (s : AList β) : (s.erase a).erase a' = (s.erase a').erase a :=
ext <| kerase_kerase
/-! ### insert -/
/-- Insert a key-value pair into an association list and erase any existing pair
with the same key. -/
def insert (a : α) (b : β a) (s : AList β) : AList β :=
⟨kinsert a b s.entries, kinsert_nodupKeys a b s.nodupKeys⟩
@[simp]
theorem insert_entries {a} {b : β a} {s : AList β} :
(insert a b s).entries = Sigma.mk a b :: kerase a s.entries :=
rfl
theorem insert_entries_of_neg {a} {b : β a} {s : AList β} (h : a ∉ s) :
(insert a b s).entries = ⟨a, b⟩ :: s.entries := by rw [insert_entries, kerase_of_not_mem_keys h]
-- Todo: rename to `insert_of_not_mem`.
theorem insert_of_neg {a} {b : β a} {s : AList β} (h : a ∉ s) :
insert a b s = ⟨⟨a, b⟩ :: s.entries, nodupKeys_cons.2 ⟨h, s.2⟩⟩ :=
ext <| insert_entries_of_neg h
@[simp]
theorem insert_empty (a) (b : β a) : insert a b ∅ = singleton a b :=
rfl
@[simp]
theorem mem_insert {a a'} {b' : β a'} (s : AList β) : a ∈ insert a' b' s ↔ a = a' ∨ a ∈ s :=
mem_keys_kinsert
@[simp]
theorem keys_insert {a} {b : β a} (s : AList β) : (insert a b s).keys = a :: s.keys.erase a := by
simp [insert, keys, keys_kerase]
theorem perm_insert {a} {b : β a} {s₁ s₂ : AList β} (p : s₁.entries ~ s₂.entries) :
(insert a b s₁).entries ~ (insert a b s₂).entries := by
simp only [insert_entries]; exact p.kinsert s₁.nodupKeys
@[simp]
theorem lookup_insert {a} {b : β a} (s : AList β) : lookup a (insert a b s) = some b := by
simp only [lookup, insert, dlookup_kinsert]
@[simp]
theorem lookup_insert_ne {a a'} {b' : β a'} {s : AList β} (h : a ≠ a') :
lookup a (insert a' b' s) = lookup a s :=
dlookup_kinsert_ne h
@[simp] theorem lookup_insert_eq_none {l : AList β} {k k' : α} {v : β k} :
(l.insert k v).lookup k' = none ↔ (k' ≠ k) ∧ l.lookup k' = none := by
by_cases h : k' = k
· subst h; simp
· simp_all [lookup_insert_ne h]
@[simp]
theorem lookup_to_alist {a} (s : List (Sigma β)) : lookup a s.toAList = s.dlookup a := by
rw [List.toAList, lookup, dlookup_dedupKeys]
@[simp]
theorem insert_insert {a} {b b' : β a} (s : AList β) :
(s.insert a b).insert a b' = s.insert a b' := by
ext : 1; simp only [AList.insert_entries, List.kerase_cons_eq]
theorem insert_insert_of_ne {a a'} {b : β a} {b' : β a'} (s : AList β) (h : a ≠ a') :
((s.insert a b).insert a' b').entries ~ ((s.insert a' b').insert a b).entries := by
simp only [insert_entries]; rw [kerase_cons_ne, kerase_cons_ne, kerase_comm] <;>
[apply Perm.swap; exact h; exact h.symm]
@[simp]
theorem insert_singleton_eq {a : α} {b b' : β a} : insert a b (singleton a b') = singleton a b :=
ext <| by
simp only [AList.insert_entries, List.kerase_cons_eq, and_self_iff, AList.singleton_entries,
heq_iff_eq, eq_self_iff_true]
@[simp]
theorem entries_toAList (xs : List (Sigma β)) : (List.toAList xs).entries = dedupKeys xs :=
rfl
theorem toAList_cons (a : α) (b : β a) (xs : List (Sigma β)) :
List.toAList (⟨a, b⟩ :: xs) = insert a b xs.toAList :=
rfl
theorem mk_cons_eq_insert (c : Sigma β) (l : List (Sigma β)) (h : (c :: l).NodupKeys) :
(⟨c :: l, h⟩ : AList β) = insert c.1 c.2 ⟨l, nodupKeys_of_nodupKeys_cons h⟩ := by
simpa [insert] using (kerase_of_not_mem_keys <| not_mem_keys_of_nodupKeys_cons h).symm
/-- Recursion on an `AList`, using `insert`. Use as `induction l`. -/
@[elab_as_elim, induction_eliminator]
def insertRec {C : AList β → Sort*} (H0 : C ∅)
(IH : ∀ (a : α) (b : β a) (l : AList β), a ∉ l → C l → C (l.insert a b)) :
∀ l : AList β, C l
| ⟨[], _⟩ => H0
| ⟨c :: l, h⟩ => by
rw [mk_cons_eq_insert]
refine IH _ _ _ ?_ (insertRec H0 IH _)
exact not_mem_keys_of_nodupKeys_cons h
-- Test that the `induction` tactic works on `insertRec`.
example (l : AList β) : True := by induction l <;> trivial
@[simp]
theorem insertRec_empty {C : AList β → Sort*} (H0 : C ∅)
(IH : ∀ (a : α) (b : β a) (l : AList β), a ∉ l → C l → C (l.insert a b)) :
@insertRec α β _ C H0 IH ∅ = H0 := by
change @insertRec α β _ C H0 IH ⟨[], _⟩ = H0
rw [insertRec]
theorem insertRec_insert {C : AList β → Sort*} (H0 : C ∅)
(IH : ∀ (a : α) (b : β a) (l : AList β), a ∉ l → C l → C (l.insert a b)) {c : Sigma β}
{l : AList β} (h : c.1 ∉ l) :
@insertRec α β _ C H0 IH (l.insert c.1 c.2) = IH c.1 c.2 l h (@insertRec α β _ C H0 IH l) := by
cases' l with l hl
suffices HEq (@insertRec α β _ C H0 IH ⟨c :: l, nodupKeys_cons.2 ⟨h, hl⟩⟩)
(IH c.1 c.2 ⟨l, hl⟩ h (@insertRec α β _ C H0 IH ⟨l, hl⟩)) by
cases c
apply eq_of_heq
convert this <;> rw [insert_of_neg h]
rw [insertRec]
apply cast_heq
theorem insertRec_insert_mk {C : AList β → Sort*} (H0 : C ∅)
(IH : ∀ (a : α) (b : β a) (l : AList β), a ∉ l → C l → C (l.insert a b)) {a : α} (b : β a)
{l : AList β} (h : a ∉ l) :
@insertRec α β _ C H0 IH (l.insert a b) = IH a b l h (@insertRec α β _ C H0 IH l) :=
@insertRec_insert α β _ C H0 IH ⟨a, b⟩ l h
/-! ### extract -/
/-- Erase a key from the map, and return the corresponding value, if found. -/
def extract (a : α) (s : AList β) : Option (β a) × AList β :=
have : (kextract a s.entries).2.NodupKeys := by
rw [kextract_eq_dlookup_kerase]; exact s.nodupKeys.kerase _
match kextract a s.entries, this with
| (b, l), h => (b, ⟨l, h⟩)
@[simp]
theorem extract_eq_lookup_erase (a : α) (s : AList β) : extract a s = (lookup a s, erase a s) := by
simp [extract]; constructor <;> rfl
/-! ### union -/
/-- `s₁ ∪ s₂` is the key-based union of two association lists. It is
left-biased: if there exists an `a ∈ s₁`, `lookup a (s₁ ∪ s₂) = lookup a s₁`.
-/
def union (s₁ s₂ : AList β) : AList β :=
⟨s₁.entries.kunion s₂.entries, s₁.nodupKeys.kunion s₂.nodupKeys⟩
instance : Union (AList β) :=
⟨union⟩
@[simp]
theorem union_entries {s₁ s₂ : AList β} : (s₁ ∪ s₂).entries = kunion s₁.entries s₂.entries :=
rfl
@[simp]
theorem empty_union {s : AList β} : (∅ : AList β) ∪ s = s :=
ext rfl
@[simp]
theorem union_empty {s : AList β} : s ∪ (∅ : AList β) = s :=
ext <| by simp
@[simp]
theorem mem_union {a} {s₁ s₂ : AList β} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ :=
mem_keys_kunion
theorem perm_union {s₁ s₂ s₃ s₄ : AList β} (p₁₂ : s₁.entries ~ s₂.entries)
(p₃₄ : s₃.entries ~ s₄.entries) : (s₁ ∪ s₃).entries ~ (s₂ ∪ s₄).entries := by
simp [p₁₂.kunion s₃.nodupKeys p₃₄]
theorem union_erase (a : α) (s₁ s₂ : AList β) : erase a (s₁ ∪ s₂) = erase a s₁ ∪ erase a s₂ :=
ext kunion_kerase.symm
@[simp]
theorem lookup_union_left {a} {s₁ s₂ : AList β} : a ∈ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₁ :=
dlookup_kunion_left
@[simp]
theorem lookup_union_right {a} {s₁ s₂ : AList β} : a ∉ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₂ :=
dlookup_kunion_right
-- Porting note: removing simp, LHS not in SNF, new theorem added instead.
theorem mem_lookup_union {a} {b : β a} {s₁ s₂ : AList β} :
b ∈ lookup a (s₁ ∪ s₂) ↔ b ∈ lookup a s₁ ∨ a ∉ s₁ ∧ b ∈ lookup a s₂ :=
mem_dlookup_kunion
@[simp]
theorem lookup_union_eq_some {a} {b : β a} {s₁ s₂ : AList β} :
lookup a (s₁ ∪ s₂) = some b ↔ lookup a s₁ = some b ∨ a ∉ s₁ ∧ lookup a s₂ = some b :=
mem_dlookup_kunion
theorem mem_lookup_union_middle {a} {b : β a} {s₁ s₂ s₃ : AList β} :
b ∈ lookup a (s₁ ∪ s₃) → a ∉ s₂ → b ∈ lookup a (s₁ ∪ s₂ ∪ s₃) :=
mem_dlookup_kunion_middle
theorem insert_union {a} {b : β a} {s₁ s₂ : AList β} :
insert a b (s₁ ∪ s₂) = insert a b s₁ ∪ s₂ := by ext; simp
theorem union_assoc {s₁ s₂ s₃ : AList β} : (s₁ ∪ s₂ ∪ s₃).entries ~ (s₁ ∪ (s₂ ∪ s₃)).entries :=
lookup_ext (AList.nodupKeys _) (AList.nodupKeys _)
(by simp [not_or, or_assoc, and_or_left, and_assoc])
end
/-! ### disjoint -/
/-- Two associative lists are disjoint if they have no common keys. -/
def Disjoint (s₁ s₂ : AList β) : Prop :=
∀ k ∈ s₁.keys, ¬k ∈ s₂.keys
variable [DecidableEq α]
theorem union_comm_of_disjoint {s₁ s₂ : AList β} (h : Disjoint s₁ s₂) :
(s₁ ∪ s₂).entries ~ (s₂ ∪ s₁).entries :=
lookup_ext (AList.nodupKeys _) (AList.nodupKeys _)
(by
intros; simp only [union_entries, Option.mem_def, dlookup_kunion_eq_some]
constructor <;> intro h'
· cases' h' with h' h'
· right
refine ⟨?_, h'⟩
apply h
rw [keys, ← List.dlookup_isSome, h']
exact rfl
· left
rw [h'.2]
· cases' h' with h' h'
· right
refine ⟨?_, h'⟩
intro h''
apply h _ h''
rw [keys, ← List.dlookup_isSome, h']
exact rfl
· left
rw [h'.2])
end AList
|
Data\List\Basic.lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import Mathlib.Data.Nat.Defs
import Mathlib.Data.Option.Basic
import Mathlib.Data.List.Defs
import Mathlib.Init.Data.List.Basic
import Mathlib.Init.Data.List.Instances
import Mathlib.Init.Data.List.Lemmas
import Mathlib.Logic.Unique
import Mathlib.Order.Basic
import Mathlib.Tactic.Common
import Batteries.Data.List.Perm
/-!
# Basic properties of lists
-/
assert_not_exists Set.range
assert_not_exists GroupWithZero
assert_not_exists Ring
open Function
open Nat hiding one_pos
namespace List
universe u v w
variable {ι : Type*} {α : Type u} {β : Type v} {γ : Type w} {l₁ l₂ : List α}
-- Porting note: Delete this attribute
-- attribute [inline] List.head!
/-- There is only one list of an empty type -/
instance uniqueOfIsEmpty [IsEmpty α] : Unique (List α) :=
{ instInhabitedList with
uniq := fun l =>
match l with
| [] => rfl
| a :: _ => isEmptyElim a }
instance : Std.LawfulIdentity (α := List α) Append.append [] where
left_id := nil_append
right_id := append_nil
instance : Std.Associative (α := List α) Append.append where
assoc := append_assoc
@[simp] theorem cons_injective {a : α} : Injective (cons a) := fun _ _ => tail_eq_of_cons_eq
theorem singleton_injective : Injective fun a : α => [a] := fun _ _ h => (cons_eq_cons.1 h).1
theorem singleton_inj {a b : α} : [a] = [b] ↔ a = b :=
singleton_injective.eq_iff
theorem set_of_mem_cons (l : List α) (a : α) : { x | x ∈ a :: l } = insert a { x | x ∈ l } :=
Set.ext fun _ => mem_cons
/-! ### mem -/
theorem _root_.Decidable.List.eq_or_ne_mem_of_mem [DecidableEq α]
{a b : α} {l : List α} (h : a ∈ b :: l) : a = b ∨ a ≠ b ∧ a ∈ l := by
by_cases hab : a = b
· exact Or.inl hab
· exact ((List.mem_cons.1 h).elim Or.inl (fun h => Or.inr ⟨hab, h⟩))
lemma mem_pair {a b c : α} : a ∈ [b, c] ↔ a = b ∨ a = c := by
rw [mem_cons, mem_singleton]
@[deprecated (since := "2024-03-23")] alias mem_split := append_of_mem
-- The simpNF linter says that the LHS can be simplified via `List.mem_map`.
-- However this is a higher priority lemma.
-- https://github.com/leanprover/std4/issues/207
@[simp 1100, nolint simpNF]
theorem mem_map_of_injective {f : α → β} (H : Injective f) {a : α} {l : List α} :
f a ∈ map f l ↔ a ∈ l :=
⟨fun m => let ⟨_, m', e⟩ := exists_of_mem_map m; H e ▸ m', mem_map_of_mem _⟩
@[simp]
theorem _root_.Function.Involutive.exists_mem_and_apply_eq_iff {f : α → α}
(hf : Function.Involutive f) (x : α) (l : List α) : (∃ y : α, y ∈ l ∧ f y = x) ↔ f x ∈ l :=
⟨by rintro ⟨y, h, rfl⟩; rwa [hf y], fun h => ⟨f x, h, hf _⟩⟩
theorem mem_map_of_involutive {f : α → α} (hf : Involutive f) {a : α} {l : List α} :
a ∈ map f l ↔ f a ∈ l := by rw [mem_map, hf.exists_mem_and_apply_eq_iff]
attribute [simp] List.mem_join
attribute [simp] List.mem_bind
-- Porting note: bExists in Lean3, And in Lean4
/-! ### length -/
alias ⟨_, length_pos_of_ne_nil⟩ := length_pos
theorem length_pos_iff_ne_nil {l : List α} : 0 < length l ↔ l ≠ [] :=
⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩
theorem exists_of_length_succ {n} : ∀ l : List α, l.length = n + 1 → ∃ h t, l = h :: t
| [], H => absurd H.symm <| succ_ne_zero n
| h :: t, _ => ⟨h, t, rfl⟩
@[simp] lemma length_injective_iff : Injective (List.length : List α → ℕ) ↔ Subsingleton α := by
constructor
· intro h; refine ⟨fun x y => ?_⟩; (suffices [x] = [y] by simpa using this); apply h; rfl
· intros hα l1 l2 hl
induction l1 generalizing l2 <;> cases l2
· rfl
· cases hl
· cases hl
· next ih _ _ =>
congr
· subsingleton
· apply ih; simpa using hl
@[simp default+1] -- Porting note: this used to be just @[simp]
lemma length_injective [Subsingleton α] : Injective (length : List α → ℕ) :=
length_injective_iff.mpr inferInstance
theorem length_eq_two {l : List α} : l.length = 2 ↔ ∃ a b, l = [a, b] :=
⟨fun _ => let [a, b] := l; ⟨a, b, rfl⟩, fun ⟨_, _, e⟩ => e ▸ rfl⟩
theorem length_eq_three {l : List α} : l.length = 3 ↔ ∃ a b c, l = [a, b, c] :=
⟨fun _ => let [a, b, c] := l; ⟨a, b, c, rfl⟩, fun ⟨_, _, _, e⟩ => e ▸ rfl⟩
/-! ### set-theoretic notation of lists -/
-- ADHOC Porting note: instance from Lean3 core
instance instSingletonList : Singleton α (List α) := ⟨fun x => [x]⟩
-- ADHOC Porting note: instance from Lean3 core
instance [DecidableEq α] : Insert α (List α) := ⟨List.insert⟩
-- ADHOC Porting note: instance from Lean3 core
instance [DecidableEq α] : LawfulSingleton α (List α) :=
{ insert_emptyc_eq := fun x =>
show (if x ∈ ([] : List α) then [] else [x]) = [x] from if_neg (not_mem_nil _) }
theorem singleton_eq (x : α) : ({x} : List α) = [x] :=
rfl
theorem insert_neg [DecidableEq α] {x : α} {l : List α} (h : x ∉ l) :
Insert.insert x l = x :: l :=
insert_of_not_mem h
theorem insert_pos [DecidableEq α] {x : α} {l : List α} (h : x ∈ l) : Insert.insert x l = l :=
insert_of_mem h
theorem doubleton_eq [DecidableEq α] {x y : α} (h : x ≠ y) : ({x, y} : List α) = [x, y] := by
rw [insert_neg, singleton_eq]
rwa [singleton_eq, mem_singleton]
/-! ### bounded quantifiers over lists -/
theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : List α} (h : ∀ x ∈ a :: l, p x) :
∀ x ∈ l, p x := (forall_mem_cons.1 h).2
-- Porting note: bExists in Lean3 and And in Lean4
theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : List α) (h : p a) : ∃ x ∈ a :: l, p x :=
⟨a, mem_cons_self _ _, h⟩
-- Porting note: bExists in Lean3 and And in Lean4
theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : List α} : (∃ x ∈ l, p x) →
∃ x ∈ a :: l, p x :=
fun ⟨x, xl, px⟩ => ⟨x, mem_cons_of_mem _ xl, px⟩
-- Porting note: bExists in Lean3 and And in Lean4
theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : List α} : (∃ x ∈ a :: l, p x) →
p a ∨ ∃ x ∈ l, p x :=
fun ⟨x, xal, px⟩ =>
Or.elim (eq_or_mem_of_mem_cons xal) (fun h : x = a => by rw [← h]; left; exact px)
fun h : x ∈ l => Or.inr ⟨x, h, px⟩
theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : List α) :
(∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x :=
Iff.intro or_exists_of_exists_mem_cons fun h =>
Or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists
/-! ### list subset -/
instance : IsTrans (List α) Subset where
trans := fun _ _ _ => List.Subset.trans
theorem cons_subset_of_subset_of_mem {a : α} {l m : List α}
(ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m :=
cons_subset.2 ⟨ainm, lsubm⟩
theorem append_subset_of_subset_of_subset {l₁ l₂ l : List α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) :
l₁ ++ l₂ ⊆ l :=
fun _ h ↦ (mem_append.1 h).elim (@l₁subl _) (@l₂subl _)
-- Porting note: in Batteries
alias ⟨eq_nil_of_subset_nil, _⟩ := subset_nil
theorem map_subset_iff {l₁ l₂ : List α} (f : α → β) (h : Injective f) :
map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ := by
refine ⟨?_, map_subset f⟩; intro h2 x hx
rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩
cases h hxx'; exact hx'
/-! ### append -/
theorem append_eq_has_append {L₁ L₂ : List α} : List.append L₁ L₂ = L₁ ++ L₂ :=
rfl
-- Porting note: in Batteries
@[deprecated (since := "2024-03-24")] alias append_eq_cons_iff := append_eq_cons
@[deprecated (since := "2024-03-24")] alias cons_eq_append_iff := cons_eq_append
@[deprecated (since := "2024-01-18")] alias append_left_cancel := append_cancel_left
@[deprecated (since := "2024-01-18")] alias append_right_cancel := append_cancel_right
@[simp] theorem append_left_eq_self {x y : List α} : x ++ y = y ↔ x = [] := by
rw [← append_left_inj (s₁ := x), nil_append]
@[simp] theorem self_eq_append_left {x y : List α} : y = x ++ y ↔ x = [] := by
rw [eq_comm, append_left_eq_self]
@[simp] theorem append_right_eq_self {x y : List α} : x ++ y = x ↔ y = [] := by
rw [← append_right_inj (t₁ := y), append_nil]
@[simp] theorem self_eq_append_right {x y : List α} : x = x ++ y ↔ y = [] := by
rw [eq_comm, append_right_eq_self]
theorem append_right_injective (s : List α) : Injective fun t ↦ s ++ t :=
fun _ _ ↦ append_cancel_left
theorem append_left_injective (t : List α) : Injective fun s ↦ s ++ t :=
fun _ _ ↦ append_cancel_right
/-! ### replicate -/
theorem eq_replicate_length {a : α} : ∀ {l : List α}, l = replicate l.length a ↔ ∀ b ∈ l, b = a
| [] => by simp
| (b :: l) => by simp [eq_replicate_length, replicate_succ]
theorem replicate_add (m n) (a : α) : replicate (m + n) a = replicate m a ++ replicate n a := by
rw [append_replicate_replicate]
theorem replicate_succ' (n) (a : α) : replicate (n + 1) a = replicate n a ++ [a] :=
replicate_add n 1 a
theorem replicate_subset_singleton (n) (a : α) : replicate n a ⊆ [a] := fun _ h =>
mem_singleton.2 (eq_of_mem_replicate h)
theorem subset_singleton_iff {a : α} {L : List α} : L ⊆ [a] ↔ ∃ n, L = replicate n a := by
simp only [eq_replicate, subset_def, mem_singleton, exists_eq_left']
@[simp] theorem tail_replicate (a : α) (n) :
tail (replicate n a) = replicate (n - 1) a := by cases n <;> rfl
theorem replicate_right_injective {n : ℕ} (hn : n ≠ 0) : Injective (@replicate α n) :=
fun _ _ h => (eq_replicate.1 h).2 _ <| mem_replicate.2 ⟨hn, rfl⟩
theorem replicate_right_inj {a b : α} {n : ℕ} (hn : n ≠ 0) :
replicate n a = replicate n b ↔ a = b :=
(replicate_right_injective hn).eq_iff
theorem replicate_right_inj' {a b : α} : ∀ {n},
replicate n a = replicate n b ↔ n = 0 ∨ a = b
| 0 => by simp
| n + 1 => (replicate_right_inj n.succ_ne_zero).trans <| by simp only [n.succ_ne_zero, false_or]
theorem replicate_left_injective (a : α) : Injective (replicate · a) :=
LeftInverse.injective (length_replicate · a)
theorem replicate_left_inj {a : α} {n m : ℕ} : replicate n a = replicate m a ↔ n = m :=
(replicate_left_injective a).eq_iff
/-! ### pure -/
theorem mem_pure (x y : α) : x ∈ (pure y : List α) ↔ x = y := by simp
/-! ### bind -/
@[simp]
theorem bind_eq_bind {α β} (f : α → List β) (l : List α) : l >>= f = l.bind f :=
rfl
/-! ### concat -/
/-! ### reverse -/
-- Porting note: Do we need this?
attribute [local simp] reverseAux
theorem reverse_cons' (a : α) (l : List α) : reverse (a :: l) = concat (reverse l) a := by
simp only [reverse_cons, concat_eq_append]
theorem reverse_concat' (l : List α) (a : α) : (l ++ [a]).reverse = a :: l.reverse := by
rw [reverse_append]; rfl
-- Porting note (#10618): simp can prove this
-- @[simp]
theorem reverse_singleton (a : α) : reverse [a] = [a] :=
rfl
@[simp]
theorem reverse_involutive : Involutive (@reverse α) :=
reverse_reverse
@[simp]
theorem reverse_injective : Injective (@reverse α) :=
reverse_involutive.injective
theorem reverse_surjective : Surjective (@reverse α) :=
reverse_involutive.surjective
theorem reverse_bijective : Bijective (@reverse α) :=
reverse_involutive.bijective
@[simp]
theorem reverse_inj {l₁ l₂ : List α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ :=
reverse_injective.eq_iff
theorem concat_eq_reverse_cons (a : α) (l : List α) : concat l a = reverse (a :: reverse l) := by
simp only [concat_eq_append, reverse_cons, reverse_reverse]
theorem map_reverseAux (f : α → β) (l₁ l₂ : List α) :
map f (reverseAux l₁ l₂) = reverseAux (map f l₁) (map f l₂) := by
simp only [reverseAux_eq, map_append, map_reverse]
/-! ### empty -/
-- Porting note: this does not work as desired
-- attribute [simp] List.isEmpty
theorem isEmpty_iff_eq_nil {l : List α} : l.isEmpty ↔ l = [] := by cases l <;> simp [isEmpty]
/-! ### dropLast -/
/-! ### getLast -/
attribute [simp] getLast_cons
theorem getLast_append_singleton {a : α} (l : List α) :
getLast (l ++ [a]) (append_ne_nil_of_right_ne_nil l (cons_ne_nil a _)) = a := by
simp [getLast_append]
-- Porting note: name should be fixed upstream
theorem getLast_append' (l₁ l₂ : List α) (h : l₂ ≠ []) :
getLast (l₁ ++ l₂) (append_ne_nil_of_right_ne_nil l₁ h) = getLast l₂ h := by
induction' l₁ with _ _ ih
· simp
· simp only [cons_append]
rw [List.getLast_cons]
exact ih
theorem getLast_concat' {a : α} (l : List α) : getLast (concat l a) (concat_ne_nil a l) = a := by
simp
@[simp]
theorem getLast_singleton' (a : α) : getLast [a] (cons_ne_nil a []) = a := rfl
-- Porting note (#10618): simp can prove this
-- @[simp]
theorem getLast_cons_cons (a₁ a₂ : α) (l : List α) :
getLast (a₁ :: a₂ :: l) (cons_ne_nil _ _) = getLast (a₂ :: l) (cons_ne_nil a₂ l) :=
rfl
theorem dropLast_append_getLast : ∀ {l : List α} (h : l ≠ []), dropLast l ++ [getLast l h] = l
| [], h => absurd rfl h
| [a], h => rfl
| a :: b :: l, h => by
rw [dropLast_cons₂, cons_append, getLast_cons (cons_ne_nil _ _)]
congr
exact dropLast_append_getLast (cons_ne_nil b l)
theorem getLast_congr {l₁ l₂ : List α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) :
getLast l₁ h₁ = getLast l₂ h₂ := by subst l₁; rfl
theorem getLast_replicate_succ (m : ℕ) (a : α) :
(replicate (m + 1) a).getLast (ne_nil_of_length_eq_add_one (length_replicate _ _)) = a := by
simp only [replicate_succ']
exact getLast_append_singleton _
/-- If the last element of `l` does not satisfy `p`, then it is also the last element of
`l.filter p`. -/
lemma getLast_filter {p : α → Bool} :
∀ (l : List α) (hlp : l.filter p ≠ []), p (l.getLast (hlp <| ·.symm ▸ rfl)) = true →
(l.filter p).getLast hlp = l.getLast (hlp <| ·.symm ▸ rfl)
| [a], h, h' => by rw [List.getLast_singleton'] at h'; simp [List.filter_cons, h']
| a :: b :: as, h, h' => by
rw [List.getLast_cons_cons] at h' ⊢
simp only [List.filter_cons (x := a)] at h ⊢
obtain ha | ha := Bool.eq_false_or_eq_true (p a)
· simp only [ha, ite_true]
rw [getLast_cons, getLast_filter (b :: as) _ h']
exact ne_nil_of_mem <| mem_filter.2 ⟨getLast_mem _, h'⟩
· simp only [ha, cond_false] at h ⊢
exact getLast_filter (b :: as) h h'
/-! ### getLast? -/
-- Porting note: Moved earlier in file, for use in subsequent lemmas.
@[simp]
theorem getLast?_cons_cons (a b : α) (l : List α) :
getLast? (a :: b :: l) = getLast? (b :: l) := rfl
@[simp]
theorem getLast?_eq_none : ∀ {l : List α}, getLast? l = none ↔ l = []
| [] => by simp
| [a] => by simp
| a :: b :: l => by simp [@getLast?_eq_none (b :: l)]
@[deprecated (since := "2024-06-20")] alias getLast?_isNone := getLast?_eq_none
@[simp]
theorem getLast?_isSome : ∀ {l : List α}, l.getLast?.isSome ↔ l ≠ []
| [] => by simp
| [a] => by simp
| a :: b :: l => by simp [@getLast?_isSome (b :: l)]
theorem mem_getLast?_eq_getLast : ∀ {l : List α} {x : α}, x ∈ l.getLast? → ∃ h, x = getLast l h
| [], x, hx => False.elim <| by simp at hx
| [a], x, hx =>
have : a = x := by simpa using hx
this ▸ ⟨cons_ne_nil a [], rfl⟩
| a :: b :: l, x, hx => by
rw [getLast?_cons_cons] at hx
rcases mem_getLast?_eq_getLast hx with ⟨_, h₂⟩
use cons_ne_nil _ _
assumption
theorem getLast?_eq_getLast_of_ne_nil : ∀ {l : List α} (h : l ≠ []), l.getLast? = some (l.getLast h)
| [], h => (h rfl).elim
| [_], _ => rfl
| _ :: b :: l, _ => @getLast?_eq_getLast_of_ne_nil (b :: l) (cons_ne_nil _ _)
theorem mem_getLast?_cons {x y : α} : ∀ {l : List α}, x ∈ l.getLast? → x ∈ (y :: l).getLast?
| [], _ => by contradiction
| _ :: _, h => h
theorem mem_of_mem_getLast? {l : List α} {a : α} (ha : a ∈ l.getLast?) : a ∈ l :=
let ⟨_, h₂⟩ := mem_getLast?_eq_getLast ha
h₂.symm ▸ getLast_mem _
theorem dropLast_append_getLast? : ∀ {l : List α}, ∀ a ∈ l.getLast?, dropLast l ++ [a] = l
| [], a, ha => (Option.not_mem_none a ha).elim
| [a], _, rfl => rfl
| a :: b :: l, c, hc => by
rw [getLast?_cons_cons] at hc
rw [dropLast_cons₂, cons_append, dropLast_append_getLast? _ hc]
theorem getLastI_eq_getLast? [Inhabited α] : ∀ l : List α, l.getLastI = l.getLast?.iget
| [] => by simp [getLastI, Inhabited.default]
| [a] => rfl
| [a, b] => rfl
| [a, b, c] => rfl
| _ :: _ :: c :: l => by simp [getLastI, getLastI_eq_getLast? (c :: l)]
#adaptation_note /-- 2024-07-10: removed `@[simp]` since the LHS simplifies using the simp set. -/
theorem getLast?_append_cons :
∀ (l₁ : List α) (a : α) (l₂ : List α), getLast? (l₁ ++ a :: l₂) = getLast? (a :: l₂)
| [], a, l₂ => rfl
| [b], a, l₂ => rfl
| b :: c :: l₁, a, l₂ => by rw [cons_append, cons_append, getLast?_cons_cons,
← cons_append, getLast?_append_cons (c :: l₁)]
theorem getLast?_append_of_ne_nil (l₁ : List α) :
∀ {l₂ : List α} (_ : l₂ ≠ []), getLast? (l₁ ++ l₂) = getLast? l₂
| [], hl₂ => by contradiction
| b :: l₂, _ => getLast?_append_cons l₁ b l₂
theorem mem_getLast?_append_of_mem_getLast? {l₁ l₂ : List α} {x : α} (h : x ∈ l₂.getLast?) :
x ∈ (l₁ ++ l₂).getLast? := by
cases l₂
· contradiction
· rw [List.getLast?_append_cons]
exact h
/-! ### head(!?) and tail -/
@[simp]
theorem head!_nil [Inhabited α] : ([] : List α).head! = default := rfl
@[simp] theorem head_cons_tail (x : List α) (h : x ≠ []) : x.head h :: x.tail = x := by
cases x <;> simp at h ⊢
theorem head!_eq_head? [Inhabited α] (l : List α) : head! l = (head? l).iget := by cases l <;> rfl
theorem surjective_head! [Inhabited α] : Surjective (@head! α _) := fun x => ⟨[x], rfl⟩
theorem surjective_head? : Surjective (@head? α) :=
Option.forall.2 ⟨⟨[], rfl⟩, fun x => ⟨[x], rfl⟩⟩
theorem surjective_tail : Surjective (@tail α)
| [] => ⟨[], rfl⟩
| a :: l => ⟨a :: a :: l, rfl⟩
theorem eq_cons_of_mem_head? {x : α} : ∀ {l : List α}, x ∈ l.head? → l = x :: tail l
| [], h => (Option.not_mem_none _ h).elim
| a :: l, h => by
simp only [head?, Option.mem_def, Option.some_inj] at h
exact h ▸ rfl
theorem mem_of_mem_head? {x : α} {l : List α} (h : x ∈ l.head?) : x ∈ l :=
(eq_cons_of_mem_head? h).symm ▸ mem_cons_self _ _
@[simp] theorem head!_cons [Inhabited α] (a : α) (l : List α) : head! (a :: l) = a := rfl
@[simp]
theorem head!_append [Inhabited α] (t : List α) {s : List α} (h : s ≠ []) :
head! (s ++ t) = head! s := by
induction s
· contradiction
· rfl
theorem mem_head?_append_of_mem_head? {s t : List α} {x : α} (h : x ∈ s.head?) :
x ∈ (s ++ t).head? := by
cases s
· contradiction
· exact h
theorem head?_append_of_ne_nil :
∀ (l₁ : List α) {l₂ : List α} (_ : l₁ ≠ []), head? (l₁ ++ l₂) = head? l₁
| _ :: _, _, _ => rfl
theorem tail_append_singleton_of_ne_nil {a : α} {l : List α} (h : l ≠ nil) :
tail (l ++ [a]) = tail l ++ [a] := by
induction l
· contradiction
· rw [tail, cons_append, tail]
theorem cons_head?_tail : ∀ {l : List α} {a : α}, a ∈ head? l → a :: tail l = l
| [], a, h => by contradiction
| b :: l, a, h => by
simp? at h says simp only [head?_cons, Option.mem_def, Option.some.injEq] at h
simp [h]
theorem head!_mem_head? [Inhabited α] : ∀ {l : List α}, l ≠ [] → head! l ∈ head? l
| [], h => by contradiction
| a :: l, _ => rfl
theorem cons_head!_tail [Inhabited α] {l : List α} (h : l ≠ []) : head! l :: tail l = l :=
cons_head?_tail (head!_mem_head? h)
theorem head!_mem_self [Inhabited α] {l : List α} (h : l ≠ nil) : l.head! ∈ l := by
have h' := mem_cons_self l.head! l.tail
rwa [cons_head!_tail h] at h'
theorem tail_append_of_ne_nil (l l' : List α) (h : l ≠ []) : (l ++ l').tail = l.tail ++ l' := by
cases l
· contradiction
· simp
theorem get_eq_get? (l : List α) (i : Fin l.length) :
l.get i = (l.get? i).get (by simp [getElem?_eq_getElem]) := by
simp [getElem_eq_iff]
section deprecated
set_option linter.deprecated false -- TODO(Mario): make replacements for theorems in this section
/-- nth element of a list `l` given `n < l.length`. -/
@[deprecated get (since := "2023-01-05")]
def nthLe (l : List α) (n) (h : n < l.length) : α := get l ⟨n, h⟩
@[simp] theorem nthLe_tail (l : List α) (i) (h : i < l.tail.length)
(h' : i + 1 < l.length := (by simp only [length_tail] at h; omega)) :
l.tail.nthLe i h = l.nthLe (i + 1) h' := by
cases l <;> [cases h; rfl]
theorem nthLe_cons_aux {l : List α} {a : α} {n} (hn : n ≠ 0) (h : n < (a :: l).length) :
n - 1 < l.length := by
contrapose! h
rw [length_cons]
omega
theorem nthLe_cons {l : List α} {a : α} {n} (hl) :
(a :: l).nthLe n hl = if hn : n = 0 then a else l.nthLe (n - 1) (nthLe_cons_aux hn hl) := by
split_ifs with h
· simp [nthLe, h]
cases l
· rw [length_singleton, Nat.lt_succ_iff] at hl
omega
cases n
· contradiction
rfl
end deprecated
@[simp 1100]
theorem modifyHead_modifyHead (l : List α) (f g : α → α) :
(l.modifyHead f).modifyHead g = l.modifyHead (g ∘ f) := by cases l <;> simp
/-! ### Induction from the right -/
/-- Induction principle from the right for lists: if a property holds for the empty list, and
for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for
a `Sort`-valued predicate, i.e., it can also be used to construct data. -/
@[elab_as_elim]
def reverseRecOn {motive : List α → Sort*} (l : List α) (nil : motive [])
(append_singleton : ∀ (l : List α) (a : α), motive l → motive (l ++ [a])) : motive l :=
match h : reverse l with
| [] => cast (congr_arg motive <| by simpa using congr(reverse $h.symm)) <|
nil
| head :: tail =>
cast (congr_arg motive <| by simpa using congr(reverse $h.symm)) <|
append_singleton _ head <| reverseRecOn (reverse tail) nil append_singleton
termination_by l.length
decreasing_by
simp_wf
rw [← length_reverse l, h, length_cons]
simp [Nat.lt_succ]
@[simp]
theorem reverseRecOn_nil {motive : List α → Sort*} (nil : motive [])
(append_singleton : ∀ (l : List α) (a : α), motive l → motive (l ++ [a])) :
reverseRecOn [] nil append_singleton = nil := reverseRecOn.eq_1 ..
-- `unusedHavesSuffices` is getting confused by the unfolding of `reverseRecOn`
@[simp, nolint unusedHavesSuffices]
theorem reverseRecOn_concat {motive : List α → Sort*} (x : α) (xs : List α) (nil : motive [])
(append_singleton : ∀ (l : List α) (a : α), motive l → motive (l ++ [a])) :
reverseRecOn (motive := motive) (xs ++ [x]) nil append_singleton =
append_singleton _ _ (reverseRecOn (motive := motive) xs nil append_singleton) := by
suffices ∀ ys (h : reverse (reverse xs) = ys),
reverseRecOn (motive := motive) (xs ++ [x]) nil append_singleton =
cast (by simp [(reverse_reverse _).symm.trans h])
(append_singleton _ x (reverseRecOn (motive := motive) ys nil append_singleton)) by
exact this _ (reverse_reverse xs)
intros ys hy
conv_lhs => unfold reverseRecOn
split
next h => simp at h
next heq =>
revert heq
simp only [reverse_append, reverse_cons, reverse_nil, nil_append, singleton_append, cons.injEq]
rintro ⟨rfl, rfl⟩
subst ys
rfl
/-- Bidirectional induction principle for lists: if a property holds for the empty list, the
singleton list, and `a :: (l ++ [b])` from `l`, then it holds for all lists. This can be used to
prove statements about palindromes. The principle is given for a `Sort`-valued predicate, i.e., it
can also be used to construct data. -/
@[elab_as_elim]
def bidirectionalRec {motive : List α → Sort*} (nil : motive []) (singleton : ∀ a : α, motive [a])
(cons_append : ∀ (a : α) (l : List α) (b : α), motive l → motive (a :: (l ++ [b]))) :
∀ l, motive l
| [] => nil
| [a] => singleton a
| a :: b :: l =>
let l' := dropLast (b :: l)
let b' := getLast (b :: l) (cons_ne_nil _ _)
cast (by rw [← dropLast_append_getLast (cons_ne_nil b l)]) <|
cons_append a l' b' (bidirectionalRec nil singleton cons_append l')
termination_by l => l.length
@[simp]
theorem bidirectionalRec_nil {motive : List α → Sort*}
(nil : motive []) (singleton : ∀ a : α, motive [a])
(cons_append : ∀ (a : α) (l : List α) (b : α), motive l → motive (a :: (l ++ [b]))) :
bidirectionalRec nil singleton cons_append [] = nil := bidirectionalRec.eq_1 ..
@[simp]
theorem bidirectionalRec_singleton {motive : List α → Sort*}
(nil : motive []) (singleton : ∀ a : α, motive [a])
(cons_append : ∀ (a : α) (l : List α) (b : α), motive l → motive (a :: (l ++ [b]))) (a : α) :
bidirectionalRec nil singleton cons_append [a] = singleton a := by
simp [bidirectionalRec]
@[simp]
theorem bidirectionalRec_cons_append {motive : List α → Sort*}
(nil : motive []) (singleton : ∀ a : α, motive [a])
(cons_append : ∀ (a : α) (l : List α) (b : α), motive l → motive (a :: (l ++ [b])))
(a : α) (l : List α) (b : α) :
bidirectionalRec nil singleton cons_append (a :: (l ++ [b])) =
cons_append a l b (bidirectionalRec nil singleton cons_append l) := by
conv_lhs => unfold bidirectionalRec
cases l with
| nil => rfl
| cons x xs =>
simp only [List.cons_append]
dsimp only [← List.cons_append]
suffices ∀ (ys init : List α) (hinit : init = ys) (last : α) (hlast : last = b),
(cons_append a init last
(bidirectionalRec nil singleton cons_append init)) =
cast (congr_arg motive <| by simp [hinit, hlast])
(cons_append a ys b (bidirectionalRec nil singleton cons_append ys)) by
rw [this (x :: xs) _ (by rw [dropLast_append_cons, dropLast_single, append_nil]) _ (by simp)]
simp
rintro ys init rfl last rfl
rfl
/-- Like `bidirectionalRec`, but with the list parameter placed first. -/
@[elab_as_elim]
abbrev bidirectionalRecOn {C : List α → Sort*} (l : List α) (H0 : C []) (H1 : ∀ a : α, C [a])
(Hn : ∀ (a : α) (l : List α) (b : α), C l → C (a :: (l ++ [b]))) : C l :=
bidirectionalRec H0 H1 Hn l
/-! ### sublists -/
attribute [refl] List.Sublist.refl
theorem Sublist.cons_cons {l₁ l₂ : List α} (a : α) (s : l₁ <+ l₂) : a :: l₁ <+ a :: l₂ :=
Sublist.cons₂ _ s
lemma cons_sublist_cons' {a b : α} : a :: l₁ <+ b :: l₂ ↔ a :: l₁ <+ l₂ ∨ a = b ∧ l₁ <+ l₂ := by
constructor
· rintro (_ | _)
· exact Or.inl ‹_›
· exact Or.inr ⟨rfl, ‹_›⟩
· rintro (h | ⟨rfl, h⟩)
· exact h.cons _
· rwa [cons_sublist_cons]
theorem sublist_cons_of_sublist (a : α) (h : l₁ <+ l₂) : l₁ <+ a :: l₂ := h.cons _
theorem tail_sublist : ∀ l : List α, tail l <+ l
| [] => .slnil
| a::l => sublist_cons_self a l
@[gcongr] protected theorem Sublist.tail : ∀ {l₁ l₂ : List α}, l₁ <+ l₂ → tail l₁ <+ tail l₂
| _, _, slnil => .slnil
| _, _, Sublist.cons _ h => (tail_sublist _).trans h
| _, _, Sublist.cons₂ _ h => h
theorem Sublist.of_cons_cons {l₁ l₂ : List α} {a b : α} (h : a :: l₁ <+ b :: l₂) : l₁ <+ l₂ :=
h.tail
@[deprecated (since := "2024-04-07")]
theorem sublist_of_cons_sublist_cons {a} (h : a :: l₁ <+ a :: l₂) : l₁ <+ l₂ := h.of_cons_cons
attribute [simp] cons_sublist_cons
@[deprecated (since := "2024-04-07")] alias cons_sublist_cons_iff := cons_sublist_cons
theorem eq_nil_of_sublist_nil {l : List α} (s : l <+ []) : l = [] :=
eq_nil_of_subset_nil <| s.subset
-- Porting note: this lemma seems to have been renamed on the occasion of its move to Batteries
alias sublist_nil_iff_eq_nil := sublist_nil
@[simp] lemma sublist_singleton {l : List α} {a : α} : l <+ [a] ↔ l = [] ∨ l = [a] := by
constructor <;> rintro (_ | _) <;> aesop
theorem Sublist.antisymm (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ :=
s₁.eq_of_length_le s₂.length_le
instance decidableSublist [DecidableEq α] : ∀ l₁ l₂ : List α, Decidable (l₁ <+ l₂)
| [], _ => isTrue <| nil_sublist _
| _ :: _, [] => isFalse fun h => List.noConfusion <| eq_nil_of_sublist_nil h
| a :: l₁, b :: l₂ =>
if h : a = b then
@decidable_of_decidable_of_iff _ _ (decidableSublist l₁ l₂) <| h ▸ cons_sublist_cons.symm
else
@decidable_of_decidable_of_iff _ _ (decidableSublist (a :: l₁) l₂)
⟨sublist_cons_of_sublist _, fun s =>
match a, l₁, s, h with
| _, _, Sublist.cons _ s', h => s'
| _, _, Sublist.cons₂ t _, h => absurd rfl h⟩
/-! ### indexOf -/
section IndexOf
variable [DecidableEq α]
/-
Porting note: The following proofs were simpler prior to the port. These proofs use the low-level
`findIdx.go`.
* `indexOf_cons_self`
* `indexOf_cons_eq`
* `indexOf_cons_ne`
* `indexOf_cons`
The ported versions of the earlier proofs are given in comments.
-/
-- indexOf_cons_eq _ rfl
@[simp]
theorem indexOf_cons_self (a : α) (l : List α) : indexOf a (a :: l) = 0 := by
rw [indexOf, findIdx_cons, beq_self_eq_true, cond]
-- fun e => if_pos e
theorem indexOf_cons_eq {a b : α} (l : List α) : b = a → indexOf a (b :: l) = 0
| e => by rw [← e]; exact indexOf_cons_self b l
-- fun n => if_neg n
@[simp]
theorem indexOf_cons_ne {a b : α} (l : List α) : b ≠ a → indexOf a (b :: l) = succ (indexOf a l)
| h => by simp only [indexOf, findIdx_cons, Bool.cond_eq_ite, beq_iff_eq, h, ite_false]
theorem indexOf_eq_length {a : α} {l : List α} : indexOf a l = length l ↔ a ∉ l := by
induction' l with b l ih
· exact iff_of_true rfl (not_mem_nil _)
simp only [length, mem_cons, indexOf_cons, eq_comm]
rw [cond_eq_if]
split_ifs with h <;> simp at h
· exact iff_of_false (by rintro ⟨⟩) fun H => H <| Or.inl h.symm
· simp only [Ne.symm h, false_or_iff]
rw [← ih]
exact succ_inj'
@[simp]
theorem indexOf_of_not_mem {l : List α} {a : α} : a ∉ l → indexOf a l = length l :=
indexOf_eq_length.2
theorem indexOf_le_length {a : α} {l : List α} : indexOf a l ≤ length l := by
induction' l with b l ih; · rfl
simp only [length, indexOf_cons, cond_eq_if, beq_iff_eq]
by_cases h : b = a
· rw [if_pos h]; exact Nat.zero_le _
· rw [if_neg h]; exact succ_le_succ ih
theorem indexOf_lt_length {a} {l : List α} : indexOf a l < length l ↔ a ∈ l :=
⟨fun h => Decidable.by_contradiction fun al => Nat.ne_of_lt h <| indexOf_eq_length.2 al,
fun al => (lt_of_le_of_ne indexOf_le_length) fun h => indexOf_eq_length.1 h al⟩
theorem indexOf_append_of_mem {a : α} (h : a ∈ l₁) : indexOf a (l₁ ++ l₂) = indexOf a l₁ := by
induction' l₁ with d₁ t₁ ih
· exfalso
exact not_mem_nil a h
rw [List.cons_append]
by_cases hh : d₁ = a
· iterate 2 rw [indexOf_cons_eq _ hh]
rw [indexOf_cons_ne _ hh, indexOf_cons_ne _ hh, ih (mem_of_ne_of_mem (Ne.symm hh) h)]
theorem indexOf_append_of_not_mem {a : α} (h : a ∉ l₁) :
indexOf a (l₁ ++ l₂) = l₁.length + indexOf a l₂ := by
induction' l₁ with d₁ t₁ ih
· rw [List.nil_append, List.length, Nat.zero_add]
rw [List.cons_append, indexOf_cons_ne _ (ne_of_not_mem_cons h).symm, List.length,
ih (not_mem_of_not_mem_cons h), Nat.succ_add]
end IndexOf
/-! ### nth element -/
section deprecated
set_option linter.deprecated false
@[deprecated get_of_mem (since := "2023-01-05")]
theorem nthLe_of_mem {a} {l : List α} (h : a ∈ l) : ∃ n h, nthLe l n h = a :=
let ⟨i, h⟩ := get_of_mem h; ⟨i.1, i.2, h⟩
@[deprecated get?_eq_get (since := "2023-01-05")]
theorem nthLe_get? {l : List α} {n} (h) : get? l n = some (nthLe l n h) := get?_eq_get _
@[simp]
theorem getElem?_length (l : List α) : l[l.length]? = none := getElem?_len_le le_rfl
@[deprecated getElem?_length (since := "2024-06-12")]
theorem get?_length (l : List α) : l.get? l.length = none := get?_len_le le_rfl
@[deprecated get_mem (since := "2023-01-05")]
theorem nthLe_mem (l : List α) (n h) : nthLe l n h ∈ l := get_mem ..
@[deprecated mem_iff_get (since := "2023-01-05")]
theorem mem_iff_nthLe {a} {l : List α} : a ∈ l ↔ ∃ n h, nthLe l n h = a :=
mem_iff_get.trans ⟨fun ⟨⟨n, h⟩, e⟩ => ⟨n, h, e⟩, fun ⟨n, h, e⟩ => ⟨⟨n, h⟩, e⟩⟩
@[deprecated (since := "2024-05-03")] alias get?_injective := get?_inj
@[deprecated get_map (since := "2023-01-05")]
theorem nthLe_map (f : α → β) {l n} (H1 H2) : nthLe (map f l) n H1 = f (nthLe l n H2) := get_map ..
/-- A version of `getElem_map` that can be used for rewriting. -/
theorem getElem_map_rev (f : α → β) {l} {n : Nat} {h : n < l.length} :
f l[n] = (map f l)[n]'((l.length_map f).symm ▸ h) := Eq.symm (getElem_map _)
/-- A version of `get_map` that can be used for rewriting. -/
@[deprecated getElem_map_rev (since := "2024-06-12")]
theorem get_map_rev (f : α → β) {l n} :
f (get l n) = get (map f l) ⟨n.1, (l.length_map f).symm ▸ n.2⟩ := Eq.symm (get_map _)
/-- A version of `nthLe_map` that can be used for rewriting. -/
@[deprecated get_map_rev (since := "2023-01-05")]
theorem nthLe_map_rev (f : α → β) {l n} (H) :
f (nthLe l n H) = nthLe (map f l) n ((l.length_map f).symm ▸ H) :=
(nthLe_map f _ _).symm
@[simp, deprecated get_map (since := "2023-01-05")]
theorem nthLe_map' (f : α → β) {l n} (H) :
nthLe (map f l) n H = f (nthLe l n (l.length_map f ▸ H)) := nthLe_map f _ _
@[simp, deprecated get_singleton (since := "2023-01-05")]
theorem nthLe_singleton (a : α) {n : ℕ} (hn : n < 1) : nthLe [a] n hn = a := get_singleton ..
@[deprecated get_append_right' (since := "2023-01-05")]
theorem nthLe_append_right {l₁ l₂ : List α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂) :
(l₁ ++ l₂).nthLe n h₂ = l₂.nthLe (n - l₁.length) (get_append_right_aux h₁ h₂) :=
get_append_right' h₁ h₂
theorem get_length_sub_one {l : List α} (h : l.length - 1 < l.length) :
l.get ⟨l.length - 1, h⟩ = l.getLast (by rintro rfl; exact Nat.lt_irrefl 0 h) :=
(getLast_eq_get l _).symm
@[deprecated get_cons_length (since := "2023-01-05")]
theorem nthLe_cons_length : ∀ (x : α) (xs : List α) (n : ℕ) (h : n = xs.length),
(x :: xs).nthLe n (by simp [h]) = (x :: xs).getLast (cons_ne_nil x xs) := get_cons_length
theorem take_one_drop_eq_of_lt_length {l : List α} {n : ℕ} (h : n < l.length) :
(l.drop n).take 1 = [l.get ⟨n, h⟩] := by
rw [drop_eq_get_cons h, take, take]
theorem ext_get?' {l₁ l₂ : List α} (h' : ∀ n < max l₁.length l₂.length, l₁.get? n = l₂.get? n) :
l₁ = l₂ := by
apply ext
intro n
rcases Nat.lt_or_ge n <| max l₁.length l₂.length with hn | hn
· exact h' n hn
· simp_all [Nat.max_le, getElem?_eq_none]
theorem ext_get?_iff {l₁ l₂ : List α} : l₁ = l₂ ↔ ∀ n, l₁.get? n = l₂.get? n :=
⟨by rintro rfl _; rfl, ext_get?⟩
theorem ext_get_iff {l₁ l₂ : List α} :
l₁ = l₂ ↔ l₁.length = l₂.length ∧ ∀ n h₁ h₂, get l₁ ⟨n, h₁⟩ = get l₂ ⟨n, h₂⟩ := by
constructor
· rintro rfl
exact ⟨rfl, fun _ _ _ ↦ rfl⟩
· intro ⟨h₁, h₂⟩
exact ext_get h₁ h₂
theorem ext_get?_iff' {l₁ l₂ : List α} : l₁ = l₂ ↔
∀ n < max l₁.length l₂.length, l₁.get? n = l₂.get? n :=
⟨by rintro rfl _ _; rfl, ext_get?'⟩
@[deprecated ext_get (since := "2023-01-05")]
theorem ext_nthLe {l₁ l₂ : List α} (hl : length l₁ = length l₂)
(h : ∀ n h₁ h₂, nthLe l₁ n h₁ = nthLe l₂ n h₂) : l₁ = l₂ :=
ext_get hl h
@[simp]
theorem getElem_indexOf [DecidableEq α] {a : α} : ∀ {l : List α} (h : indexOf a l < l.length),
l[indexOf a l] = a
| b :: l, h => by
by_cases h' : b = a <;>
simp [h', if_pos, if_false, getElem_indexOf]
-- This is incorrectly named and should be `get_indexOf`;
-- this already exists, so will require a deprecation dance.
theorem indexOf_get [DecidableEq α] {a : α} {l : List α} (h) : get l ⟨indexOf a l, h⟩ = a := by
simp
@[simp]
theorem getElem?_indexOf [DecidableEq α] {a : α} {l : List α} (h : a ∈ l) :
l[indexOf a l]? = some a := by rw [getElem?_eq_getElem, getElem_indexOf (indexOf_lt_length.2 h)]
-- This is incorrectly named and should be `get?_indexOf`;
-- this already exists, so will require a deprecation dance.
theorem indexOf_get? [DecidableEq α] {a : α} {l : List α} (h : a ∈ l) :
get? l (indexOf a l) = some a := by simp [h]
@[deprecated (since := "2023-01-05")]
theorem get_reverse_aux₁ :
∀ (l r : List α) (i h1 h2), get (reverseAux l r) ⟨i + length l, h1⟩ = get r ⟨i, h2⟩
| [], r, i => fun h1 _ => rfl
| a :: l, r, i => by
rw [show i + length (a :: l) = i + 1 + length l from Nat.add_right_comm i (length l) 1]
exact fun h1 h2 => get_reverse_aux₁ l (a :: r) (i + 1) h1 (succ_lt_succ h2)
theorem indexOf_inj [DecidableEq α] {l : List α} {x y : α} (hx : x ∈ l) (hy : y ∈ l) :
indexOf x l = indexOf y l ↔ x = y :=
⟨fun h => by
have x_eq_y :
get l ⟨indexOf x l, indexOf_lt_length.2 hx⟩ =
get l ⟨indexOf y l, indexOf_lt_length.2 hy⟩ := by
simp only [h]
simp only [indexOf_get] at x_eq_y; exact x_eq_y, fun h => by subst h; rfl⟩
theorem getElem_reverse_aux₂ :
∀ (l r : List α) (i : Nat) (h1) (h2),
(reverseAux l r)[length l - 1 - i]'h1 = l[i]'h2
| [], r, i, h1, h2 => absurd h2 (Nat.not_lt_zero _)
| a :: l, r, 0, h1, _ => by
have aux := get_reverse_aux₁ l (a :: r) 0
rw [Nat.zero_add] at aux
exact aux _ (zero_lt_succ _)
| a :: l, r, i + 1, h1, h2 => by
have aux := getElem_reverse_aux₂ l (a :: r) i
have heq : length (a :: l) - 1 - (i + 1) = length l - 1 - i := by rw [length]; omega
rw [← heq] at aux
apply aux
@[simp] theorem getElem_reverse (l : List α) (i : Nat) (h1 h2) :
(reverse l)[length l - 1 - i]'h1 = l[i]'h2 :=
getElem_reverse_aux₂ _ _ _ _ _
@[deprecated getElem_reverse_aux₂ (since := "2024-06-12")]
theorem get_reverse_aux₂ (l r : List α) (i : Nat) (h1) (h2) :
get (reverseAux l r) ⟨length l - 1 - i, h1⟩ = get l ⟨i, h2⟩ := by
simp [getElem_reverse_aux₂, h1, h2]
@[deprecated getElem_reverse (since := "2024-06-12")]
theorem get_reverse (l : List α) (i : Nat) (h1 h2) :
get (reverse l) ⟨length l - 1 - i, h1⟩ = get l ⟨i, h2⟩ :=
get_reverse_aux₂ _ _ _ _ _
@[simp, deprecated get_reverse (since := "2023-01-05")]
theorem nthLe_reverse (l : List α) (i : Nat) (h1 h2) :
nthLe (reverse l) (length l - 1 - i) h1 = nthLe l i h2 :=
get_reverse ..
theorem nthLe_reverse' (l : List α) (n : ℕ) (hn : n < l.reverse.length) (hn') :
l.reverse.nthLe n hn = l.nthLe (l.length - 1 - n) hn' := by
rw [eq_comm]
convert nthLe_reverse l.reverse n (by simpa) hn using 1
simp
theorem get_reverse' (l : List α) (n) (hn') :
l.reverse.get n = l.get ⟨l.length - 1 - n, hn'⟩ := nthLe_reverse' ..
-- FIXME: prove it the other way around
attribute [deprecated get_reverse' (since := "2023-01-05")] nthLe_reverse'
theorem eq_cons_of_length_one {l : List α} (h : l.length = 1) :
l = [l.nthLe 0 (by omega)] := by
refine ext_get (by convert h) fun n h₁ h₂ => ?_
simp only [get_singleton]
congr
omega
end deprecated
theorem modifyNthTail_modifyNthTail {f g : List α → List α} (m : ℕ) :
∀ (n) (l : List α),
(l.modifyNthTail f n).modifyNthTail g (m + n) =
l.modifyNthTail (fun l => (f l).modifyNthTail g m) n
| 0, _ => rfl
| _ + 1, [] => rfl
| n + 1, a :: l => congr_arg (List.cons a) (modifyNthTail_modifyNthTail m n l)
theorem modifyNthTail_modifyNthTail_le {f g : List α → List α} (m n : ℕ) (l : List α)
(h : n ≤ m) :
(l.modifyNthTail f n).modifyNthTail g m =
l.modifyNthTail (fun l => (f l).modifyNthTail g (m - n)) n := by
rcases Nat.exists_eq_add_of_le h with ⟨m, rfl⟩
rw [Nat.add_comm, modifyNthTail_modifyNthTail, Nat.add_sub_cancel]
theorem modifyNthTail_modifyNthTail_same {f g : List α → List α} (n : ℕ) (l : List α) :
(l.modifyNthTail f n).modifyNthTail g n = l.modifyNthTail (g ∘ f) n := by
rw [modifyNthTail_modifyNthTail_le n n l (le_refl n), Nat.sub_self]; rfl
@[deprecated (since := "2024-05-04")] alias removeNth_eq_nthTail := eraseIdx_eq_modifyNthTail
theorem modifyNth_eq_set (f : α → α) :
∀ (n) (l : List α), modifyNth f n l = ((fun a => set l n (f a)) <$> l[n]?).getD l
| 0, l => by cases l <;> simp
| n + 1, [] => rfl
| n + 1, b :: l =>
(congr_arg (cons b) (modifyNth_eq_set f n l)).trans <| by cases h : l[n]? <;> simp [h]
theorem length_modifyNthTail (f : List α → List α) (H : ∀ l, length (f l) = length l) :
∀ n l, length (modifyNthTail f n l) = length l
| 0, _ => H _
| _ + 1, [] => rfl
| _ + 1, _ :: _ => @congr_arg _ _ _ _ (· + 1) (length_modifyNthTail _ H _ _)
-- Porting note: Duplicate of `modify_get?_length`
-- (but with a substantially better name?)
-- @[simp]
theorem length_modifyNth (f : α → α) : ∀ n l, length (modifyNth f n l) = length l :=
modify_get?_length f
@[simp]
theorem getElem_set_of_ne {l : List α} {i j : ℕ} (h : i ≠ j) (a : α)
(hj : j < (l.set i a).length) :
(l.set i a)[j] = l[j]'(by simpa using hj) := by
rw [← Option.some_inj, ← List.getElem?_eq_getElem, List.getElem?_set_ne h,
List.getElem?_eq_getElem]
@[deprecated getElem_set_of_ne (since := "2024-06-12")]
theorem get_set_of_ne {l : List α} {i j : ℕ} (h : i ≠ j) (a : α)
(hj : j < (l.set i a).length) :
(l.set i a).get ⟨j, hj⟩ = l.get ⟨j, by simpa using hj⟩ := by
simp [getElem_set_of_ne, h]
/-! ### map -/
@[deprecated (since := "2024-06-21")] alias map_congr := map_congr_left
theorem bind_pure_eq_map (f : α → β) (l : List α) : l.bind (pure ∘ f) = map f l :=
.symm <| map_eq_bind ..
set_option linter.deprecated false in
@[deprecated bind_pure_eq_map (since := "2024-03-24")]
theorem bind_ret_eq_map (f : α → β) (l : List α) : l.bind (List.ret ∘ f) = map f l :=
bind_pure_eq_map f l
theorem bind_congr {l : List α} {f g : α → List β} (h : ∀ x ∈ l, f x = g x) :
List.bind l f = List.bind l g :=
(congr_arg List.join <| map_congr_left h : _)
theorem infix_bind_of_mem {a : α} {as : List α} (h : a ∈ as) (f : α → List α) :
f a <:+: as.bind f :=
List.infix_of_mem_join (List.mem_map_of_mem f h)
@[simp]
theorem map_eq_map {α β} (f : α → β) (l : List α) : f <$> l = map f l :=
rfl
@[simp]
theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) := by cases l <;> rfl
/-- A single `List.map` of a composition of functions is equal to
composing a `List.map` with another `List.map`, fully applied.
This is the reverse direction of `List.map_map`.
-/
theorem comp_map (h : β → γ) (g : α → β) (l : List α) : map (h ∘ g) l = map h (map g l) :=
(map_map _ _ _).symm
/-- Composing a `List.map` with another `List.map` is equal to
a single `List.map` of composed functions.
-/
@[simp]
theorem map_comp_map (g : β → γ) (f : α → β) : map g ∘ map f = map (g ∘ f) := by
ext l; rw [comp_map, Function.comp_apply]
section map_bijectivity
theorem _root_.Function.LeftInverse.list_map {f : α → β} {g : β → α} (h : LeftInverse f g) :
LeftInverse (map f) (map g)
| [] => by simp_rw [map_nil]
| x :: xs => by simp_rw [map_cons, h x, h.list_map xs]
nonrec theorem _root_.Function.RightInverse.list_map {f : α → β} {g : β → α}
(h : RightInverse f g) : RightInverse (map f) (map g) :=
h.list_map
nonrec theorem _root_.Function.Involutive.list_map {f : α → α}
(h : Involutive f) : Involutive (map f) :=
Function.LeftInverse.list_map h
@[simp]
theorem map_leftInverse_iff {f : α → β} {g : β → α} :
LeftInverse (map f) (map g) ↔ LeftInverse f g :=
⟨fun h x => by injection h [x], (·.list_map)⟩
@[simp]
theorem map_rightInverse_iff {f : α → β} {g : β → α} :
RightInverse (map f) (map g) ↔ RightInverse f g := map_leftInverse_iff
@[simp]
theorem map_involutive_iff {f : α → α} :
Involutive (map f) ↔ Involutive f := map_leftInverse_iff
theorem _root_.Function.Injective.list_map {f : α → β} (h : Injective f) :
Injective (map f)
| [], [], _ => rfl
| x :: xs, y :: ys, hxy => by
injection hxy with hxy hxys
rw [h hxy, h.list_map hxys]
@[simp]
theorem map_injective_iff {f : α → β} : Injective (map f) ↔ Injective f := by
refine ⟨fun h x y hxy => ?_, (·.list_map)⟩
suffices [x] = [y] by simpa using this
apply h
simp [hxy]
theorem _root_.Function.Surjective.list_map {f : α → β} (h : Surjective f) :
Surjective (map f) :=
let ⟨_, h⟩ := h.hasRightInverse; h.list_map.surjective
@[simp]
theorem map_surjective_iff {f : α → β} : Surjective (map f) ↔ Surjective f := by
refine ⟨fun h x => ?_, (·.list_map)⟩
let ⟨[y], hxy⟩ := h [x]
exact ⟨_, List.singleton_injective hxy⟩
theorem _root_.Function.Bijective.list_map {f : α → β} (h : Bijective f) : Bijective (map f) :=
⟨h.1.list_map, h.2.list_map⟩
@[simp]
theorem map_bijective_iff {f : α → β} : Bijective (map f) ↔ Bijective f := by
simp_rw [Function.Bijective, map_injective_iff, map_surjective_iff]
end map_bijectivity
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : List α} (h : b₁ ∈ map (const α b₂) l) :
b₁ = b₂ := by rw [map_const] at h; exact eq_of_mem_replicate h
/-! ### zipWith -/
theorem nil_zipWith (f : α → β → γ) (l : List β) : zipWith f [] l = [] := by cases l <;> rfl
theorem zipWith_nil (f : α → β → γ) (l : List α) : zipWith f l [] = [] := by cases l <;> rfl
@[simp]
theorem zipWith_flip (f : α → β → γ) : ∀ as bs, zipWith (flip f) bs as = zipWith f as bs
| [], [] => rfl
| [], b :: bs => rfl
| a :: as, [] => rfl
| a :: as, b :: bs => by
simp! [zipWith_flip]
rfl
/-! ### take, drop -/
theorem take_cons (n) (a : α) (l : List α) : take (succ n) (a :: l) = a :: take n l :=
rfl
@[simp]
theorem drop_tail (l : List α) (n : ℕ) : l.tail.drop n = l.drop (n + 1) := by
rw [← drop_drop, drop_one]
theorem cons_getElem_drop_succ {l : List α} {n : Nat} {h : n < l.length} :
l[n] :: l.drop (n + 1) = l.drop n :=
(drop_eq_getElem_cons h).symm
theorem cons_get_drop_succ {l : List α} {n} :
l.get n :: l.drop (n.1 + 1) = l.drop n.1 :=
(drop_eq_getElem_cons n.2).symm
section TakeI
variable [Inhabited α]
@[simp]
theorem takeI_length : ∀ n l, length (@takeI α _ n l) = n
| 0, _ => rfl
| _ + 1, _ => congr_arg succ (takeI_length _ _)
@[simp]
theorem takeI_nil : ∀ n, takeI n (@nil α) = replicate n default
| 0 => rfl
| _ + 1 => congr_arg (cons _) (takeI_nil _)
theorem takeI_eq_take : ∀ {n} {l : List α}, n ≤ length l → takeI n l = take n l
| 0, _, _ => rfl
| _ + 1, _ :: _, h => congr_arg (cons _) <| takeI_eq_take <| le_of_succ_le_succ h
@[simp]
theorem takeI_left (l₁ l₂ : List α) : takeI (length l₁) (l₁ ++ l₂) = l₁ :=
(takeI_eq_take (by simp only [length_append, Nat.le_add_right])).trans (take_left _ _)
theorem takeI_left' {l₁ l₂ : List α} {n} (h : length l₁ = n) : takeI n (l₁ ++ l₂) = l₁ := by
rw [← h]; apply takeI_left
end TakeI
/- Porting note: in mathlib3 we just had `take` and `take'`. Now we have `take`, `takeI`, and
`takeD`. The following section replicates the theorems above but for `takeD`. -/
section TakeD
@[simp]
theorem takeD_length : ∀ n l a, length (@takeD α n l a) = n
| 0, _, _ => rfl
| _ + 1, _, _ => congr_arg succ (takeD_length _ _ _)
-- `takeD_nil` is already in batteries
theorem takeD_eq_take : ∀ {n} {l : List α} a, n ≤ length l → takeD n l a = take n l
| 0, _, _, _ => rfl
| _ + 1, _ :: _, a, h => congr_arg (cons _) <| takeD_eq_take a <| le_of_succ_le_succ h
@[simp]
theorem takeD_left (l₁ l₂ : List α) (a : α) : takeD (length l₁) (l₁ ++ l₂) a = l₁ :=
(takeD_eq_take a (by simp only [length_append, Nat.le_add_right])).trans (take_left _ _)
theorem takeD_left' {l₁ l₂ : List α} {n} {a} (h : length l₁ = n) : takeD n (l₁ ++ l₂) a = l₁ := by
rw [← h]; apply takeD_left
end TakeD
/-! ### foldl, foldr -/
theorem foldl_ext (f g : α → β → α) (a : α) {l : List β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) :
foldl f a l = foldl g a l := by
induction l generalizing a with
| nil => rfl
| cons hd tl ih =>
unfold foldl
rw [ih _ fun a b bin => H a b <| mem_cons_of_mem _ bin, H a hd (mem_cons_self _ _)]
theorem foldr_ext (f g : α → β → β) (b : β) {l : List α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) :
foldr f b l = foldr g b l := by
induction' l with hd tl ih; · rfl
simp only [mem_cons, or_imp, forall_and, forall_eq] at H
simp only [foldr, ih H.2, H.1]
theorem foldl_concat
(f : β → α → β) (b : β) (x : α) (xs : List α) :
List.foldl f b (xs ++ [x]) = f (List.foldl f b xs) x := by
simp only [List.foldl_append, List.foldl]
theorem foldr_concat
(f : α → β → β) (b : β) (x : α) (xs : List α) :
List.foldr f b (xs ++ [x]) = (List.foldr f (f x b) xs) := by
simp only [List.foldr_append, List.foldr]
theorem foldl_fixed' {f : α → β → α} {a : α} (hf : ∀ b, f a b = a) : ∀ l : List β, foldl f a l = a
| [] => rfl
| b :: l => by rw [foldl_cons, hf b, foldl_fixed' hf l]
theorem foldr_fixed' {f : α → β → β} {b : β} (hf : ∀ a, f a b = b) : ∀ l : List α, foldr f b l = b
| [] => rfl
| a :: l => by rw [foldr_cons, foldr_fixed' hf l, hf a]
@[simp]
theorem foldl_fixed {a : α} : ∀ l : List β, foldl (fun a _ => a) a l = a :=
foldl_fixed' fun _ => rfl
@[simp]
theorem foldr_fixed {b : β} : ∀ l : List α, foldr (fun _ b => b) b l = b :=
foldr_fixed' fun _ => rfl
-- Porting note (#10618): simp can prove this
-- @[simp]
theorem foldr_eta : ∀ l : List α, foldr cons [] l = l := by
simp only [foldr_self_append, append_nil, forall_const]
@[simp]
theorem reverse_foldl {l : List α} : reverse (foldl (fun t h => h :: t) [] l) = l := by
rw [← foldr_reverse]; simp only [foldr_self_append, append_nil, reverse_reverse]
theorem foldl_hom₂ (l : List ι) (f : α → β → γ) (op₁ : α → ι → α) (op₂ : β → ι → β)
(op₃ : γ → ι → γ) (a : α) (b : β) (h : ∀ a b i, f (op₁ a i) (op₂ b i) = op₃ (f a b) i) :
foldl op₃ (f a b) l = f (foldl op₁ a l) (foldl op₂ b l) :=
Eq.symm <| by
revert a b
induction l <;> intros <;> [rfl; simp only [*, foldl]]
theorem foldr_hom₂ (l : List ι) (f : α → β → γ) (op₁ : ι → α → α) (op₂ : ι → β → β)
(op₃ : ι → γ → γ) (a : α) (b : β) (h : ∀ a b i, f (op₁ i a) (op₂ i b) = op₃ i (f a b)) :
foldr op₃ (f a b) l = f (foldr op₁ a l) (foldr op₂ b l) := by
revert a
induction l <;> intros <;> [rfl; simp only [*, foldr]]
theorem injective_foldl_comp {l : List (α → α)} {f : α → α}
(hl : ∀ f ∈ l, Function.Injective f) (hf : Function.Injective f) :
Function.Injective (@List.foldl (α → α) (α → α) Function.comp f l) := by
induction' l with lh lt l_ih generalizing f
· exact hf
· apply l_ih fun _ h => hl _ (List.mem_cons_of_mem _ h)
apply Function.Injective.comp hf
apply hl _ (List.mem_cons_self _ _)
/-- Induction principle for values produced by a `foldr`: if a property holds
for the seed element `b : β` and for all incremental `op : α → β → β`
performed on the elements `(a : α) ∈ l`. The principle is given for
a `Sort`-valued predicate, i.e., it can also be used to construct data. -/
def foldrRecOn {C : β → Sort*} (l : List α) (op : α → β → β) (b : β) (hb : C b)
(hl : ∀ b, C b → ∀ a ∈ l, C (op a b)) : C (foldr op b l) := by
induction l with
| nil => exact hb
| cons hd tl IH =>
refine hl _ ?_ hd (mem_cons_self hd tl)
refine IH ?_
intro y hy x hx
exact hl y hy x (mem_cons_of_mem hd hx)
/-- Induction principle for values produced by a `foldl`: if a property holds
for the seed element `b : β` and for all incremental `op : β → α → β`
performed on the elements `(a : α) ∈ l`. The principle is given for
a `Sort`-valued predicate, i.e., it can also be used to construct data. -/
def foldlRecOn {C : β → Sort*} (l : List α) (op : β → α → β) (b : β) (hb : C b)
(hl : ∀ b, C b → ∀ a ∈ l, C (op b a)) : C (foldl op b l) := by
induction l generalizing b with
| nil => exact hb
| cons hd tl IH =>
refine IH _ ?_ ?_
· exact hl b hb hd (mem_cons_self hd tl)
· intro y hy x hx
exact hl y hy x (mem_cons_of_mem hd hx)
@[simp]
theorem foldrRecOn_nil {C : β → Sort*} (op : α → β → β) (b) (hb : C b) (hl) :
foldrRecOn [] op b hb hl = hb :=
rfl
@[simp]
theorem foldrRecOn_cons {C : β → Sort*} (x : α) (l : List α) (op : α → β → β) (b) (hb : C b)
(hl : ∀ b, C b → ∀ a ∈ x :: l, C (op a b)) :
foldrRecOn (x :: l) op b hb hl =
hl _ (foldrRecOn l op b hb fun b hb a ha => hl b hb a (mem_cons_of_mem _ ha)) x
(mem_cons_self _ _) :=
rfl
@[simp]
theorem foldlRecOn_nil {C : β → Sort*} (op : β → α → β) (b) (hb : C b) (hl) :
foldlRecOn [] op b hb hl = hb :=
rfl
/-- Consider two lists `l₁` and `l₂` with designated elements `a₁` and `a₂` somewhere in them:
`l₁ = x₁ ++ [a₁] ++ z₁` and `l₂ = x₂ ++ [a₂] ++ z₂`.
Assume the designated element `a₂` is present in neither `x₁` nor `z₁`.
We conclude that the lists are equal (`l₁ = l₂`) if and only if their respective parts are equal
(`x₁ = x₂ ∧ a₁ = a₂ ∧ z₁ = z₂`). -/
lemma append_cons_inj_of_not_mem {x₁ x₂ z₁ z₂ : List α} {a₁ a₂ : α}
(notin_x : a₂ ∉ x₁) (notin_z : a₂ ∉ z₁) :
x₁ ++ a₁ :: z₁ = x₂ ++ a₂ :: z₂ ↔ x₁ = x₂ ∧ a₁ = a₂ ∧ z₁ = z₂ := by
constructor
· simp only [append_eq_append_iff, cons_eq_append, cons_eq_cons]
rintro (⟨c, rfl, ⟨rfl, rfl, rfl⟩ | ⟨d, rfl, rfl⟩⟩ |
⟨c, rfl, ⟨rfl, rfl, rfl⟩ | ⟨d, rfl, rfl⟩⟩) <;> simp_all
· rintro ⟨rfl, rfl, rfl⟩
rfl
section Scanl
variable {f : β → α → β} {b : β} {a : α} {l : List α}
theorem length_scanl : ∀ a l, length (scanl f a l) = l.length + 1
| a, [] => rfl
| a, x :: l => by
rw [scanl, length_cons, length_cons, ← succ_eq_add_one, congr_arg succ]
exact length_scanl _ _
@[simp]
theorem scanl_nil (b : β) : scanl f b nil = [b] :=
rfl
@[simp]
theorem scanl_cons : scanl f b (a :: l) = [b] ++ scanl f (f b a) l := by
simp only [scanl, eq_self_iff_true, singleton_append, and_self_iff]
@[simp]
theorem getElem?_scanl_zero : (scanl f b l)[0]? = some b := by
cases l
· simp [scanl_nil]
· simp [scanl_cons, singleton_append]
@[deprecated getElem?_scanl_zero (since := "2024-06-12")]
theorem get?_zero_scanl : (scanl f b l).get? 0 = some b := by
simp [getElem?_scanl_zero]
@[simp]
theorem getElem_scanl_zero {h : 0 < (scanl f b l).length} : (scanl f b l)[0] = b := by
cases l
· simp [scanl_nil]
· simp [scanl_cons, singleton_append]
@[deprecated getElem_scanl_zero (since := "2024-06-12")]
theorem get_zero_scanl {h : 0 < (scanl f b l).length} : (scanl f b l).get ⟨0, h⟩ = b := by
simp [getElem_scanl_zero]
set_option linter.deprecated false in
@[simp, deprecated get_zero_scanl (since := "2023-01-05")]
theorem nthLe_zero_scanl {h : 0 < (scanl f b l).length} : (scanl f b l).nthLe 0 h = b :=
get_zero_scanl
theorem get?_succ_scanl {i : ℕ} : (scanl f b l).get? (i + 1) =
((scanl f b l).get? i).bind fun x => (l.get? i).map fun y => f x y := by
induction' l with hd tl hl generalizing b i
· symm
simp only [Option.bind_eq_none', get?, forall₂_true_iff, not_false_iff, Option.map_none',
scanl_nil, Option.not_mem_none, forall_true_iff]
· simp only [scanl_cons, singleton_append]
cases i
· simp
· simp only [hl, get?]
set_option linter.deprecated false in
theorem nthLe_succ_scanl {i : ℕ} {h : i + 1 < (scanl f b l).length} :
(scanl f b l).nthLe (i + 1) h =
f ((scanl f b l).nthLe i (Nat.lt_of_succ_lt h))
(l.nthLe i (Nat.lt_of_succ_lt_succ (lt_of_lt_of_le h (le_of_eq (length_scanl b l))))) := by
induction i generalizing b l with
| zero =>
cases l
· simp only [length, zero_eq, lt_self_iff_false] at h
· simp [scanl_cons, singleton_append, nthLe_zero_scanl, nthLe_cons]
| succ i hi =>
cases l
· simp only [length] at h
exact absurd h (by omega)
· simp_rw [scanl_cons]
rw [nthLe_append_right]
· simp only [length, Nat.zero_add 1, succ_add_sub_one, hi]; rfl
· simp only [length_singleton]; omega
theorem get_succ_scanl {i : ℕ} {h : i + 1 < (scanl f b l).length} :
(scanl f b l).get ⟨i + 1, h⟩ =
f ((scanl f b l).get ⟨i, Nat.lt_of_succ_lt h⟩)
(l.get ⟨i, Nat.lt_of_succ_lt_succ (lt_of_lt_of_le h (le_of_eq (length_scanl b l)))⟩) :=
nthLe_succ_scanl
-- FIXME: we should do the proof the other way around
attribute [deprecated get_succ_scanl (since := "2023-01-05")] nthLe_succ_scanl
end Scanl
-- scanr
@[simp]
theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] :=
rfl
@[simp]
theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : List α) :
scanr f b (a :: l) = foldr f b (a :: l) :: scanr f b l := by
simp only [scanr, foldr, cons.injEq, and_true]
induction l generalizing a with
| nil => rfl
| cons hd tl ih => simp only [foldr, ih]
section FoldlEqFoldr
-- foldl and foldr coincide when f is commutative and associative
variable {f : α → α → α}
theorem foldl1_eq_foldr1 (hassoc : Associative f) :
∀ a b l, foldl f a (l ++ [b]) = foldr f b (a :: l)
| a, b, nil => rfl
| a, b, c :: l => by
simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 hassoc _ _ l]; rw [hassoc]
theorem foldl_eq_of_comm_of_assoc (hcomm : Commutative f) (hassoc : Associative f) :
∀ a b l, foldl f a (b :: l) = f b (foldl f a l)
| a, b, nil => hcomm a b
| a, b, c :: l => by
simp only [foldl_cons]
rw [← foldl_eq_of_comm_of_assoc hcomm hassoc .., right_comm _ hcomm hassoc]; rfl
theorem foldl_eq_foldr (hcomm : Commutative f) (hassoc : Associative f) :
∀ a l, foldl f a l = foldr f a l
| a, nil => rfl
| a, b :: l => by
simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]
rw [foldl_eq_foldr hcomm hassoc a l]
end FoldlEqFoldr
section FoldlEqFoldlr'
variable {f : α → β → α}
variable (hf : ∀ a b c, f (f a b) c = f (f a c) b)
theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b :: l) = f (foldl f a l) b
| a, b, [] => rfl
| a, b, c :: l => by rw [foldl, foldl, foldl, ← foldl_eq_of_comm' .., foldl, hf]
theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l
| a, [] => rfl
| a, b :: l => by rw [foldl_eq_of_comm' hf, foldr, foldl_eq_foldr' ..]; rfl
end FoldlEqFoldlr'
section FoldlEqFoldlr'
variable {f : α → β → β}
theorem foldr_eq_of_comm' (hf : ∀ a b c, f a (f b c) = f b (f a c)) :
∀ a b l, foldr f a (b :: l) = foldr f (f b a) l
| a, b, [] => rfl
| a, b, c :: l => by rw [foldr, foldr, foldr, hf, ← foldr_eq_of_comm' hf ..]; rfl
end FoldlEqFoldlr'
section
variable {op : α → α → α} [ha : Std.Associative op]
/-- Notation for `op a b`. -/
local notation a " ⋆ " b => op a b
/-- Notation for `foldl op a l`. -/
local notation l " <*> " a => foldl op a l
theorem foldl_assoc : ∀ {l : List α} {a₁ a₂}, (l <*> a₁ ⋆ a₂) = a₁ ⋆ l <*> a₂
| [], a₁, a₂ => rfl
| a :: l, a₁, a₂ =>
calc
((a :: l) <*> a₁ ⋆ a₂) = l <*> a₁ ⋆ a₂ ⋆ a := by simp only [foldl_cons, ha.assoc]
_ = a₁ ⋆ (a :: l) <*> a₂ := by rw [foldl_assoc, foldl_cons]
theorem foldl_op_eq_op_foldr_assoc :
∀ {l : List α} {a₁ a₂}, ((l <*> a₁) ⋆ a₂) = a₁ ⋆ l.foldr (· ⋆ ·) a₂
| [], a₁, a₂ => rfl
| a :: l, a₁, a₂ => by
simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc]
variable [hc : Std.Commutative op]
theorem foldl_assoc_comm_cons {l : List α} {a₁ a₂} : ((a₁ :: l) <*> a₂) = a₁ ⋆ l <*> a₂ := by
rw [foldl_cons, hc.comm, foldl_assoc]
end
/-! ### foldlM, foldrM, mapM -/
section FoldlMFoldrM
variable {m : Type v → Type w} [Monad m]
variable [LawfulMonad m]
theorem foldrM_eq_foldr (f : α → β → m β) (b l) :
foldrM f b l = foldr (fun a mb => mb >>= f a) (pure b) l := by induction l <;> simp [*]
attribute [simp] mapM mapM'
theorem foldlM_eq_foldl (f : β → α → m β) (b l) :
List.foldlM f b l = foldl (fun mb a => mb >>= fun b => f b a) (pure b) l := by
suffices h :
∀ mb : m β, (mb >>= fun b => List.foldlM f b l) = foldl (fun mb a => mb >>= fun b => f b a) mb l
by simp [← h (pure b)]
induction l with
| nil => intro; simp
| cons _ _ l_ih => intro; simp only [List.foldlM, foldl, ← l_ih, functor_norm]
end FoldlMFoldrM
/-! ### intersperse -/
@[simp]
theorem intersperse_singleton (a b : α) : intersperse a [b] = [b] :=
rfl
@[simp]
theorem intersperse_cons_cons (a b c : α) (tl : List α) :
intersperse a (b :: c :: tl) = b :: a :: intersperse a (c :: tl) :=
rfl
/-! ### splitAt and splitOn -/
section SplitAtOn
/- Porting note: the new version of `splitOnP` uses a `Bool`-valued predicate instead of a
`Prop`-valued one. All downstream definitions have been updated to match. -/
variable (p : α → Bool) (xs ys : List α) (ls : List (List α)) (f : List α → List α)
/- Porting note: this had to be rewritten because of the new implementation of `splitAt`. It's
long in large part because `splitAt.go` (`splitAt`'s auxiliary function) works differently
in the case where n ≥ length l, requiring two separate cases (and two separate inductions). Still,
this can hopefully be golfed. -/
@[simp]
theorem splitAt_eq_take_drop (n : ℕ) (l : List α) : splitAt n l = (take n l, drop n l) := by
by_cases h : n < l.length <;> rw [splitAt, go_eq_take_drop]
· rw [if_pos h]; rfl
· rw [if_neg h, take_of_length_le <| le_of_not_lt h, drop_eq_nil_of_le <| le_of_not_lt h]
where
go_eq_take_drop (n : ℕ) (l xs : List α) (acc : Array α) : splitAt.go l xs n acc =
if n < xs.length then (acc.toList ++ take n xs, drop n xs) else (l, []) := by
split_ifs with h
· induction n generalizing xs acc with
| zero =>
rw [splitAt.go, take, drop, append_nil]
· intros h₁; rw [h₁] at h; contradiction
· intros; contradiction
| succ _ ih =>
cases xs with
| nil => contradiction
| cons hd tl =>
rw [length] at h
rw [splitAt.go, take, drop, append_cons, Array.toList_eq, ← Array.push_data,
← Array.toList_eq]
exact ih _ _ <| (by omega)
· induction n generalizing xs acc with
| zero =>
replace h : xs.length = 0 := by omega
rw [eq_nil_of_length_eq_zero h, splitAt.go]
| succ _ ih =>
cases xs with
| nil => rw [splitAt.go]
| cons hd tl =>
rw [length] at h
rw [splitAt.go]
exact ih _ _ <| not_imp_not.mpr (Nat.add_lt_add_right · 1) h
@[simp]
theorem splitOn_nil [DecidableEq α] (a : α) : [].splitOn a = [[]] :=
rfl
@[simp]
theorem splitOnP_nil : [].splitOnP p = [[]] :=
rfl
/- Porting note: `split_on_p_aux` and `split_on_p_aux'` were used to prove facts about
`split_on_p`. `splitOnP` has a different structure, and we need different facts about
`splitOnP.go`. Theorems involving `split_on_p_aux` have been omitted where possible. -/
theorem splitOnP.go_ne_nil (xs acc : List α) : splitOnP.go p xs acc ≠ [] := by
induction xs generalizing acc <;> simp [go]; split <;> simp [*]
theorem splitOnP.go_acc (xs acc : List α) :
splitOnP.go p xs acc = modifyHead (acc.reverse ++ ·) (splitOnP p xs) := by
induction xs generalizing acc with
| nil => simp only [go, modifyHead, splitOnP_nil, append_nil]
| cons hd tl ih =>
simp only [splitOnP, go]; split
· simp only [modifyHead, reverse_nil, append_nil]
· rw [ih [hd], modifyHead_modifyHead, ih]
congr; funext x; simp only [reverse_cons, append_assoc]; rfl
theorem splitOnP_ne_nil (xs : List α) : xs.splitOnP p ≠ [] := splitOnP.go_ne_nil _ _ _
@[simp]
theorem splitOnP_cons (x : α) (xs : List α) :
(x :: xs).splitOnP p =
if p x then [] :: xs.splitOnP p else (xs.splitOnP p).modifyHead (cons x) := by
rw [splitOnP, splitOnP.go]; split <;> [rfl; simp [splitOnP.go_acc]]
/-- The original list `L` can be recovered by joining the lists produced by `splitOnP p L`,
interspersed with the elements `L.filter p`. -/
theorem splitOnP_spec (as : List α) :
join (zipWith (· ++ ·) (splitOnP p as) (((as.filter p).map fun x => [x]) ++ [[]])) = as := by
induction as with
| nil => rfl
| cons a as' ih =>
rw [splitOnP_cons, filter]
by_cases h : p a
· rw [if_pos h, h, map, cons_append, zipWith, nil_append, join, cons_append, cons_inj_right]
exact ih
· rw [if_neg h, eq_false_of_ne_true h, join_zipWith (splitOnP_ne_nil _ _)
(append_ne_nil_of_right_ne_nil _ (cons_ne_nil [] [])), cons_inj_right]
exact ih
where
join_zipWith {xs ys : List (List α)} {a : α} (hxs : xs ≠ []) (hys : ys ≠ []) :
join (zipWith (fun x x_1 ↦ x ++ x_1) (modifyHead (cons a) xs) ys) =
a :: join (zipWith (fun x x_1 ↦ x ++ x_1) xs ys) := by
cases xs with | nil => contradiction | cons =>
cases ys with | nil => contradiction | cons => rfl
/-- If no element satisfies `p` in the list `xs`, then `xs.splitOnP p = [xs]` -/
theorem splitOnP_eq_single (h : ∀ x ∈ xs, ¬p x) : xs.splitOnP p = [xs] := by
induction xs with
| nil => rfl
| cons hd tl ih =>
simp only [splitOnP_cons, h hd (mem_cons_self hd tl), if_neg]
rw [ih <| forall_mem_of_forall_mem_cons h]
rfl
/-- When a list of the form `[...xs, sep, ...as]` is split on `p`, the first element is `xs`,
assuming no element in `xs` satisfies `p` but `sep` does satisfy `p` -/
theorem splitOnP_first (h : ∀ x ∈ xs, ¬p x) (sep : α) (hsep : p sep) (as : List α) :
(xs ++ sep :: as).splitOnP p = xs :: as.splitOnP p := by
induction xs with
| nil => simp [hsep]
| cons hd tl ih => simp [h hd _, ih <| forall_mem_of_forall_mem_cons h]
/-- `intercalate [x]` is the left inverse of `splitOn x` -/
theorem intercalate_splitOn (x : α) [DecidableEq α] : [x].intercalate (xs.splitOn x) = xs := by
simp only [intercalate, splitOn]
induction' xs with hd tl ih; · simp [join]
cases' h' : splitOnP (· == x) tl with hd' tl'; · exact (splitOnP_ne_nil _ tl h').elim
rw [h'] at ih
rw [splitOnP_cons]
split_ifs with h
· rw [beq_iff_eq] at h
subst h
simp [ih, join, h']
cases tl' <;> simpa [join, h'] using ih
/-- `splitOn x` is the left inverse of `intercalate [x]`, on the domain
consisting of each nonempty list of lists `ls` whose elements do not contain `x` -/
theorem splitOn_intercalate [DecidableEq α] (x : α) (hx : ∀ l ∈ ls, x ∉ l) (hls : ls ≠ []) :
([x].intercalate ls).splitOn x = ls := by
simp only [intercalate]
induction' ls with hd tl ih; · contradiction
cases tl
· suffices hd.splitOn x = [hd] by simpa [join]
refine splitOnP_eq_single _ _ ?_
intro y hy H
rw [eq_of_beq H] at hy
refine hx hd ?_ hy
simp
· simp only [intersperse_cons_cons, singleton_append, join]
specialize ih _ _
· intro l hl
apply hx l
simp only [mem_cons] at hl ⊢
exact Or.inr hl
· exact List.noConfusion
have := splitOnP_first (· == x) hd ?h x (beq_self_eq_true _)
case h =>
intro y hy H
rw [eq_of_beq H] at hy
exact hx hd (.head _) hy
simp only [splitOn] at ih ⊢
rw [this, ih]
end SplitAtOn
/- Porting note: new; here tentatively -/
/-! ### modifyLast -/
section ModifyLast
theorem modifyLast.go_append_one (f : α → α) (a : α) (tl : List α) (r : Array α) :
modifyLast.go f (tl ++ [a]) r = (r.toListAppend <| modifyLast.go f (tl ++ [a]) #[]) := by
cases tl with
| nil =>
simp only [nil_append, modifyLast.go]; rfl
| cons hd tl =>
simp only [cons_append]
rw [modifyLast.go, modifyLast.go]
case x_3 | x_3 => exact append_ne_nil_of_right_ne_nil tl (cons_ne_nil a [])
rw [modifyLast.go_append_one _ _ tl _, modifyLast.go_append_one _ _ tl (Array.push #[] hd)]
simp only [Array.toListAppend_eq, Array.push_data, Array.data_toArray, nil_append, append_assoc]
theorem modifyLast_append_one (f : α → α) (a : α) (l : List α) :
modifyLast f (l ++ [a]) = l ++ [f a] := by
cases l with
| nil =>
simp only [nil_append, modifyLast, modifyLast.go, Array.toListAppend_eq, Array.data_toArray]
| cons _ tl =>
simp only [cons_append, modifyLast]
rw [modifyLast.go]
case x_3 => exact append_ne_nil_of_right_ne_nil tl (cons_ne_nil a [])
rw [modifyLast.go_append_one, Array.toListAppend_eq, Array.push_data, Array.data_toArray,
nil_append, cons_append, nil_append, cons_inj_right]
exact modifyLast_append_one _ _ tl
theorem modifyLast_append (f : α → α) (l₁ l₂ : List α) (_ : l₂ ≠ []) :
modifyLast f (l₁ ++ l₂) = l₁ ++ modifyLast f l₂ := by
cases l₂ with
| nil => contradiction
| cons hd tl =>
cases tl with
| nil => exact modifyLast_append_one _ hd _
| cons hd' tl' =>
rw [append_cons, ← nil_append (hd :: hd' :: tl'), append_cons [], nil_append,
modifyLast_append _ (l₁ ++ [hd]) (hd' :: tl') _, modifyLast_append _ [hd] (hd' :: tl') _,
append_assoc]
all_goals { exact cons_ne_nil _ _ }
end ModifyLast
/-! ### map for partial functions -/
theorem sizeOf_lt_sizeOf_of_mem [SizeOf α] {x : α} {l : List α} (hx : x ∈ l) :
SizeOf.sizeOf x < SizeOf.sizeOf l := by
induction' l with h t ih <;> cases hx <;> rw [cons.sizeOf_spec]
· omega
· specialize ih ‹_›
omega
@[deprecated attach_map_coe (since := "2024-07-29")] alias attach_map_coe' := attach_map_coe
@[deprecated attach_map_val (since := "2024-07-29")] alias attach_map_val' := attach_map_val
set_option linter.deprecated false in
@[deprecated get_pmap (since := "2023-01-05")]
theorem nthLe_pmap {p : α → Prop} (f : ∀ a, p a → β) {l : List α} (h : ∀ a ∈ l, p a) {n : ℕ}
(hn : n < (pmap f l h).length) :
nthLe (pmap f l h) n hn =
f (nthLe l n (@length_pmap _ _ p f l h ▸ hn))
(h _ (get_mem l n (@length_pmap _ _ p f l h ▸ hn))) :=
get_pmap ..
/-! ### find -/
section find?
variable {p : α → Bool} {l : List α} {a : α}
-- @[simp]
-- Later porting note (at time of this lemma moving to Batteries):
-- removing attribute `nolint simpNF`
attribute [simp 1100] find?_cons_of_pos
-- @[simp]
-- Later porting note (at time of this lemma moving to Batteries):
-- removing attribute `nolint simpNF`
attribute [simp 1100] find?_cons_of_neg
attribute [simp] find?_eq_none
@[deprecated (since := "2024-05-05")] alias find?_mem := mem_of_find?_eq_some
end find?
/-! ### lookmap -/
section Lookmap
variable (f : α → Option α)
/- Porting note: need a helper theorem for lookmap.go. -/
theorem lookmap.go_append (l : List α) (acc : Array α) :
lookmap.go f l acc = acc.toListAppend (lookmap f l) := by
cases l with
| nil => rfl
| cons hd tl =>
rw [lookmap, go, go]
cases f hd with
| none => simp only [go_append tl _, Array.toListAppend_eq, append_assoc, Array.push_data]; rfl
| some a => rfl
@[simp]
theorem lookmap_nil : [].lookmap f = [] :=
rfl
@[simp]
theorem lookmap_cons_none {a : α} (l : List α) (h : f a = none) :
(a :: l).lookmap f = a :: l.lookmap f := by
simp only [lookmap, lookmap.go, Array.toListAppend_eq, Array.data_toArray, nil_append]
rw [lookmap.go_append, h]; rfl
@[simp]
theorem lookmap_cons_some {a b : α} (l : List α) (h : f a = some b) :
(a :: l).lookmap f = b :: l := by
simp only [lookmap, lookmap.go, Array.toListAppend_eq, Array.data_toArray, nil_append]
rw [h]
theorem lookmap_some : ∀ l : List α, l.lookmap some = l
| [] => rfl
| _ :: _ => rfl
theorem lookmap_none : ∀ l : List α, (l.lookmap fun _ => none) = l
| [] => rfl
| a :: l => (lookmap_cons_none _ l rfl).trans (congr_arg (cons a) (lookmap_none l))
theorem lookmap_congr {f g : α → Option α} :
∀ {l : List α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g
| [], _ => rfl
| a :: l, H => by
cases' forall_mem_cons.1 H with H₁ H₂
cases' h : g a with b
· simp [h, H₁.trans h, lookmap_congr H₂]
· simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)]
theorem lookmap_of_forall_not {l : List α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l :=
(lookmap_congr H).trans (lookmap_none l)
theorem lookmap_map_eq (g : α → β) (h : ∀ (a), ∀ b ∈ f a, g a = g b) :
∀ l : List α, map g (l.lookmap f) = map g l
| [] => rfl
| a :: l => by
cases' h' : f a with b
· simpa [h'] using lookmap_map_eq _ h l
· simp [lookmap_cons_some _ _ h', h _ _ h']
theorem lookmap_id' (h : ∀ (a), ∀ b ∈ f a, a = b) (l : List α) : l.lookmap f = l := by
rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h
theorem length_lookmap (l : List α) : length (l.lookmap f) = length l := by
rw [← length_map, lookmap_map_eq _ fun _ => (), length_map]; simp
end Lookmap
/-! ### filter -/
theorem length_eq_length_filter_add {l : List (α)} (f : α → Bool) :
l.length = (l.filter f).length + (l.filter (! f ·)).length := by
simp_rw [← List.countP_eq_length_filter, l.length_eq_countP_add_countP f, Bool.not_eq_true,
Bool.decide_eq_false]
/-! ### filterMap -/
-- Later porting note (at time of this lemma moving to Batteries):
-- removing attribute `nolint simpNF`
attribute [simp 1100] filterMap_cons_none
-- Later porting note (at time of this lemma moving to Batteries):
-- removing attribute `nolint simpNF`
attribute [simp 1100] filterMap_cons_some
theorem filterMap_eq_bind_toList (f : α → Option β) (l : List α) :
l.filterMap f = l.bind fun a ↦ (f a).toList := by
induction' l with a l ih <;> simp [filterMap_cons]
rcases f a <;> simp [ih]
theorem filterMap_congr {f g : α → Option β} {l : List α}
(h : ∀ x ∈ l, f x = g x) : l.filterMap f = l.filterMap g := by
induction' l with a l ih <;> simp [filterMap_cons]
simp [ih (fun x hx ↦ h x (List.mem_cons_of_mem a hx))]
cases' hfa : f a with b
· have : g a = none := Eq.symm (by simpa [hfa] using h a (by simp))
simp [this]
· have : g a = some b := Eq.symm (by simpa [hfa] using h a (by simp))
simp [this]
theorem filterMap_eq_map_iff_forall_eq_some {f : α → Option β} {g : α → β} {l : List α} :
l.filterMap f = l.map g ↔ ∀ x ∈ l, f x = some (g x) where
mp := by
induction' l with a l ih
· simp
cases' ha : f a with b <;> simp [ha, filterMap_cons]
· intro h
simpa [show (filterMap f l).length = l.length + 1 from by simp[h], Nat.add_one_le_iff]
using List.length_filterMap_le f l
· rintro rfl h
exact ⟨rfl, ih h⟩
mpr h := Eq.trans (filterMap_congr <| by simpa) (congr_fun (List.filterMap_eq_map _) _)
/-! ### filter -/
section Filter
-- Porting note: Lemmas for `filter` are stated in terms of `p : α → Bool`
-- rather than `p : α → Prop` with `DecidablePred p`, since `filter` itself is.
-- Likewise, `if` sometimes becomes `bif`.
variable {p : α → Bool}
theorem filter_singleton {a : α} : [a].filter p = bif p a then [a] else [] :=
rfl
theorem filter_eq_foldr (p : α → Bool) (l : List α) :
filter p l = foldr (fun a out => bif p a then a :: out else out) [] l := by
induction l <;> simp [*, filter]; rfl
#adaptation_note
/--
This has to be temporarily renamed to avoid an unintentional collision.
The prime should be removed at nightly-2024-07-27.
-/
@[simp]
theorem filter_subset' (l : List α) : filter p l ⊆ l :=
(filter_sublist l).subset
theorem of_mem_filter {a : α} {l} (h : a ∈ filter p l) : p a := (mem_filter.1 h).2
theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l :=
filter_subset' l h
theorem mem_filter_of_mem {a : α} {l} (h₁ : a ∈ l) (h₂ : p a) : a ∈ filter p l :=
mem_filter.2 ⟨h₁, h₂⟩
theorem monotone_filter_left (p : α → Bool) ⦃l l' : List α⦄ (h : l ⊆ l') :
filter p l ⊆ filter p l' := by
intro x hx
rw [mem_filter] at hx ⊢
exact ⟨h hx.left, hx.right⟩
variable (p)
theorem monotone_filter_right (l : List α) ⦃p q : α → Bool⦄
(h : ∀ a, p a → q a) : l.filter p <+ l.filter q := by
induction' l with hd tl IH
· rfl
· by_cases hp : p hd
· rw [filter_cons_of_pos hp, filter_cons_of_pos (h _ hp)]
exact IH.cons_cons hd
· rw [filter_cons_of_neg hp]
by_cases hq : q hd
· rw [filter_cons_of_pos hq]
exact sublist_cons_of_sublist hd IH
· rw [filter_cons_of_neg hq]
exact IH
-- TODO rename to `map_filter` when the deprecated `map_filter` is removed from Lean.
lemma map_filter' {f : α → β} (hf : Injective f) (l : List α)
[DecidablePred fun b => ∃ a, p a ∧ f a = b] :
(l.filter p).map f = (l.map f).filter fun b => ∃ a, p a ∧ f a = b := by
simp [(· ∘ ·), filter_map, hf.eq_iff]
lemma filter_attach' (l : List α) (p : {a // a ∈ l} → Bool) [DecidableEq α] :
l.attach.filter p =
(l.filter fun x => ∃ h, p ⟨x, h⟩).attach.map (Subtype.map id fun x => mem_of_mem_filter) := by
classical
refine map_injective_iff.2 Subtype.coe_injective ?_
simp [(· ∘ ·), map_filter' _ Subtype.coe_injective]
-- Porting note: `Lean.Internal.coeM` forces us to type-ascript `{x // x ∈ l}`
lemma filter_attach (l : List α) (p : α → Bool) :
(l.attach.filter fun x => p x : List {x // x ∈ l}) =
(l.filter p).attach.map (Subtype.map id fun x => mem_of_mem_filter) :=
map_injective_iff.2 Subtype.coe_injective <| by
simp_rw [map_map, (· ∘ ·), Subtype.map, id, ← Function.comp_apply (g := Subtype.val),
← filter_map, attach_map_subtype_val]
lemma filter_comm (q) (l : List α) : filter p (filter q l) = filter q (filter p l) := by
simp [and_comm]
@[simp]
theorem filter_true (l : List α) :
filter (fun _ => true) l = l := by induction l <;> simp [*, filter]
@[simp]
theorem filter_false (l : List α) :
filter (fun _ => false) l = [] := by induction l <;> simp [*, filter]
/- Porting note: need a helper theorem for span.loop. -/
theorem span.loop_eq_take_drop :
∀ l₁ l₂ : List α, span.loop p l₁ l₂ = (l₂.reverse ++ takeWhile p l₁, dropWhile p l₁)
| [], l₂ => by simp [span.loop, takeWhile, dropWhile]
| (a :: l), l₂ => by
cases hp : p a <;> simp [hp, span.loop, span.loop_eq_take_drop, takeWhile, dropWhile]
@[simp]
theorem span_eq_take_drop (l : List α) : span p l = (takeWhile p l, dropWhile p l) := by
simpa using span.loop_eq_take_drop p l []
-- TODO update to use `get` instead of `nthLe`
set_option linter.deprecated false in
theorem dropWhile_nthLe_zero_not (l : List α) (hl : 0 < (l.dropWhile p).length) :
¬p ((l.dropWhile p).nthLe 0 hl) := by
induction' l with hd tl IH
· cases hl
· simp only [dropWhile]
by_cases hp : p hd
· simp [hp, IH]
· simp [hp, nthLe_cons]
-- Porting note: How did the Lean 3 proof work,
-- without mentioning nthLe_cons?
-- Same question for takeWhile_eq_nil_iff below
variable {p} {l : List α}
@[simp]
theorem dropWhile_eq_nil_iff : dropWhile p l = [] ↔ ∀ x ∈ l, p x := by
induction' l with x xs IH
· simp [dropWhile]
· by_cases hp : p x <;> simp [hp, dropWhile, IH]
@[simp]
theorem takeWhile_eq_self_iff : takeWhile p l = l ↔ ∀ x ∈ l, p x := by
induction' l with x xs IH
· simp
· by_cases hp : p x <;> simp [hp, takeWhile_cons, IH]
-- TODO update to use `get` instead of `nthLe`
set_option linter.deprecated false in
@[simp]
theorem takeWhile_eq_nil_iff : takeWhile p l = [] ↔ ∀ hl : 0 < l.length, ¬p (l.nthLe 0 hl) := by
induction' l with x xs IH
· simp only [takeWhile_nil, Bool.not_eq_true, true_iff]
intro h
simp at h
· by_cases hp : p x <;> simp [hp, takeWhile_cons, IH, nthLe_cons]
theorem mem_takeWhile_imp {x : α} (hx : x ∈ takeWhile p l) : p x := by
induction l with simp [takeWhile] at hx
| cons hd tl IH =>
cases hp : p hd
· simp [hp] at hx
· rw [hp, mem_cons] at hx
rcases hx with (rfl | hx)
· exact hp
· exact IH hx
theorem takeWhile_takeWhile (p q : α → Bool) (l : List α) :
takeWhile p (takeWhile q l) = takeWhile (fun a => p a ∧ q a) l := by
induction' l with hd tl IH
· simp
· by_cases hp : p hd <;> by_cases hq : q hd <;> simp [takeWhile, hp, hq, IH]
theorem takeWhile_idem : takeWhile p (takeWhile p l) = takeWhile p l := by
simp_rw [takeWhile_takeWhile, and_self_iff, Bool.decide_coe]
end Filter
/-! ### erasep -/
section eraseP
variable {p : α → Bool}
@[simp]
theorem length_eraseP_add_one {l : List α} {a} (al : a ∈ l) (pa : p a) :
(l.eraseP p).length + 1 = l.length := by
let ⟨_, l₁, l₂, _, _, h₁, h₂⟩ := exists_of_eraseP al pa
rw [h₂, h₁, length_append, length_append]
rfl
end eraseP
/-! ### erase -/
section Erase
variable [DecidableEq α]
@[simp] theorem length_erase_add_one {a : α} {l : List α} (h : a ∈ l) :
(l.erase a).length + 1 = l.length := by
rw [erase_eq_eraseP, length_eraseP_add_one h (decide_eq_true rfl)]
theorem map_erase [DecidableEq β] {f : α → β} (finj : Injective f) {a : α} (l : List α) :
map f (l.erase a) = (map f l).erase (f a) := by
have this : (a == ·) = (f a == f ·) := by ext b; simp [beq_eq_decide, finj.eq_iff]
rw [erase_eq_eraseP, erase_eq_eraseP, eraseP_map, this]; rfl
theorem map_foldl_erase [DecidableEq β] {f : α → β} (finj : Injective f) {l₁ l₂ : List α} :
map f (foldl List.erase l₁ l₂) = foldl (fun l a => l.erase (f a)) (map f l₁) l₂ := by
induction l₂ generalizing l₁ <;> [rfl; simp only [foldl_cons, map_erase finj, *]]
theorem erase_get [DecidableEq ι] {l : List ι} (i : Fin l.length) :
Perm (l.erase (l.get i)) (l.eraseIdx ↑i) := by
induction l with
| nil => simp
| cons a l IH =>
cases i using Fin.cases with
| zero => simp
| succ i =>
by_cases ha : a = l.get i
· simpa [ha] using .trans (perm_cons_erase (l.get_mem i i.isLt)) (.cons _ (IH i))
· simp only [get_eq_getElem] at IH ha ⊢
simpa [ha] using IH i
theorem length_eraseIdx_add_one {l : List ι} {i : ℕ} (h : i < l.length) :
(l.eraseIdx i).length + 1 = l.length := calc
(l.eraseIdx i).length + 1
_ = (l.take i ++ l.drop (i + 1)).length + 1 := by rw [eraseIdx_eq_take_drop_succ]
_ = (l.take i).length + (l.drop (i + 1)).length + 1 := by rw [length_append]
_ = i + (l.drop (i + 1)).length + 1 := by rw [length_take_of_le (le_of_lt h)]
_ = i + (l.length - (i + 1)) + 1 := by rw [length_drop]
_ = (i + 1) + (l.length - (i + 1)) := by omega
_ = l.length := Nat.add_sub_cancel' (succ_le_of_lt h)
end Erase
/-! ### diff -/
section Diff
variable [DecidableEq α]
@[simp]
theorem map_diff [DecidableEq β] {f : α → β} (finj : Injective f) {l₁ l₂ : List α} :
map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) := by
simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj]
theorem erase_diff_erase_sublist_of_sublist {a : α} :
∀ {l₁ l₂ : List α}, l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁
| [], l₂, _ => erase_sublist _ _
| b :: l₁, l₂, h =>
if heq : b = a then by simp only [heq, erase_cons_head, diff_cons]; rfl
else by
simp only [erase_cons_head b l₁, erase_cons_tail (not_beq_of_ne heq),
diff_cons ((List.erase l₂ a)) (List.erase l₁ a) b, diff_cons l₂ l₁ b, erase_comm a b l₂]
have h' := h.erase b
rw [erase_cons_head] at h'
exact @erase_diff_erase_sublist_of_sublist _ l₁ (l₂.erase b) h'
end Diff
section Choose
variable (p : α → Prop) [DecidablePred p] (l : List α)
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
/-! ### map₂Left' -/
section Map₂Left'
-- The definitional equalities for `map₂Left'` can already be used by the
-- simplifier because `map₂Left'` is marked `@[simp]`.
@[simp]
theorem map₂Left'_nil_right (f : α → Option β → γ) (as) :
map₂Left' f as [] = (as.map fun a => f a none, []) := by cases as <;> rfl
end Map₂Left'
/-! ### map₂Right' -/
section Map₂Right'
variable (f : Option α → β → γ) (a : α) (as : List α) (b : β) (bs : List β)
@[simp]
theorem map₂Right'_nil_left : map₂Right' f [] bs = (bs.map (f none), []) := by cases bs <;> rfl
@[simp]
theorem map₂Right'_nil_right : map₂Right' f as [] = ([], as) :=
rfl
-- Porting note (#10618): simp can prove this
-- @[simp]
theorem map₂Right'_nil_cons : map₂Right' f [] (b :: bs) = (f none b :: bs.map (f none), []) :=
rfl
@[simp]
theorem map₂Right'_cons_cons :
map₂Right' f (a :: as) (b :: bs) =
let r := map₂Right' f as bs
(f (some a) b :: r.fst, r.snd) :=
rfl
end Map₂Right'
/-! ### zipLeft' -/
section ZipLeft'
variable (a : α) (as : List α) (b : β) (bs : List β)
@[simp]
theorem zipLeft'_nil_right : zipLeft' as ([] : List β) = (as.map fun a => (a, none), []) := by
cases as <;> rfl
@[simp]
theorem zipLeft'_nil_left : zipLeft' ([] : List α) bs = ([], bs) :=
rfl
-- Porting note (#10618): simp can prove this
-- @[simp]
theorem zipLeft'_cons_nil :
zipLeft' (a :: as) ([] : List β) = ((a, none) :: as.map fun a => (a, none), []) :=
rfl
@[simp]
theorem zipLeft'_cons_cons :
zipLeft' (a :: as) (b :: bs) =
let r := zipLeft' as bs
((a, some b) :: r.fst, r.snd) :=
rfl
end ZipLeft'
/-! ### zipRight' -/
section ZipRight'
variable (a : α) (as : List α) (b : β) (bs : List β)
@[simp]
theorem zipRight'_nil_left : zipRight' ([] : List α) bs = (bs.map fun b => (none, b), []) := by
cases bs <;> rfl
@[simp]
theorem zipRight'_nil_right : zipRight' as ([] : List β) = ([], as) :=
rfl
-- Porting note (#10618): simp can prove this
-- @[simp]
theorem zipRight'_nil_cons :
zipRight' ([] : List α) (b :: bs) = ((none, b) :: bs.map fun b => (none, b), []) :=
rfl
@[simp]
theorem zipRight'_cons_cons :
zipRight' (a :: as) (b :: bs) =
let r := zipRight' as bs
((some a, b) :: r.fst, r.snd) :=
rfl
end ZipRight'
/-! ### map₂Left -/
section Map₂Left
variable (f : α → Option β → γ) (as : List α)
-- The definitional equalities for `map₂Left` can already be used by the
-- simplifier because `map₂Left` is marked `@[simp]`.
@[simp]
theorem map₂Left_nil_right : map₂Left f as [] = as.map fun a => f a none := by cases as <;> rfl
theorem map₂Left_eq_map₂Left' : ∀ as bs, map₂Left f as bs = (map₂Left' f as bs).fst
| [], _ => by simp
| a :: as, [] => by simp
| a :: as, b :: bs => by simp [map₂Left_eq_map₂Left']
theorem map₂Left_eq_zipWith :
∀ as bs, length as ≤ length bs → map₂Left f as bs = zipWith (fun a b => f a (some b)) as bs
| [], [], _ => by simp
| [], _ :: _, _ => by simp
| a :: as, [], h => by
simp at h
| a :: as, b :: bs, h => by
simp only [length_cons, succ_le_succ_iff] at h
simp [h, map₂Left_eq_zipWith]
end Map₂Left
/-! ### map₂Right -/
section Map₂Right
variable (f : Option α → β → γ) (a : α) (as : List α) (b : β) (bs : List β)
@[simp]
theorem map₂Right_nil_left : map₂Right f [] bs = bs.map (f none) := by cases bs <;> rfl
@[simp]
theorem map₂Right_nil_right : map₂Right f as [] = [] :=
rfl
-- Porting note (#10618): simp can prove this
-- @[simp]
theorem map₂Right_nil_cons : map₂Right f [] (b :: bs) = f none b :: bs.map (f none) :=
rfl
@[simp]
theorem map₂Right_cons_cons :
map₂Right f (a :: as) (b :: bs) = f (some a) b :: map₂Right f as bs :=
rfl
theorem map₂Right_eq_map₂Right' : map₂Right f as bs = (map₂Right' f as bs).fst := by
simp only [map₂Right, map₂Right', map₂Left_eq_map₂Left']
theorem map₂Right_eq_zipWith (h : length bs ≤ length as) :
map₂Right f as bs = zipWith (fun a b => f (some a) b) as bs := by
have : (fun a b => flip f a (some b)) = flip fun a b => f (some a) b := rfl
simp only [map₂Right, map₂Left_eq_zipWith, zipWith_flip, *]
end Map₂Right
/-! ### zipLeft -/
section ZipLeft
variable (a : α) (as : List α) (b : β) (bs : List β)
@[simp]
theorem zipLeft_nil_right : zipLeft as ([] : List β) = as.map fun a => (a, none) := by
cases as <;> rfl
@[simp]
theorem zipLeft_nil_left : zipLeft ([] : List α) bs = [] :=
rfl
-- Porting note (#10618): simp can prove this
-- @[simp]
theorem zipLeft_cons_nil :
zipLeft (a :: as) ([] : List β) = (a, none) :: as.map fun a => (a, none) :=
rfl
@[simp]
theorem zipLeft_cons_cons : zipLeft (a :: as) (b :: bs) = (a, some b) :: zipLeft as bs :=
rfl
-- Porting note: arguments explicit for recursion
theorem zipLeft_eq_zipLeft' (as : List α) (bs : List β) : zipLeft as bs = (zipLeft' as bs).fst := by
rw [zipLeft, zipLeft']
cases as with
| nil => rfl
| cons _ atl =>
cases bs with
| nil => rfl
| cons _ btl =>
rw [zipWithLeft, zipWithLeft', cons_inj_right]
exact @zipLeft_eq_zipLeft' atl btl
end ZipLeft
/-! ### zipRight -/
section ZipRight
variable (a : α) (as : List α) (b : β) (bs : List β)
@[simp]
theorem zipRight_nil_left : zipRight ([] : List α) bs = bs.map fun b => (none, b) := by
cases bs <;> rfl
@[simp]
theorem zipRight_nil_right : zipRight as ([] : List β) = [] :=
rfl
-- Porting note (#10618): simp can prove this
-- @[simp]
theorem zipRight_nil_cons :
zipRight ([] : List α) (b :: bs) = (none, b) :: bs.map fun b => (none, b) :=
rfl
@[simp]
theorem zipRight_cons_cons : zipRight (a :: as) (b :: bs) = (some a, b) :: zipRight as bs :=
rfl
theorem zipRight_eq_zipRight' : zipRight as bs = (zipRight' as bs).fst := by
induction as generalizing bs <;> cases bs <;> simp [*]
end ZipRight
/-! ### toChunks -/
-- Porting note:
-- The definition of `toChunks` has changed substantially from Lean 3.
-- The theorems about `toChunks` are not used anywhere in mathlib, anyways.
-- TODO: Prove these theorems for the new definitions.
/-! ### Forall -/
section Forall
variable {p q : α → Prop} {l : List α}
@[simp]
theorem forall_cons (p : α → Prop) (x : α) : ∀ l : List α, Forall p (x :: l) ↔ p x ∧ Forall p l
| [] => (and_true_iff _).symm
| _ :: _ => Iff.rfl
theorem forall_iff_forall_mem : ∀ {l : List α}, Forall p l ↔ ∀ x ∈ l, p x
| [] => (iff_true_intro <| forall_mem_nil _).symm
| x :: l => by rw [forall_mem_cons, forall_cons, forall_iff_forall_mem]
theorem Forall.imp (h : ∀ x, p x → q x) : ∀ {l : List α}, Forall p l → Forall q l
| [] => id
| x :: l => by
simp only [forall_cons, and_imp]
rw [← and_imp]
exact And.imp (h x) (Forall.imp h)
@[simp]
theorem forall_map_iff {p : β → Prop} (f : α → β) : Forall p (l.map f) ↔ Forall (p ∘ f) l := by
induction l <;> simp [*]
instance (p : α → Prop) [DecidablePred p] : DecidablePred (Forall p) := fun _ =>
decidable_of_iff' _ forall_iff_forall_mem
end Forall
/-! ### Miscellaneous lemmas -/
@[simp]
theorem getElem_attach (L : List α) (i : Nat) (h : i < L.attach.length) :
L.attach[i].1 = L[i]'(length_attach L ▸ h) :=
calc
L.attach[i].1 = (L.attach.map Subtype.val)[i]'(by simpa using h) := by
rw [getElem_map]
_ = L[i]'_ := by congr 2; simp
theorem get_attach (L : List α) (i) :
(L.attach.get i).1 = L.get ⟨i, length_attach L ▸ i.2⟩ := by simp
@[simp 1100]
theorem mem_map_swap (x : α) (y : β) (xs : List (α × β)) :
(y, x) ∈ map Prod.swap xs ↔ (x, y) ∈ xs := by
induction' xs with x xs xs_ih
· simp only [not_mem_nil, map_nil]
· cases' x with a b
simp only [mem_cons, Prod.mk.inj_iff, map, Prod.swap_prod_mk, Prod.exists, xs_ih, and_comm]
theorem dropSlice_eq (xs : List α) (n m : ℕ) : dropSlice n m xs = xs.take n ++ xs.drop (n + m) := by
induction n generalizing xs
· cases xs <;> simp [dropSlice]
· cases xs <;> simp [dropSlice, *, Nat.succ_add]
@[simp]
theorem length_dropSlice (i j : ℕ) (xs : List α) :
(List.dropSlice i j xs).length = xs.length - min j (xs.length - i) := by
induction xs generalizing i j with
| nil => simp
| cons x xs xs_ih =>
cases i <;> simp only [List.dropSlice]
· cases j with
| zero => simp
| succ n => simp_all [xs_ih]; omega
· simp [xs_ih]; omega
theorem length_dropSlice_lt (i j : ℕ) (hj : 0 < j) (xs : List α) (hi : i < xs.length) :
(List.dropSlice i j xs).length < xs.length := by
simp; omega
set_option linter.deprecated false in
@[deprecated (since := "2024-07-25")]
theorem sizeOf_dropSlice_lt [SizeOf α] (i j : ℕ) (hj : 0 < j) (xs : List α) (hi : i < xs.length) :
SizeOf.sizeOf (List.dropSlice i j xs) < SizeOf.sizeOf xs := by
induction xs generalizing i j hj with
| nil => cases hi
| cons x xs xs_ih =>
cases i <;> simp only [List.dropSlice]
· cases j with
| zero => contradiction
| succ n =>
dsimp only [drop]; apply lt_of_le_of_lt (drop_sizeOf_le xs n)
simp only [cons.sizeOf_spec]; omega
· simp only [cons.sizeOf_spec, Nat.add_lt_add_iff_left]
apply xs_ih _ j hj
apply lt_of_succ_lt_succ hi
section Disjoint
/-- The images of disjoint lists under a partially defined map are disjoint -/
theorem disjoint_pmap {p : α → Prop} {f : ∀ a : α, p a → β} {s t : List α}
(hs : ∀ a ∈ s, p a) (ht : ∀ a ∈ t, p a)
(hf : ∀ (a a' : α) (ha : p a) (ha' : p a'), f a ha = f a' ha' → a = a')
(h : Disjoint s t) :
Disjoint (s.pmap f hs) (t.pmap f ht) := by
simp only [Disjoint, mem_pmap]
rintro b ⟨a, ha, rfl⟩ ⟨a', ha', ha''⟩
apply h ha
rwa [hf a a' (hs a ha) (ht a' ha') ha''.symm]
/-- The images of disjoint lists under an injective map are disjoint -/
theorem disjoint_map {f : α → β} {s t : List α} (hf : Function.Injective f)
(h : Disjoint s t) : Disjoint (s.map f) (t.map f) := by
rw [← pmap_eq_map _ _ _ (fun _ _ ↦ trivial), ← pmap_eq_map _ _ _ (fun _ _ ↦ trivial)]
exact disjoint_pmap _ _ (fun _ _ _ _ h' ↦ hf h') h
end Disjoint
section lookup
variable {α β : Type*} [BEq α] [LawfulBEq α]
lemma lookup_graph (f : α → β) {a : α} {as : List α} (h : a ∈ as) :
lookup a (as.map fun x => (x, f x)) = some (f a) := by
induction' as with a' as ih
· exact (List.not_mem_nil _ h).elim
· by_cases ha : a = a'
· simp [ha, lookup_cons]
· simpa [lookup_cons, beq_false_of_ne ha] using ih (List.mem_of_ne_of_mem ha h)
end lookup
end List
assert_not_exists Lattice
|
Data\List\Chain.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kenny Lau, Yury Kudryashov
-/
import Mathlib.Logic.Relation
import Mathlib.Data.List.Forall2
import Mathlib.Data.List.Lex
import Mathlib.Data.List.Infix
/-!
# Relation chain
This file provides basic results about `List.Chain` (definition in `Data.List.Defs`).
A list `[a₂, ..., aₙ]` is a `Chain` starting at `a₁` with respect to the relation `r` if `r a₁ a₂`
and `r a₂ a₃` and ... and `r aₙ₋₁ aₙ`. We write it `Chain r a₁ [a₂, ..., aₙ]`.
A graph-specialized version is in development and will hopefully be added under `combinatorics.`
sometime soon.
-/
-- Make sure we haven't imported `Data.Nat.Order.Basic`
assert_not_exists OrderedSub
universe u v
open Nat
namespace List
variable {α : Type u} {β : Type v} {R r : α → α → Prop} {l l₁ l₂ : List α} {a b : α}
mk_iff_of_inductive_prop List.Chain List.chain_iff
theorem Chain.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {a : α} {l : List α} :
Chain R a l ↔ Chain S a l :=
⟨Chain.imp fun a b => (H a b).1, Chain.imp fun a b => (H a b).2⟩
theorem Chain.iff_mem {a : α} {l : List α} :
Chain R a l ↔ Chain (fun x y => x ∈ a :: l ∧ y ∈ l ∧ R x y) a l :=
⟨fun p => by
induction' p with _ a b l r _ IH <;> constructor <;>
[exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩;
exact IH.imp fun a b ⟨am, bm, h⟩ => ⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩],
Chain.imp fun a b h => h.2.2⟩
theorem chain_singleton {a b : α} : Chain R a [b] ↔ R a b := by
simp only [chain_cons, Chain.nil, and_true_iff]
theorem chain_split {a b : α} {l₁ l₂ : List α} :
Chain R a (l₁ ++ b :: l₂) ↔ Chain R a (l₁ ++ [b]) ∧ Chain R b l₂ := by
induction' l₁ with x l₁ IH generalizing a <;>
simp only [*, nil_append, cons_append, Chain.nil, chain_cons, and_true_iff, and_assoc]
@[simp]
theorem chain_append_cons_cons {a b c : α} {l₁ l₂ : List α} :
Chain R a (l₁ ++ b :: c :: l₂) ↔ Chain R a (l₁ ++ [b]) ∧ R b c ∧ Chain R c l₂ := by
rw [chain_split, chain_cons]
theorem chain_iff_forall₂ :
∀ {a : α} {l : List α}, Chain R a l ↔ l = [] ∨ Forall₂ R (a :: dropLast l) l
| a, [] => by simp
| a, b :: l => by
by_cases h : l = [] <;>
simp [@chain_iff_forall₂ b l, dropLast, *]
theorem chain_append_singleton_iff_forall₂ :
Chain R a (l ++ [b]) ↔ Forall₂ R (a :: l) (l ++ [b]) := by simp [chain_iff_forall₂]
theorem chain_map (f : β → α) {b : β} {l : List β} :
Chain R (f b) (map f l) ↔ Chain (fun a b : β => R (f a) (f b)) b l := by
induction l generalizing b <;> simp only [map, Chain.nil, chain_cons, *]
theorem chain_of_chain_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b)
{a : α} {l : List α} (p : Chain S (f a) (map f l)) : Chain R a l :=
((chain_map f).1 p).imp H
theorem chain_map_of_chain {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b))
{a : α} {l : List α} (p : Chain R a l) : Chain S (f a) (map f l) :=
(chain_map f).2 <| p.imp H
theorem chain_pmap_of_chain {S : β → β → Prop} {p : α → Prop} {f : ∀ a, p a → β}
(H : ∀ a b ha hb, R a b → S (f a ha) (f b hb)) {a : α} {l : List α} (hl₁ : Chain R a l)
(ha : p a) (hl₂ : ∀ a ∈ l, p a) : Chain S (f a ha) (List.pmap f l hl₂) := by
induction' l with lh lt l_ih generalizing a
· simp
· simp [H _ _ _ _ (rel_of_chain_cons hl₁), l_ih (chain_of_chain_cons hl₁)]
theorem chain_of_chain_pmap {S : β → β → Prop} {p : α → Prop} (f : ∀ a, p a → β) {l : List α}
(hl₁ : ∀ a ∈ l, p a) {a : α} (ha : p a) (hl₂ : Chain S (f a ha) (List.pmap f l hl₁))
(H : ∀ a b ha hb, S (f a ha) (f b hb) → R a b) : Chain R a l := by
induction' l with lh lt l_ih generalizing a
· simp
· simp [H _ _ _ _ (rel_of_chain_cons hl₂), l_ih _ _ (chain_of_chain_cons hl₂)]
protected theorem Chain.pairwise [IsTrans α R] :
∀ {a : α} {l : List α}, Chain R a l → Pairwise R (a :: l)
| a, [], Chain.nil => pairwise_singleton _ _
| a, _, @Chain.cons _ _ _ b l h hb =>
hb.pairwise.cons
(by
simp only [mem_cons, forall_eq_or_imp, h, true_and_iff]
exact fun c hc => _root_.trans h (rel_of_pairwise_cons hb.pairwise hc))
theorem chain_iff_pairwise [IsTrans α R] {a : α} {l : List α} : Chain R a l ↔ Pairwise R (a :: l) :=
⟨Chain.pairwise, Pairwise.chain⟩
protected theorem Chain.sublist [IsTrans α R] (hl : l₂.Chain R a) (h : l₁ <+ l₂) :
l₁.Chain R a := by
rw [chain_iff_pairwise] at hl ⊢
exact hl.sublist (h.cons_cons a)
protected theorem Chain.rel [IsTrans α R] (hl : l.Chain R a) (hb : b ∈ l) : R a b := by
rw [chain_iff_pairwise] at hl
exact rel_of_pairwise_cons hl hb
theorem chain_iff_get {R} : ∀ {a : α} {l : List α}, Chain R a l ↔
(∀ h : 0 < length l, R a (get l ⟨0, h⟩)) ∧
∀ (i : ℕ) (h : i < l.length - 1),
R (get l ⟨i, by omega⟩) (get l ⟨i+1, by omega⟩)
| a, [] => iff_of_true (by simp) ⟨fun h => by simp at h, fun _ h => by simp at h⟩
| a, b :: t => by
rw [chain_cons, @chain_iff_get _ _ t]
constructor
· rintro ⟨R, ⟨h0, h⟩⟩
constructor
· intro _
exact R
intro i w
cases' i with i
· apply h0
· exact h i (by simp only [length_cons] at w; omega)
rintro ⟨h0, h⟩; constructor
· apply h0
simp
constructor
· apply h 0
intro i w
exact h (i+1) (by simp only [length_cons]; omega)
theorem Chain'.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : List α} (p : Chain' R l) :
Chain' S l := by cases l <;> [trivial; exact Chain.imp H p]
theorem Chain'.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : List α} :
Chain' R l ↔ Chain' S l :=
⟨Chain'.imp fun a b => (H a b).1, Chain'.imp fun a b => (H a b).2⟩
theorem Chain'.iff_mem : ∀ {l : List α}, Chain' R l ↔ Chain' (fun x y => x ∈ l ∧ y ∈ l ∧ R x y) l
| [] => Iff.rfl
| _ :: _ =>
⟨fun h => (Chain.iff_mem.1 h).imp fun _ _ ⟨h₁, h₂, h₃⟩ => ⟨h₁, mem_cons.2 (Or.inr h₂), h₃⟩,
Chain'.imp fun _ _ h => h.2.2⟩
@[simp]
theorem chain'_nil : Chain' R [] :=
trivial
@[simp]
theorem chain'_singleton (a : α) : Chain' R [a] :=
Chain.nil
@[simp]
theorem chain'_cons {x y l} : Chain' R (x :: y :: l) ↔ R x y ∧ Chain' R (y :: l) :=
chain_cons
theorem chain'_isInfix : ∀ l : List α, Chain' (fun x y => [x, y] <:+: l) l
| [] => chain'_nil
| [a] => chain'_singleton _
| a :: b :: l =>
chain'_cons.2
⟨⟨[], l, by simp⟩, (chain'_isInfix (b :: l)).imp fun x y h => h.trans ⟨[a], [], by simp⟩⟩
theorem chain'_split {a : α} :
∀ {l₁ l₂ : List α}, Chain' R (l₁ ++ a :: l₂) ↔ Chain' R (l₁ ++ [a]) ∧ Chain' R (a :: l₂)
| [], _ => (and_iff_right (chain'_singleton a)).symm
| _ :: _, _ => chain_split
@[simp]
theorem chain'_append_cons_cons {b c : α} {l₁ l₂ : List α} :
Chain' R (l₁ ++ b :: c :: l₂) ↔ Chain' R (l₁ ++ [b]) ∧ R b c ∧ Chain' R (c :: l₂) := by
rw [chain'_split, chain'_cons]
theorem chain'_map (f : β → α) {l : List β} :
Chain' R (map f l) ↔ Chain' (fun a b : β => R (f a) (f b)) l := by
cases l <;> [rfl; exact chain_map _]
theorem chain'_of_chain'_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b)
{l : List α} (p : Chain' S (map f l)) : Chain' R l :=
((chain'_map f).1 p).imp H
theorem chain'_map_of_chain' {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b))
{l : List α} (p : Chain' R l) : Chain' S (map f l) :=
(chain'_map f).2 <| p.imp H
theorem Pairwise.chain' : ∀ {l : List α}, Pairwise R l → Chain' R l
| [], _ => trivial
| _ :: _, h => Pairwise.chain h
theorem chain'_iff_pairwise [IsTrans α R] : ∀ {l : List α}, Chain' R l ↔ Pairwise R l
| [] => (iff_true_intro Pairwise.nil).symm
| _ :: _ => chain_iff_pairwise
protected theorem Chain'.sublist [IsTrans α R] (hl : l₂.Chain' R) (h : l₁ <+ l₂) : l₁.Chain' R := by
rw [chain'_iff_pairwise] at hl ⊢
exact hl.sublist h
theorem Chain'.cons {x y l} (h₁ : R x y) (h₂ : Chain' R (y :: l)) : Chain' R (x :: y :: l) :=
chain'_cons.2 ⟨h₁, h₂⟩
theorem Chain'.tail : ∀ {l}, Chain' R l → Chain' R l.tail
| [], _ => trivial
| [_], _ => trivial
| _ :: _ :: _, h => (chain'_cons.mp h).right
theorem Chain'.rel_head {x y l} (h : Chain' R (x :: y :: l)) : R x y :=
rel_of_chain_cons h
theorem Chain'.rel_head? {x l} (h : Chain' R (x :: l)) ⦃y⦄ (hy : y ∈ head? l) : R x y := by
rw [← cons_head?_tail hy] at h
exact h.rel_head
theorem Chain'.cons' {x} : ∀ {l : List α}, Chain' R l → (∀ y ∈ l.head?, R x y) → Chain' R (x :: l)
| [], _, _ => chain'_singleton x
| _ :: _, hl, H => hl.cons <| H _ rfl
theorem chain'_cons' {x l} : Chain' R (x :: l) ↔ (∀ y ∈ head? l, R x y) ∧ Chain' R l :=
⟨fun h => ⟨h.rel_head?, h.tail⟩, fun ⟨h₁, h₂⟩ => h₂.cons' h₁⟩
theorem chain'_append :
∀ {l₁ l₂ : List α},
Chain' R (l₁ ++ l₂) ↔ Chain' R l₁ ∧ Chain' R l₂ ∧ ∀ x ∈ l₁.getLast?, ∀ y ∈ l₂.head?, R x y
| [], l => by simp
| [a], l => by simp [chain'_cons', and_comm]
| a :: b :: l₁, l₂ => by
rw [cons_append, cons_append, chain'_cons, chain'_cons, ← cons_append, chain'_append,
and_assoc]
simp
theorem Chain'.append (h₁ : Chain' R l₁) (h₂ : Chain' R l₂)
(h : ∀ x ∈ l₁.getLast?, ∀ y ∈ l₂.head?, R x y) : Chain' R (l₁ ++ l₂) :=
chain'_append.2 ⟨h₁, h₂, h⟩
theorem Chain'.left_of_append (h : Chain' R (l₁ ++ l₂)) : Chain' R l₁ :=
(chain'_append.1 h).1
theorem Chain'.right_of_append (h : Chain' R (l₁ ++ l₂)) : Chain' R l₂ :=
(chain'_append.1 h).2.1
theorem Chain'.infix (h : Chain' R l) (h' : l₁ <:+: l) : Chain' R l₁ := by
rcases h' with ⟨l₂, l₃, rfl⟩
exact h.left_of_append.right_of_append
theorem Chain'.suffix (h : Chain' R l) (h' : l₁ <:+ l) : Chain' R l₁ :=
h.infix h'.isInfix
theorem Chain'.prefix (h : Chain' R l) (h' : l₁ <+: l) : Chain' R l₁ :=
h.infix h'.isInfix
theorem Chain'.drop (h : Chain' R l) (n : ℕ) : Chain' R (drop n l) :=
h.suffix (drop_suffix _ _)
theorem Chain'.init (h : Chain' R l) : Chain' R l.dropLast :=
h.prefix l.dropLast_prefix
theorem Chain'.take (h : Chain' R l) (n : ℕ) : Chain' R (take n l) :=
h.prefix (take_prefix _ _)
theorem chain'_pair {x y} : Chain' R [x, y] ↔ R x y := by
simp only [chain'_singleton, chain'_cons, and_true_iff]
theorem Chain'.imp_head {x y} (h : ∀ {z}, R x z → R y z) {l} (hl : Chain' R (x :: l)) :
Chain' R (y :: l) :=
hl.tail.cons' fun _ hz => h <| hl.rel_head? hz
theorem chain'_reverse : ∀ {l}, Chain' R (reverse l) ↔ Chain' (flip R) l
| [] => Iff.rfl
| [a] => by simp only [chain'_singleton, reverse_singleton]
| a :: b :: l => by
rw [chain'_cons, reverse_cons, reverse_cons, append_assoc, cons_append, nil_append,
chain'_split, ← reverse_cons, @chain'_reverse (b :: l), and_comm, chain'_pair, flip]
theorem chain'_iff_get {R} : ∀ {l : List α}, Chain' R l ↔
∀ (i : ℕ) (h : i < length l - 1),
R (get l ⟨i, by omega⟩) (get l ⟨i + 1, by omega⟩)
| [] => iff_of_true (by simp) (fun _ h => by simp at h)
| [a] => iff_of_true (by simp) (fun _ h => by simp at h)
| a :: b :: t => by
rw [← and_forall_add_one, chain'_cons, chain'_iff_get]
simp
/-- If `l₁ l₂` and `l₃` are lists and `l₁ ++ l₂` and `l₂ ++ l₃` both satisfy
`Chain' R`, then so does `l₁ ++ l₂ ++ l₃` provided `l₂ ≠ []` -/
theorem Chain'.append_overlap {l₁ l₂ l₃ : List α} (h₁ : Chain' R (l₁ ++ l₂))
(h₂ : Chain' R (l₂ ++ l₃)) (hn : l₂ ≠ []) : Chain' R (l₁ ++ l₂ ++ l₃) :=
h₁.append h₂.right_of_append <| by
simpa only [getLast?_append_of_ne_nil _ hn] using (chain'_append.1 h₂).2.2
lemma chain'_join : ∀ {L : List (List α)}, [] ∉ L →
(Chain' R L.join ↔ (∀ l ∈ L, Chain' R l) ∧
L.Chain' (fun l₁ l₂ => ∀ᵉ (x ∈ l₁.getLast?) (y ∈ l₂.head?), R x y))
| [], _ => by simp
| [l], _ => by simp [join]
| (l₁ :: l₂ :: L), hL => by
rw [mem_cons, not_or, ← Ne] at hL
rw [join, chain'_append, chain'_join hL.2, forall_mem_cons, chain'_cons]
rw [mem_cons, not_or, ← Ne] at hL
simp only [forall_mem_cons, and_assoc, join, head?_append_of_ne_nil _ hL.2.1.symm]
exact Iff.rfl.and (Iff.rfl.and <| Iff.rfl.and and_comm)
/-- If `a` and `b` are related by the reflexive transitive closure of `r`, then there is an
`r`-chain starting from `a` and ending on `b`.
The converse of `relationReflTransGen_of_exists_chain`.
-/
theorem exists_chain_of_relationReflTransGen (h : Relation.ReflTransGen r a b) :
∃ l, Chain r a l ∧ getLast (a :: l) (cons_ne_nil _ _) = b := by
refine Relation.ReflTransGen.head_induction_on h ?_ ?_
· exact ⟨[], Chain.nil, rfl⟩
· intro c d e _ ih
obtain ⟨l, hl₁, hl₂⟩ := ih
refine ⟨d :: l, Chain.cons e hl₁, ?_⟩
rwa [getLast_cons_cons]
/-- Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y → p y → p x` then
the predicate is true everywhere in the chain and at `a`.
That is, we can propagate the predicate up the chain.
-/
theorem Chain.induction (p : α → Prop) (l : List α) (h : Chain r a l)
(hb : getLast (a :: l) (cons_ne_nil _ _) = b) (carries : ∀ ⦃x y : α⦄, r x y → p y → p x)
(final : p b) : ∀ i ∈ a :: l, p i := by
induction' l with _ _ l_ih generalizing a
· cases hb
simpa using final
· rw [chain_cons] at h
simp only [mem_cons]
rintro _ (rfl | H)
· apply carries h.1 (l_ih h.2 hb _ (mem_cons.2 (Or.inl rfl)))
· apply l_ih h.2 hb _ (mem_cons.2 H)
/-- Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y → p y → p x` then
the predicate is true at `a`.
That is, we can propagate the predicate all the way up the chain.
-/
@[elab_as_elim]
theorem Chain.induction_head (p : α → Prop) (l : List α) (h : Chain r a l)
(hb : getLast (a :: l) (cons_ne_nil _ _) = b) (carries : ∀ ⦃x y : α⦄, r x y → p y → p x)
(final : p b) : p a :=
(Chain.induction p l h hb carries final) _ (mem_cons_self _ _)
/--
If there is an `r`-chain starting from `a` and ending at `b`, then `a` and `b` are related by the
reflexive transitive closure of `r`. The converse of `exists_chain_of_relationReflTransGen`.
-/
theorem relationReflTransGen_of_exists_chain (l : List α) (hl₁ : Chain r a l)
(hl₂ : getLast (a :: l) (cons_ne_nil _ _) = b) : Relation.ReflTransGen r a b :=
Chain.induction_head _ l hl₁ hl₂ (fun _ _ => Relation.ReflTransGen.head)
Relation.ReflTransGen.refl
theorem Chain'.cons_of_le [LinearOrder α] {a : α} {as m : List α}
(ha : List.Chain' (· > ·) (a :: as)) (hm : List.Chain' (· > ·) m) (hmas : m ≤ as) :
List.Chain' (· > ·) (a :: m) := by
cases m with
| nil => simp only [List.chain'_singleton]
| cons b bs =>
apply hm.cons
cases as with
| nil =>
simp only [le_iff_lt_or_eq, or_false] at hmas
exact (List.Lex.not_nil_right (·<·) _ hmas).elim
| cons a' as =>
rw [List.chain'_cons] at ha
refine gt_of_gt_of_ge ha.1 ?_
rw [le_iff_lt_or_eq] at hmas
cases' hmas with hmas hmas
· by_contra! hh
rw [← not_le] at hmas
apply hmas
apply le_of_lt
exact (List.lt_iff_lex_lt _ _).mp (List.lt.head _ _ hh)
· simp_all only [List.cons.injEq, le_refl]
end List
/-! In this section, we consider the type of `r`-decreasing chains (`List.Chain' (flip r)`)
equipped with lexicographic order `List.Lex r`. -/
variable {α : Type*} (r : α → α → Prop)
/-- The type of `r`-decreasing chains -/
abbrev List.chains := { l : List α // l.Chain' (flip r) }
/-- The lexicographic order on the `r`-decreasing chains -/
abbrev List.lex_chains (l m : List.chains r) : Prop := List.Lex r l.val m.val
variable {r}
/-- If an `r`-decreasing chain `l` is empty or its head is accessible by `r`, then
`l` is accessible by the lexicographic order `List.Lex r`. -/
theorem Acc.list_chain' {l : List.chains r} (acc : ∀ a ∈ l.val.head?, Acc r a) :
Acc (List.lex_chains r) l := by
obtain ⟨_ | ⟨a, l⟩, hl⟩ := l
· apply Acc.intro; rintro ⟨_⟩ ⟨_⟩
specialize acc a _
· rw [List.head?_cons, Option.mem_some_iff]
/- For an r-decreasing chain of the form a :: l, apply induction on a -/
induction acc generalizing l with
| intro a _ ih =>
/- Bundle l with a proof that it is r-decreasing to form l' -/
have hl' := (List.chain'_cons'.1 hl).2
let l' : List.chains r := ⟨l, hl'⟩
have : Acc (List.lex_chains r) l' := by
cases' l with b l
· apply Acc.intro; rintro ⟨_⟩ ⟨_⟩
/- l' is accessible by induction hypothesis -/
· apply ih b (List.chain'_cons.1 hl).1
/- make l' a free variable and induct on l' -/
revert hl
rw [(by rfl : l = l'.1)]
clear_value l'
induction this with
| intro l _ ihl =>
intro hl
apply Acc.intro
rintro ⟨_ | ⟨b, m⟩, hm⟩ (_ | hr | hr)
· apply Acc.intro; rintro ⟨_⟩ ⟨_⟩
· apply ihl ⟨m, (List.chain'_cons'.1 hm).2⟩ hr
· apply ih b hr
/-- If `r` is well-founded, the lexicographic order on `r`-decreasing chains is also. -/
theorem WellFounded.list_chain' (hwf : WellFounded r) :
WellFounded (List.lex_chains r) :=
⟨fun _ ↦ Acc.list_chain' (fun _ _ => hwf.apply _)⟩
instance [hwf : IsWellFounded α r] :
IsWellFounded (List.chains r) (List.lex_chains r) :=
⟨hwf.wf.list_chain'⟩
|
Data\List\Count.lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import Mathlib.Data.Nat.Defs
/-!
# Counting in lists
This file proves basic properties of `List.countP` and `List.count`, which count the number of
elements of a list satisfying a predicate and equal to a given element respectively. Their
definitions can be found in `Batteries.Data.List.Basic`.
-/
assert_not_exists Set.range
assert_not_exists GroupWithZero
assert_not_exists Ring
open Nat
variable {α : Type*} {l : List α}
namespace List
/-! ### count -/
section Count
@[simp]
theorem count_map_of_injective {β} [DecidableEq α] [DecidableEq β] (l : List α) (f : α → β)
(hf : Function.Injective f) (x : α) : count (f x) (map f l) = count x l := by
simp only [count, countP_map, (· ∘ ·), hf.beq_eq]
variable [DecidableEq α]
@[deprecated (since := "2023-08-23")]
theorem count_cons' (a b : α) (l : List α) :
count a (b :: l) = count a l + if a = b then 1 else 0 := by
simp only [count, beq_iff_eq, countP_cons, Nat.add_right_inj]
simp only [eq_comm]
end Count
end List
|
Data\List\Cycle.lean | /-
Copyright (c) 2021 Yakov Pechersky. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky
-/
import Mathlib.Data.Fintype.List
/-!
# Cycles of a list
Lists have an equivalence relation of whether they are rotational permutations of one another.
This relation is defined as `IsRotated`.
Based on this, we define the quotient of lists by the rotation relation, called `Cycle`.
We also define a representation of concrete cycles, available when viewing them in a goal state or
via `#eval`, when over representable types. For example, the cycle `(2 1 4 3)` will be shown
as `c[2, 1, 4, 3]`. Two equal cycles may be printed differently if their internal representation
is different.
-/
assert_not_exists MonoidWithZero
namespace List
variable {α : Type*} [DecidableEq α]
/-- Return the `z` such that `x :: z :: _` appears in `xs`, or `default` if there is no such `z`. -/
def nextOr : ∀ (_ : List α) (_ _ : α), α
| [], _, default => default
| [_], _, default => default
-- Handles the not-found and the wraparound case
| y :: z :: xs, x, default => if x = y then z else nextOr (z :: xs) x default
@[simp]
theorem nextOr_nil (x d : α) : nextOr [] x d = d :=
rfl
@[simp]
theorem nextOr_singleton (x y d : α) : nextOr [y] x d = d :=
rfl
@[simp]
theorem nextOr_self_cons_cons (xs : List α) (x y d : α) : nextOr (x :: y :: xs) x d = y :=
if_pos rfl
theorem nextOr_cons_of_ne (xs : List α) (y x d : α) (h : x ≠ y) :
nextOr (y :: xs) x d = nextOr xs x d := by
cases' xs with z zs
· rfl
· exact if_neg h
/-- `nextOr` does not depend on the default value, if the next value appears. -/
theorem nextOr_eq_nextOr_of_mem_of_ne (xs : List α) (x d d' : α) (x_mem : x ∈ xs)
(x_ne : x ≠ xs.getLast (ne_nil_of_mem x_mem)) : nextOr xs x d = nextOr xs x d' := by
induction' xs with y ys IH
· cases x_mem
cases' ys with z zs
· simp at x_mem x_ne
contradiction
by_cases h : x = y
· rw [h, nextOr_self_cons_cons, nextOr_self_cons_cons]
· rw [nextOr, nextOr, IH]
· simpa [h] using x_mem
· simpa using x_ne
theorem mem_of_nextOr_ne {xs : List α} {x d : α} (h : nextOr xs x d ≠ d) : x ∈ xs := by
induction' xs with y ys IH
· simp at h
cases' ys with z zs
· simp at h
· by_cases hx : x = y
· simp [hx]
· rw [nextOr_cons_of_ne _ _ _ _ hx] at h
simpa [hx] using IH h
theorem nextOr_concat {xs : List α} {x : α} (d : α) (h : x ∉ xs) : nextOr (xs ++ [x]) x d = d := by
induction' xs with z zs IH
· simp
· obtain ⟨hz, hzs⟩ := not_or.mp (mt mem_cons.2 h)
rw [cons_append, nextOr_cons_of_ne _ _ _ _ hz, IH hzs]
theorem nextOr_mem {xs : List α} {x d : α} (hd : d ∈ xs) : nextOr xs x d ∈ xs := by
revert hd
suffices ∀ xs' : List α, (∀ x ∈ xs, x ∈ xs') → d ∈ xs' → nextOr xs x d ∈ xs' by
exact this xs fun _ => id
intro xs' hxs' hd
induction' xs with y ys ih
· exact hd
cases' ys with z zs
· exact hd
rw [nextOr]
split_ifs with h
· exact hxs' _ (mem_cons_of_mem _ (mem_cons_self _ _))
· exact ih fun _ h => hxs' _ (mem_cons_of_mem _ h)
/-- Given an element `x : α` of `l : List α` such that `x ∈ l`, get the next
element of `l`. This works from head to tail, (including a check for last element)
so it will match on first hit, ignoring later duplicates.
For example:
* `next [1, 2, 3] 2 _ = 3`
* `next [1, 2, 3] 3 _ = 1`
* `next [1, 2, 3, 2, 4] 2 _ = 3`
* `next [1, 2, 3, 2] 2 _ = 3`
* `next [1, 1, 2, 3, 2] 1 _ = 1`
-/
def next (l : List α) (x : α) (h : x ∈ l) : α :=
nextOr l x (l.get ⟨0, length_pos_of_mem h⟩)
/-- Given an element `x : α` of `l : List α` such that `x ∈ l`, get the previous
element of `l`. This works from head to tail, (including a check for last element)
so it will match on first hit, ignoring later duplicates.
* `prev [1, 2, 3] 2 _ = 1`
* `prev [1, 2, 3] 1 _ = 3`
* `prev [1, 2, 3, 2, 4] 2 _ = 1`
* `prev [1, 2, 3, 4, 2] 2 _ = 1`
* `prev [1, 1, 2] 1 _ = 2`
-/
def prev : ∀ l : List α, ∀ x ∈ l, α
| [], _, h => by simp at h
| [y], _, _ => y
| y :: z :: xs, x, h =>
if hx : x = y then getLast (z :: xs) (cons_ne_nil _ _)
else if x = z then y else prev (z :: xs) x (by simpa [hx] using h)
variable (l : List α) (x : α)
@[simp]
theorem next_singleton (x y : α) (h : x ∈ [y]) : next [y] x h = y :=
rfl
@[simp]
theorem prev_singleton (x y : α) (h : x ∈ [y]) : prev [y] x h = y :=
rfl
theorem next_cons_cons_eq' (y z : α) (h : x ∈ y :: z :: l) (hx : x = y) :
next (y :: z :: l) x h = z := by rw [next, nextOr, if_pos hx]
@[simp]
theorem next_cons_cons_eq (z : α) (h : x ∈ x :: z :: l) : next (x :: z :: l) x h = z :=
next_cons_cons_eq' l x x z h rfl
theorem next_ne_head_ne_getLast (h : x ∈ l) (y : α) (h : x ∈ y :: l) (hy : x ≠ y)
(hx : x ≠ getLast (y :: l) (cons_ne_nil _ _)) :
next (y :: l) x h = next l x (by simpa [hy] using h) := by
rw [next, next, nextOr_cons_of_ne _ _ _ _ hy, nextOr_eq_nextOr_of_mem_of_ne]
· rwa [getLast_cons] at hx
exact ne_nil_of_mem (by assumption)
· rwa [getLast_cons] at hx
theorem next_cons_concat (y : α) (hy : x ≠ y) (hx : x ∉ l)
(h : x ∈ y :: l ++ [x] := mem_append_right _ (mem_singleton_self x)) :
next (y :: l ++ [x]) x h = y := by
rw [next, nextOr_concat]
· rfl
· simp [hy, hx]
theorem next_getLast_cons (h : x ∈ l) (y : α) (h : x ∈ y :: l) (hy : x ≠ y)
(hx : x = getLast (y :: l) (cons_ne_nil _ _)) (hl : Nodup l) : next (y :: l) x h = y := by
rw [next, get, ← dropLast_append_getLast (cons_ne_nil y l), hx, nextOr_concat]
subst hx
intro H
obtain ⟨⟨_ | k, hk⟩, hk'⟩ := get_of_mem H
· rw [← Option.some_inj] at hk'
rw [← get?_eq_get, dropLast_eq_take, get?_eq_getElem?, getElem?_take, getElem?_cons_zero,
Option.some_inj] at hk'
· exact hy (Eq.symm hk')
rw [length_cons]
exact length_pos_of_mem (by assumption)
suffices k + 1 = l.length by simp [this] at hk
cases' l with hd tl
· simp at hk
· rw [nodup_iff_injective_get] at hl
rw [length, Nat.succ_inj']
refine Fin.val_eq_of_eq <| @hl ⟨k, Nat.lt_of_succ_lt <| by simpa using hk⟩
⟨tl.length, by simp⟩ ?_
rw [← Option.some_inj] at hk'
rw [← get?_eq_get, dropLast_eq_take, get?_eq_getElem?, getElem?_take, getElem?_cons_succ,
getElem?_eq_getElem, Option.some_inj] at hk'
· rw [get_eq_getElem, hk']
simp only [getLast_eq_getElem, length_cons, Nat.succ_eq_add_one, Nat.succ_sub_succ_eq_sub,
Nat.sub_zero, get_eq_getElem, getElem_cons_succ]
simpa using hk
theorem prev_getLast_cons' (y : α) (hxy : x ∈ y :: l) (hx : x = y) :
prev (y :: l) x hxy = getLast (y :: l) (cons_ne_nil _ _) := by cases l <;> simp [prev, hx]
@[simp]
theorem prev_getLast_cons (h : x ∈ x :: l) :
prev (x :: l) x h = getLast (x :: l) (cons_ne_nil _ _) :=
prev_getLast_cons' l x x h rfl
theorem prev_cons_cons_eq' (y z : α) (h : x ∈ y :: z :: l) (hx : x = y) :
prev (y :: z :: l) x h = getLast (z :: l) (cons_ne_nil _ _) := by rw [prev, dif_pos hx]
--@[simp] Porting note (#10618): `simp` can prove it
theorem prev_cons_cons_eq (z : α) (h : x ∈ x :: z :: l) :
prev (x :: z :: l) x h = getLast (z :: l) (cons_ne_nil _ _) :=
prev_cons_cons_eq' l x x z h rfl
theorem prev_cons_cons_of_ne' (y z : α) (h : x ∈ y :: z :: l) (hy : x ≠ y) (hz : x = z) :
prev (y :: z :: l) x h = y := by
cases l
· simp [prev, hy, hz]
· rw [prev, dif_neg hy, if_pos hz]
theorem prev_cons_cons_of_ne (y : α) (h : x ∈ y :: x :: l) (hy : x ≠ y) :
prev (y :: x :: l) x h = y :=
prev_cons_cons_of_ne' _ _ _ _ _ hy rfl
theorem prev_ne_cons_cons (y z : α) (h : x ∈ y :: z :: l) (hy : x ≠ y) (hz : x ≠ z) :
prev (y :: z :: l) x h = prev (z :: l) x (by simpa [hy] using h) := by
cases l
· simp [hy, hz] at h
· rw [prev, dif_neg hy, if_neg hz]
theorem next_mem (h : x ∈ l) : l.next x h ∈ l :=
nextOr_mem (get_mem _ _ _)
theorem prev_mem (h : x ∈ l) : l.prev x h ∈ l := by
cases' l with hd tl
· simp at h
induction' tl with hd' tl hl generalizing hd
· simp
· by_cases hx : x = hd
· simp only [hx, prev_cons_cons_eq]
exact mem_cons_of_mem _ (getLast_mem _)
· rw [prev, dif_neg hx]
split_ifs with hm
· exact mem_cons_self _ _
· exact mem_cons_of_mem _ (hl _ _)
theorem next_get : ∀ (l : List α) (_h : Nodup l) (i : Fin l.length),
next l (l.get i) (get_mem _ _ _) = l.get ⟨(i + 1) % l.length,
Nat.mod_lt _ (i.1.zero_le.trans_lt i.2)⟩
| [], _, i => by simpa using i.2
| [_], _, _ => by simp
| x::y::l, _h, ⟨0, h0⟩ => by
have h₁ : get (x :: y :: l) { val := 0, isLt := h0 } = x := by simp
rw [next_cons_cons_eq' _ _ _ _ _ h₁]
simp
| x::y::l, hn, ⟨i+1, hi⟩ => by
have hx' : (x :: y :: l).get ⟨i+1, hi⟩ ≠ x := by
intro H
suffices (i + 1 : ℕ) = 0 by simpa
rw [nodup_iff_injective_get] at hn
refine Fin.val_eq_of_eq (@hn ⟨i + 1, hi⟩ ⟨0, by simp⟩ ?_)
simpa using H
have hi' : i ≤ l.length := Nat.le_of_lt_succ (Nat.succ_lt_succ_iff.1 hi)
rcases hi'.eq_or_lt with (hi' | hi')
· subst hi'
rw [next_getLast_cons]
· simp [hi', get]
· rw [get_cons_succ]; exact get_mem _ _ _
· exact hx'
· simp [getLast_eq_getElem]
· exact hn.of_cons
· rw [next_ne_head_ne_getLast _ _ _ _ _ hx']
· simp only [get_cons_succ]
rw [next_get (y::l), ← get_cons_succ (a := x)]
· congr
dsimp
rw [Nat.mod_eq_of_lt (Nat.succ_lt_succ_iff.2 hi'),
Nat.mod_eq_of_lt (Nat.succ_lt_succ_iff.2 (Nat.succ_lt_succ_iff.2 hi'))]
· simp [Nat.mod_eq_of_lt (Nat.succ_lt_succ_iff.2 hi'), hi']
· exact hn.of_cons
· rw [getLast_eq_getElem]
intro h
have := nodup_iff_injective_get.1 hn h
simp at this; simp [this] at hi'
· rw [get_cons_succ]; exact get_mem _ _ _
set_option linter.deprecated false in
@[deprecated next_get (since := "2023-01-27")]
theorem next_nthLe (l : List α) (h : Nodup l) (n : ℕ) (hn : n < l.length) :
next l (l.nthLe n hn) (nthLe_mem _ _ _) =
l.nthLe ((n + 1) % l.length) (Nat.mod_lt _ (n.zero_le.trans_lt hn)) :=
next_get l h ⟨n, hn⟩
set_option linter.deprecated false in
theorem prev_nthLe (l : List α) (h : Nodup l) (n : ℕ) (hn : n < l.length) :
prev l (l.nthLe n hn) (nthLe_mem _ _ _) =
l.nthLe ((n + (l.length - 1)) % l.length) (Nat.mod_lt _ (n.zero_le.trans_lt hn)) := by
cases' l with x l
· simp at hn
induction' l with y l hl generalizing n x
· simp
· rcases n with (_ | _ | n)
· simp [Nat.add_succ_sub_one, add_zero, List.prev_cons_cons_eq, Nat.zero_eq, List.length,
List.nthLe, Nat.succ_add_sub_one, zero_add, getLast_eq_get,
Nat.mod_eq_of_lt (Nat.succ_lt_succ l.length.lt_succ_self)]
· simp only [mem_cons, nodup_cons] at h
push_neg at h
simp only [List.prev_cons_cons_of_ne _ _ _ _ h.left.left.symm, Nat.zero_eq, List.length,
List.nthLe, add_comm, eq_self_iff_true, Nat.succ_add_sub_one, Nat.mod_self, zero_add,
List.get]
· rw [prev_ne_cons_cons]
· convert hl n.succ y h.of_cons (Nat.le_of_succ_le_succ hn) using 1
have : ∀ k hk, (y :: l).nthLe k hk = (x :: y :: l).nthLe (k + 1) (Nat.succ_lt_succ hk) := by
simp [List.nthLe]
rw [this]
congr
simp only [Nat.add_succ_sub_one, add_zero, length]
simp only [length, Nat.succ_lt_succ_iff] at hn
set k := l.length
rw [Nat.succ_add, ← Nat.add_succ, Nat.add_mod_right, Nat.succ_add, ← Nat.add_succ _ k,
Nat.add_mod_right, Nat.mod_eq_of_lt, Nat.mod_eq_of_lt]
· exact Nat.lt_succ_of_lt hn
· exact Nat.succ_lt_succ (Nat.lt_succ_of_lt hn)
· intro H
suffices n.succ.succ = 0 by simpa
rw [nodup_iff_nthLe_inj] at h
refine h _ _ hn Nat.succ_pos' ?_
simpa using H
· intro H
suffices n.succ.succ = 1 by simpa
rw [nodup_iff_nthLe_inj] at h
refine h _ _ hn (Nat.succ_lt_succ Nat.succ_pos') ?_
simpa using H
set_option linter.deprecated false in
theorem pmap_next_eq_rotate_one (h : Nodup l) : (l.pmap l.next fun _ h => h) = l.rotate 1 := by
apply List.ext_nthLe
· simp
· intros
rw [nthLe_pmap, nthLe_rotate, next_nthLe _ h]
set_option linter.deprecated false in
theorem pmap_prev_eq_rotate_length_sub_one (h : Nodup l) :
(l.pmap l.prev fun _ h => h) = l.rotate (l.length - 1) := by
apply List.ext_nthLe
· simp
· intro n hn hn'
rw [nthLe_rotate, nthLe_pmap, prev_nthLe _ h]
set_option linter.deprecated false in
theorem prev_next (l : List α) (h : Nodup l) (x : α) (hx : x ∈ l) :
prev l (next l x hx) (next_mem _ _ _) = x := by
obtain ⟨n, hn, rfl⟩ := nthLe_of_mem hx
simp only [next_nthLe, prev_nthLe, h, Nat.mod_add_mod]
cases' l with hd tl
· simp at hx
· have : (n + 1 + length tl) % (length tl + 1) = n := by
rw [length_cons] at hn
rw [add_assoc, add_comm 1, Nat.add_mod_right, Nat.mod_eq_of_lt hn]
simp only [length_cons, Nat.succ_sub_succ_eq_sub, Nat.sub_zero, Nat.succ_eq_add_one, this]
set_option linter.deprecated false in
theorem next_prev (l : List α) (h : Nodup l) (x : α) (hx : x ∈ l) :
next l (prev l x hx) (prev_mem _ _ _) = x := by
obtain ⟨n, hn, rfl⟩ := nthLe_of_mem hx
simp only [next_nthLe, prev_nthLe, h, Nat.mod_add_mod]
cases' l with hd tl
· simp at hx
· have : (n + length tl + 1) % (length tl + 1) = n := by
rw [length_cons] at hn
rw [add_assoc, Nat.add_mod_right, Nat.mod_eq_of_lt hn]
simp [this]
set_option linter.deprecated false in
theorem prev_reverse_eq_next (l : List α) (h : Nodup l) (x : α) (hx : x ∈ l) :
prev l.reverse x (mem_reverse.mpr hx) = next l x hx := by
obtain ⟨k, hk, rfl⟩ := nthLe_of_mem hx
have lpos : 0 < l.length := k.zero_le.trans_lt hk
have key : l.length - 1 - k < l.length := by omega
rw [← nthLe_pmap l.next (fun _ h => h) (by simpa using hk)]
simp_rw [← nthLe_reverse l k (key.trans_le (by simp)), pmap_next_eq_rotate_one _ h]
rw [← nthLe_pmap l.reverse.prev fun _ h => h]
· simp_rw [pmap_prev_eq_rotate_length_sub_one _ (nodup_reverse.mpr h), rotate_reverse,
length_reverse, Nat.mod_eq_of_lt (Nat.sub_lt lpos Nat.succ_pos'),
Nat.sub_sub_self (Nat.succ_le_of_lt lpos)]
rw [← nthLe_reverse]
· simp [Nat.sub_sub_self (Nat.le_sub_one_of_lt hk)]
· simpa using (Nat.sub_le _ _).trans_lt (Nat.sub_lt lpos Nat.succ_pos')
· simpa
theorem next_reverse_eq_prev (l : List α) (h : Nodup l) (x : α) (hx : x ∈ l) :
next l.reverse x (mem_reverse.mpr hx) = prev l x hx := by
convert (prev_reverse_eq_next l.reverse (nodup_reverse.mpr h) x (mem_reverse.mpr hx)).symm
exact (reverse_reverse l).symm
theorem isRotated_next_eq {l l' : List α} (h : l ~r l') (hn : Nodup l) {x : α} (hx : x ∈ l) :
l.next x hx = l'.next x (h.mem_iff.mp hx) := by
obtain ⟨k, hk, rfl⟩ := get_of_mem hx
obtain ⟨n, rfl⟩ := id h
rw [next_get _ hn]
simp_rw [get_eq_get_rotate _ n k]
rw [next_get _ (h.nodup_iff.mp hn), get_eq_get_rotate _ n]
simp [add_assoc]
theorem isRotated_prev_eq {l l' : List α} (h : l ~r l') (hn : Nodup l) {x : α} (hx : x ∈ l) :
l.prev x hx = l'.prev x (h.mem_iff.mp hx) := by
rw [← next_reverse_eq_prev _ hn, ← next_reverse_eq_prev _ (h.nodup_iff.mp hn)]
exact isRotated_next_eq h.reverse (nodup_reverse.mpr hn) _
end List
open List
/-- `Cycle α` is the quotient of `List α` by cyclic permutation.
Duplicates are allowed.
-/
def Cycle (α : Type*) : Type _ :=
Quotient (IsRotated.setoid α)
namespace Cycle
variable {α : Type*}
-- Porting note (#11445): new definition
/-- The coercion from `List α` to `Cycle α` -/
@[coe] def ofList : List α → Cycle α :=
Quot.mk _
instance : Coe (List α) (Cycle α) :=
⟨ofList⟩
@[simp]
theorem coe_eq_coe {l₁ l₂ : List α} : (l₁ : Cycle α) = (l₂ : Cycle α) ↔ l₁ ~r l₂ :=
@Quotient.eq _ (IsRotated.setoid _) _ _
@[simp]
theorem mk_eq_coe (l : List α) : Quot.mk _ l = (l : Cycle α) :=
rfl
@[simp]
theorem mk''_eq_coe (l : List α) : Quotient.mk'' l = (l : Cycle α) :=
rfl
theorem coe_cons_eq_coe_append (l : List α) (a : α) :
(↑(a :: l) : Cycle α) = (↑(l ++ [a]) : Cycle α) :=
Quot.sound ⟨1, by rw [rotate_cons_succ, rotate_zero]⟩
/-- The unique empty cycle. -/
def nil : Cycle α :=
([] : List α)
@[simp]
theorem coe_nil : ↑([] : List α) = @nil α :=
rfl
@[simp]
theorem coe_eq_nil (l : List α) : (l : Cycle α) = nil ↔ l = [] :=
coe_eq_coe.trans isRotated_nil_iff
/-- For consistency with `EmptyCollection (List α)`. -/
instance : EmptyCollection (Cycle α) :=
⟨nil⟩
@[simp]
theorem empty_eq : ∅ = @nil α :=
rfl
instance : Inhabited (Cycle α) :=
⟨nil⟩
/-- An induction principle for `Cycle`. Use as `induction s`. -/
@[elab_as_elim, induction_eliminator]
theorem induction_on {C : Cycle α → Prop} (s : Cycle α) (H0 : C nil)
(HI : ∀ (a) (l : List α), C ↑l → C ↑(a :: l)) : C s :=
Quotient.inductionOn' s fun l => by
refine List.recOn l ?_ ?_ <;> simp
assumption'
/-- For `x : α`, `s : Cycle α`, `x ∈ s` indicates that `x` occurs at least once in `s`. -/
def Mem (a : α) (s : Cycle α) : Prop :=
Quot.liftOn s (fun l => a ∈ l) fun _ _ e => propext <| e.mem_iff
instance : Membership α (Cycle α) :=
⟨Mem⟩
@[simp]
theorem mem_coe_iff {a : α} {l : List α} : a ∈ (↑l : Cycle α) ↔ a ∈ l :=
Iff.rfl
@[simp]
theorem not_mem_nil : ∀ a, a ∉ @nil α :=
List.not_mem_nil
instance [DecidableEq α] : DecidableEq (Cycle α) := fun s₁ s₂ =>
Quotient.recOnSubsingleton₂' s₁ s₂ fun _ _ => decidable_of_iff' _ Quotient.eq''
instance [DecidableEq α] (x : α) (s : Cycle α) : Decidable (x ∈ s) :=
Quotient.recOnSubsingleton' s fun l => show Decidable (x ∈ l) from inferInstance
/-- Reverse a `s : Cycle α` by reversing the underlying `List`. -/
nonrec def reverse (s : Cycle α) : Cycle α :=
Quot.map reverse (fun _ _ => IsRotated.reverse) s
@[simp]
theorem reverse_coe (l : List α) : (l : Cycle α).reverse = l.reverse :=
rfl
@[simp]
theorem mem_reverse_iff {a : α} {s : Cycle α} : a ∈ s.reverse ↔ a ∈ s :=
Quot.inductionOn s fun _ => mem_reverse
@[simp]
theorem reverse_reverse (s : Cycle α) : s.reverse.reverse = s :=
Quot.inductionOn s fun _ => by simp
@[simp]
theorem reverse_nil : nil.reverse = @nil α :=
rfl
/-- The length of the `s : Cycle α`, which is the number of elements, counting duplicates. -/
def length (s : Cycle α) : ℕ :=
Quot.liftOn s List.length fun _ _ e => e.perm.length_eq
@[simp]
theorem length_coe (l : List α) : length (l : Cycle α) = l.length :=
rfl
@[simp]
theorem length_nil : length (@nil α) = 0 :=
rfl
@[simp]
theorem length_reverse (s : Cycle α) : s.reverse.length = s.length :=
Quot.inductionOn s List.length_reverse
/-- A `s : Cycle α` that is at most one element. -/
def Subsingleton (s : Cycle α) : Prop :=
s.length ≤ 1
theorem subsingleton_nil : Subsingleton (@nil α) := Nat.zero_le _
theorem length_subsingleton_iff {s : Cycle α} : Subsingleton s ↔ length s ≤ 1 :=
Iff.rfl
@[simp]
theorem subsingleton_reverse_iff {s : Cycle α} : s.reverse.Subsingleton ↔ s.Subsingleton := by
simp [length_subsingleton_iff]
theorem Subsingleton.congr {s : Cycle α} (h : Subsingleton s) :
∀ ⦃x⦄ (_hx : x ∈ s) ⦃y⦄ (_hy : y ∈ s), x = y := by
induction' s using Quot.inductionOn with l
simp only [length_subsingleton_iff, length_coe, mk_eq_coe, le_iff_lt_or_eq, Nat.lt_add_one_iff,
length_eq_zero, length_eq_one, Nat.not_lt_zero, false_or_iff] at h
rcases h with (rfl | ⟨z, rfl⟩) <;> simp
/-- A `s : Cycle α` that is made up of at least two unique elements. -/
def Nontrivial (s : Cycle α) : Prop :=
∃ x y : α, x ≠ y ∧ x ∈ s ∧ y ∈ s
@[simp]
theorem nontrivial_coe_nodup_iff {l : List α} (hl : l.Nodup) :
Nontrivial (l : Cycle α) ↔ 2 ≤ l.length := by
rw [Nontrivial]
rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩)
· simp
· simp
· simp only [mem_cons, exists_prop, mem_coe_iff, List.length, Ne, Nat.succ_le_succ_iff,
Nat.zero_le, iff_true_iff]
refine ⟨hd, hd', ?_, by simp⟩
simp only [not_or, mem_cons, nodup_cons] at hl
exact hl.left.left
@[simp]
theorem nontrivial_reverse_iff {s : Cycle α} : s.reverse.Nontrivial ↔ s.Nontrivial := by
simp [Nontrivial]
theorem length_nontrivial {s : Cycle α} (h : Nontrivial s) : 2 ≤ length s := by
obtain ⟨x, y, hxy, hx, hy⟩ := h
induction' s using Quot.inductionOn with l
rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩)
· simp at hx
· simp only [mem_coe_iff, mk_eq_coe, mem_singleton] at hx hy
simp [hx, hy] at hxy
· simp [Nat.succ_le_succ_iff]
/-- The `s : Cycle α` contains no duplicates. -/
nonrec def Nodup (s : Cycle α) : Prop :=
Quot.liftOn s Nodup fun _l₁ _l₂ e => propext <| e.nodup_iff
@[simp]
nonrec theorem nodup_nil : Nodup (@nil α) :=
nodup_nil
@[simp]
theorem nodup_coe_iff {l : List α} : Nodup (l : Cycle α) ↔ l.Nodup :=
Iff.rfl
@[simp]
theorem nodup_reverse_iff {s : Cycle α} : s.reverse.Nodup ↔ s.Nodup :=
Quot.inductionOn s fun _ => nodup_reverse
theorem Subsingleton.nodup {s : Cycle α} (h : Subsingleton s) : Nodup s := by
induction' s using Quot.inductionOn with l
cases' l with hd tl
· simp
· have : tl = [] := by simpa [Subsingleton, length_eq_zero, Nat.succ_le_succ_iff] using h
simp [this]
theorem Nodup.nontrivial_iff {s : Cycle α} (h : Nodup s) : Nontrivial s ↔ ¬Subsingleton s := by
rw [length_subsingleton_iff]
induction s using Quotient.inductionOn'
simp only [mk''_eq_coe, nodup_coe_iff] at h
simp [h, Nat.succ_le_iff]
/-- The `s : Cycle α` as a `Multiset α`.
-/
def toMultiset (s : Cycle α) : Multiset α :=
Quotient.liftOn' s (↑) fun _ _ h => Multiset.coe_eq_coe.mpr h.perm
@[simp]
theorem coe_toMultiset (l : List α) : (l : Cycle α).toMultiset = l :=
rfl
@[simp]
theorem nil_toMultiset : nil.toMultiset = (0 : Multiset α) :=
rfl
@[simp]
theorem card_toMultiset (s : Cycle α) : Multiset.card s.toMultiset = s.length :=
Quotient.inductionOn' s (by simp)
@[simp]
theorem toMultiset_eq_nil {s : Cycle α} : s.toMultiset = 0 ↔ s = Cycle.nil :=
Quotient.inductionOn' s (by simp)
/-- The lift of `list.map`. -/
def map {β : Type*} (f : α → β) : Cycle α → Cycle β :=
Quotient.map' (List.map f) fun _ _ h => h.map _
@[simp]
theorem map_nil {β : Type*} (f : α → β) : map f nil = nil :=
rfl
@[simp]
theorem map_coe {β : Type*} (f : α → β) (l : List α) : map f ↑l = List.map f l :=
rfl
@[simp]
theorem map_eq_nil {β : Type*} (f : α → β) (s : Cycle α) : map f s = nil ↔ s = nil :=
Quotient.inductionOn' s (by simp)
@[simp]
theorem mem_map {β : Type*} {f : α → β} {b : β} {s : Cycle α} :
b ∈ s.map f ↔ ∃ a, a ∈ s ∧ f a = b :=
Quotient.inductionOn' s (by simp)
/-- The `Multiset` of lists that can make the cycle. -/
def lists (s : Cycle α) : Multiset (List α) :=
Quotient.liftOn' s (fun l => (l.cyclicPermutations : Multiset (List α))) fun l₁ l₂ h => by
simpa using h.cyclicPermutations.perm
@[simp]
theorem lists_coe (l : List α) : lists (l : Cycle α) = ↑l.cyclicPermutations :=
rfl
@[simp]
theorem mem_lists_iff_coe_eq {s : Cycle α} {l : List α} : l ∈ s.lists ↔ (l : Cycle α) = s :=
Quotient.inductionOn' s fun l => by
rw [lists, Quotient.liftOn'_mk'']
simp
@[simp]
theorem lists_nil : lists (@nil α) = [([] : List α)] := by
rw [nil, lists_coe, cyclicPermutations_nil]
section Decidable
variable [DecidableEq α]
/-- Auxiliary decidability algorithm for lists that contain at least two unique elements.
-/
def decidableNontrivialCoe : ∀ l : List α, Decidable (Nontrivial (l : Cycle α))
| [] => isFalse (by simp [Nontrivial])
| [x] => isFalse (by simp [Nontrivial])
| x :: y :: l =>
if h : x = y then
@decidable_of_iff' _ (Nontrivial (x :: l : Cycle α)) (by simp [h, Nontrivial])
(decidableNontrivialCoe (x :: l))
else isTrue ⟨x, y, h, by simp, by simp⟩
instance {s : Cycle α} : Decidable (Nontrivial s) :=
Quot.recOnSubsingleton' s decidableNontrivialCoe
instance {s : Cycle α} : Decidable (Nodup s) :=
Quot.recOnSubsingleton' s List.nodupDecidable
instance fintypeNodupCycle [Fintype α] : Fintype { s : Cycle α // s.Nodup } :=
Fintype.ofSurjective (fun l : { l : List α // l.Nodup } => ⟨l.val, by simpa using l.prop⟩)
fun ⟨s, hs⟩ => by
induction' s using Quotient.inductionOn' with s hs
exact ⟨⟨s, hs⟩, by simp⟩
instance fintypeNodupNontrivialCycle [Fintype α] :
Fintype { s : Cycle α // s.Nodup ∧ s.Nontrivial } :=
Fintype.subtype
(((Finset.univ : Finset { s : Cycle α // s.Nodup }).map (Function.Embedding.subtype _)).filter
Cycle.Nontrivial)
(by simp)
/-- The `s : Cycle α` as a `Finset α`. -/
def toFinset (s : Cycle α) : Finset α :=
s.toMultiset.toFinset
@[simp]
theorem toFinset_toMultiset (s : Cycle α) : s.toMultiset.toFinset = s.toFinset :=
rfl
@[simp]
theorem coe_toFinset (l : List α) : (l : Cycle α).toFinset = l.toFinset :=
rfl
@[simp]
theorem nil_toFinset : (@nil α).toFinset = ∅ :=
rfl
@[simp]
theorem toFinset_eq_nil {s : Cycle α} : s.toFinset = ∅ ↔ s = Cycle.nil :=
Quotient.inductionOn' s (by simp)
/-- Given a `s : Cycle α` such that `Nodup s`, retrieve the next element after `x ∈ s`. -/
nonrec def next : ∀ (s : Cycle α) (_hs : Nodup s) (x : α) (_hx : x ∈ s), α := fun s =>
Quot.hrecOn (motive := fun (s : Cycle α) => ∀ (_hs : Cycle.Nodup s) (x : α) (_hx : x ∈ s), α) s
(fun l _hn x hx => next l x hx) fun l₁ l₂ h =>
Function.hfunext (propext h.nodup_iff) fun h₁ h₂ _he =>
Function.hfunext rfl fun x y hxy =>
Function.hfunext (propext (by rw [eq_of_heq hxy]; simpa [eq_of_heq hxy] using h.mem_iff))
fun hm hm' he' => heq_of_eq
(by rw [heq_iff_eq] at hxy; subst x; simpa using isRotated_next_eq h h₁ _)
/-- Given a `s : Cycle α` such that `Nodup s`, retrieve the previous element before `x ∈ s`. -/
nonrec def prev : ∀ (s : Cycle α) (_hs : Nodup s) (x : α) (_hx : x ∈ s), α := fun s =>
Quot.hrecOn (motive := fun (s : Cycle α) => ∀ (_hs : Cycle.Nodup s) (x : α) (_hx : x ∈ s), α) s
(fun l _hn x hx => prev l x hx) fun l₁ l₂ h =>
Function.hfunext (propext h.nodup_iff) fun h₁ h₂ _he =>
Function.hfunext rfl fun x y hxy =>
Function.hfunext (propext (by rw [eq_of_heq hxy]; simpa [eq_of_heq hxy] using h.mem_iff))
fun hm hm' he' => heq_of_eq
(by rw [heq_iff_eq] at hxy; subst x; simpa using isRotated_prev_eq h h₁ _)
-- Porting note: removed `simp` and added `prev_reverse_eq_next'` with `simp` attribute
nonrec theorem prev_reverse_eq_next (s : Cycle α) : ∀ (hs : Nodup s) (x : α) (hx : x ∈ s),
s.reverse.prev (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.next hs x hx :=
Quotient.inductionOn' s prev_reverse_eq_next
@[simp]
nonrec theorem prev_reverse_eq_next' (s : Cycle α) (hs : Nodup s.reverse) (x : α)
(hx : x ∈ s.reverse) :
s.reverse.prev hs x hx = s.next (nodup_reverse_iff.mp hs) x (mem_reverse_iff.mp hx) :=
prev_reverse_eq_next s (nodup_reverse_iff.mp hs) x (mem_reverse_iff.mp hx)
-- Porting note: removed `simp` and added `next_reverse_eq_prev'` with `simp` attribute
theorem next_reverse_eq_prev (s : Cycle α) (hs : Nodup s) (x : α) (hx : x ∈ s) :
s.reverse.next (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.prev hs x hx := by
simp [← prev_reverse_eq_next]
@[simp]
theorem next_reverse_eq_prev' (s : Cycle α) (hs : Nodup s.reverse) (x : α) (hx : x ∈ s.reverse) :
s.reverse.next hs x hx = s.prev (nodup_reverse_iff.mp hs) x (mem_reverse_iff.mp hx) := by
simp [← prev_reverse_eq_next]
@[simp]
nonrec theorem next_mem (s : Cycle α) (hs : Nodup s) (x : α) (hx : x ∈ s) : s.next hs x hx ∈ s := by
induction s using Quot.inductionOn
apply next_mem; assumption
theorem prev_mem (s : Cycle α) (hs : Nodup s) (x : α) (hx : x ∈ s) : s.prev hs x hx ∈ s := by
rw [← next_reverse_eq_prev, ← mem_reverse_iff]
apply next_mem
@[simp]
nonrec theorem prev_next (s : Cycle α) : ∀ (hs : Nodup s) (x : α) (hx : x ∈ s),
s.prev hs (s.next hs x hx) (next_mem s hs x hx) = x :=
Quotient.inductionOn' s prev_next
@[simp]
nonrec theorem next_prev (s : Cycle α) : ∀ (hs : Nodup s) (x : α) (hx : x ∈ s),
s.next hs (s.prev hs x hx) (prev_mem s hs x hx) = x :=
Quotient.inductionOn' s next_prev
end Decidable
/-- We define a representation of concrete cycles, available when viewing them in a goal state or
via `#eval`, when over representable types. For example, the cycle `(2 1 4 3)` will be shown
as `c[2, 1, 4, 3]`. Two equal cycles may be printed differently if their internal representation
is different.
-/
unsafe instance [Repr α] : Repr (Cycle α) :=
⟨fun s _ => "c[" ++ Std.Format.joinSep (s.map repr).lists.unquot.head! ", " ++ "]"⟩
/-- `chain R s` means that `R` holds between adjacent elements of `s`.
`chain R ([a, b, c] : Cycle α) ↔ R a b ∧ R b c ∧ R c a` -/
nonrec def Chain (r : α → α → Prop) (c : Cycle α) : Prop :=
Quotient.liftOn' c
(fun l =>
match l with
| [] => True
| a :: m => Chain r a (m ++ [a]))
fun a b hab =>
propext <| by
cases' a with a l <;> cases' b with b m
· rfl
· have := isRotated_nil_iff'.1 hab
contradiction
· have := isRotated_nil_iff.1 hab
contradiction
· dsimp only
cases' hab with n hn
induction' n with d hd generalizing a b l m
· simp only [Nat.zero_eq, rotate_zero, cons.injEq] at hn
rw [hn.1, hn.2]
· cases' l with c s
· simp only [rotate_cons_succ, nil_append, rotate_singleton, cons.injEq] at hn
rw [hn.1, hn.2]
· rw [Nat.add_comm, ← rotate_rotate, rotate_cons_succ, rotate_zero, cons_append] at hn
rw [← hd c _ _ _ hn]
simp [and_comm]
@[simp]
theorem Chain.nil (r : α → α → Prop) : Cycle.Chain r (@nil α) := by trivial
@[simp]
theorem chain_coe_cons (r : α → α → Prop) (a : α) (l : List α) :
Chain r (a :: l) ↔ List.Chain r a (l ++ [a]) :=
Iff.rfl
--@[simp] Porting note (#10618): `simp` can prove it
theorem chain_singleton (r : α → α → Prop) (a : α) : Chain r [a] ↔ r a a := by
rw [chain_coe_cons, nil_append, List.chain_singleton]
theorem chain_ne_nil (r : α → α → Prop) {l : List α} :
∀ hl : l ≠ [], Chain r l ↔ List.Chain r (getLast l hl) l :=
l.reverseRecOn (fun hm => hm.irrefl.elim) (by
intro m a _H _
rw [← coe_cons_eq_coe_append, chain_coe_cons, getLast_append_singleton])
theorem chain_map {β : Type*} {r : α → α → Prop} (f : β → α) {s : Cycle β} :
Chain r (s.map f) ↔ Chain (fun a b => r (f a) (f b)) s :=
Quotient.inductionOn' s fun l => by
cases' l with a l
· rfl
dsimp only [Chain, ← mk''_eq_coe, Quotient.liftOn'_mk'', Cycle.map, Quotient.map', Quot.map,
Quotient.mk'', Quotient.liftOn', Quotient.liftOn, Quot.liftOn_mk, List.map]
rw [← concat_eq_append, ← List.map_concat, List.chain_map f]
simp
nonrec theorem chain_range_succ (r : ℕ → ℕ → Prop) (n : ℕ) :
Chain r (List.range n.succ) ↔ r n 0 ∧ ∀ m < n, r m m.succ := by
rw [range_succ, ← coe_cons_eq_coe_append, chain_coe_cons, ← range_succ, chain_range_succ]
variable {r : α → α → Prop} {s : Cycle α}
theorem Chain.imp {r₁ r₂ : α → α → Prop} (H : ∀ a b, r₁ a b → r₂ a b) (p : Chain r₁ s) :
Chain r₂ s := by
induction s
· trivial
· rw [chain_coe_cons] at p ⊢
exact p.imp H
/-- As a function from a relation to a predicate, `chain` is monotonic. -/
theorem chain_mono : Monotone (Chain : (α → α → Prop) → Cycle α → Prop) := fun _a _b hab _s =>
Chain.imp hab
theorem chain_of_pairwise : (∀ a ∈ s, ∀ b ∈ s, r a b) → Chain r s := by
induction' s with a l _
· exact fun _ => Cycle.Chain.nil r
intro hs
have Ha : a ∈ (a :: l : Cycle α) := by simp
have Hl : ∀ {b} (_hb : b ∈ l), b ∈ (a :: l : Cycle α) := @fun b hb => by simp [hb]
rw [Cycle.chain_coe_cons]
apply Pairwise.chain
rw [pairwise_cons]
refine
⟨fun b hb => ?_,
pairwise_append.2
⟨pairwise_of_forall_mem_list fun b hb c hc => hs b (Hl hb) c (Hl hc),
pairwise_singleton r a, fun b hb c hc => ?_⟩⟩
· rw [mem_append] at hb
cases' hb with hb hb
· exact hs a Ha b (Hl hb)
· rw [mem_singleton] at hb
rw [hb]
exact hs a Ha a Ha
· rw [mem_singleton] at hc
rw [hc]
exact hs b (Hl hb) a Ha
theorem chain_iff_pairwise [IsTrans α r] : Chain r s ↔ ∀ a ∈ s, ∀ b ∈ s, r a b :=
⟨by
induction' s with a l _
· exact fun _ b hb => (not_mem_nil _ hb).elim
intro hs b hb c hc
rw [Cycle.chain_coe_cons, List.chain_iff_pairwise] at hs
simp only [pairwise_append, pairwise_cons, mem_append, mem_singleton, List.not_mem_nil,
IsEmpty.forall_iff, imp_true_iff, Pairwise.nil, forall_eq, true_and_iff] at hs
simp only [mem_coe_iff, mem_cons] at hb hc
rcases hb with (rfl | hb) <;> rcases hc with (rfl | hc)
· exact hs.1 c (Or.inr rfl)
· exact hs.1 c (Or.inl hc)
· exact hs.2.2 b hb
· exact _root_.trans (hs.2.2 b hb) (hs.1 c (Or.inl hc)), Cycle.chain_of_pairwise⟩
theorem Chain.eq_nil_of_irrefl [IsTrans α r] [IsIrrefl α r] (h : Chain r s) : s = Cycle.nil := by
induction' s with a l _ h
· rfl
· have ha := mem_cons_self a l
exact (irrefl_of r a <| chain_iff_pairwise.1 h a ha a ha).elim
theorem Chain.eq_nil_of_well_founded [IsWellFounded α r] (h : Chain r s) : s = Cycle.nil :=
Chain.eq_nil_of_irrefl <| h.imp fun _ _ => Relation.TransGen.single
theorem forall_eq_of_chain [IsTrans α r] [IsAntisymm α r] (hs : Chain r s) {a b : α} (ha : a ∈ s)
(hb : b ∈ s) : a = b := by
rw [chain_iff_pairwise] at hs
exact antisymm (hs a ha b hb) (hs b hb a ha)
end Cycle
|
Data\List\Dedup.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.List.Nodup
import Mathlib.Data.List.Lattice
/-!
# Erasure of duplicates in a list
This file proves basic results about `List.dedup` (definition in `Data.List.Defs`).
`dedup l` returns `l` without its duplicates. It keeps the earliest (that is, rightmost)
occurrence of each.
## Tags
duplicate, multiplicity, nodup, `nub`
-/
universe u
namespace List
variable {α β : Type*} [DecidableEq α]
@[simp]
theorem dedup_nil : dedup [] = ([] : List α) :=
rfl
theorem dedup_cons_of_mem' {a : α} {l : List α} (h : a ∈ dedup l) : dedup (a :: l) = dedup l :=
pwFilter_cons_of_neg <| by simpa only [forall_mem_ne, not_not] using h
theorem dedup_cons_of_not_mem' {a : α} {l : List α} (h : a ∉ dedup l) :
dedup (a :: l) = a :: dedup l :=
pwFilter_cons_of_pos <| by simpa only [forall_mem_ne] using h
@[simp]
theorem mem_dedup {a : α} {l : List α} : a ∈ dedup l ↔ a ∈ l := by
have := not_congr (@forall_mem_pwFilter α (· ≠ ·) _ ?_ a l)
· simpa only [dedup, forall_mem_ne, not_not] using this
· intros x y z xz
exact not_and_or.1 <| mt (fun h ↦ h.1.trans h.2) xz
@[simp]
theorem dedup_cons_of_mem {a : α} {l : List α} (h : a ∈ l) : dedup (a :: l) = dedup l :=
dedup_cons_of_mem' <| mem_dedup.2 h
@[simp]
theorem dedup_cons_of_not_mem {a : α} {l : List α} (h : a ∉ l) : dedup (a :: l) = a :: dedup l :=
dedup_cons_of_not_mem' <| mt mem_dedup.1 h
theorem dedup_sublist : ∀ l : List α, dedup l <+ l :=
pwFilter_sublist
theorem dedup_subset : ∀ l : List α, dedup l ⊆ l :=
pwFilter_subset
theorem subset_dedup (l : List α) : l ⊆ dedup l := fun _ => mem_dedup.2
theorem nodup_dedup : ∀ l : List α, Nodup (dedup l) :=
pairwise_pwFilter
theorem headI_dedup [Inhabited α] (l : List α) :
l.dedup.headI = if l.headI ∈ l.tail then l.tail.dedup.headI else l.headI :=
match l with
| [] => rfl
| a :: l => by by_cases ha : a ∈ l <;> simp [ha, List.dedup_cons_of_mem]
theorem tail_dedup [Inhabited α] (l : List α) :
l.dedup.tail = if l.headI ∈ l.tail then l.tail.dedup.tail else l.tail.dedup :=
match l with
| [] => rfl
| a :: l => by by_cases ha : a ∈ l <;> simp [ha, List.dedup_cons_of_mem]
theorem dedup_eq_self {l : List α} : dedup l = l ↔ Nodup l :=
pwFilter_eq_self
theorem dedup_eq_cons (l : List α) (a : α) (l' : List α) :
l.dedup = a :: l' ↔ a ∈ l ∧ a ∉ l' ∧ l.dedup.tail = l' := by
refine ⟨fun h => ?_, fun h => ?_⟩
· refine ⟨mem_dedup.1 (h.symm ▸ mem_cons_self _ _), fun ha => ?_, by rw [h, tail_cons]⟩
have := count_pos_iff_mem.2 ha
have : count a l.dedup ≤ 1 := nodup_iff_count_le_one.1 (nodup_dedup l) a
rw [h, count_cons_self] at this
omega
· have := @List.cons_head!_tail α ⟨a⟩ _ (ne_nil_of_mem (mem_dedup.2 h.1))
have hal : a ∈ l.dedup := mem_dedup.2 h.1
rw [← this, mem_cons, or_iff_not_imp_right] at hal
exact this ▸ h.2.2.symm ▸ cons_eq_cons.2 ⟨(hal (h.2.2.symm ▸ h.2.1)).symm, rfl⟩
@[simp]
theorem dedup_eq_nil (l : List α) : l.dedup = [] ↔ l = [] := by
induction' l with a l hl
· exact Iff.rfl
· by_cases h : a ∈ l
· simp only [List.dedup_cons_of_mem h, hl, List.ne_nil_of_mem h]
· simp only [List.dedup_cons_of_not_mem h, List.cons_ne_nil]
protected theorem Nodup.dedup {l : List α} (h : l.Nodup) : l.dedup = l :=
List.dedup_eq_self.2 h
@[simp]
theorem dedup_idem {l : List α} : dedup (dedup l) = dedup l :=
pwFilter_idem
theorem dedup_append (l₁ l₂ : List α) : dedup (l₁ ++ l₂) = l₁ ∪ dedup l₂ := by
induction' l₁ with a l₁ IH; · rfl
simp only [cons_union] at *
rw [← IH, cons_append]
by_cases h : a ∈ dedup (l₁ ++ l₂)
· rw [dedup_cons_of_mem' h, insert_of_mem h]
· rw [dedup_cons_of_not_mem' h, insert_of_not_mem h]
theorem dedup_map_of_injective [DecidableEq β] {f : α → β} (hf : Function.Injective f)
(xs : List α) :
(xs.map f).dedup = xs.dedup.map f := by
induction xs with
| nil => simp
| cons x xs ih =>
rw [map_cons]
by_cases h : x ∈ xs
· rw [dedup_cons_of_mem h, dedup_cons_of_mem (mem_map_of_mem f h), ih]
· rw [dedup_cons_of_not_mem h, dedup_cons_of_not_mem <| (mem_map_of_injective hf).not.mpr h, ih,
map_cons]
/-- Note that the weaker `List.Subset.dedup_append_left` is proved later. -/
theorem Subset.dedup_append_right {xs ys : List α} (h : xs ⊆ ys) :
dedup (xs ++ ys) = dedup ys := by
rw [List.dedup_append, Subset.union_eq_right (h.trans <| subset_dedup _)]
theorem Disjoint.union_eq {xs ys : List α} (h : Disjoint xs ys) :
xs ∪ ys = xs.dedup ++ ys := by
induction xs with
| nil => simp
| cons x xs ih =>
rw [cons_union]
rw [disjoint_cons_left] at h
by_cases hx : x ∈ xs
· rw [dedup_cons_of_mem hx, insert_of_mem (mem_union_left hx _), ih h.2]
· rw [dedup_cons_of_not_mem hx, insert_of_not_mem, ih h.2, cons_append]
rw [mem_union_iff, not_or]
exact ⟨hx, h.1⟩
theorem Disjoint.dedup_append {xs ys : List α} (h : Disjoint xs ys) :
dedup (xs ++ ys) = dedup xs ++ dedup ys := by
rw [List.dedup_append, Disjoint.union_eq]
intro a hx hy
exact h hx (mem_dedup.mp hy)
theorem replicate_dedup {x : α} : ∀ {k}, k ≠ 0 → (replicate k x).dedup = [x]
| 0, h => (h rfl).elim
| 1, _ => rfl
| n + 2, _ => by
rw [replicate_succ, dedup_cons_of_mem (mem_replicate.2 ⟨n.succ_ne_zero, rfl⟩),
replicate_dedup n.succ_ne_zero]
theorem count_dedup (l : List α) (a : α) : l.dedup.count a = if a ∈ l then 1 else 0 := by
simp_rw [count_eq_of_nodup <| nodup_dedup l, mem_dedup]
end List
|
Data\List\Defs.lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import Mathlib.Data.Nat.Notation
import Mathlib.Control.Functor
import Mathlib.Data.SProd
import Mathlib.Util.CompileInductive
import Batteries.Tactic.Lint.Basic
import Batteries.Data.List.Lemmas
import Batteries.Data.RBMap.Basic
/-!
## Definitions on lists
This file contains various definitions on lists. It does not contain
proofs about these definitions, those are contained in other files in `Data.List`
-/
namespace List
open Function Nat
universe u v w x
variable {α β γ δ ε ζ : Type*}
instance [DecidableEq α] : SDiff (List α) :=
⟨List.diff⟩
-- mathlib3 `array` is not ported.
-- Porting note: see
-- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/List.2Ehead/near/313204716
-- for the fooI naming convention.
/-- "Inhabited" `get` function: returns `default` instead of `none` in the case
that the index is out of bounds. -/
def getI [Inhabited α] (l : List α) (n : Nat) : α :=
getD l n default
/-- "Inhabited" `take` function: Take `n` elements from a list `l`. If `l` has less than `n`
elements, append `n - length l` elements `default`. -/
def takeI [Inhabited α] (n : Nat) (l : List α) : List α :=
takeD n l default
/-- `findM tac l` returns the first element of `l` on which `tac` succeeds, and
fails otherwise. -/
def findM {α} {m : Type u → Type v} [Alternative m] (tac : α → m PUnit) : List α → m α :=
List.firstM fun a => (tac a) $> a
/-- `findM? p l` returns the first element `a` of `l` for which `p a` returns
true. `findM?` short-circuits, so `p` is not necessarily run on every `a` in
`l`. This is a monadic version of `List.find`. -/
def findM?'
{m : Type u → Type v}
[Monad m] {α : Type u}
(p : α → m (ULift Bool)) : List α → m (Option α)
| [] => pure none
| x :: xs => do
let ⟨px⟩ ← p x
if px then pure (some x) else findM?' p xs
section
variable {m : Type → Type v} [Monad m]
/-- `orM xs` runs the actions in `xs`, returning true if any of them returns
true. `orM` short-circuits, so if an action returns true, later actions are
not run. -/
def orM : List (m Bool) → m Bool :=
anyM id
/-- `andM xs` runs the actions in `xs`, returning true if all of them return
true. `andM` short-circuits, so if an action returns false, later actions are
not run. -/
def andM : List (m Bool) → m Bool :=
allM id
end
section foldIdxM
variable {m : Type v → Type w} [Monad m]
/-- Monadic variant of `foldlIdx`. -/
def foldlIdxM {α β} (f : ℕ → β → α → m β) (b : β) (as : List α) : m β :=
as.foldlIdx
(fun i ma b => do
let a ← ma
f i a b)
(pure b)
/-- Monadic variant of `foldrIdx`. -/
def foldrIdxM {α β} (f : ℕ → α → β → m β) (b : β) (as : List α) : m β :=
as.foldrIdx
(fun i a mb => do
let b ← mb
f i a b)
(pure b)
end foldIdxM
section mapIdxM
variable {m : Type v → Type w} [Monad m]
/-- Auxiliary definition for `mapIdxM'`. -/
def mapIdxMAux' {α} (f : ℕ → α → m PUnit) : ℕ → List α → m PUnit
| _, [] => pure ⟨⟩
| i, a :: as => f i a *> mapIdxMAux' f (i + 1) as
/-- A variant of `mapIdxM` specialised to applicative actions which
return `Unit`. -/
def mapIdxM' {α} (f : ℕ → α → m PUnit) (as : List α) : m PUnit :=
mapIdxMAux' f 0 as
end mapIdxM
/-- `l.Forall p` is equivalent to `∀ a ∈ l, p a`, but unfolds directly to a conjunction, i.e.
`List.Forall p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/
@[simp]
def Forall (p : α → Prop) : List α → Prop
| [] => True
| x :: [] => p x
| x :: l => p x ∧ Forall p l
section Permutations
/-- An auxiliary function for defining `permutations`. `permutationsAux2 t ts r ys f` is equal to
`(ys ++ ts, (insert_left ys t ts).map f ++ r)`, where `insert_left ys t ts` (not explicitly
defined) is the list of lists of the form `insert_nth n t (ys ++ ts)` for `0 ≤ n < length ys`.
permutations_aux2 10 [4, 5, 6] [] [1, 2, 3] id =
([1, 2, 3, 4, 5, 6],
[[10, 1, 2, 3, 4, 5, 6],
[1, 10, 2, 3, 4, 5, 6],
[1, 2, 10, 3, 4, 5, 6]]) -/
def permutationsAux2 (t : α) (ts : List α) (r : List β) : List α → (List α → β) → List α × List β
| [], _ => (ts, r)
| y :: ys, f =>
let (us, zs) := permutationsAux2 t ts r ys (fun x : List α => f (y :: x))
(y :: us, f (t :: y :: us) :: zs)
-- Porting note: removed `[elab_as_elim]` per Mario C
-- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/Status.20of.20data.2Elist.2Edefs.3F/near/313571979
/-- A recursor for pairs of lists. To have `C l₁ l₂` for all `l₁`, `l₂`, it suffices to have it for
`l₂ = []` and to be able to pour the elements of `l₁` into `l₂`. -/
def permutationsAux.rec {C : List α → List α → Sort v} (H0 : ∀ is, C [] is)
(H1 : ∀ t ts is, C ts (t :: is) → C is [] → C (t :: ts) is) : ∀ l₁ l₂, C l₁ l₂
| [], is => H0 is
| t :: ts, is =>
H1 t ts is (permutationsAux.rec H0 H1 ts (t :: is)) (permutationsAux.rec H0 H1 is [])
termination_by ts is => (length ts + length is, length ts)
decreasing_by all_goals (simp_wf; omega)
/-- An auxiliary function for defining `permutations`. `permutationsAux ts is` is the set of all
permutations of `is ++ ts` that do not fix `ts`. -/
def permutationsAux : List α → List α → List (List α) :=
permutationsAux.rec (fun _ => []) fun t ts is IH1 IH2 =>
foldr (fun y r => (permutationsAux2 t ts r y id).2) IH1 (is :: IH2)
/-- List of all permutations of `l`.
permutations [1, 2, 3] =
[[1, 2, 3], [2, 1, 3], [3, 2, 1],
[2, 3, 1], [3, 1, 2], [1, 3, 2]] -/
def permutations (l : List α) : List (List α) :=
l :: permutationsAux l []
/-- `permutations'Aux t ts` inserts `t` into every position in `ts`, including the last.
This function is intended for use in specifications, so it is simpler than `permutationsAux2`,
which plays roughly the same role in `permutations`.
Note that `(permutationsAux2 t [] [] ts id).2` is similar to this function, but skips the last
position:
permutations'Aux 10 [1, 2, 3] =
[[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3], [1, 2, 3, 10]]
(permutationsAux2 10 [] [] [1, 2, 3] id).2 =
[[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3]] -/
@[simp]
def permutations'Aux (t : α) : List α → List (List α)
| [] => [[t]]
| y :: ys => (t :: y :: ys) :: (permutations'Aux t ys).map (cons y)
/-- List of all permutations of `l`. This version of `permutations` is less efficient but has
simpler definitional equations. The permutations are in a different order,
but are equal up to permutation, as shown by `List.permutations_perm_permutations'`.
permutations [1, 2, 3] =
[[1, 2, 3], [2, 1, 3], [2, 3, 1],
[1, 3, 2], [3, 1, 2], [3, 2, 1]] -/
@[simp]
def permutations' : List α → List (List α)
| [] => [[]]
| t :: ts => (permutations' ts).bind <| permutations'Aux t
end Permutations
/-- `extractp p l` returns a pair of an element `a` of `l` satisfying the predicate
`p`, and `l`, with `a` removed. If there is no such element `a` it returns `(none, l)`. -/
def extractp (p : α → Prop) [DecidablePred p] : List α → Option α × List α
| [] => (none, [])
| a :: l =>
if p a then (some a, l)
else
let (a', l') := extractp p l
(a', a :: l')
/-- Notation for calculating the product of a `List`
-/
instance instSProd : SProd (List α) (List β) (List (α × β)) where
sprod := List.product
section Chain
instance decidableChain {R : α → α → Prop} [DecidableRel R] (a : α) (l : List α) :
Decidable (Chain R a l) := by
induction l generalizing a with
| nil => simp only [List.Chain.nil]; infer_instance
| cons a as ih => haveI := ih; simp only [List.chain_cons]; infer_instance
instance decidableChain' {R : α → α → Prop} [DecidableRel R] (l : List α) :
Decidable (Chain' R l) := by
cases l <;> dsimp only [List.Chain'] <;> infer_instance
end Chain
/-- `dedup l` removes duplicates from `l` (taking only the last occurrence).
Defined as `pwFilter (≠)`.
dedup [1, 0, 2, 2, 1] = [0, 2, 1] -/
def dedup [DecidableEq α] : List α → List α :=
pwFilter (· ≠ ·)
/-- Greedily create a sublist of `a :: l` such that, for every two adjacent elements `a, b`,
`R a b` holds. Mostly used with ≠; for example, `destutter' (≠) 1 [2, 2, 1, 1] = [1, 2, 1]`,
`destutter' (≠) 1, [2, 3, 3] = [1, 2, 3]`, `destutter' (<) 1 [2, 5, 2, 3, 4, 9] = [1, 2, 5, 9]`. -/
def destutter' (R : α → α → Prop) [DecidableRel R] : α → List α → List α
| a, [] => [a]
| a, h :: l => if R a h then a :: destutter' R h l else destutter' R a l
-- TODO: should below be "lazily"?
/-- Greedily create a sublist of `l` such that, for every two adjacent elements `a, b ∈ l`,
`R a b` holds. Mostly used with ≠; for example, `destutter (≠) [1, 2, 2, 1, 1] = [1, 2, 1]`,
`destutter (≠) [1, 2, 3, 3] = [1, 2, 3]`, `destutter (<) [1, 2, 5, 2, 3, 4, 9] = [1, 2, 5, 9]`. -/
def destutter (R : α → α → Prop) [DecidableRel R] : List α → List α
| h :: l => destutter' R h l
| [] => []
-- Porting note: replace ilast' by getLastD
-- Porting note: remove last' from Batteries
section Choose
variable (p : α → Prop) [DecidablePred p] (l : List α)
/-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`,
choose the first element with this property. This version returns both `a` and proofs
of `a ∈ l` and `p a`. -/
def chooseX : ∀ l : List α, ∀ _ : ∃ a, a ∈ l ∧ p a, { a // a ∈ l ∧ p a }
| [], hp => False.elim (Exists.elim hp fun a h => not_mem_nil a h.left)
| l :: ls, hp =>
if pl : p l then ⟨l, ⟨mem_cons.mpr <| Or.inl rfl, pl⟩⟩
else
-- pattern matching on `hx` too makes this not reducible!
let ⟨a, ha⟩ :=
chooseX ls
(hp.imp fun _ ⟨o, h₂⟩ => ⟨(mem_cons.mp o).resolve_left fun e => pl <| e ▸ h₂, h₂⟩)
⟨a, mem_cons.mpr <| Or.inr ha.1, ha.2⟩
/-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`,
choose the first element with this property. This version returns `a : α`, and properties
are given by `choose_mem` and `choose_property`. -/
def choose (hp : ∃ a, a ∈ l ∧ p a) : α :=
chooseX p l hp
end Choose
/-- `mapDiagM' f l` calls `f` on all elements in the upper triangular part of `l × l`.
That is, for each `e ∈ l`, it will run `f e e` and then `f e e'`
for each `e'` that appears after `e` in `l`.
Example: suppose `l = [1, 2, 3]`. `mapDiagM' f l` will evaluate, in this order,
`f 1 1`, `f 1 2`, `f 1 3`, `f 2 2`, `f 2 3`, `f 3 3`.
-/
def mapDiagM' {m} [Monad m] {α} (f : α → α → m Unit) : List α → m Unit
| [] => return ()
| h :: t => do
_ ← f h h
_ ← t.mapM' (f h)
t.mapDiagM' f
-- as ported:
-- | [] => return ()
-- | h :: t => (f h h >> t.mapM' (f h)) >> t.mapDiagM'
/-- Left-biased version of `List.map₂`. `map₂Left' f as bs` applies `f` to each
pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is
applied to `none` for the remaining `aᵢ`. Returns the results of the `f`
applications and the remaining `bs`.
```
map₂Left' prod.mk [1, 2] ['a'] = ([(1, some 'a'), (2, none)], [])
map₂Left' prod.mk [1] ['a', 'b'] = ([(1, some 'a')], ['b'])
```
-/
@[simp]
def map₂Left' (f : α → Option β → γ) : List α → List β → List γ × List β
| [], bs => ([], bs)
| a :: as, [] => ((a :: as).map fun a => f a none, [])
| a :: as, b :: bs =>
let rec' := map₂Left' f as bs
(f a (some b) :: rec'.fst, rec'.snd)
/-- Right-biased version of `List.map₂`. `map₂Right' f as bs` applies `f` to each
pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is
applied to `none` for the remaining `bᵢ`. Returns the results of the `f`
applications and the remaining `as`.
```
map₂Right' prod.mk [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], [])
map₂Right' prod.mk [1, 2] ['a'] = ([(some 1, 'a')], [2])
```
-/
def map₂Right' (f : Option α → β → γ) (as : List α) (bs : List β) : List γ × List α :=
map₂Left' (flip f) bs as
/-- Left-biased version of `List.map₂`. `map₂Left f as bs` applies `f` to each pair
`aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none`
for the remaining `aᵢ`.
```
map₂Left Prod.mk [1, 2] ['a'] = [(1, some 'a'), (2, none)]
map₂Left Prod.mk [1] ['a', 'b'] = [(1, some 'a')]
map₂Left f as bs = (map₂Left' f as bs).fst
```
-/
@[simp]
def map₂Left (f : α → Option β → γ) : List α → List β → List γ
| [], _ => []
| a :: as, [] => (a :: as).map fun a => f a none
| a :: as, b :: bs => f a (some b) :: map₂Left f as bs
/-- Right-biased version of `List.map₂`. `map₂Right f as bs` applies `f` to each
pair `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is applied to
`none` for the remaining `bᵢ`.
```
map₂Right Prod.mk [1, 2] ['a'] = [(some 1, 'a')]
map₂Right Prod.mk [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')]
map₂Right f as bs = (map₂Right' f as bs).fst
```
-/
def map₂Right (f : Option α → β → γ) (as : List α) (bs : List β) : List γ :=
map₂Left (flip f) bs as
-- porting note -- was `unsafe` but removed for Lean 4 port
-- TODO: naming is awkward...
/-- Asynchronous version of `List.map`.
-/
def mapAsyncChunked {α β} (f : α → β) (xs : List α) (chunk_size := 1024) : List β :=
((xs.toChunks chunk_size).map fun xs => Task.spawn fun _ => List.map f xs).bind Task.get
/-!
We add some n-ary versions of `List.zipWith` for functions with more than two arguments.
These can also be written in terms of `List.zip` or `List.zipWith`.
For example, `zipWith3 f xs ys zs` could also be written as
`zipWith id (zipWith f xs ys) zs`
or as
`(zip xs <| zip ys zs).map <| fun ⟨x, y, z⟩ ↦ f x y z`.
-/
/-- Ternary version of `List.zipWith`. -/
def zipWith3 (f : α → β → γ → δ) : List α → List β → List γ → List δ
| x :: xs, y :: ys, z :: zs => f x y z :: zipWith3 f xs ys zs
| _, _, _ => []
/-- Quaternary version of `list.zipWith`. -/
def zipWith4 (f : α → β → γ → δ → ε) : List α → List β → List γ → List δ → List ε
| x :: xs, y :: ys, z :: zs, u :: us => f x y z u :: zipWith4 f xs ys zs us
| _, _, _, _ => []
/-- Quinary version of `list.zipWith`. -/
def zipWith5 (f : α → β → γ → δ → ε → ζ) : List α → List β → List γ → List δ → List ε → List ζ
| x :: xs, y :: ys, z :: zs, u :: us, v :: vs => f x y z u v :: zipWith5 f xs ys zs us vs
| _, _, _, _, _ => []
/-- Given a starting list `old`, a list of booleans and a replacement list `new`,
read the items in `old` in succession and either replace them with the next element of `new` or
not, according as to whether the corresponding boolean is `true` or `false`. -/
def replaceIf : List α → List Bool → List α → List α
| l, _, [] => l
| [], _, _ => []
| l, [], _ => l
| n :: ns, tf :: bs, e@(c :: cs) => if tf then c :: ns.replaceIf bs cs else n :: ns.replaceIf bs e
/-- `iterate f a n` is `[a, f a, ..., f^[n - 1] a]`. -/
@[simp]
def iterate (f : α → α) (a : α) : (n : ℕ) → List α
| 0 => []
| n + 1 => a :: iterate f (f a) n
/-- Tail-recursive version of `List.iterate`. -/
@[inline]
def iterateTR (f : α → α) (a : α) (n : ℕ) : List α :=
loop a n []
where
/-- `iterateTR.loop f a n l := iterate f a n ++ reverse l`. -/
@[simp, specialize]
loop (a : α) (n : ℕ) (l : List α) : List α :=
match n with
| 0 => reverse l
| n + 1 => loop (f a) n (a :: l)
theorem iterateTR_loop_eq (f : α → α) (a : α) (n : ℕ) (l : List α) :
iterateTR.loop f a n l = reverse l ++ iterate f a n := by
induction n generalizing a l <;> simp [*]
@[csimp]
theorem iterate_eq_iterateTR : @iterate = @iterateTR := by
funext α f a n
exact Eq.symm <| iterateTR_loop_eq f a n []
end List
|
Data\List\Destutter.lean | /-
Copyright (c) 2022 Eric Rodriguez. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Rodriguez, Eric Wieser
-/
import Mathlib.Data.List.Chain
/-!
# Destuttering of Lists
This file proves theorems about `List.destutter` (in `Data.List.Defs`), which greedily removes all
non-related items that are adjacent in a list, e.g. `[2, 2, 3, 3, 2].destutter (≠) = [2, 3, 2]`.
Note that we make no guarantees of being the longest sublist with this property; e.g.,
`[123, 1, 2, 5, 543, 1000].destutter (<) = [123, 543, 1000]`, but a longer ascending chain could be
`[1, 2, 5, 543, 1000]`.
## Main statements
* `List.destutter_sublist`: `l.destutter` is a sublist of `l`.
* `List.destutter_is_chain'`: `l.destutter` satisfies `Chain' R`.
* Analogies of these theorems for `List.destutter'`, which is the `destutter` equivalent of `Chain`.
## Tags
adjacent, chain, duplicates, remove, list, stutter, destutter
-/
variable {α : Type*} (l : List α) (R : α → α → Prop) [DecidableRel R] {a b : α}
namespace List
@[simp]
theorem destutter'_nil : destutter' R a [] = [a] :=
rfl
theorem destutter'_cons :
(b :: l).destutter' R a = if R a b then a :: destutter' R b l else destutter' R a l :=
rfl
variable {R}
@[simp]
theorem destutter'_cons_pos (h : R b a) : (a :: l).destutter' R b = b :: l.destutter' R a := by
rw [destutter', if_pos h]
@[simp]
theorem destutter'_cons_neg (h : ¬R b a) : (a :: l).destutter' R b = l.destutter' R b := by
rw [destutter', if_neg h]
variable (R)
@[simp]
theorem destutter'_singleton : [b].destutter' R a = if R a b then [a, b] else [a] := by
split_ifs with h <;> simp! [h]
theorem destutter'_sublist (a) : l.destutter' R a <+ a :: l := by
induction' l with b l hl generalizing a
· simp
rw [destutter']
split_ifs
· exact Sublist.cons₂ a (hl b)
· exact (hl a).trans ((l.sublist_cons_self b).cons_cons a)
theorem mem_destutter' (a) : a ∈ l.destutter' R a := by
induction' l with b l hl
· simp
rw [destutter']
split_ifs
· simp
· assumption
theorem destutter'_is_chain : ∀ l : List α, ∀ {a b}, R a b → (l.destutter' R b).Chain R a
| [], a, b, h => chain_singleton.mpr h
| c :: l, a, b, h => by
rw [destutter']
split_ifs with hbc
· rw [chain_cons]
exact ⟨h, destutter'_is_chain l hbc⟩
· exact destutter'_is_chain l h
theorem destutter'_is_chain' (a) : (l.destutter' R a).Chain' R := by
induction' l with b l hl generalizing a
· simp
rw [destutter']
split_ifs with h
· exact destutter'_is_chain R l h
· exact hl a
theorem destutter'_of_chain (h : l.Chain R a) : l.destutter' R a = a :: l := by
induction' l with b l hb generalizing a
· simp
obtain ⟨h, hc⟩ := chain_cons.mp h
rw [l.destutter'_cons_pos h, hb hc]
@[simp]
theorem destutter'_eq_self_iff (a) : l.destutter' R a = a :: l ↔ l.Chain R a :=
⟨fun h => by
suffices Chain' R (a::l) by
assumption
rw [← h]
exact l.destutter'_is_chain' R a, destutter'_of_chain _ _⟩
theorem destutter'_ne_nil : l.destutter' R a ≠ [] :=
ne_nil_of_mem <| l.mem_destutter' R a
@[simp]
theorem destutter_nil : ([] : List α).destutter R = [] :=
rfl
theorem destutter_cons' : (a :: l).destutter R = destutter' R a l :=
rfl
theorem destutter_cons_cons :
(a :: b :: l).destutter R = if R a b then a :: destutter' R b l else destutter' R a l :=
rfl
@[simp]
theorem destutter_singleton : destutter R [a] = [a] :=
rfl
@[simp]
theorem destutter_pair : destutter R [a, b] = if R a b then [a, b] else [a] :=
destutter_cons_cons _ R
theorem destutter_sublist : ∀ l : List α, l.destutter R <+ l
| [] => Sublist.slnil
| h :: l => l.destutter'_sublist R h
theorem destutter_is_chain' : ∀ l : List α, (l.destutter R).Chain' R
| [] => List.chain'_nil
| h :: l => l.destutter'_is_chain' R h
theorem destutter_of_chain' : ∀ l : List α, l.Chain' R → l.destutter R = l
| [], _ => rfl
| _ :: l, h => l.destutter'_of_chain _ h
@[simp]
theorem destutter_eq_self_iff : ∀ l : List α, l.destutter R = l ↔ l.Chain' R
| [] => by simp
| a :: l => l.destutter'_eq_self_iff R a
theorem destutter_idem : (l.destutter R).destutter R = l.destutter R :=
destutter_of_chain' R _ <| l.destutter_is_chain' R
@[simp]
theorem destutter_eq_nil : ∀ {l : List α}, destutter R l = [] ↔ l = []
| [] => Iff.rfl
| _ :: l => ⟨fun h => absurd h <| l.destutter'_ne_nil R, fun h => nomatch h⟩
end List
|
Data\List\DropRight.lean | /-
Copyright (c) 2022 Yakov Pechersky. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky
-/
import Mathlib.Data.List.Infix
/-!
# Dropping or taking from lists on the right
Taking or removing element from the tail end of a list
## Main definitions
- `rdrop n`: drop `n : ℕ` elements from the tail
- `rtake n`: take `n : ℕ` elements from the tail
- `rdropWhile p`: remove all the elements from the tail of a list until it finds the first element
for which `p : α → Bool` returns false. This element and everything before is returned.
- `rtakeWhile p`: Returns the longest terminal segment of a list for which `p : α → Bool` returns
true.
## Implementation detail
The two predicate-based methods operate by performing the regular "from-left" operation on
`List.reverse`, followed by another `List.reverse`, so they are not the most performant.
The other two rely on `List.length l` so they still traverse the list twice. One could construct
another function that takes a `L : ℕ` and use `L - n`. Under a proof condition that
`L = l.length`, the function would do the right thing.
-/
-- Make sure we don't import algebra
assert_not_exists Monoid
variable {α : Type*} (p : α → Bool) (l : List α) (n : ℕ)
namespace List
/-- Drop `n` elements from the tail end of a list. -/
def rdrop : List α :=
l.take (l.length - n)
@[simp]
theorem rdrop_nil : rdrop ([] : List α) n = [] := by simp [rdrop]
@[simp]
theorem rdrop_zero : rdrop l 0 = l := by simp [rdrop]
theorem rdrop_eq_reverse_drop_reverse : l.rdrop n = reverse (l.reverse.drop n) := by
rw [rdrop]
induction' l using List.reverseRecOn with xs x IH generalizing n
· simp
· cases n
· simp [take_append]
· simp [take_append_eq_append_take, IH]
@[simp]
theorem rdrop_concat_succ (x : α) : rdrop (l ++ [x]) (n + 1) = rdrop l n := by
simp [rdrop_eq_reverse_drop_reverse]
/-- Take `n` elements from the tail end of a list. -/
def rtake : List α :=
l.drop (l.length - n)
@[simp]
theorem rtake_nil : rtake ([] : List α) n = [] := by simp [rtake]
@[simp]
theorem rtake_zero : rtake l 0 = [] := by simp [rtake]
theorem rtake_eq_reverse_take_reverse : l.rtake n = reverse (l.reverse.take n) := by
rw [rtake]
induction' l using List.reverseRecOn with xs x IH generalizing n
· simp
· cases n
· exact drop_length _
· simp [drop_append_eq_append_drop, IH]
@[simp]
theorem rtake_concat_succ (x : α) : rtake (l ++ [x]) (n + 1) = rtake l n ++ [x] := by
simp [rtake_eq_reverse_take_reverse]
/-- Drop elements from the tail end of a list that satisfy `p : α → Bool`.
Implemented naively via `List.reverse` -/
def rdropWhile : List α :=
reverse (l.reverse.dropWhile p)
@[simp]
theorem rdropWhile_nil : rdropWhile p ([] : List α) = [] := by simp [rdropWhile, dropWhile]
theorem rdropWhile_concat (x : α) :
rdropWhile p (l ++ [x]) = if p x then rdropWhile p l else l ++ [x] := by
simp only [rdropWhile, dropWhile, reverse_append, reverse_singleton, singleton_append]
split_ifs with h <;> simp [h]
@[simp]
theorem rdropWhile_concat_pos (x : α) (h : p x) : rdropWhile p (l ++ [x]) = rdropWhile p l := by
rw [rdropWhile_concat, if_pos h]
@[simp]
theorem rdropWhile_concat_neg (x : α) (h : ¬p x) : rdropWhile p (l ++ [x]) = l ++ [x] := by
rw [rdropWhile_concat, if_neg h]
theorem rdropWhile_singleton (x : α) : rdropWhile p [x] = if p x then [] else [x] := by
rw [← nil_append [x], rdropWhile_concat, rdropWhile_nil]
theorem rdropWhile_last_not (hl : l.rdropWhile p ≠ []) : ¬p ((rdropWhile p l).getLast hl) := by
simp_rw [rdropWhile]
rw [getLast_reverse, head_dropWhile_not p]
simp
theorem rdropWhile_prefix : l.rdropWhile p <+: l := by
rw [← reverse_suffix, rdropWhile, reverse_reverse]
exact dropWhile_suffix _
variable {p} {l}
@[simp]
theorem rdropWhile_eq_nil_iff : rdropWhile p l = [] ↔ ∀ x ∈ l, p x := by simp [rdropWhile]
-- it is in this file because it requires `List.Infix`
@[simp]
theorem dropWhile_eq_self_iff : dropWhile p l = l ↔ ∀ hl : 0 < l.length, ¬p (l.get ⟨0, hl⟩) := by
cases' l with hd tl
· simp only [dropWhile, true_iff]
intro h
by_contra
rwa [length_nil, lt_self_iff_false] at h
· rw [dropWhile]
refine ⟨fun h => ?_, fun h => ?_⟩
· intro _ H
rw [get] at H
refine (cons_ne_self hd tl) (Sublist.antisymm ?_ (sublist_cons_self _ _))
rw [← h]
simp only [H]
exact List.IsSuffix.sublist (dropWhile_suffix p)
· have := h (by simp only [length, Nat.succ_pos])
rw [get] at this
simp_rw [this]
/- porting note: This proof is longer than it used to be because `simp` refuses to rewrite
the `l ≠ []` condition if `hl` is not `intro`'d yet -/
@[simp]
theorem rdropWhile_eq_self_iff : rdropWhile p l = l ↔ ∀ hl : l ≠ [], ¬p (l.getLast hl) := by
simp only [rdropWhile, reverse_eq_iff, dropWhile_eq_self_iff, getLast_eq_getElem]
refine ⟨fun h hl => ?_, fun h hl => ?_⟩
· rw [← length_pos, ← length_reverse] at hl
have := h hl
rwa [get_reverse'] at this
· rw [length_reverse, length_pos] at hl
have := h hl
rwa [get_reverse']
variable (p) (l)
theorem dropWhile_idempotent : dropWhile p (dropWhile p l) = dropWhile p l := by
simp only [dropWhile_eq_self_iff]
exact fun h => dropWhile_nthLe_zero_not p l h
theorem rdropWhile_idempotent : rdropWhile p (rdropWhile p l) = rdropWhile p l :=
rdropWhile_eq_self_iff.mpr (rdropWhile_last_not _ _)
/-- Take elements from the tail end of a list that satisfy `p : α → Bool`.
Implemented naively via `List.reverse` -/
def rtakeWhile : List α :=
reverse (l.reverse.takeWhile p)
@[simp]
theorem rtakeWhile_nil : rtakeWhile p ([] : List α) = [] := by simp [rtakeWhile, takeWhile]
theorem rtakeWhile_concat (x : α) :
rtakeWhile p (l ++ [x]) = if p x then rtakeWhile p l ++ [x] else [] := by
simp only [rtakeWhile, takeWhile, reverse_append, reverse_singleton, singleton_append]
split_ifs with h <;> simp [h]
@[simp]
theorem rtakeWhile_concat_pos (x : α) (h : p x) :
rtakeWhile p (l ++ [x]) = rtakeWhile p l ++ [x] := by rw [rtakeWhile_concat, if_pos h]
@[simp]
theorem rtakeWhile_concat_neg (x : α) (h : ¬p x) : rtakeWhile p (l ++ [x]) = [] := by
rw [rtakeWhile_concat, if_neg h]
theorem rtakeWhile_suffix : l.rtakeWhile p <:+ l := by
rw [← reverse_prefix, rtakeWhile, reverse_reverse]
exact takeWhile_prefix _
variable {p} {l}
@[simp]
theorem rtakeWhile_eq_self_iff : rtakeWhile p l = l ↔ ∀ x ∈ l, p x := by
simp [rtakeWhile, reverse_eq_iff]
-- Porting note: This needed a lot of rewriting.
@[simp]
theorem rtakeWhile_eq_nil_iff : rtakeWhile p l = [] ↔ ∀ hl : l ≠ [], ¬p (l.getLast hl) := by
induction' l using List.reverseRecOn with l a
· simp only [rtakeWhile, takeWhile, reverse_nil, true_iff]
intro f; contradiction
· simp only [rtakeWhile, reverse_append, takeWhile, ne_eq, not_false_eq_true,
getLast_append_of_ne_nil, getLast_singleton]
refine ⟨fun h => ?_ , fun h => ?_⟩
· split at h <;> simp_all
· simp [h]
theorem mem_rtakeWhile_imp {x : α} (hx : x ∈ rtakeWhile p l) : p x := by
rw [rtakeWhile, mem_reverse] at hx
exact mem_takeWhile_imp hx
theorem rtakeWhile_idempotent (p : α → Bool) (l : List α) :
rtakeWhile p (rtakeWhile p l) = rtakeWhile p l :=
rtakeWhile_eq_self_iff.mpr fun _ => mem_rtakeWhile_imp
lemma rdrop_add (i j : ℕ) : (l.rdrop i).rdrop j = l.rdrop (i + j) := by
simp_rw [rdrop_eq_reverse_drop_reverse, reverse_reverse, drop_drop, Nat.add_comm]
@[simp]
lemma rdrop_append_length {l₁ l₂ : List α} :
List.rdrop (l₁ ++ l₂) (List.length l₂) = l₁ := by
rw [rdrop_eq_reverse_drop_reverse, ← length_reverse l₂,
reverse_append, drop_left, reverse_reverse]
lemma rdrop_append_of_le_length {l₁ l₂ : List α} (k : ℕ) :
k ≤ length l₂ → List.rdrop (l₁ ++ l₂) k = l₁ ++ List.rdrop l₂ k := by
intro hk
rw [← length_reverse] at hk
rw [rdrop_eq_reverse_drop_reverse, reverse_append, drop_append_of_le_length hk,
reverse_append, reverse_reverse, ← rdrop_eq_reverse_drop_reverse]
@[simp]
lemma rdrop_append_length_add {l₁ l₂ : List α} (k : ℕ) :
List.rdrop (l₁ ++ l₂) (length l₂ + k) = List.rdrop l₁ k := by
rw [← rdrop_add, rdrop_append_length]
end List
|
Data\List\Duplicate.lean | /-
Copyright (c) 2021 Yakov Pechersky. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky, Chris Hughes
-/
import Mathlib.Data.List.Nodup
/-!
# List duplicates
## Main definitions
* `List.Duplicate x l : Prop` is an inductive property that holds when `x` is a duplicate in `l`
## Implementation details
In this file, `x ∈+ l` notation is shorthand for `List.Duplicate x l`.
-/
variable {α : Type*}
namespace List
/-- Property that an element `x : α` of `l : List α` can be found in the list more than once. -/
inductive Duplicate (x : α) : List α → Prop
| cons_mem {l : List α} : x ∈ l → Duplicate x (x :: l)
| cons_duplicate {y : α} {l : List α} : Duplicate x l → Duplicate x (y :: l)
local infixl:50 " ∈+ " => List.Duplicate
variable {l : List α} {x : α}
theorem Mem.duplicate_cons_self (h : x ∈ l) : x ∈+ x :: l :=
Duplicate.cons_mem h
theorem Duplicate.duplicate_cons (h : x ∈+ l) (y : α) : x ∈+ y :: l :=
Duplicate.cons_duplicate h
theorem Duplicate.mem (h : x ∈+ l) : x ∈ l := by
induction' h with l' _ y l' _ hm
· exact mem_cons_self _ _
· exact mem_cons_of_mem _ hm
theorem Duplicate.mem_cons_self (h : x ∈+ x :: l) : x ∈ l := by
cases' h with _ h _ _ h
· exact h
· exact h.mem
@[simp]
theorem duplicate_cons_self_iff : x ∈+ x :: l ↔ x ∈ l :=
⟨Duplicate.mem_cons_self, Mem.duplicate_cons_self⟩
theorem Duplicate.ne_nil (h : x ∈+ l) : l ≠ [] := fun H => (mem_nil_iff x).mp (H ▸ h.mem)
@[simp]
theorem not_duplicate_nil (x : α) : ¬x ∈+ [] := fun H => H.ne_nil rfl
theorem Duplicate.ne_singleton (h : x ∈+ l) (y : α) : l ≠ [y] := by
induction' h with l' h z l' h _
· simp [ne_nil_of_mem h]
· simp [ne_nil_of_mem h.mem]
@[simp]
theorem not_duplicate_singleton (x y : α) : ¬x ∈+ [y] := fun H => H.ne_singleton _ rfl
theorem Duplicate.elim_nil (h : x ∈+ []) : False :=
not_duplicate_nil x h
theorem Duplicate.elim_singleton {y : α} (h : x ∈+ [y]) : False :=
not_duplicate_singleton x y h
theorem duplicate_cons_iff {y : α} : x ∈+ y :: l ↔ y = x ∧ x ∈ l ∨ x ∈+ l := by
refine ⟨fun h => ?_, fun h => ?_⟩
· cases' h with _ hm _ _ hm
· exact Or.inl ⟨rfl, hm⟩
· exact Or.inr hm
· rcases h with (⟨rfl | h⟩ | h)
· simpa
· exact h.cons_duplicate
theorem Duplicate.of_duplicate_cons {y : α} (h : x ∈+ y :: l) (hx : x ≠ y) : x ∈+ l := by
simpa [duplicate_cons_iff, hx.symm] using h
theorem duplicate_cons_iff_of_ne {y : α} (hne : x ≠ y) : x ∈+ y :: l ↔ x ∈+ l := by
simp [duplicate_cons_iff, hne.symm]
theorem Duplicate.mono_sublist {l' : List α} (hx : x ∈+ l) (h : l <+ l') : x ∈+ l' := by
induction' h with l₁ l₂ y _ IH l₁ l₂ y h IH
· exact hx
· exact (IH hx).duplicate_cons _
· rw [duplicate_cons_iff] at hx ⊢
rcases hx with (⟨rfl, hx⟩ | hx)
· simp [h.subset hx]
· simp [IH hx]
/-- The contrapositive of `List.nodup_iff_sublist`. -/
theorem duplicate_iff_sublist : x ∈+ l ↔ [x, x] <+ l := by
induction' l with y l IH
· simp
· by_cases hx : x = y
· simp [hx, cons_sublist_cons, singleton_sublist]
· rw [duplicate_cons_iff_of_ne hx, IH]
refine ⟨sublist_cons_of_sublist y, fun h => ?_⟩
cases h
· assumption
· contradiction
theorem nodup_iff_forall_not_duplicate : Nodup l ↔ ∀ x : α, ¬x ∈+ l := by
simp_rw [nodup_iff_sublist, duplicate_iff_sublist]
theorem exists_duplicate_iff_not_nodup : (∃ x : α, x ∈+ l) ↔ ¬Nodup l := by
simp [nodup_iff_forall_not_duplicate]
theorem Duplicate.not_nodup (h : x ∈+ l) : ¬Nodup l := fun H =>
nodup_iff_forall_not_duplicate.mp H _ h
theorem duplicate_iff_two_le_count [DecidableEq α] : x ∈+ l ↔ 2 ≤ count x l := by
simp [replicate_succ, duplicate_iff_sublist, le_count_iff_replicate_sublist]
instance decidableDuplicate [DecidableEq α] (x : α) : ∀ l : List α, Decidable (x ∈+ l)
| [] => isFalse (not_duplicate_nil x)
| y :: l =>
match decidableDuplicate x l with
| isTrue h => isTrue (h.duplicate_cons y)
| isFalse h =>
if hx : y = x ∧ x ∈ l then isTrue (hx.left.symm ▸ List.Mem.duplicate_cons_self hx.right)
else isFalse (by simpa [duplicate_cons_iff, h] using hx)
end List
|
Data\List\Enum.lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Yakov Pechersky, Eric Wieser
-/
import Batteries.Tactic.Alias
import Mathlib.Tactic.TypeStar
import Mathlib.Data.Nat.Notation
/-!
# Properties of `List.enum`
-/
namespace List
variable {α β : Type*}
theorem get?_enumFrom (n) (l : List α) (m) :
get? (enumFrom n l) m = (get? l m).map fun a => (n + m, a) := by
simp
@[deprecated (since := "2024-04-06")] alias enumFrom_get? := get?_enumFrom
theorem get?_enum (l : List α) (n) : get? (enum l) n = (get? l n).map fun a => (n, a) := by
simp
@[deprecated (since := "2024-04-06")] alias enum_get? := get?_enum
theorem get_enumFrom (l : List α) (n) (i : Fin (l.enumFrom n).length) :
(l.enumFrom n).get i = (n + i, l.get (i.cast enumFrom_length)) := by
simp
theorem get_enum (l : List α) (i : Fin l.enum.length) :
l.enum.get i = (i.1, l.get (i.cast enum_length)) := by
simp
theorem mk_add_mem_enumFrom_iff_get? {n i : ℕ} {x : α} {l : List α} :
(n + i, x) ∈ enumFrom n l ↔ l.get? i = x := by
simp [mem_iff_get?]
theorem mk_mem_enumFrom_iff_le_and_get?_sub {n i : ℕ} {x : α} {l : List α} :
(i, x) ∈ enumFrom n l ↔ n ≤ i ∧ l.get? (i - n) = x := by
if h : n ≤ i then
rcases Nat.exists_eq_add_of_le h with ⟨i, rfl⟩
simp [mk_add_mem_enumFrom_iff_get?, Nat.add_sub_cancel_left]
else
have : ∀ k, n + k ≠ i := by rintro k rfl; simp at h
simp [h, mem_iff_get?, this]
theorem mk_mem_enum_iff_get? {i : ℕ} {x : α} {l : List α} : (i, x) ∈ enum l ↔ l.get? i = x := by
simp [enum, mk_mem_enumFrom_iff_le_and_get?_sub]
theorem mem_enum_iff_get? {x : ℕ × α} {l : List α} : x ∈ enum l ↔ l.get? x.1 = x.2 :=
mk_mem_enum_iff_get?
end List
|
Data\List\FinRange.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kenny Lau, Scott Morrison, Alex Keizer
-/
import Mathlib.Data.List.OfFn
import Mathlib.Data.List.Range
/-!
# Lists of elements of `Fin n`
This file develops some results on `finRange n`.
-/
assert_not_exists Monoid
universe u
namespace List
variable {α : Type u}
@[simp]
theorem map_coe_finRange (n : ℕ) : ((finRange n) : List (Fin n)).map (Fin.val) = List.range n := by
simp_rw [finRange, map_pmap, pmap_eq_map]
exact List.map_id _
theorem finRange_succ_eq_map (n : ℕ) : finRange n.succ = 0 :: (finRange n).map Fin.succ := by
apply map_injective_iff.mpr Fin.val_injective
rw [map_cons, map_coe_finRange, range_succ_eq_map, Fin.val_zero, ← map_coe_finRange, map_map,
map_map]
simp only [Function.comp, Fin.val_succ]
theorem finRange_succ (n : ℕ) :
finRange n.succ = (finRange n |>.map Fin.castSucc |>.concat (.last _)) := by
apply map_injective_iff.mpr Fin.val_injective
simp [range_succ, Function.comp_def]
-- Porting note: `map_nth_le` moved to `List.finRange_map_get` in Data.List.Range
theorem ofFn_eq_pmap {n} {f : Fin n → α} :
ofFn f = pmap (fun i hi => f ⟨i, hi⟩) (range n) fun _ => mem_range.1 := by
rw [pmap_eq_map_attach]
exact ext_getElem (by simp) fun i hi1 hi2 => by simp [getElem_ofFn f i hi1]
theorem ofFn_id (n) : ofFn id = finRange n :=
ofFn_eq_pmap
theorem ofFn_eq_map {n} {f : Fin n → α} : ofFn f = (finRange n).map f := by
rw [← ofFn_id, map_ofFn, Function.comp_id]
theorem nodup_ofFn_ofInjective {n} {f : Fin n → α} (hf : Function.Injective f) :
Nodup (ofFn f) := by
rw [ofFn_eq_pmap]
exact (nodup_range n).pmap fun _ _ _ _ H => Fin.val_eq_of_eq <| hf H
theorem nodup_ofFn {n} {f : Fin n → α} : Nodup (ofFn f) ↔ Function.Injective f := by
refine ⟨?_, nodup_ofFn_ofInjective⟩
refine Fin.consInduction ?_ (fun x₀ xs ih => ?_) f
· intro _
exact Function.injective_of_subsingleton _
· intro h
rw [Fin.cons_injective_iff]
simp_rw [ofFn_succ, Fin.cons_succ, nodup_cons, Fin.cons_zero, mem_ofFn] at h
exact h.imp_right ih
end List
open List
theorem Equiv.Perm.map_finRange_perm {n : ℕ} (σ : Equiv.Perm (Fin n)) :
map σ (finRange n) ~ finRange n := by
rw [perm_ext_iff_of_nodup ((nodup_finRange n).map σ.injective) <| nodup_finRange n]
simpa [mem_map, mem_finRange, true_and_iff, iff_true_iff] using σ.surjective
/-- The list obtained from a permutation of a tuple `f` is permutation equivalent to
the list obtained from `f`. -/
theorem Equiv.Perm.ofFn_comp_perm {n : ℕ} {α : Type u} (σ : Equiv.Perm (Fin n)) (f : Fin n → α) :
ofFn (f ∘ σ) ~ ofFn f := by
rw [ofFn_eq_map, ofFn_eq_map, ← map_map]
exact σ.map_finRange_perm.map f
|
Data\List\Forall2.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johannes Hölzl
-/
import Mathlib.Data.List.Basic
/-!
# Double universal quantification on a list
This file provides an API for `List.Forall₂` (definition in `Data.List.Defs`).
`Forall₂ R l₁ l₂` means that `l₁` and `l₂` have the same length, and whenever `a` is the nth element
of `l₁`, and `b` is the nth element of `l₂`, then `R a b` is satisfied.
-/
open Nat Function
namespace List
variable {α β γ δ : Type*} {R S : α → β → Prop} {P : γ → δ → Prop} {Rₐ : α → α → Prop}
open Relator
mk_iff_of_inductive_prop List.Forall₂ List.forall₂_iff
theorem Forall₂.imp (H : ∀ a b, R a b → S a b) {l₁ l₂} (h : Forall₂ R l₁ l₂) : Forall₂ S l₁ l₂ := by
induction h <;> constructor <;> solve_by_elim
theorem Forall₂.mp {Q : α → β → Prop} (h : ∀ a b, Q a b → R a b → S a b) :
∀ {l₁ l₂}, Forall₂ Q l₁ l₂ → Forall₂ R l₁ l₂ → Forall₂ S l₁ l₂
| [], [], Forall₂.nil, Forall₂.nil => Forall₂.nil
| a :: _, b :: _, Forall₂.cons hr hrs, Forall₂.cons hq hqs =>
Forall₂.cons (h a b hr hq) (Forall₂.mp h hrs hqs)
theorem Forall₂.flip : ∀ {a b}, Forall₂ (flip R) b a → Forall₂ R a b
| _, _, Forall₂.nil => Forall₂.nil
| _ :: _, _ :: _, Forall₂.cons h₁ h₂ => Forall₂.cons h₁ h₂.flip
@[simp]
theorem forall₂_same : ∀ {l : List α}, Forall₂ Rₐ l l ↔ ∀ x ∈ l, Rₐ x x
| [] => by simp
| a :: l => by simp [@forall₂_same l]
theorem forall₂_refl [IsRefl α Rₐ] (l : List α) : Forall₂ Rₐ l l :=
forall₂_same.2 fun _ _ => refl _
@[simp]
theorem forall₂_eq_eq_eq : Forall₂ ((· = ·) : α → α → Prop) = Eq := by
funext a b; apply propext
constructor
· intro h
induction h
· rfl
simp only [*]
· rintro rfl
exact forall₂_refl _
@[simp]
theorem forall₂_nil_left_iff {l} : Forall₂ R nil l ↔ l = nil :=
⟨fun H => by cases H; rfl, by rintro rfl; exact Forall₂.nil⟩
@[simp]
theorem forall₂_nil_right_iff {l} : Forall₂ R l nil ↔ l = nil :=
⟨fun H => by cases H; rfl, by rintro rfl; exact Forall₂.nil⟩
theorem forall₂_cons_left_iff {a l u} :
Forall₂ R (a :: l) u ↔ ∃ b u', R a b ∧ Forall₂ R l u' ∧ u = b :: u' :=
Iff.intro
(fun h =>
match u, h with
| b :: u', Forall₂.cons h₁ h₂ => ⟨b, u', h₁, h₂, rfl⟩)
fun h =>
match u, h with
| _, ⟨_, _, h₁, h₂, rfl⟩ => Forall₂.cons h₁ h₂
theorem forall₂_cons_right_iff {b l u} :
Forall₂ R u (b :: l) ↔ ∃ a u', R a b ∧ Forall₂ R u' l ∧ u = a :: u' :=
Iff.intro
(fun h =>
match u, h with
| b :: u', Forall₂.cons h₁ h₂ => ⟨b, u', h₁, h₂, rfl⟩)
fun h =>
match u, h with
| _, ⟨_, _, h₁, h₂, rfl⟩ => Forall₂.cons h₁ h₂
theorem forall₂_and_left {p : α → Prop} :
∀ l u, Forall₂ (fun a b => p a ∧ R a b) l u ↔ (∀ a ∈ l, p a) ∧ Forall₂ R l u
| [], u => by
simp only [forall₂_nil_left_iff, forall_prop_of_false (not_mem_nil _), imp_true_iff,
true_and_iff]
| a :: l, u => by
simp only [forall₂_and_left l, forall₂_cons_left_iff, forall_mem_cons, and_assoc,
@and_comm _ (p a), @and_left_comm _ (p a), exists_and_left]
simp only [and_comm, and_assoc, and_left_comm, ← exists_and_right]
@[simp]
theorem forall₂_map_left_iff {f : γ → α} :
∀ {l u}, Forall₂ R (map f l) u ↔ Forall₂ (fun c b => R (f c) b) l u
| [], _ => by simp only [map, forall₂_nil_left_iff]
| a :: l, _ => by simp only [map, forall₂_cons_left_iff, forall₂_map_left_iff]
@[simp]
theorem forall₂_map_right_iff {f : γ → β} :
∀ {l u}, Forall₂ R l (map f u) ↔ Forall₂ (fun a c => R a (f c)) l u
| _, [] => by simp only [map, forall₂_nil_right_iff]
| _, b :: u => by simp only [map, forall₂_cons_right_iff, forall₂_map_right_iff]
theorem left_unique_forall₂' (hr : LeftUnique R) : ∀ {a b c}, Forall₂ R a c → Forall₂ R b c → a = b
| _, _, _, Forall₂.nil, Forall₂.nil => rfl
| _, _, _, Forall₂.cons ha₀ h₀, Forall₂.cons ha₁ h₁ =>
hr ha₀ ha₁ ▸ left_unique_forall₂' hr h₀ h₁ ▸ rfl
theorem _root_.Relator.LeftUnique.forall₂ (hr : LeftUnique R) : LeftUnique (Forall₂ R) :=
@left_unique_forall₂' _ _ _ hr
theorem right_unique_forall₂' (hr : RightUnique R) :
∀ {a b c}, Forall₂ R a b → Forall₂ R a c → b = c
| _, _, _, Forall₂.nil, Forall₂.nil => rfl
| _, _, _, Forall₂.cons ha₀ h₀, Forall₂.cons ha₁ h₁ =>
hr ha₀ ha₁ ▸ right_unique_forall₂' hr h₀ h₁ ▸ rfl
theorem _root_.Relator.RightUnique.forall₂ (hr : RightUnique R) : RightUnique (Forall₂ R) :=
@right_unique_forall₂' _ _ _ hr
theorem _root_.Relator.BiUnique.forall₂ (hr : BiUnique R) : BiUnique (Forall₂ R) :=
⟨hr.left.forall₂, hr.right.forall₂⟩
theorem Forall₂.length_eq : ∀ {l₁ l₂}, Forall₂ R l₁ l₂ → length l₁ = length l₂
| _, _, Forall₂.nil => rfl
| _, _, Forall₂.cons _ h₂ => congr_arg succ (Forall₂.length_eq h₂)
theorem Forall₂.get :
∀ {x : List α} {y : List β}, Forall₂ R x y →
∀ ⦃i : ℕ⦄ (hx : i < x.length) (hy : i < y.length), R (x.get ⟨i, hx⟩) (y.get ⟨i, hy⟩)
| _, _, Forall₂.cons ha _, 0, _, _ => ha
| _, _, Forall₂.cons _ hl, succ _, _, _ => hl.get _ _
set_option linter.deprecated false in
@[deprecated (since := "2024-05-05")] theorem Forall₂.nthLe {x y} (h : Forall₂ R x y) ⦃i : ℕ⦄
(hx : i < x.length) (hy : i < y.length) : R (x.nthLe i hx) (y.nthLe i hy) := h.get hx hy
theorem forall₂_of_length_eq_of_get :
∀ {x : List α} {y : List β},
x.length = y.length → (∀ i h₁ h₂, R (x.get ⟨i, h₁⟩) (y.get ⟨i, h₂⟩)) → Forall₂ R x y
| [], [], _, _ => Forall₂.nil
| _ :: _, _ :: _, hl, h =>
Forall₂.cons (h 0 (Nat.zero_lt_succ _) (Nat.zero_lt_succ _))
(forall₂_of_length_eq_of_get (succ.inj hl) fun i h₁ h₂ =>
h i.succ (succ_lt_succ h₁) (succ_lt_succ h₂))
set_option linter.deprecated false in
@[deprecated (since := "2024-05-05")] theorem forall₂_of_length_eq_of_nthLe {x y}
(H : x.length = y.length) (H' : ∀ i h₁ h₂, R (x.nthLe i h₁) (y.nthLe i h₂)) :
Forall₂ R x y := forall₂_of_length_eq_of_get H H'
theorem forall₂_iff_get {l₁ : List α} {l₂ : List β} :
Forall₂ R l₁ l₂ ↔ l₁.length = l₂.length ∧ ∀ i h₁ h₂, R (l₁.get ⟨i, h₁⟩) (l₂.get ⟨i, h₂⟩) :=
⟨fun h => ⟨h.length_eq, h.get⟩, fun h => forall₂_of_length_eq_of_get h.1 h.2⟩
set_option linter.deprecated false in
@[deprecated (since := "2024-05-05")] theorem forall₂_iff_nthLe {l₁ : List α} {l₂ : List β} :
Forall₂ R l₁ l₂ ↔ l₁.length = l₂.length ∧ ∀ i h₁ h₂, R (l₁.nthLe i h₁) (l₂.nthLe i h₂) :=
forall₂_iff_get
theorem forall₂_zip : ∀ {l₁ l₂}, Forall₂ R l₁ l₂ → ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b
| _, _, Forall₂.cons h₁ h₂, x, y, hx => by
rw [zip, zipWith, mem_cons] at hx
match hx with
| Or.inl rfl => exact h₁
| Or.inr h₃ => exact forall₂_zip h₂ h₃
theorem forall₂_iff_zip {l₁ l₂} :
Forall₂ R l₁ l₂ ↔ length l₁ = length l₂ ∧ ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b :=
⟨fun h => ⟨Forall₂.length_eq h, @forall₂_zip _ _ _ _ _ h⟩, fun h => by
cases' h with h₁ h₂
induction' l₁ with a l₁ IH generalizing l₂
· cases length_eq_zero.1 h₁.symm
constructor
· cases' l₂ with b l₂
· simp at h₁
· simp only [length_cons, succ.injEq] at h₁
exact Forall₂.cons (h₂ <| by simp [zip])
(IH h₁ fun h => h₂ <| by
simp only [zip, zipWith, find?, mem_cons, Prod.mk.injEq]; right
simpa [zip] using h)⟩
theorem forall₂_take : ∀ (n) {l₁ l₂}, Forall₂ R l₁ l₂ → Forall₂ R (take n l₁) (take n l₂)
| 0, _, _, _ => by simp only [Forall₂.nil, take]
| _ + 1, _, _, Forall₂.nil => by simp only [Forall₂.nil, take]
| n + 1, _, _, Forall₂.cons h₁ h₂ => by simp [And.intro h₁ h₂, forall₂_take n]
theorem forall₂_drop : ∀ (n) {l₁ l₂}, Forall₂ R l₁ l₂ → Forall₂ R (drop n l₁) (drop n l₂)
| 0, _, _, h => by simp only [drop, h]
| _ + 1, _, _, Forall₂.nil => by simp only [Forall₂.nil, drop]
| n + 1, _, _, Forall₂.cons h₁ h₂ => by simp [And.intro h₁ h₂, forall₂_drop n]
theorem forall₂_take_append (l : List α) (l₁ : List β) (l₂ : List β) (h : Forall₂ R l (l₁ ++ l₂)) :
Forall₂ R (List.take (length l₁) l) l₁ := by
have h' : Forall₂ R (take (length l₁) l) (take (length l₁) (l₁ ++ l₂)) :=
forall₂_take (length l₁) h
rwa [take_left] at h'
theorem forall₂_drop_append (l : List α) (l₁ : List β) (l₂ : List β) (h : Forall₂ R l (l₁ ++ l₂)) :
Forall₂ R (List.drop (length l₁) l) l₂ := by
have h' : Forall₂ R (drop (length l₁) l) (drop (length l₁) (l₁ ++ l₂)) :=
forall₂_drop (length l₁) h
rwa [drop_left] at h'
theorem rel_mem (hr : BiUnique R) : (R ⇒ Forall₂ R ⇒ Iff) (· ∈ ·) (· ∈ ·)
| a, b, _, [], [], Forall₂.nil => by simp only [not_mem_nil]
| a, b, h, a' :: as, b' :: bs, Forall₂.cons h₁ h₂ => by
simp only [mem_cons]
exact rel_or (rel_eq hr h h₁) (rel_mem hr h h₂)
theorem rel_map : ((R ⇒ P) ⇒ Forall₂ R ⇒ Forall₂ P) map map
| _, _, _, [], [], Forall₂.nil => Forall₂.nil
| _, _, h, _ :: _, _ :: _, Forall₂.cons h₁ h₂ => Forall₂.cons (h h₁) (rel_map (@h) h₂)
theorem rel_append : (Forall₂ R ⇒ Forall₂ R ⇒ Forall₂ R) (· ++ ·) (· ++ ·)
| [], [], _, _, _, hl => hl
| _, _, Forall₂.cons h₁ h₂, _, _, hl => Forall₂.cons h₁ (rel_append h₂ hl)
theorem rel_reverse : (Forall₂ R ⇒ Forall₂ R) reverse reverse
| [], [], Forall₂.nil => Forall₂.nil
| _, _, Forall₂.cons h₁ h₂ => by
simp only [reverse_cons]
exact rel_append (rel_reverse h₂) (Forall₂.cons h₁ Forall₂.nil)
@[simp]
theorem forall₂_reverse_iff {l₁ l₂} : Forall₂ R (reverse l₁) (reverse l₂) ↔ Forall₂ R l₁ l₂ :=
Iff.intro
(fun h => by
rw [← reverse_reverse l₁, ← reverse_reverse l₂]
exact rel_reverse h)
fun h => rel_reverse h
theorem rel_join : (Forall₂ (Forall₂ R) ⇒ Forall₂ R) join join
| [], [], Forall₂.nil => Forall₂.nil
| _, _, Forall₂.cons h₁ h₂ => rel_append h₁ (rel_join h₂)
theorem rel_bind : (Forall₂ R ⇒ (R ⇒ Forall₂ P) ⇒ Forall₂ P) List.bind List.bind :=
fun _ _ h₁ _ _ h₂ => rel_join (rel_map (@h₂) h₁)
theorem rel_foldl : ((P ⇒ R ⇒ P) ⇒ P ⇒ Forall₂ R ⇒ P) foldl foldl
| _, _, _, _, _, h, _, _, Forall₂.nil => h
| _, _, hfg, _, _, hxy, _, _, Forall₂.cons hab hs => rel_foldl (@hfg) (hfg hxy hab) hs
theorem rel_foldr : ((R ⇒ P ⇒ P) ⇒ P ⇒ Forall₂ R ⇒ P) foldr foldr
| _, _, _, _, _, h, _, _, Forall₂.nil => h
| _, _, hfg, _, _, hxy, _, _, Forall₂.cons hab hs => hfg hab (rel_foldr (@hfg) hxy hs)
theorem rel_filter {p : α → Bool} {q : β → Bool}
(hpq : (R ⇒ (· ↔ ·)) (fun x => p x) (fun x => q x)) :
(Forall₂ R ⇒ Forall₂ R) (filter p) (filter q)
| _, _, Forall₂.nil => Forall₂.nil
| a :: as, b :: bs, Forall₂.cons h₁ h₂ => by
dsimp [LiftFun] at hpq
by_cases h : p a
· have : q b := by rwa [← hpq h₁]
simp only [filter_cons_of_pos h, filter_cons_of_pos this, forall₂_cons, h₁, true_and_iff,
rel_filter hpq h₂]
· have : ¬q b := by rwa [← hpq h₁]
simp only [filter_cons_of_neg h, filter_cons_of_neg this, rel_filter hpq h₂]
theorem rel_filterMap : ((R ⇒ Option.Rel P) ⇒ Forall₂ R ⇒ Forall₂ P) filterMap filterMap
| _, _, _, _, _, Forall₂.nil => Forall₂.nil
| f, g, hfg, a :: as, b :: bs, Forall₂.cons h₁ h₂ => by
rw [filterMap_cons, filterMap_cons]
exact
match f a, g b, hfg h₁ with
| _, _, Option.Rel.none => rel_filterMap (@hfg) h₂
| _, _, Option.Rel.some h => Forall₂.cons h (rel_filterMap (@hfg) h₂)
/-- Given a relation `R`, `sublist_forall₂ r l₁ l₂` indicates that there is a sublist of `l₂` such
that `forall₂ r l₁ l₂`. -/
inductive SublistForall₂ (R : α → β → Prop) : List α → List β → Prop
| nil {l} : SublistForall₂ R [] l
| cons {a₁ a₂ l₁ l₂} : R a₁ a₂ → SublistForall₂ R l₁ l₂ → SublistForall₂ R (a₁ :: l₁) (a₂ :: l₂)
| cons_right {a l₁ l₂} : SublistForall₂ R l₁ l₂ → SublistForall₂ R l₁ (a :: l₂)
theorem sublistForall₂_iff {l₁ : List α} {l₂ : List β} :
SublistForall₂ R l₁ l₂ ↔ ∃ l, Forall₂ R l₁ l ∧ l <+ l₂ := by
constructor <;> intro h
· induction' h with _ a b l1 l2 rab _ ih b l1 l2 _ ih
· exact ⟨nil, Forall₂.nil, nil_sublist _⟩
· obtain ⟨l, hl1, hl2⟩ := ih
exact ⟨b :: l, Forall₂.cons rab hl1, hl2.cons_cons b⟩
· obtain ⟨l, hl1, hl2⟩ := ih
exact ⟨l, hl1, hl2.trans (Sublist.cons _ (Sublist.refl _))⟩
· obtain ⟨l, hl1, hl2⟩ := h
revert l₁
induction' hl2 with _ _ _ _ ih _ _ _ _ ih <;> intro l₁ hl1
· rw [forall₂_nil_right_iff.1 hl1]
exact SublistForall₂.nil
· exact SublistForall₂.cons_right (ih hl1)
· cases' hl1 with _ _ _ _ hr hl _
exact SublistForall₂.cons hr (ih hl)
instance SublistForall₂.is_refl [IsRefl α Rₐ] : IsRefl (List α) (SublistForall₂ Rₐ) :=
⟨fun l => sublistForall₂_iff.2 ⟨l, forall₂_refl l, Sublist.refl l⟩⟩
instance SublistForall₂.is_trans [IsTrans α Rₐ] : IsTrans (List α) (SublistForall₂ Rₐ) :=
⟨fun a b c => by
revert a b
induction' c with _ _ ih
· rintro _ _ h1 h2
cases h2
exact h1
· rintro a b h1 h2
cases' h2 with _ _ _ _ _ hbc tbc _ _ y1 btc
· cases h1
exact SublistForall₂.nil
· cases' h1 with _ _ _ _ _ hab tab _ _ _ atb
· exact SublistForall₂.nil
· exact SublistForall₂.cons (_root_.trans hab hbc) (ih _ _ tab tbc)
· exact SublistForall₂.cons_right (ih _ _ atb tbc)
· exact SublistForall₂.cons_right (ih _ _ h1 btc)⟩
theorem Sublist.sublistForall₂ {l₁ l₂ : List α} (h : l₁ <+ l₂) [IsRefl α Rₐ] :
SublistForall₂ Rₐ l₁ l₂ :=
sublistForall₂_iff.2 ⟨l₁, forall₂_refl l₁, h⟩
theorem tail_sublistForall₂_self [IsRefl α Rₐ] (l : List α) : SublistForall₂ Rₐ l.tail l :=
l.tail_sublist.sublistForall₂
end List
|
Data\List\GetD.lean | /-
Copyright (c) 2024 Bolton Bailey. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bolton Bailey, Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn,
Mario Carneiro
-/
import Mathlib.Data.List.Defs
import Mathlib.Data.Option.Basic
import Mathlib.Init.Data.List.Basic
import Mathlib.Util.AssertExists
/-! # getD and getI
This file provides theorems for working with the `getD` and `getI` functions. These are used to
access an element of a list by numerical index, with a default value as a fallback when the index
is out of range.
-/
-- Make sure we haven't imported `Data.Nat.Order.Basic`
assert_not_exists OrderedSub
namespace List
universe u v
variable {α : Type u} {β : Type v} (l : List α) (x : α) (xs : List α) (n : ℕ)
section getD
variable (d : α)
theorem getD_eq_get {n : ℕ} (hn : n < l.length) : l.getD n d = l.get ⟨n, hn⟩ := by
induction l generalizing n with
| nil => simp at hn
| cons head tail ih =>
cases n
· exact getD_cons_zero
· exact ih _
theorem getD_map {n : ℕ} (f : α → β) : (map f l).getD n (f d) = f (l.getD n d) := by simp
theorem getD_eq_default {n : ℕ} (hn : l.length ≤ n) : l.getD n d = d := by
induction l generalizing n with
| nil => exact getD_nil
| cons head tail ih =>
cases n
· simp at hn
· exact ih (Nat.le_of_succ_le_succ hn)
/-- An empty list can always be decidably checked for the presence of an element.
Not an instance because it would clash with `DecidableEq α`. -/
def decidableGetDNilNe (a : α) : DecidablePred fun i : ℕ => getD ([] : List α) i a ≠ a :=
fun _ => isFalse fun H => H getD_nil
@[simp]
theorem getElem?_getD_singleton_default_eq (n : ℕ) : [d][n]?.getD d = d := by cases n <;> simp
@[deprecated (since := "2024-06-12")]
alias getD_singleton_default_eq := getElem?_getD_singleton_default_eq
@[simp]
theorem getElem?_getD_replicate_default_eq (r n : ℕ) : (replicate r d)[n]?.getD d = d := by
induction r generalizing n with
| zero => simp
| succ n ih => simp at ih; cases n <;> simp [ih, replicate_succ]
@[deprecated (since := "2024-06-12")]
alias getD_replicate_default_eq := getElem?_getD_replicate_default_eq
set_option linter.deprecated false in
theorem getD_append (l l' : List α) (d : α) (n : ℕ) (h : n < l.length) :
(l ++ l').getD n d = l.getD n d := by
rw [getD_eq_get _ _ (Nat.lt_of_lt_of_le h (length_append _ _ ▸ Nat.le_add_right _ _)),
get_append _ h, getD_eq_get]
theorem getD_append_right (l l' : List α) (d : α) (n : ℕ) (h : l.length ≤ n) :
(l ++ l').getD n d = l'.getD (n - l.length) d := by
cases Nat.lt_or_ge n (l ++ l').length with
| inl h' =>
rw [getD_eq_get (l ++ l') d h', get_eq_getElem, getElem_append_right, getD_eq_get,
get_eq_getElem]
· rw [length_append] at h'
exact Nat.sub_lt_left_of_lt_add h h'
· exact Nat.not_lt_of_le h
| inr h' =>
rw [getD_eq_default _ _ h', getD_eq_default]
rwa [Nat.le_sub_iff_add_le' h, ← length_append]
theorem getD_eq_getD_get? (n : ℕ) : l.getD n d = (l.get? n).getD d := by
cases Nat.lt_or_ge n l.length with
| inl h => rw [getD_eq_get _ _ h, get?_eq_get h, Option.getD_some]
| inr h => rw [getD_eq_default _ _ h, get?_eq_none.mpr h, Option.getD_none]
end getD
section getI
variable [Inhabited α]
@[simp]
theorem getI_nil : getI ([] : List α) n = default :=
rfl
@[simp]
theorem getI_cons_zero : getI (x :: xs) 0 = x :=
rfl
@[simp]
theorem getI_cons_succ : getI (x :: xs) (n + 1) = getI xs n :=
rfl
theorem getI_eq_get {n : ℕ} (hn : n < l.length) : l.getI n = l.get ⟨n, hn⟩ :=
getD_eq_get ..
theorem getI_eq_default {n : ℕ} (hn : l.length ≤ n) : l.getI n = default :=
getD_eq_default _ _ hn
theorem getD_default_eq_getI {n : ℕ} : l.getD n default = l.getI n :=
rfl
theorem getI_append (l l' : List α) (n : ℕ) (h : n < l.length) :
(l ++ l').getI n = l.getI n := getD_append _ _ _ _ h
theorem getI_append_right (l l' : List α) (n : ℕ) (h : l.length ≤ n) :
(l ++ l').getI n = l'.getI (n - l.length) :=
getD_append_right _ _ _ _ h
theorem getI_eq_iget_get? (n : ℕ) : l.getI n = (l.get? n).iget := by
rw [← getD_default_eq_getI, getD_eq_getD_get?, Option.getD_default_eq_iget]
theorem getI_zero_eq_headI : l.getI 0 = l.headI := by cases l <;> rfl
end getI
|
Data\List\Indexes.lean | /-
Copyright (c) 2020 Jannis Limperg. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jannis Limperg
-/
import Mathlib.Data.List.OfFn
import Mathlib.Data.List.Range
import Mathlib.Data.List.Zip
/-!
# Lemmas about List.*Idx functions.
Some specification lemmas for `List.mapIdx`, `List.mapIdxM`, `List.foldlIdx` and `List.foldrIdx`.
-/
assert_not_exists MonoidWithZero
universe u v
open Function
namespace List
variable {α : Type u} {β : Type v}
section MapIdx
-- Porting note: Add back old definition because it's easier for writing proofs.
/-- Lean3 `map_with_index` helper function -/
protected def oldMapIdxCore (f : ℕ → α → β) : ℕ → List α → List β
| _, [] => []
| k, a :: as => f k a :: List.oldMapIdxCore f (k + 1) as
/-- Given a function `f : ℕ → α → β` and `as : List α`, `as = [a₀, a₁, ...]`, returns the list
`[f 0 a₀, f 1 a₁, ...]`. -/
protected def oldMapIdx (f : ℕ → α → β) (as : List α) : List β :=
List.oldMapIdxCore f 0 as
@[simp]
theorem mapIdx_nil {α β} (f : ℕ → α → β) : mapIdx f [] = [] :=
rfl
protected theorem oldMapIdxCore_eq (l : List α) (f : ℕ → α → β) (n : ℕ) :
l.oldMapIdxCore f n = l.oldMapIdx fun i a ↦ f (i + n) a := by
induction' l with hd tl hl generalizing f n
· rfl
· rw [List.oldMapIdx]
simp only [List.oldMapIdxCore, hl, Nat.add_left_comm, Nat.add_comm, Nat.add_zero]
-- Porting note: convert new definition to old definition.
-- A few new theorems are added to achieve this
-- 1. Prove that `oldMapIdxCore f (l ++ [e]) = oldMapIdxCore f l ++ [f l.length e]`
-- 2. Prove that `oldMapIdx f (l ++ [e]) = oldMapIdx f l ++ [f l.length e]`
-- 3. Prove list induction using `∀ l e, p [] → (p l → p (l ++ [e])) → p l`
theorem list_reverse_induction (p : List α → Prop) (base : p [])
(ind : ∀ (l : List α) (e : α), p l → p (l ++ [e])) : (∀ (l : List α), p l) := by
let q := fun l ↦ p (reverse l)
have pq : ∀ l, p (reverse l) → q l := by simp only [q, reverse_reverse]; intro; exact id
have qp : ∀ l, q (reverse l) → p l := by simp only [q, reverse_reverse]; intro; exact id
intro l
apply qp
generalize (reverse l) = l
induction' l with head tail ih
· apply pq; simp only [reverse_nil, base]
· apply pq; simp only [reverse_cons]; apply ind; apply qp; rw [reverse_reverse]; exact ih
protected theorem oldMapIdxCore_append : ∀ (f : ℕ → α → β) (n : ℕ) (l₁ l₂ : List α),
List.oldMapIdxCore f n (l₁ ++ l₂) =
List.oldMapIdxCore f n l₁ ++ List.oldMapIdxCore f (n + l₁.length) l₂ := by
intros f n l₁ l₂
generalize e : (l₁ ++ l₂).length = len
revert n l₁ l₂
induction' len with len ih <;> intros n l₁ l₂ h
· have l₁_nil : l₁ = [] := by
cases l₁
· rfl
· contradiction
have l₂_nil : l₂ = [] := by
cases l₂
· rfl
· rw [List.length_append] at h; contradiction
simp only [l₁_nil, l₂_nil]; rfl
· cases' l₁ with head tail
· rfl
· simp only [List.oldMapIdxCore, List.append_eq, length_cons, cons_append,cons.injEq, true_and]
suffices n + Nat.succ (length tail) = n + 1 + tail.length by
rw [this]
apply ih (n + 1) _ _ _
simp only [cons_append, length_cons, length_append, Nat.succ.injEq] at h
simp only [length_append, h]
rw [Nat.add_assoc]; simp only [Nat.add_comm]
protected theorem oldMapIdx_append : ∀ (f : ℕ → α → β) (l : List α) (e : α),
List.oldMapIdx f (l ++ [e]) = List.oldMapIdx f l ++ [f l.length e] := by
intros f l e
unfold List.oldMapIdx
rw [List.oldMapIdxCore_append f 0 l [e]]
simp only [Nat.zero_add]; rfl
theorem mapIdxGo_append : ∀ (f : ℕ → α → β) (l₁ l₂ : List α) (arr : Array β),
mapIdx.go f (l₁ ++ l₂) arr = mapIdx.go f l₂ (List.toArray (mapIdx.go f l₁ arr)) := by
intros f l₁ l₂ arr
generalize e : (l₁ ++ l₂).length = len
revert l₁ l₂ arr
induction' len with len ih <;> intros l₁ l₂ arr h
· have l₁_nil : l₁ = [] := by
cases l₁
· rfl
· contradiction
have l₂_nil : l₂ = [] := by
cases l₂
· rfl
· rw [List.length_append] at h; contradiction
rw [l₁_nil, l₂_nil]; simp only [mapIdx.go, Array.toList_eq, Array.toArray_data]
· cases' l₁ with head tail <;> simp only [mapIdx.go]
· simp only [nil_append, Array.toList_eq, Array.toArray_data]
· simp only [List.append_eq]
rw [ih]
· simp only [cons_append, length_cons, length_append, Nat.succ.injEq] at h
simp only [length_append, h]
theorem mapIdxGo_length : ∀ (f : ℕ → α → β) (l : List α) (arr : Array β),
length (mapIdx.go f l arr) = length l + arr.size := by
intro f l
induction' l with head tail ih
· intro; simp only [mapIdx.go, Array.toList_eq, length_nil, Nat.zero_add]
· intro; simp only [mapIdx.go]; rw [ih]; simp only [Array.size_push, length_cons]
simp only [Nat.add_succ, Fin.add_zero, Nat.add_comm]
theorem mapIdx_append_one : ∀ (f : ℕ → α → β) (l : List α) (e : α),
mapIdx f (l ++ [e]) = mapIdx f l ++ [f l.length e] := by
intros f l e
unfold mapIdx
rw [mapIdxGo_append f l [e]]
simp only [mapIdx.go, Array.size_toArray, mapIdxGo_length, length_nil, Nat.add_zero,
Array.toList_eq, Array.push_data, Array.data_toArray]
protected theorem new_def_eq_old_def :
∀ (f : ℕ → α → β) (l : List α), l.mapIdx f = List.oldMapIdx f l := by
intro f
apply list_reverse_induction
· rfl
· intro l e h
rw [List.oldMapIdx_append, mapIdx_append_one, h]
@[local simp]
theorem map_enumFrom_eq_zipWith : ∀ (l : List α) (n : ℕ) (f : ℕ → α → β),
map (uncurry f) (enumFrom n l) = zipWith (fun i ↦ f (i + n)) (range (length l)) l := by
intro l
generalize e : l.length = len
revert l
induction' len with len ih <;> intros l e n f
· have : l = [] := by
cases l
· rfl
· contradiction
rw [this]; rfl
· cases' l with head tail
· contradiction
· simp only [map, uncurry_apply_pair, range_succ_eq_map, zipWith, Nat.zero_add,
zipWith_map_left]
rw [ih]
· suffices (fun i ↦ f (i + (n + 1))) = ((fun i ↦ f (i + n)) ∘ Nat.succ) by
rw [this]
rfl
funext n' a
simp only [comp, Nat.add_assoc, Nat.add_comm, Nat.add_succ]
simp only [length_cons, Nat.succ.injEq] at e; exact e
theorem mapIdx_eq_enum_map (l : List α) (f : ℕ → α → β) :
l.mapIdx f = l.enum.map (Function.uncurry f) := by
rw [List.new_def_eq_old_def]
induction' l with hd tl hl generalizing f
· rfl
· rw [List.oldMapIdx, List.oldMapIdxCore, List.oldMapIdxCore_eq, hl]
simp [map, enum_eq_zip_range, map_uncurry_zip_eq_zipWith]
@[simp]
theorem mapIdx_cons (l : List α) (f : ℕ → α → β) (a : α) :
mapIdx f (a :: l) = f 0 a :: mapIdx (fun i ↦ f (i + 1)) l := by
simp [mapIdx_eq_enum_map, enum_eq_zip_range, map_uncurry_zip_eq_zipWith,
range_succ_eq_map, zipWith_map_left]
theorem mapIdx_append (K L : List α) (f : ℕ → α → β) :
(K ++ L).mapIdx f = K.mapIdx f ++ L.mapIdx fun i a ↦ f (i + K.length) a := by
induction' K with a J IH generalizing f
· rfl
· simp [IH fun i ↦ f (i + 1), Nat.add_assoc]
@[simp]
theorem length_mapIdx (l : List α) (f : ℕ → α → β) : (l.mapIdx f).length = l.length := by
induction' l with hd tl IH generalizing f
· rfl
· simp [IH]
@[simp]
theorem mapIdx_eq_nil {f : ℕ → α → β} {l : List α} : List.mapIdx f l = [] ↔ l = [] := by
rw [List.mapIdx_eq_enum_map, List.map_eq_nil, List.enum_eq_nil]
set_option linter.deprecated false in
@[simp, deprecated (since := "2023-02-11")]
theorem nthLe_mapIdx (l : List α) (f : ℕ → α → β) (i : ℕ) (h : i < l.length)
(h' : i < (l.mapIdx f).length := h.trans_le (l.length_mapIdx f).ge) :
(l.mapIdx f).nthLe i h' = f i (l.nthLe i h) := by
simp [mapIdx_eq_enum_map, enum_eq_zip_range]
theorem mapIdx_eq_ofFn (l : List α) (f : ℕ → α → β) :
l.mapIdx f = ofFn fun i : Fin l.length ↦ f (i : ℕ) (l.get i) := by
induction l generalizing f with
| nil => simp
| cons _ _ IH => simp [IH]
end MapIdx
section FoldrIdx
-- Porting note: Changed argument order of `foldrIdxSpec` to align better with `foldrIdx`.
/-- Specification of `foldrIdx`. -/
def foldrIdxSpec (f : ℕ → α → β → β) (b : β) (as : List α) (start : ℕ) : β :=
foldr (uncurry f) b <| enumFrom start as
theorem foldrIdxSpec_cons (f : ℕ → α → β → β) (b a as start) :
foldrIdxSpec f b (a :: as) start = f start a (foldrIdxSpec f b as (start + 1)) :=
rfl
theorem foldrIdx_eq_foldrIdxSpec (f : ℕ → α → β → β) (b as start) :
foldrIdx f b as start = foldrIdxSpec f b as start := by
induction as generalizing start
· rfl
· simp only [foldrIdx, foldrIdxSpec_cons, *]
theorem foldrIdx_eq_foldr_enum (f : ℕ → α → β → β) (b : β) (as : List α) :
foldrIdx f b as = foldr (uncurry f) b (enum as) := by
simp only [foldrIdx, foldrIdxSpec, foldrIdx_eq_foldrIdxSpec, enum]
end FoldrIdx
theorem indexesValues_eq_filter_enum (p : α → Prop) [DecidablePred p] (as : List α) :
indexesValues p as = filter (p ∘ Prod.snd) (enum as) := by
simp (config := { unfoldPartialApp := true }) [indexesValues, foldrIdx_eq_foldr_enum, uncurry,
filter_eq_foldr, cond_eq_if]
theorem findIdxs_eq_map_indexesValues (p : α → Prop) [DecidablePred p] (as : List α) :
findIdxs p as = map Prod.fst (indexesValues p as) := by
simp (config := { unfoldPartialApp := true }) only [indexesValues_eq_filter_enum,
map_filter_eq_foldr, findIdxs, uncurry, foldrIdx_eq_foldr_enum, decide_eq_true_eq, comp_apply,
Bool.cond_decide]
section FindIdx -- TODO: upstream to Batteries
theorem findIdx_eq_length {p : α → Bool} {xs : List α} :
xs.findIdx p = xs.length ↔ ∀ x ∈ xs, ¬p x := by
induction xs with
| nil => simp_all
| cons x xs ih =>
rw [findIdx_cons, length_cons]
constructor <;> intro h
· have : ¬p x := by contrapose h; simp_all
simp_all
· simp_rw [h x (mem_cons_self x xs), cond_false, Nat.succ.injEq, ih]
exact fun y hy ↦ h y <| mem_cons.mpr (Or.inr hy)
theorem findIdx_le_length (p : α → Bool) {xs : List α} : xs.findIdx p ≤ xs.length := by
by_cases e : ∃ x ∈ xs, p x
· exact (findIdx_lt_length_of_exists e).le
· push_neg at e; exact (findIdx_eq_length.mpr e).le
theorem findIdx_lt_length {p : α → Bool} {xs : List α} :
xs.findIdx p < xs.length ↔ ∃ x ∈ xs, p x := by
rw [← not_iff_not, not_lt]
have := @le_antisymm_iff _ _ (xs.findIdx p) xs.length
simp only [findIdx_le_length, true_and] at this
rw [← this, findIdx_eq_length, not_exists]
simp only [Bool.not_eq_true, not_and]
/-- `p` does not hold for elements with indices less than `xs.findIdx p`. -/
theorem not_of_lt_findIdx {p : α → Bool} {xs : List α} {i : ℕ} (h : i < xs.findIdx p) :
¬p (xs.get ⟨i, h.trans_le (findIdx_le_length p)⟩) := by
revert i
induction xs with
| nil => intro i h; rw [findIdx_nil] at h; omega
| cons x xs ih =>
intro i h
have ho := h
rw [findIdx_cons] at h
have npx : ¬p x := by by_contra y; rw [y, cond_true] at h; omega
simp_rw [npx, cond_false] at h
cases' i.eq_zero_or_pos with e e
· simpa only [e, Fin.zero_eta, get_cons_zero]
· have ipm := Nat.succ_pred_eq_of_pos e
have ilt := ho.trans_le (findIdx_le_length p)
rw [(Fin.mk_eq_mk (h' := ipm ▸ ilt)).mpr ipm.symm, get_cons_succ]
rw [← ipm, Nat.succ_lt_succ_iff] at h
exact ih h
theorem le_findIdx_of_not {p : α → Bool} {xs : List α} {i : ℕ} (h : i < xs.length)
(h2 : ∀ j (hji : j < i), ¬p (xs.get ⟨j, hji.trans h⟩)) : i ≤ xs.findIdx p := by
by_contra! f
exact absurd (@findIdx_get _ p xs (f.trans h)) (h2 (xs.findIdx p) f)
theorem lt_findIdx_of_not {p : α → Bool} {xs : List α} {i : ℕ} (h : i < xs.length)
(h2 : ∀ j (hji : j ≤ i), ¬p (xs.get ⟨j, hji.trans_lt h⟩)) : i < xs.findIdx p := by
by_contra! f
exact absurd (@findIdx_get _ p xs (f.trans_lt h)) (h2 (xs.findIdx p) f)
theorem findIdx_eq {p : α → Bool} {xs : List α} {i : ℕ} (h : i < xs.length) :
xs.findIdx p = i ↔ p (xs.get ⟨i, h⟩) ∧ ∀ j (hji : j < i), ¬p (xs.get ⟨j, hji.trans h⟩) := by
refine ⟨fun f ↦ ⟨f ▸ (@findIdx_get _ p xs (f ▸ h)), fun _ hji ↦ not_of_lt_findIdx (f ▸ hji)⟩,
fun ⟨h1, h2⟩ ↦ ?_⟩
apply Nat.le_antisymm _ (le_findIdx_of_not h h2)
contrapose! h1
exact not_of_lt_findIdx h1
end FindIdx
section FoldlIdx
-- Porting note: Changed argument order of `foldlIdxSpec` to align better with `foldlIdx`.
/-- Specification of `foldlIdx`. -/
def foldlIdxSpec (f : ℕ → α → β → α) (a : α) (bs : List β) (start : ℕ) : α :=
foldl (fun a p ↦ f p.fst a p.snd) a <| enumFrom start bs
theorem foldlIdxSpec_cons (f : ℕ → α → β → α) (a b bs start) :
foldlIdxSpec f a (b :: bs) start = foldlIdxSpec f (f start a b) bs (start + 1) :=
rfl
theorem foldlIdx_eq_foldlIdxSpec (f : ℕ → α → β → α) (a bs start) :
foldlIdx f a bs start = foldlIdxSpec f a bs start := by
induction bs generalizing start a
· rfl
· simp [foldlIdxSpec, *]
theorem foldlIdx_eq_foldl_enum (f : ℕ → α → β → α) (a : α) (bs : List β) :
foldlIdx f a bs = foldl (fun a p ↦ f p.fst a p.snd) a (enum bs) := by
simp only [foldlIdx, foldlIdxSpec, foldlIdx_eq_foldlIdxSpec, enum]
end FoldlIdx
section FoldIdxM
-- Porting note: `foldrM_eq_foldr` now depends on `[LawfulMonad m]`
variable {m : Type u → Type v} [Monad m]
theorem foldrIdxM_eq_foldrM_enum {β} (f : ℕ → α → β → m β) (b : β) (as : List α) [LawfulMonad m] :
foldrIdxM f b as = foldrM (uncurry f) b (enum as) := by
simp (config := { unfoldPartialApp := true }) only [foldrIdxM, foldrM_eq_foldr,
foldrIdx_eq_foldr_enum, uncurry]
theorem foldlIdxM_eq_foldlM_enum [LawfulMonad m] {β} (f : ℕ → β → α → m β) (b : β) (as : List α) :
foldlIdxM f b as = List.foldlM (fun b p ↦ f p.fst b p.snd) b (enum as) := by
rw [foldlIdxM, foldlM_eq_foldl, foldlIdx_eq_foldl_enum]
end FoldIdxM
section MapIdxM
-- Porting note: `[Applicative m]` replaced by `[Monad m] [LawfulMonad m]`
variable {m : Type u → Type v} [Monad m]
/-- Specification of `mapIdxMAux`. -/
def mapIdxMAuxSpec {β} (f : ℕ → α → m β) (start : ℕ) (as : List α) : m (List β) :=
List.traverse (uncurry f) <| enumFrom start as
-- Note: `traverse` the class method would require a less universe-polymorphic
-- `m : Type u → Type u`.
theorem mapIdxMAuxSpec_cons {β} (f : ℕ → α → m β) (start : ℕ) (a : α) (as : List α) :
mapIdxMAuxSpec f start (a :: as) = cons <$> f start a <*> mapIdxMAuxSpec f (start + 1) as :=
rfl
theorem mapIdxMGo_eq_mapIdxMAuxSpec
[LawfulMonad m] {β} (f : ℕ → α → m β) (arr : Array β) (as : List α) :
mapIdxM.go f as arr = (arr.toList ++ ·) <$> mapIdxMAuxSpec f arr.size as := by
generalize e : as.length = len
revert as arr
induction' len with len ih <;> intro arr as h
· have : as = [] := by
cases as
· rfl
· contradiction
simp only [this, mapIdxM.go, mapIdxMAuxSpec, List.traverse, map_pure, append_nil]
· match as with
| nil => contradiction
| cons head tail =>
simp only [length_cons, Nat.succ.injEq] at h
simp only [mapIdxM.go, mapIdxMAuxSpec_cons, map_eq_pure_bind, seq_eq_bind_map,
LawfulMonad.bind_assoc, pure_bind]
congr
conv => { lhs; intro x; rw [ih _ _ h]; }
funext x
simp only [Array.toList_eq, Array.push_data, append_assoc, singleton_append, Array.size_push,
map_eq_pure_bind]
theorem mapIdxM_eq_mmap_enum [LawfulMonad m] {β} (f : ℕ → α → m β) (as : List α) :
as.mapIdxM f = List.traverse (uncurry f) (enum as) := by
simp only [mapIdxM, mapIdxMGo_eq_mapIdxMAuxSpec, Array.toList_eq, Array.data_toArray,
nil_append, mapIdxMAuxSpec, Array.size_toArray, length_nil, id_map', enum]
end MapIdxM
section MapIdxM'
-- Porting note: `[Applicative m] [LawfulApplicative m]` replaced by [Monad m] [LawfulMonad m]
variable {m : Type u → Type v} [Monad m] [LawfulMonad m]
theorem mapIdxMAux'_eq_mapIdxMGo {α} (f : ℕ → α → m PUnit) (as : List α) (arr : Array PUnit) :
mapIdxMAux' f arr.size as = mapIdxM.go f as arr *> pure PUnit.unit := by
revert arr
induction' as with head tail ih <;> intro arr
· simp only [mapIdxMAux', mapIdxM.go, seqRight_eq, map_pure, seq_pure]
· simp only [mapIdxMAux', seqRight_eq, map_eq_pure_bind, seq_eq_bind, bind_pure_unit,
LawfulMonad.bind_assoc, pure_bind, mapIdxM.go, seq_pure]
generalize (f (Array.size arr) head) = head
let arr_1 := arr.push ⟨⟩
have : arr_1.size = arr.size + 1 := Array.size_push arr ⟨⟩
rw [← this, ih arr_1]
simp only [seqRight_eq, map_eq_pure_bind, seq_pure, LawfulMonad.bind_assoc, pure_bind]
theorem mapIdxM'_eq_mapIdxM {α} (f : ℕ → α → m PUnit) (as : List α) :
mapIdxM' f as = mapIdxM as f *> pure PUnit.unit :=
mapIdxMAux'_eq_mapIdxMGo f as #[]
end MapIdxM'
end List
|
Data\List\Infix.lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.List.Basic
/-!
# Prefixes, suffixes, infixes
This file proves properties about
* `List.isPrefix`: `l₁` is a prefix of `l₂` if `l₂` starts with `l₁`.
* `List.isSuffix`: `l₁` is a suffix of `l₂` if `l₂` ends with `l₁`.
* `List.isInfix`: `l₁` is an infix of `l₂` if `l₁` is a prefix of some suffix of `l₂`.
* `List.inits`: The list of prefixes of a list.
* `List.tails`: The list of prefixes of a list.
* `insert` on lists
All those (except `insert`) are defined in `Mathlib.Data.List.Defs`.
## Notation
* `l₁ <+: l₂`: `l₁` is a prefix of `l₂`.
* `l₁ <:+ l₂`: `l₁` is a suffix of `l₂`.
* `l₁ <:+: l₂`: `l₁` is an infix of `l₂`.
-/
open Nat
variable {α β : Type*}
namespace List
variable {l l₁ l₂ l₃ : List α} {a b : α} {m n : ℕ}
/-! ### prefix, suffix, infix -/
section Fix
theorem prefix_rfl : l <+: l :=
prefix_refl _
theorem suffix_rfl : l <:+ l :=
suffix_refl _
theorem infix_rfl : l <:+: l :=
infix_refl _
theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp
theorem prefix_concat_iff {l₁ l₂ : List α} {a : α} :
l₁ <+: l₂ ++ [a] ↔ l₁ = l₂ ++ [a] ∨ l₁ <+: l₂ := by
simpa only [← reverse_concat', reverse_inj, reverse_suffix] using
suffix_cons_iff (l₁ := l₁.reverse) (l₂ := l₂.reverse)
protected alias ⟨_, isSuffix.reverse⟩ := reverse_prefix
protected alias ⟨_, isPrefix.reverse⟩ := reverse_suffix
protected alias ⟨_, isInfix.reverse⟩ := reverse_infix
alias ⟨eq_nil_of_infix_nil, _⟩ := infix_nil
alias ⟨eq_nil_of_prefix_nil, _⟩ := prefix_nil
alias ⟨eq_nil_of_suffix_nil, _⟩ := suffix_nil
theorem eq_of_infix_of_length_eq (h : l₁ <:+: l₂) : l₁.length = l₂.length → l₁ = l₂ :=
h.sublist.eq_of_length
theorem eq_of_prefix_of_length_eq (h : l₁ <+: l₂) : l₁.length = l₂.length → l₁ = l₂ :=
h.sublist.eq_of_length
theorem eq_of_suffix_of_length_eq (h : l₁ <:+ l₂) : l₁.length = l₂.length → l₁ = l₂ :=
h.sublist.eq_of_length
lemma dropSlice_sublist (n m : ℕ) (l : List α) : l.dropSlice n m <+ l :=
calc
l.dropSlice n m = take n l ++ drop m (drop n l) := by rw [dropSlice_eq, drop_drop, Nat.add_comm]
_ <+ take n l ++ drop n l := (Sublist.refl _).append (drop_sublist _ _)
_ = _ := take_append_drop _ _
lemma dropSlice_subset (n m : ℕ) (l : List α) : l.dropSlice n m ⊆ l :=
(dropSlice_sublist n m l).subset
lemma mem_of_mem_dropSlice {n m : ℕ} {l : List α} {a : α} (h : a ∈ l.dropSlice n m) : a ∈ l :=
dropSlice_subset n m l h
theorem takeWhile_prefix (p : α → Bool) : l.takeWhile p <+: l :=
⟨l.dropWhile p, takeWhile_append_dropWhile p l⟩
theorem dropWhile_suffix (p : α → Bool) : l.dropWhile p <:+ l :=
⟨l.takeWhile p, takeWhile_append_dropWhile p l⟩
theorem dropLast_prefix : ∀ l : List α, l.dropLast <+: l
| [] => ⟨nil, by rw [dropLast, List.append_nil]⟩
| a :: l => ⟨_, dropLast_append_getLast (cons_ne_nil a l)⟩
theorem tail_suffix (l : List α) : tail l <:+ l := by rw [← drop_one]; apply drop_suffix
theorem dropLast_sublist (l : List α) : l.dropLast <+ l :=
(dropLast_prefix l).sublist
@[gcongr]
theorem drop_sublist_drop_left (l : List α) {m n : ℕ} (h : m ≤ n) : drop n l <+ drop m l := by
rw [← Nat.sub_add_cancel h, ← drop_drop]
apply drop_sublist
theorem dropLast_subset (l : List α) : l.dropLast ⊆ l :=
(dropLast_sublist l).subset
theorem tail_subset (l : List α) : tail l ⊆ l :=
(tail_sublist l).subset
theorem mem_of_mem_dropLast (h : a ∈ l.dropLast) : a ∈ l :=
dropLast_subset l h
theorem mem_of_mem_tail (h : a ∈ l.tail) : a ∈ l :=
tail_subset l h
@[gcongr]
protected theorem Sublist.drop : ∀ {l₁ l₂ : List α}, l₁ <+ l₂ → ∀ n, l₁.drop n <+ l₂.drop n
| _, _, h, 0 => h
| _, _, h, n + 1 => by rw [← drop_tail, ← drop_tail]; exact h.tail.drop n
theorem prefix_iff_eq_append : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ :=
⟨by rintro ⟨r, rfl⟩; rw [drop_left], fun e => ⟨_, e⟩⟩
theorem suffix_iff_eq_append : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ :=
⟨by rintro ⟨r, rfl⟩; simp only [length_append, Nat.add_sub_cancel_right, take_left], fun e =>
⟨_, e⟩⟩
theorem prefix_iff_eq_take : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ :=
⟨fun h => append_cancel_right <| (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
fun e => e.symm ▸ take_prefix _ _⟩
theorem prefix_take_iff {x y : List α} {n : ℕ} : x <+: y.take n ↔ x <+: y ∧ x.length ≤ n := by
constructor
· intro h
constructor
· exact List.IsPrefix.trans h <| List.take_prefix n y
· replace h := h.length_le
rw [length_take, Nat.le_min] at h
exact h.left
· intro ⟨hp, hl⟩
have hl' := hp.length_le
rw [List.prefix_iff_eq_take] at *
rw [hp, List.take_take]
simp [min_eq_left, hl, hl']
theorem concat_get_prefix {x y : List α} (h : x <+: y) (hl : x.length < y.length) :
x ++ [y.get ⟨x.length, hl⟩] <+: y := by
use y.drop (x.length + 1)
nth_rw 1 [List.prefix_iff_eq_take.mp h]
convert List.take_append_drop (x.length + 1) y using 2
rw [← List.take_concat_get, List.concat_eq_append]; rfl
theorem suffix_iff_eq_drop : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ :=
⟨fun h => append_cancel_left <| (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
fun e => e.symm ▸ drop_suffix _ _⟩
instance decidablePrefix [DecidableEq α] : ∀ l₁ l₂ : List α, Decidable (l₁ <+: l₂)
| [], l₂ => isTrue ⟨l₂, rfl⟩
| a :: l₁, [] => isFalse fun ⟨t, te⟩ => List.noConfusion te
| a :: l₁, b :: l₂ =>
if h : a = b then
@decidable_of_decidable_of_iff _ _ (decidablePrefix l₁ l₂) (by rw [← h, prefix_cons_inj])
else
isFalse fun ⟨t, te⟩ => h <| by injection te
-- Alternatively, use mem_tails
instance decidableSuffix [DecidableEq α] : ∀ l₁ l₂ : List α, Decidable (l₁ <:+ l₂)
| [], l₂ => isTrue ⟨l₂, append_nil _⟩
| a :: l₁, [] => isFalse <| mt (Sublist.length_le ∘ IsSuffix.sublist) (by simp)
| l₁, b :: l₂ =>
@decidable_of_decidable_of_iff _ _
(@instDecidableOr _ _ _ (l₁.decidableSuffix l₂))
suffix_cons_iff.symm
instance decidableInfix [DecidableEq α] : ∀ l₁ l₂ : List α, Decidable (l₁ <:+: l₂)
| [], l₂ => isTrue ⟨[], l₂, rfl⟩
| a :: l₁, [] => isFalse fun ⟨s, t, te⟩ => by simp at te
| l₁, b :: l₂ =>
@decidable_of_decidable_of_iff _ _
(@instDecidableOr _ _ (l₁.decidablePrefix (b :: l₂)) (l₁.decidableInfix l₂))
infix_cons_iff.symm
theorem prefix_take_le_iff {L : List (List (Option α))} (hm : m < L.length) :
L.take m <+: L.take n ↔ m ≤ n := by
simp only [prefix_iff_eq_take, length_take]
induction m generalizing L n with
| zero => simp [min_eq_left, eq_self_iff_true, Nat.zero_le, take]
| succ m IH =>
cases L with
| nil => simp_all
| cons l ls =>
cases n with
| zero =>
simp
| succ n =>
simp only [length_cons, succ_eq_add_one, Nat.add_lt_add_iff_right] at hm
simp [← @IH n ls hm, Nat.min_eq_left, Nat.le_of_lt hm]
theorem cons_prefix_iff : a :: l₁ <+: b :: l₂ ↔ a = b ∧ l₁ <+: l₂ := by
constructor
· rintro ⟨L, hL⟩
simp only [cons_append] at hL
injection hL with hLLeft hLRight
exact ⟨hLLeft, ⟨L, hLRight⟩⟩
· rintro ⟨rfl, h⟩
rwa [prefix_cons_inj]
protected theorem IsPrefix.map (h : l₁ <+: l₂) (f : α → β) : l₁.map f <+: l₂.map f := by
induction' l₁ with hd tl hl generalizing l₂
· simp only [nil_prefix, map_nil]
· cases' l₂ with hd₂ tl₂
· simpa only using eq_nil_of_prefix_nil h
· rw [cons_prefix_iff] at h
simp only [List.map_cons, h, prefix_cons_inj, hl, map]
protected theorem IsPrefix.filterMap (h : l₁ <+: l₂) (f : α → Option β) :
l₁.filterMap f <+: l₂.filterMap f := by
induction' l₁ with hd₁ tl₁ hl generalizing l₂
· simp only [nil_prefix, filterMap_nil]
· cases' l₂ with hd₂ tl₂
· simpa only using eq_nil_of_prefix_nil h
· rw [cons_prefix_iff] at h
rw [← @singleton_append _ hd₁ _, ← @singleton_append _ hd₂ _, filterMap_append,
filterMap_append, h.left, prefix_append_right_inj]
exact hl h.right
@[deprecated (since := "2024-03-26")] alias IsPrefix.filter_map := IsPrefix.filterMap
protected theorem IsPrefix.reduceOption {l₁ l₂ : List (Option α)} (h : l₁ <+: l₂) :
l₁.reduceOption <+: l₂.reduceOption :=
h.filterMap id
instance : IsPartialOrder (List α) (· <+: ·) where
refl := prefix_refl
trans _ _ _ := IsPrefix.trans
antisymm _ _ h₁ h₂ := eq_of_prefix_of_length_eq h₁ <| h₁.length_le.antisymm h₂.length_le
instance : IsPartialOrder (List α) (· <:+ ·) where
refl := suffix_refl
trans _ _ _ := IsSuffix.trans
antisymm _ _ h₁ h₂ := eq_of_suffix_of_length_eq h₁ <| h₁.length_le.antisymm h₂.length_le
instance : IsPartialOrder (List α) (· <:+: ·) where
refl := infix_refl
trans _ _ _ := IsInfix.trans
antisymm _ _ h₁ h₂ := eq_of_infix_of_length_eq h₁ <| h₁.length_le.antisymm h₂.length_le
end Fix
section InitsTails
@[simp]
theorem mem_inits : ∀ s t : List α, s ∈ inits t ↔ s <+: t
| s, [] =>
suffices s = nil ↔ s <+: nil by simpa only [inits, mem_singleton]
⟨fun h => h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩
| s, a :: t =>
suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t by simpa
⟨fun o =>
match s, o with
| _, Or.inl rfl => ⟨_, rfl⟩
| s, Or.inr ⟨r, hr, hs⟩ => by
let ⟨s, ht⟩ := (mem_inits _ _).1 hr
rw [← hs, ← ht]; exact ⟨s, rfl⟩,
fun mi =>
match s, mi with
| [], ⟨_, rfl⟩ => Or.inl rfl
| b :: s, ⟨r, hr⟩ =>
(List.noConfusion hr) fun ba (st : s ++ r = t) =>
Or.inr <| by rw [ba]; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩⟩
@[simp]
theorem mem_tails : ∀ s t : List α, s ∈ tails t ↔ s <:+ t
| s, [] => by
simp only [tails, mem_singleton, suffix_nil]
| s, a :: t => by
simp only [tails, mem_cons, mem_tails s t]
exact
show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t from
⟨fun o =>
match s, t, o with
| _, t, Or.inl rfl => suffix_rfl
| s, _, Or.inr ⟨l, rfl⟩ => ⟨a :: l, rfl⟩,
fun e =>
match s, t, e with
| _, t, ⟨[], rfl⟩ => Or.inl rfl
| s, t, ⟨b :: l, he⟩ => List.noConfusion he fun _ lt => Or.inr ⟨l, lt⟩⟩
theorem inits_cons (a : α) (l : List α) : inits (a :: l) = [] :: l.inits.map fun t => a :: t := by
simp
theorem tails_cons (a : α) (l : List α) : tails (a :: l) = (a :: l) :: l.tails := by simp
@[simp]
theorem inits_append : ∀ s t : List α, inits (s ++ t) = s.inits ++ t.inits.tail.map fun l => s ++ l
| [], [] => by simp
| [], a :: t => by simp [· ∘ ·]
| a :: s, t => by simp [inits_append s t, · ∘ ·]
@[simp]
theorem tails_append :
∀ s t : List α, tails (s ++ t) = (s.tails.map fun l => l ++ t) ++ t.tails.tail
| [], [] => by simp
| [], a :: t => by simp
| a :: s, t => by simp [tails_append s t]
-- the lemma names `inits_eq_tails` and `tails_eq_inits` are like `sublists_eq_sublists'`
theorem inits_eq_tails : ∀ l : List α, l.inits = (reverse <| map reverse <| tails <| reverse l)
| [] => by simp
| a :: l => by simp [inits_eq_tails l, map_inj_left, ← map_reverse]
theorem tails_eq_inits : ∀ l : List α, l.tails = (reverse <| map reverse <| inits <| reverse l)
| [] => by simp
| a :: l => by simp [tails_eq_inits l, append_left_inj]
theorem inits_reverse (l : List α) : inits (reverse l) = reverse (map reverse l.tails) := by
rw [tails_eq_inits l]
simp [reverse_involutive.comp_self, ← map_reverse]
theorem tails_reverse (l : List α) : tails (reverse l) = reverse (map reverse l.inits) := by
rw [inits_eq_tails l]
simp [reverse_involutive.comp_self, ← map_reverse]
theorem map_reverse_inits (l : List α) : map reverse l.inits = (reverse <| tails <| reverse l) := by
rw [inits_eq_tails l]
simp [reverse_involutive.comp_self, ← map_reverse]
theorem map_reverse_tails (l : List α) : map reverse l.tails = (reverse <| inits <| reverse l) := by
rw [tails_eq_inits l]
simp [reverse_involutive.comp_self, ← map_reverse]
@[simp]
theorem length_tails (l : List α) : length (tails l) = length l + 1 := by
induction' l with x l IH
· simp
· simpa using IH
@[simp]
theorem length_inits (l : List α) : length (inits l) = length l + 1 := by simp [inits_eq_tails]
@[simp]
theorem getElem_tails (l : List α) (n : Nat) (h : n < (tails l).length) :
(tails l)[n] = l.drop n := by
induction l generalizing n with
| nil => simp
| cons a l ihl =>
cases n with
| zero => simp
| succ n => simp [ihl]
theorem get_tails (l : List α) (n : Fin (length (tails l))) : (tails l).get n = l.drop n := by
simp
@[simp]
theorem getElem_inits (l : List α) (n : Nat) (h : n < length (inits l)) :
(inits l)[n] = l.take n := by
induction l generalizing n with
| nil => simp
| cons a l ihl =>
cases n with
| zero => simp
| succ n => simp [ihl]
theorem get_inits (l : List α) (n : Fin (length (inits l))) : (inits l).get n = l.take n := by
simp
section deprecated
set_option linter.deprecated false
@[simp, deprecated get_tails (since := "2024-04-16")]
theorem nth_le_tails (l : List α) (n : ℕ) (hn : n < length (tails l)) :
nthLe (tails l) n hn = l.drop n :=
get_tails l _
@[simp, deprecated get_inits (since := "2024-04-16")]
theorem nth_le_inits (l : List α) (n : ℕ) (hn : n < length (inits l)) :
nthLe (inits l) n hn = l.take n :=
get_inits l _
end deprecated
end InitsTails
/-! ### insert -/
section Insert
variable [DecidableEq α]
theorem insert_eq_ite (a : α) (l : List α) : insert a l = if a ∈ l then l else a :: l := by
simp only [← elem_iff]
rfl
@[simp]
theorem suffix_insert (a : α) (l : List α) : l <:+ l.insert a := by
by_cases h : a ∈ l
· simp only [insert_of_mem h, insert, suffix_refl]
· simp only [insert_of_not_mem h, suffix_cons, insert]
theorem infix_insert (a : α) (l : List α) : l <:+: l.insert a :=
(suffix_insert a l).isInfix
theorem sublist_insert (a : α) (l : List α) : l <+ l.insert a :=
(suffix_insert a l).sublist
theorem subset_insert (a : α) (l : List α) : l ⊆ l.insert a :=
(sublist_insert a l).subset
end Insert
theorem mem_of_mem_suffix (hx : a ∈ l₁) (hl : l₁ <:+ l₂) : a ∈ l₂ :=
hl.subset hx
theorem IsPrefix.ne_nil {x y : List α} (h : x <+: y) (hx : x ≠ []) : y ≠ [] := by
rintro rfl; exact hx <| List.prefix_nil.mp h
theorem IsPrefix.getElem {x y : List α} (h : x <+: y) {n} (hn : n < x.length) :
x[n] = y[n]'(hn.trans_le h.length_le) := by
obtain ⟨_, rfl⟩ := h
exact (List.getElem_append n hn).symm
theorem IsPrefix.get_eq {x y : List α} (h : x <+: y) {n} (hn : n < x.length) :
x.get ⟨n, hn⟩ = y.get ⟨n, hn.trans_le h.length_le⟩ := by
simp only [get_eq_getElem, IsPrefix.getElem h hn]
theorem IsPrefix.head_eq {x y : List α} (h : x <+: y) (hx : x ≠ []) :
x.head hx = y.head (h.ne_nil hx) := by
cases x <;> cases y <;> simp only [head_cons, ne_eq, not_true_eq_false] at hx ⊢
all_goals (obtain ⟨_, h⟩ := h; injection h)
end List
|
Data\List\InsertNth.lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import Mathlib.Data.List.Basic
/-!
# insertNth
Proves various lemmas about `List.insertNth`.
-/
open Function
open Nat hiding one_pos
assert_not_exists Set.range
namespace List
universe u v w
variable {ι : Type*} {α : Type u} {β : Type v} {γ : Type w} {l₁ l₂ : List α}
section InsertNth
variable {a : α}
@[simp]
theorem insertNth_zero (s : List α) (x : α) : insertNth 0 x s = x :: s :=
rfl
@[simp]
theorem insertNth_succ_nil (n : ℕ) (a : α) : insertNth (n + 1) a [] = [] :=
rfl
@[simp]
theorem insertNth_succ_cons (s : List α) (hd x : α) (n : ℕ) :
insertNth (n + 1) x (hd :: s) = hd :: insertNth n x s :=
rfl
theorem length_insertNth : ∀ n as, n ≤ length as → length (insertNth n a as) = length as + 1
| 0, _, _ => rfl
| _ + 1, [], h => (Nat.not_succ_le_zero _ h).elim
| n + 1, _ :: as, h => congr_arg Nat.succ <| length_insertNth n as (Nat.le_of_succ_le_succ h)
theorem eraseIdx_insertNth (n : ℕ) (l : List α) : (l.insertNth n a).eraseIdx n = l := by
rw [eraseIdx_eq_modifyNthTail, insertNth, modifyNthTail_modifyNthTail_same]
exact modifyNthTail_id _ _
@[deprecated (since := "2024-05-04")] alias removeNth_insertNth := eraseIdx_insertNth
theorem insertNth_eraseIdx_of_ge :
∀ n m as,
n < length as → n ≤ m → insertNth m a (as.eraseIdx n) = (as.insertNth (m + 1) a).eraseIdx n
| 0, 0, [], has, _ => (lt_irrefl _ has).elim
| 0, 0, _ :: as, _, _ => by simp [eraseIdx, insertNth]
| 0, m + 1, a :: as, _, _ => rfl
| n + 1, m + 1, a :: as, has, hmn =>
congr_arg (cons a) <|
insertNth_eraseIdx_of_ge n m as (Nat.lt_of_succ_lt_succ has) (Nat.le_of_succ_le_succ hmn)
@[deprecated (since := "2024-05-04")] alias insertNth_removeNth_of_ge := insertNth_eraseIdx_of_ge
theorem insertNth_eraseIdx_of_le :
∀ n m as,
n < length as → m ≤ n → insertNth m a (as.eraseIdx n) = (as.insertNth m a).eraseIdx (n + 1)
| _, 0, _ :: _, _, _ => rfl
| n + 1, m + 1, a :: as, has, hmn =>
congr_arg (cons a) <|
insertNth_eraseIdx_of_le n m as (Nat.lt_of_succ_lt_succ has) (Nat.le_of_succ_le_succ hmn)
@[deprecated (since := "2024-05-04")] alias insertNth_removeNth_of_le := insertNth_eraseIdx_of_le
theorem insertNth_comm (a b : α) :
∀ (i j : ℕ) (l : List α) (_ : i ≤ j) (_ : j ≤ length l),
(l.insertNth i a).insertNth (j + 1) b = (l.insertNth j b).insertNth i a
| 0, j, l => by simp [insertNth]
| i + 1, 0, l => fun h => (Nat.not_lt_zero _ h).elim
| i + 1, j + 1, [] => by simp
| i + 1, j + 1, c :: l => fun h₀ h₁ => by
simp only [insertNth_succ_cons, cons.injEq, true_and]
exact insertNth_comm a b i j l (Nat.le_of_succ_le_succ h₀) (Nat.le_of_succ_le_succ h₁)
theorem mem_insertNth {a b : α} :
∀ {n : ℕ} {l : List α} (_ : n ≤ l.length), a ∈ l.insertNth n b ↔ a = b ∨ a ∈ l
| 0, as, _ => by simp
| n + 1, [], h => (Nat.not_succ_le_zero _ h).elim
| n + 1, a' :: as, h => by
rw [List.insertNth_succ_cons, mem_cons, mem_insertNth (Nat.le_of_succ_le_succ h),
← or_assoc, @or_comm (a = a'), or_assoc, mem_cons]
theorem insertNth_of_length_lt (l : List α) (x : α) (n : ℕ) (h : l.length < n) :
insertNth n x l = l := by
induction' l with hd tl IH generalizing n
· cases n
· simp at h
· simp
· cases n
· simp at h
· simp only [Nat.succ_lt_succ_iff, length] at h
simpa using IH _ h
@[simp]
theorem insertNth_length_self (l : List α) (x : α) : insertNth l.length x l = l ++ [x] := by
induction' l with hd tl IH
· simp
· simpa using IH
theorem length_le_length_insertNth (l : List α) (x : α) (n : ℕ) :
l.length ≤ (insertNth n x l).length := by
rcases le_or_lt n l.length with hn | hn
· rw [length_insertNth _ _ hn]
exact (Nat.lt_succ_self _).le
· rw [insertNth_of_length_lt _ _ _ hn]
theorem length_insertNth_le_succ (l : List α) (x : α) (n : ℕ) :
(insertNth n x l).length ≤ l.length + 1 := by
rcases le_or_lt n l.length with hn | hn
· rw [length_insertNth _ _ hn]
· rw [insertNth_of_length_lt _ _ _ hn]
exact (Nat.lt_succ_self _).le
theorem getElem_insertNth_of_lt (l : List α) (x : α) (n k : ℕ) (hn : k < n) (hk : k < l.length)
(hk' : k < (insertNth n x l).length := hk.trans_le (length_le_length_insertNth _ _ _)) :
(insertNth n x l)[k] = l[k] := by
induction' n with n IH generalizing k l
· simp at hn
· cases' l with hd tl
· simp
· cases k
· simp [get]
· rw [Nat.succ_lt_succ_iff] at hn
simpa using IH _ _ hn _
theorem get_insertNth_of_lt (l : List α) (x : α) (n k : ℕ) (hn : k < n) (hk : k < l.length)
(hk' : k < (insertNth n x l).length := hk.trans_le (length_le_length_insertNth _ _ _)) :
(insertNth n x l).get ⟨k, hk'⟩ = l.get ⟨k, hk⟩ := by
simp_all [getElem_insertNth_of_lt]
set_option linter.deprecated false in
@[deprecated get_insertNth_of_lt (since := "2023-01-05")]
theorem nthLe_insertNth_of_lt : ∀ (l : List α) (x : α) (n k : ℕ), k < n → ∀ (hk : k < l.length)
(hk' : k < (insertNth n x l).length := hk.trans_le (length_le_length_insertNth _ _ _)),
(insertNth n x l).nthLe k hk' = l.nthLe k hk := @get_insertNth_of_lt _
@[simp]
theorem getElem_insertNth_self (l : List α) (x : α) (n : ℕ) (hn : n ≤ l.length)
(hn' : n < (insertNth n x l).length := (by rwa [length_insertNth _ _ hn, Nat.lt_succ_iff])) :
(insertNth n x l)[n] = x := by
induction' l with hd tl IH generalizing n
· simp only [length] at hn
cases hn
simp only [insertNth_zero, getElem_singleton]
· cases n
· simp
· simp only [Nat.succ_le_succ_iff, length] at hn
simpa using IH _ hn
theorem get_insertNth_self (l : List α) (x : α) (n : ℕ) (hn : n ≤ l.length)
(hn' : n < (insertNth n x l).length := (by rwa [length_insertNth _ _ hn, Nat.lt_succ_iff])) :
(insertNth n x l).get ⟨n, hn'⟩ = x := by
simp [hn, hn']
set_option linter.deprecated false in
@[simp, deprecated get_insertNth_self (since := "2023-01-05")]
theorem nthLe_insertNth_self (l : List α) (x : α) (n : ℕ) (hn : n ≤ l.length)
(hn' : n < (insertNth n x l).length := (by rwa [length_insertNth _ _ hn, Nat.lt_succ_iff])) :
(insertNth n x l).nthLe n hn' = x := get_insertNth_self _ _ _ hn
theorem getElem_insertNth_add_succ (l : List α) (x : α) (n k : ℕ) (hk' : n + k < l.length)
(hk : n + k + 1 < (insertNth n x l).length := (by
rwa [length_insertNth _ _ (by omega), Nat.succ_lt_succ_iff])) :
(insertNth n x l)[n + k + 1] = l[n + k] := by
induction' l with hd tl IH generalizing n k
· simp at hk'
· cases n
· simp
· simpa [Nat.add_right_comm] using IH _ _ _
theorem get_insertNth_add_succ (l : List α) (x : α) (n k : ℕ) (hk' : n + k < l.length)
(hk : n + k + 1 < (insertNth n x l).length := (by
rwa [length_insertNth _ _ (by omega), Nat.succ_lt_succ_iff])) :
(insertNth n x l).get ⟨n + k + 1, hk⟩ = get l ⟨n + k, hk'⟩ := by
simp [getElem_insertNth_add_succ, hk, hk']
set_option linter.deprecated false in
@[deprecated get_insertNth_add_succ (since := "2023-01-05")]
theorem nthLe_insertNth_add_succ : ∀ (l : List α) (x : α) (n k : ℕ) (hk' : n + k < l.length)
(hk : n + k + 1 < (insertNth n x l).length := (by
rwa [length_insertNth _ _ (by omega), Nat.succ_lt_succ_iff])),
(insertNth n x l).nthLe (n + k + 1) hk = nthLe l (n + k) hk' :=
@get_insertNth_add_succ _
set_option linter.unnecessarySimpa false in
theorem insertNth_injective (n : ℕ) (x : α) : Function.Injective (insertNth n x) := by
induction' n with n IH
· have : insertNth 0 x = cons x := funext fun _ => rfl
simp [this]
· rintro (_ | ⟨a, as⟩) (_ | ⟨b, bs⟩) h <;> simpa [IH.eq_iff] using h
end InsertNth
end List
|
Data\List\Intervals.lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Mathlib.Data.List.Lattice
import Mathlib.Data.Bool.Basic
import Mathlib.Init.Data.Nat.Lemmas
import Mathlib.Order.Lattice
/-!
# Intervals in ℕ
This file defines intervals of naturals. `List.Ico m n` is the list of integers greater than `m`
and strictly less than `n`.
## TODO
- Define `Ioo` and `Icc`, state basic lemmas about them.
- Also do the versions for integers?
- One could generalise even further, defining 'locally finite partial orders', for which
`Set.Ico a b` is `[Finite]`, and 'locally finite total orders', for which there is a list model.
- Once the above is done, get rid of `Data.Int.range` (and maybe `List.range'`?).
-/
open Nat
namespace List
/-- `Ico n m` is the list of natural numbers `n ≤ x < m`.
(Ico stands for "interval, closed-open".)
See also `Data/Set/Intervals.lean` for `Set.Ico`, modelling intervals in general preorders, and
`Multiset.Ico` and `Finset.Ico` for `n ≤ x < m` as a multiset or as a finset.
-/
def Ico (n m : ℕ) : List ℕ :=
range' n (m - n)
namespace Ico
theorem zero_bot (n : ℕ) : Ico 0 n = range n := by rw [Ico, Nat.sub_zero, range_eq_range']
@[simp]
theorem length (n m : ℕ) : length (Ico n m) = m - n := by
dsimp [Ico]
simp [length_range', autoParam]
theorem pairwise_lt (n m : ℕ) : Pairwise (· < ·) (Ico n m) := by
dsimp [Ico]
simp [pairwise_lt_range', autoParam]
theorem nodup (n m : ℕ) : Nodup (Ico n m) := by
dsimp [Ico]
simp [nodup_range', autoParam]
@[simp]
theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := by
suffices n ≤ l ∧ l < n + (m - n) ↔ n ≤ l ∧ l < m by simp [Ico, this]
rcases le_total n m with hnm | hmn
· rw [Nat.add_sub_cancel' hnm]
· rw [Nat.sub_eq_zero_iff_le.mpr hmn, Nat.add_zero]
exact
and_congr_right fun hnl =>
Iff.intro (fun hln => (not_le_of_gt hln hnl).elim) fun hlm => lt_of_lt_of_le hlm hmn
theorem eq_nil_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = [] := by
simp [Ico, Nat.sub_eq_zero_iff_le.mpr h]
theorem map_add (n m k : ℕ) : (Ico n m).map (k + ·) = Ico (n + k) (m + k) := by
rw [Ico, Ico, map_add_range', Nat.add_sub_add_right m k, Nat.add_comm n k]
theorem map_sub (n m k : ℕ) (h₁ : k ≤ n) :
((Ico n m).map fun x => x - k) = Ico (n - k) (m - k) := by
rw [Ico, Ico, Nat.sub_sub_sub_cancel_right h₁, map_sub_range' _ _ _ h₁]
@[simp]
theorem self_empty {n : ℕ} : Ico n n = [] :=
eq_nil_of_le (le_refl n)
@[simp]
theorem eq_empty_iff {n m : ℕ} : Ico n m = [] ↔ m ≤ n :=
Iff.intro (fun h => Nat.sub_eq_zero_iff_le.mp <| by rw [← length, h, List.length]) eq_nil_of_le
theorem append_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) :
Ico n m ++ Ico m l = Ico n l := by
dsimp only [Ico]
convert range'_append n (m-n) (l-m) 1 using 2
· rw [Nat.one_mul, Nat.add_sub_cancel' hnm]
· rw [Nat.sub_add_sub_cancel hml hnm]
@[simp]
theorem inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = [] := by
apply eq_nil_iff_forall_not_mem.2
intro a
simp only [and_imp, not_and, not_lt, List.mem_inter_iff, List.Ico.mem]
intro _ h₂ h₃
exfalso
exact not_lt_of_ge h₃ h₂
@[simp]
theorem bagInter_consecutive (n m l : Nat) :
@List.bagInter ℕ instBEqOfDecidableEq (Ico n m) (Ico m l) = [] :=
(bagInter_nil_iff_inter_nil _ _).2 (by convert inter_consecutive n m l)
@[simp]
theorem succ_singleton {n : ℕ} : Ico n (n + 1) = [n] := by
dsimp [Ico]
simp [range', Nat.add_sub_cancel_left]
theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = Ico n m ++ [m] := by
rwa [← succ_singleton, append_consecutive]
exact Nat.le_succ _
theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := by
rw [← append_consecutive (Nat.le_succ n) h, succ_singleton]
rfl
@[simp]
theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = [m - 1] := by
dsimp [Ico]
rw [Nat.sub_sub_self (succ_le_of_lt h)]
simp [← Nat.one_eq_succ_zero]
theorem chain'_succ (n m : ℕ) : Chain' (fun a b => b = succ a) (Ico n m) := by
by_cases h : n < m
· rw [eq_cons h]
exact chain_succ_range' _ _ 1
· rw [eq_nil_of_le (le_of_not_gt h)]
trivial
-- Porting note (#10618): simp can prove this
-- @[simp]
theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := by simp
theorem filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) :
((Ico n m).filter fun x => x < l) = Ico n m :=
filter_eq_self.2 fun k hk => by
simp only [(lt_of_lt_of_le (mem.1 hk).2 hml), decide_True]
theorem filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : ((Ico n m).filter fun x => x < l) = [] :=
filter_eq_nil.2 fun k hk => by
simp only [decide_eq_true_eq, not_lt]
apply le_trans hln
exact (mem.1 hk).1
theorem filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) :
((Ico n m).filter fun x => x < l) = Ico n l := by
rcases le_total n l with hnl | hln
· rw [← append_consecutive hnl hlm, filter_append, filter_lt_of_top_le (le_refl l),
filter_lt_of_le_bot (le_refl l), append_nil]
· rw [eq_nil_of_le hln, filter_lt_of_le_bot hln]
@[simp]
theorem filter_lt (n m l : ℕ) :
((Ico n m).filter fun x => x < l) = Ico n (min m l) := by
rcases le_total m l with hml | hlm
· rw [min_eq_left hml, filter_lt_of_top_le hml]
· rw [min_eq_right hlm, filter_lt_of_ge hlm]
theorem filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) :
((Ico n m).filter fun x => l ≤ x) = Ico n m :=
filter_eq_self.2 fun k hk => by
rw [decide_eq_true_eq]
exact le_trans hln (mem.1 hk).1
theorem filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : ((Ico n m).filter fun x => l ≤ x) = [] :=
filter_eq_nil.2 fun k hk => by
rw [decide_eq_true_eq]
exact not_le_of_gt (lt_of_lt_of_le (mem.1 hk).2 hml)
theorem filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) :
((Ico n m).filter fun x => l ≤ x) = Ico l m := by
rcases le_total l m with hlm | hml
· rw [← append_consecutive hnl hlm, filter_append, filter_le_of_top_le (le_refl l),
filter_le_of_le_bot (le_refl l), nil_append]
· rw [eq_nil_of_le hml, filter_le_of_top_le hml]
@[simp]
theorem filter_le (n m l : ℕ) : ((Ico n m).filter fun x => l ≤ x) = Ico (max n l) m := by
rcases le_total n l with hnl | hln
· rw [max_eq_right hnl, filter_le_of_le hnl]
· rw [max_eq_left hln, filter_le_of_le_bot hln]
theorem filter_lt_of_succ_bot {n m : ℕ} (hnm : n < m) :
((Ico n m).filter fun x => x < n + 1) = [n] := by
have r : min m (n + 1) = n + 1 := (@inf_eq_right _ _ m (n + 1)).mpr hnm
simp [filter_lt n m (n + 1), r]
@[simp]
theorem filter_le_of_bot {n m : ℕ} (hnm : n < m) : ((Ico n m).filter fun x => x ≤ n) = [n] := by
rw [← filter_lt_of_succ_bot hnm]
exact filter_congr fun _ _ => by
simpa using Nat.lt_succ_iff.symm
/-- For any natural numbers n, a, and b, one of the following holds:
1. n < a
2. n ≥ b
3. n ∈ Ico a b
-/
theorem trichotomy (n a b : ℕ) : n < a ∨ b ≤ n ∨ n ∈ Ico a b := by
by_cases h₁ : n < a
· left
exact h₁
· right
by_cases h₂ : n ∈ Ico a b
· right
exact h₂
· left
simp only [Ico.mem, not_and, not_lt] at *
exact h₂ h₁
end Ico
end List
|
Data\List\Iterate.lean | /-
Copyright (c) 2024 Miyahara Kō. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Miyahara Kō
-/
import Mathlib.Algebra.Order.Ring.Nat
import Mathlib.Data.List.Defs
import Mathlib.Data.Set.Function
/-!
# iterate
Proves various lemmas about `List.iterate`.
-/
variable {α : Type*}
namespace List
@[simp]
theorem length_iterate (f : α → α) (a : α) (n : ℕ) : length (iterate f a n) = n := by
induction n generalizing a <;> simp [*]
@[simp]
theorem iterate_eq_nil {f : α → α} {a : α} {n : ℕ} : iterate f a n = [] ↔ n = 0 := by
rw [← length_eq_zero, length_iterate]
theorem getElem?_iterate (f : α → α) (a : α) :
∀ (n i : ℕ), i < n → (iterate f a n)[i]? = f^[i] a
| n + 1, 0 , _ => by simp
| n + 1, i + 1, h => by simp [getElem?_iterate f (f a) n i (by simpa using h)]
theorem get?_iterate (f : α → α) (a : α) (n i : ℕ) (h : i < n) :
get? (iterate f a n) i = f^[i] a := by
simp only [get?_eq_getElem?, length_iterate, h, Option.some.injEq, getElem?_iterate]
@[simp]
theorem getElem_iterate (f : α → α) (a : α) (n : ℕ) (i : Nat) (h : i < (iterate f a n).length) :
(iterate f a n)[i] = f^[↑i] a :=
(get?_eq_some.1 <| get?_iterate f a n i (by simpa using h)).2
theorem get_iterate (f : α → α) (a : α) (n : ℕ) (i : Fin (iterate f a n).length) :
get (iterate f a n) i = f^[↑i] a := by
simp
@[simp]
theorem mem_iterate {f : α → α} {a : α} {n : ℕ} {b : α} :
b ∈ iterate f a n ↔ ∃ m < n, b = f^[m] a := by
simp [List.mem_iff_get, Fin.exists_iff, eq_comm (b := b)]
@[simp]
theorem range_map_iterate (n : ℕ) (f : α → α) (a : α) :
(List.range n).map (f^[·] a) = List.iterate f a n := by
apply List.ext_get <;> simp
theorem iterate_add (f : α → α) (a : α) (m n : ℕ) :
iterate f a (m + n) = iterate f a m ++ iterate f (f^[m] a) n := by
induction m generalizing a with
| zero => simp
| succ n ih => rw [iterate, add_right_comm, iterate, ih, Nat.iterate, cons_append]
theorem take_iterate (f : α → α) (a : α) (m n : ℕ) :
take m (iterate f a n) = iterate f a (min m n) := by
rw [← range_map_iterate, ← range_map_iterate, ← map_take, take_range]
end List
|
Data\List\Join.lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Floris van Doorn, Mario Carneiro, Martin Dvorak
-/
import Mathlib.Data.List.Basic
/-!
# Join of a list of lists
This file proves basic properties of `List.join`, which concatenates a list of lists. It is defined
in `Init.Data.List.Basic`.
-/
-- Make sure we don't import algebra
assert_not_exists Monoid
variable {α β : Type*}
namespace List
-- Porting note (#10618): simp can prove this
-- @[simp]
theorem join_singleton (l : List α) : [l].join = l := by rw [join, join, append_nil]
@[deprecated join_eq_nil_iff (since := "2024-07-10")]
theorem join_eq_nil : ∀ {L : List (List α)}, join L = [] ↔ ∀ l ∈ L, l = [] := join_eq_nil_iff
@[simp]
theorem join_filter_not_isEmpty :
∀ {L : List (List α)}, join (L.filter fun l => !l.isEmpty) = L.join
| [] => rfl
| [] :: L => by
simp [join_filter_not_isEmpty (L := L), isEmpty_iff_eq_nil]
| (a :: l) :: L => by
simp [join_filter_not_isEmpty (L := L)]
@[deprecated (since := "2024-02-25")] alias join_filter_isEmpty_eq_false := join_filter_not_isEmpty
@[simp]
theorem join_filter_ne_nil [DecidablePred fun l : List α => l ≠ []] {L : List (List α)} :
join (L.filter fun l => l ≠ []) = L.join := by
simp only [ne_eq, ← isEmpty_iff_eq_nil, Bool.not_eq_true, Bool.decide_eq_false,
join_filter_not_isEmpty]
/-- See `List.length_join` for the corresponding statement using `List.sum`. -/
lemma length_join' (L : List (List α)) : length (join L) = Nat.sum (map length L) := by
induction L <;> [rfl; simp only [*, join, map, Nat.sum_cons, length_append]]
/-- See `List.countP_join` for the corresponding statement using `List.sum`. -/
lemma countP_join' (p : α → Bool) :
∀ L : List (List α), countP p L.join = Nat.sum (L.map (countP p))
| [] => rfl
| a :: l => by rw [join, countP_append, map_cons, Nat.sum_cons, countP_join' _ l]
/-- See `List.count_join` for the corresponding statement using `List.sum`. -/
lemma count_join' [BEq α] (L : List (List α)) (a : α) :
L.join.count a = Nat.sum (L.map (count a)) := countP_join' _ _
/-- See `List.length_bind` for the corresponding statement using `List.sum`. -/
lemma length_bind' (l : List α) (f : α → List β) :
length (l.bind f) = Nat.sum (map (length ∘ f) l) := by rw [List.bind, length_join', map_map]
/-- See `List.countP_bind` for the corresponding statement using `List.sum`. -/
lemma countP_bind' (p : β → Bool) (l : List α) (f : α → List β) :
countP p (l.bind f) = Nat.sum (map (countP p ∘ f) l) := by rw [List.bind, countP_join', map_map]
/-- See `List.count_bind` for the corresponding statement using `List.sum`. -/
lemma count_bind' [BEq β] (l : List α) (f : α → List β) (x : β) :
count x (l.bind f) = Nat.sum (map (count x ∘ f) l) := countP_bind' _ _ _
@[simp]
theorem bind_eq_nil {l : List α} {f : α → List β} : List.bind l f = [] ↔ ∀ x ∈ l, f x = [] :=
join_eq_nil_iff.trans <| by
simp only [mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂]
/-- In a join, taking the first elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join of the first `i` sublists.
See `List.take_sum_join` for the corresponding statement using `List.sum`. -/
theorem take_sum_join' (L : List (List α)) (i : ℕ) :
L.join.take (Nat.sum ((L.map length).take i)) = (L.take i).join := by
induction L generalizing i
· simp
· cases i <;> simp [take_append, *]
/-- In a join, dropping all the elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join after dropping the first `i` sublists.
See `List.drop_sum_join` for the corresponding statement using `List.sum`. -/
theorem drop_sum_join' (L : List (List α)) (i : ℕ) :
L.join.drop (Nat.sum ((L.map length).take i)) = (L.drop i).join := by
induction L generalizing i
· simp
· cases i <;> simp [drop_append, *]
/-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is
left with a list of length `1` made of the `i`-th element of the original list. -/
theorem drop_take_succ_eq_cons_getElem (L : List α) (i : Nat) (h : i < L.length) :
(L.take (i + 1)).drop i = [L[i]] := by
induction' L with head tail ih generalizing i
· exact (Nat.not_succ_le_zero i h).elim
rcases i with _ | i
· simp
· simpa using ih _ (by simpa using h)
@[deprecated drop_take_succ_eq_cons_getElem (since := "2024-06-11")]
theorem drop_take_succ_eq_cons_get (L : List α) (i : Fin L.length) :
(L.take (i + 1)).drop i = [get L i] := by
simp [drop_take_succ_eq_cons_getElem]
set_option linter.deprecated false in
/-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is
left with a list of length `1` made of the `i`-th element of the original list. -/
@[deprecated drop_take_succ_eq_cons_get (since := "2023-01-10")]
theorem drop_take_succ_eq_cons_nthLe (L : List α) {i : ℕ} (hi : i < L.length) :
(L.take (i + 1)).drop i = [nthLe L i hi] := by
induction' L with head tail generalizing i
· simp only [length] at hi
exact (Nat.not_succ_le_zero i hi).elim
cases' i with i hi
· simp
rfl
have : i < tail.length := by simpa using hi
simp [*]
rfl
/-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the
original sublist of index `i` if `A` is the sum of the lengths of sublists of index `< i`, and
`B` is the sum of the lengths of sublists of index `≤ i`.
See `List.drop_take_succ_join_eq_getElem` for the corresponding statement using `List.sum`. -/
theorem drop_take_succ_join_eq_getElem' (L : List (List α)) (i : Nat) (h : i < L.length) :
(L.join.take (Nat.sum ((L.map length).take (i + 1)))).drop (Nat.sum ((L.map length).take i)) =
L[i] := by
have : (L.map length).take i = ((L.take (i + 1)).map length).take i := by
simp [map_take, take_take, Nat.min_eq_left]
simp only [this, length_map, take_sum_join', drop_sum_join', drop_take_succ_eq_cons_getElem, h,
join, append_nil]
@[deprecated drop_take_succ_join_eq_getElem' (since := "2024-06-11")]
theorem drop_take_succ_join_eq_get' (L : List (List α)) (i : Fin L.length) :
(L.join.take (Nat.sum ((L.map length).take (i + 1)))).drop (Nat.sum ((L.map length).take i)) =
get L i := by
simp [drop_take_succ_join_eq_getElem']
/-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the
sublists. -/
theorem eq_iff_join_eq (L L' : List (List α)) :
L = L' ↔ L.join = L'.join ∧ map length L = map length L' := by
refine ⟨fun H => by simp [H], ?_⟩
rintro ⟨join_eq, length_eq⟩
apply ext_getElem
· have : length (map length L) = length (map length L') := by rw [length_eq]
simpa using this
· intro n h₁ h₂
rw [← drop_take_succ_join_eq_getElem', ← drop_take_succ_join_eq_getElem', join_eq, length_eq]
theorem join_drop_length_sub_one {L : List (List α)} (h : L ≠ []) :
(L.drop (L.length - 1)).join = L.getLast h := by
induction L using List.reverseRecOn
· cases h rfl
· simp
/-- We can rebracket `x ++ (l₁ ++ x) ++ (l₂ ++ x) ++ ... ++ (lₙ ++ x)` to
`(x ++ l₁) ++ (x ++ l₂) ++ ... ++ (x ++ lₙ) ++ x` where `L = [l₁, l₂, ..., lₙ]`. -/
theorem append_join_map_append (L : List (List α)) (x : List α) :
x ++ (L.map (· ++ x)).join = (L.map (x ++ ·)).join ++ x := by
induction' L with _ _ ih
· rw [map_nil, join, append_nil, map_nil, join, nil_append]
· rw [map_cons, join, map_cons, join, append_assoc, ih, append_assoc, append_assoc]
/-- Any member of `L : List (List α))` is a sublist of `L.join` -/
lemma sublist_join (L : List (List α)) {s : List α} (hs : s ∈ L) :
s.Sublist L.join := by
induction L with
| nil =>
exfalso
exact not_mem_nil s hs
| cons t m ht =>
cases mem_cons.mp hs with
| inl h =>
rw [h]
simp only [join_cons, sublist_append_left]
| inr h =>
simp only [join_cons]
exact sublist_append_of_sublist_right (ht h)
end List
|
Data\List\Lattice.lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro,
Scott Morrison
-/
import Mathlib.Data.List.Basic
/-!
# Lattice structure of lists
This files prove basic properties about `List.disjoint`, `List.union`, `List.inter` and
`List.bagInter`, which are defined in core Lean and `Data.List.Defs`.
`l₁ ∪ l₂` is the list where all elements of `l₁` have been inserted in `l₂` in order. For example,
`[0, 0, 1, 2, 2, 3] ∪ [4, 3, 3, 0] = [1, 2, 4, 3, 3, 0]`
`l₁ ∩ l₂` is the list of elements of `l₁` in order which are in `l₂`. For example,
`[0, 0, 1, 2, 2, 3] ∪ [4, 3, 3, 0] = [0, 0, 3]`
`List.bagInter l₁ l₂` is the list of elements that are in both `l₁` and `l₂`,
counted with multiplicity and in the order they appear in `l₁`.
As opposed to `List.inter`, `List.bagInter` copes well with multiplicity. For example,
`bagInter [0, 1, 2, 3, 2, 1, 0] [1, 0, 1, 4, 3] = [0, 1, 3, 1]`
-/
open Nat
namespace List
variable {α : Type*} {l l₁ l₂ : List α} {p : α → Prop} {a : α}
/-! ### `Disjoint` -/
section Disjoint
@[symm]
theorem Disjoint.symm (d : Disjoint l₁ l₂) : Disjoint l₂ l₁ := fun _ i₂ i₁ => d i₁ i₂
end Disjoint
variable [DecidableEq α]
/-! ### `union` -/
section Union
theorem mem_union_left (h : a ∈ l₁) (l₂ : List α) : a ∈ l₁ ∪ l₂ :=
mem_union_iff.2 (Or.inl h)
theorem mem_union_right (l₁ : List α) (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ :=
mem_union_iff.2 (Or.inr h)
theorem sublist_suffix_of_union : ∀ l₁ l₂ : List α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂
| [], l₂ => ⟨[], by rfl, rfl⟩
| a :: l₁, l₂ =>
let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂
if h : a ∈ l₁ ∪ l₂ then
⟨t, sublist_cons_of_sublist _ s, by
simp only [e, cons_union, insert_of_mem h]⟩
else
⟨a :: t, s.cons_cons _, by
simp only [cons_append, cons_union, e, insert_of_not_mem h]⟩
theorem suffix_union_right (l₁ l₂ : List α) : l₂ <:+ l₁ ∪ l₂ :=
(sublist_suffix_of_union l₁ l₂).imp fun _ => And.right
theorem union_sublist_append (l₁ l₂ : List α) : l₁ ∪ l₂ <+ l₁ ++ l₂ :=
let ⟨_, s, e⟩ := sublist_suffix_of_union l₁ l₂
e ▸ (append_sublist_append_right _).2 s
theorem forall_mem_union : (∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ ∀ x ∈ l₂, p x := by
simp only [mem_union_iff, or_imp, forall_and]
theorem forall_mem_of_forall_mem_union_left (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x :=
(forall_mem_union.1 h).1
theorem forall_mem_of_forall_mem_union_right (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x :=
(forall_mem_union.1 h).2
theorem Subset.union_eq_right {xs ys : List α} (h : xs ⊆ ys) : xs ∪ ys = ys := by
induction xs with
| nil => simp
| cons x xs ih =>
rw [cons_union, insert_of_mem <| mem_union_right _ <| h <| mem_cons_self _ _,
ih <| subset_of_cons_subset h]
end Union
/-! ### `inter` -/
section Inter
@[simp]
theorem inter_nil (l : List α) : [] ∩ l = [] :=
rfl
@[simp]
theorem inter_cons_of_mem (l₁ : List α) (h : a ∈ l₂) : (a :: l₁) ∩ l₂ = a :: l₁ ∩ l₂ := by
simp [Inter.inter, List.inter, h]
@[simp]
theorem inter_cons_of_not_mem (l₁ : List α) (h : a ∉ l₂) : (a :: l₁) ∩ l₂ = l₁ ∩ l₂ := by
simp [Inter.inter, List.inter, h]
@[simp]
theorem inter_nil' (l : List α) : l ∩ [] = [] := by
induction l with
| nil => rfl
| cons x xs ih => by_cases x ∈ xs <;> simp [ih]
theorem mem_of_mem_inter_left : a ∈ l₁ ∩ l₂ → a ∈ l₁ :=
mem_of_mem_filter
theorem mem_of_mem_inter_right (h : a ∈ l₁ ∩ l₂) : a ∈ l₂ := by simpa using of_mem_filter h
theorem mem_inter_of_mem_of_mem (h₁ : a ∈ l₁) (h₂ : a ∈ l₂) : a ∈ l₁ ∩ l₂ :=
mem_filter_of_mem h₁ <| by simpa using h₂
theorem inter_subset_left {l₁ l₂ : List α} : l₁ ∩ l₂ ⊆ l₁ :=
filter_subset' _
theorem inter_subset_right {l₁ l₂ : List α} : l₁ ∩ l₂ ⊆ l₂ := fun _ => mem_of_mem_inter_right
theorem subset_inter {l l₁ l₂ : List α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ := fun _ h =>
mem_inter_iff.2 ⟨h₁ h, h₂ h⟩
theorem inter_eq_nil_iff_disjoint : l₁ ∩ l₂ = [] ↔ Disjoint l₁ l₂ := by
simp only [eq_nil_iff_forall_not_mem, mem_inter_iff, not_and]
rfl
alias ⟨_, Disjoint.inter_eq_nil⟩ := inter_eq_nil_iff_disjoint
theorem forall_mem_inter_of_forall_left (h : ∀ x ∈ l₁, p x) (l₂ : List α) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
BAll.imp_left (fun _ => mem_of_mem_inter_left) h
theorem forall_mem_inter_of_forall_right (l₁ : List α) (h : ∀ x ∈ l₂, p x) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
BAll.imp_left (fun _ => mem_of_mem_inter_right) h
@[simp]
theorem inter_reverse {xs ys : List α} : xs.inter ys.reverse = xs.inter ys := by
simp only [List.inter, elem_eq_mem, mem_reverse]
theorem Subset.inter_eq_left {xs ys : List α} (h : xs ⊆ ys) : xs ∩ ys = xs :=
List.filter_eq_self.mpr fun _ ha => elem_eq_true_of_mem (h ha)
end Inter
/-! ### `bagInter` -/
section BagInter
@[simp]
theorem nil_bagInter (l : List α) : [].bagInter l = [] := by cases l <;> rfl
@[simp]
theorem bagInter_nil (l : List α) : l.bagInter [] = [] := by cases l <;> rfl
@[simp]
theorem cons_bagInter_of_pos (l₁ : List α) (h : a ∈ l₂) :
(a :: l₁).bagInter l₂ = a :: l₁.bagInter (l₂.erase a) := by
cases l₂
· exact if_pos h
· simp only [List.bagInter, if_pos (elem_eq_true_of_mem h)]
@[simp]
theorem cons_bagInter_of_neg (l₁ : List α) (h : a ∉ l₂) :
(a :: l₁).bagInter l₂ = l₁.bagInter l₂ := by
cases l₂; · simp only [bagInter_nil]
simp only [erase_of_not_mem h, List.bagInter, if_neg (mt mem_of_elem_eq_true h)]
@[simp]
theorem mem_bagInter {a : α} : ∀ {l₁ l₂ : List α}, a ∈ l₁.bagInter l₂ ↔ a ∈ l₁ ∧ a ∈ l₂
| [], l₂ => by simp only [nil_bagInter, not_mem_nil, false_and_iff]
| b :: l₁, l₂ => by
by_cases h : b ∈ l₂
· rw [cons_bagInter_of_pos _ h, mem_cons, mem_cons, mem_bagInter]
by_cases ba : a = b
· simp only [ba, h, eq_self_iff_true, true_or_iff, true_and_iff]
· simp only [mem_erase_of_ne ba, ba, false_or_iff]
· rw [cons_bagInter_of_neg _ h, mem_bagInter, mem_cons, or_and_right]
symm
apply or_iff_right_of_imp
rintro ⟨rfl, h'⟩
exact h.elim h'
@[simp]
theorem count_bagInter {a : α} :
∀ {l₁ l₂ : List α}, count a (l₁.bagInter l₂) = min (count a l₁) (count a l₂)
| [], l₂ => by simp
| l₁, [] => by simp
| b :: l₁, l₂ => by
by_cases hb : b ∈ l₂
· rw [cons_bagInter_of_pos _ hb, count_cons, count_cons, count_bagInter, count_erase,
← Nat.add_min_add_right]
by_cases ba : b = a
· simp only [beq_iff_eq]
rw [if_pos ba, Nat.sub_add_cancel]
rwa [succ_le_iff, count_pos_iff_mem, ← ba]
· simp only [beq_iff_eq]
rw [if_neg ba, Nat.sub_zero, Nat.add_zero, Nat.add_zero]
· rw [cons_bagInter_of_neg _ hb, count_bagInter]
by_cases ab : a = b
· rw [← ab] at hb
rw [count_eq_zero.2 hb, Nat.min_zero, Nat.min_zero]
· rw [count_cons_of_ne ab]
theorem bagInter_sublist_left : ∀ l₁ l₂ : List α, l₁.bagInter l₂ <+ l₁
| [], l₂ => by simp
| b :: l₁, l₂ => by
by_cases h : b ∈ l₂ <;> simp only [h, cons_bagInter_of_pos, cons_bagInter_of_neg, not_false_iff]
· exact (bagInter_sublist_left _ _).cons_cons _
· apply sublist_cons_of_sublist
apply bagInter_sublist_left
theorem bagInter_nil_iff_inter_nil : ∀ l₁ l₂ : List α, l₁.bagInter l₂ = [] ↔ l₁ ∩ l₂ = []
| [], l₂ => by simp
| b :: l₁, l₂ => by
by_cases h : b ∈ l₂
· simp [h]
· simpa [h] using bagInter_nil_iff_inter_nil l₁ l₂
end BagInter
end List
|
Data\List\Lemmas.lean | /-
Copyright (c) 2021 Yakov Pechersky. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky, Yury Kudryashov
-/
import Mathlib.Data.Set.Image
import Mathlib.Data.List.InsertNth
import Mathlib.Init.Data.List.Lemmas
/-! # Some lemmas about lists involving sets
Split out from `Data.List.Basic` to reduce its dependencies.
-/
open List
variable {α β γ : Type*}
namespace List
theorem injOn_insertNth_index_of_not_mem (l : List α) (x : α) (hx : x ∉ l) :
Set.InjOn (fun k => insertNth k x l) { n | n ≤ l.length } := by
induction' l with hd tl IH
· intro n hn m hm _
simp only [Set.mem_singleton_iff, Set.setOf_eq_eq_singleton,
length] at hn hm
simp_all [hn, hm]
· intro n hn m hm h
simp only [length, Set.mem_setOf_eq] at hn hm
simp only [mem_cons, not_or] at hx
cases n <;> cases m
· rfl
· simp [hx.left] at h
· simp [Ne.symm hx.left] at h
· simp only [true_and_iff, eq_self_iff_true, insertNth_succ_cons] at h
rw [Nat.succ_inj']
refine IH hx.right ?_ ?_ (by injection h)
· simpa [Nat.succ_le_succ_iff] using hn
· simpa [Nat.succ_le_succ_iff] using hm
theorem foldr_range_subset_of_range_subset {f : β → α → α} {g : γ → α → α}
(hfg : Set.range f ⊆ Set.range g) (a : α) : Set.range (foldr f a) ⊆ Set.range (foldr g a) := by
rintro _ ⟨l, rfl⟩
induction' l with b l H
· exact ⟨[], rfl⟩
· cases' hfg (Set.mem_range_self b) with c hgf
cases' H with m hgf'
rw [foldr_cons, ← hgf, ← hgf']
exact ⟨c :: m, rfl⟩
theorem foldl_range_subset_of_range_subset {f : α → β → α} {g : α → γ → α}
(hfg : (Set.range fun a c => f c a) ⊆ Set.range fun b c => g c b) (a : α) :
Set.range (foldl f a) ⊆ Set.range (foldl g a) := by
change (Set.range fun l => _) ⊆ Set.range fun l => _
-- Porting note: This was simply `simp_rw [← foldr_reverse]`
simp_rw [← foldr_reverse _ (fun z w => g w z), ← foldr_reverse _ (fun z w => f w z)]
-- Porting note: This `change` was not necessary in mathlib3
change (Set.range (foldr (fun z w => f w z) a ∘ reverse)) ⊆
Set.range (foldr (fun z w => g w z) a ∘ reverse)
simp_rw [Set.range_comp _ reverse, reverse_involutive.bijective.surjective.range_eq,
Set.image_univ]
exact foldr_range_subset_of_range_subset hfg a
theorem foldr_range_eq_of_range_eq {f : β → α → α} {g : γ → α → α} (hfg : Set.range f = Set.range g)
(a : α) : Set.range (foldr f a) = Set.range (foldr g a) :=
(foldr_range_subset_of_range_subset hfg.le a).antisymm
(foldr_range_subset_of_range_subset hfg.ge a)
theorem foldl_range_eq_of_range_eq {f : α → β → α} {g : α → γ → α}
(hfg : (Set.range fun a c => f c a) = Set.range fun b c => g c b) (a : α) :
Set.range (foldl f a) = Set.range (foldl g a) :=
(foldl_range_subset_of_range_subset hfg.le a).antisymm
(foldl_range_subset_of_range_subset hfg.ge a)
/-!
### MapAccumr and Foldr
Some lemmas relation `mapAccumr` and `foldr`
-/
section MapAccumr
theorem mapAccumr_eq_foldr {σ : Type*} (f : α → σ → σ × β) : ∀ (as : List α) (s : σ),
mapAccumr f as s = List.foldr (fun a s =>
let r := f a s.1
(r.1, r.2 :: s.2)
) (s, []) as
| [], s => rfl
| a :: as, s => by
simp only [mapAccumr, foldr, mapAccumr_eq_foldr f as]
theorem mapAccumr₂_eq_foldr {σ φ : Type*} (f : α → β → σ → σ × φ) :
∀ (as : List α) (bs : List β) (s : σ),
mapAccumr₂ f as bs s = foldr (fun ab s =>
let r := f ab.1 ab.2 s.1
(r.1, r.2 :: s.2)
) (s, []) (as.zip bs)
| [], [], s => rfl
| a :: as, [], s => rfl
| [], b :: bs, s => rfl
| a :: as, b :: bs, s => by
simp only [mapAccumr₂, foldr, mapAccumr₂_eq_foldr f as]
rfl
end MapAccumr
end List
|
Data\List\Lex.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Order.RelClasses
import Mathlib.Data.List.Basic
/-!
# Lexicographic ordering of lists.
The lexicographic order on `List α` is defined by `L < M` iff
* `[] < (a :: L)` for any `a` and `L`,
* `(a :: L) < (b :: M)` where `a < b`, or
* `(a :: L) < (a :: M)` where `L < M`.
## See also
Related files are:
* `Mathlib.Data.Finset.Colex`: Colexicographic order on finite sets.
* `Mathlib.Data.PSigma.Order`: Lexicographic order on `Σ' i, α i`.
* `Mathlib.Data.Pi.Lex`: Lexicographic order on `Πₗ i, α i`.
* `Mathlib.Data.Sigma.Order`: Lexicographic order on `Σ i, α i`.
* `Mathlib.Data.Prod.Lex`: Lexicographic order on `α × β`.
-/
namespace List
open Nat
universe u
variable {α : Type u}
/-! ### lexicographic ordering -/
/-- Given a strict order `<` on `α`, the lexicographic strict order on `List α`, for which
`[a0, ..., an] < [b0, ..., b_k]` if `a0 < b0` or `a0 = b0` and `[a1, ..., an] < [b1, ..., bk]`.
The definition is given for any relation `r`, not only strict orders. -/
inductive Lex (r : α → α → Prop) : List α → List α → Prop
| nil {a l} : Lex r [] (a :: l)
| cons {a l₁ l₂} (h : Lex r l₁ l₂) : Lex r (a :: l₁) (a :: l₂)
| rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : Lex r (a₁ :: l₁) (a₂ :: l₂)
namespace Lex
theorem cons_iff {r : α → α → Prop} [IsIrrefl α r] {a l₁ l₂} :
Lex r (a :: l₁) (a :: l₂) ↔ Lex r l₁ l₂ :=
⟨fun h => by cases' h with _ _ _ _ _ h _ _ _ _ h; exacts [h, (irrefl_of r a h).elim], Lex.cons⟩
@[simp]
theorem not_nil_right (r : α → α → Prop) (l : List α) : ¬Lex r l [] :=
nofun
theorem nil_left_or_eq_nil {r : α → α → Prop} (l : List α) : List.Lex r [] l ∨ l = [] :=
match l with
| [] => Or.inr rfl
| (_ :: _) => Or.inl nil
@[simp]
theorem singleton_iff {r : α → α → Prop} (a b : α) : List.Lex r [a] [b] ↔ r a b :=
⟨fun | rel h => h, List.Lex.rel⟩
instance isOrderConnected (r : α → α → Prop) [IsOrderConnected α r] [IsTrichotomous α r] :
IsOrderConnected (List α) (Lex r) where
conn := aux where
aux
| _, [], c :: l₃, nil => Or.inr nil
| _, [], c :: l₃, rel _ => Or.inr nil
| _, [], c :: l₃, cons _ => Or.inr nil
| _, b :: l₂, c :: l₃, nil => Or.inl nil
| a :: l₁, b :: l₂, c :: l₃, rel h => (IsOrderConnected.conn _ b _ h).imp rel rel
| a :: l₁, b :: l₂, _ :: l₃, cons h => by
rcases trichotomous_of r a b with (ab | rfl | ab)
· exact Or.inl (rel ab)
· exact (aux _ l₂ _ h).imp cons cons
· exact Or.inr (rel ab)
instance isTrichotomous (r : α → α → Prop) [IsTrichotomous α r] :
IsTrichotomous (List α) (Lex r) where
trichotomous := aux where
aux
| [], [] => Or.inr (Or.inl rfl)
| [], b :: l₂ => Or.inl nil
| a :: l₁, [] => Or.inr (Or.inr nil)
| a :: l₁, b :: l₂ => by
rcases trichotomous_of r a b with (ab | rfl | ab)
· exact Or.inl (rel ab)
· exact (aux l₁ l₂).imp cons (Or.imp (congr_arg _) cons)
· exact Or.inr (Or.inr (rel ab))
instance isAsymm (r : α → α → Prop) [IsAsymm α r] : IsAsymm (List α) (Lex r) where
asymm := aux where
aux
| _, _, Lex.rel h₁, Lex.rel h₂ => asymm h₁ h₂
| _, _, Lex.rel h₁, Lex.cons _ => asymm h₁ h₁
| _, _, Lex.cons _, Lex.rel h₂ => asymm h₂ h₂
| _, _, Lex.cons h₁, Lex.cons h₂ => aux _ _ h₁ h₂
instance isStrictTotalOrder (r : α → α → Prop) [IsStrictTotalOrder α r] :
IsStrictTotalOrder (List α) (Lex r) :=
{ isStrictWeakOrder_of_isOrderConnected with }
instance decidableRel [DecidableEq α] (r : α → α → Prop) [DecidableRel r] : DecidableRel (Lex r)
| l₁, [] => isFalse fun h => by cases h
| [], b :: l₂ => isTrue Lex.nil
| a :: l₁, b :: l₂ => by
haveI := decidableRel r l₁ l₂
refine decidable_of_iff (r a b ∨ a = b ∧ Lex r l₁ l₂) ⟨fun h => ?_, fun h => ?_⟩
· rcases h with (h | ⟨rfl, h⟩)
· exact Lex.rel h
· exact Lex.cons h
· rcases h with (_ | h | h)
· exact Or.inr ⟨rfl, h⟩
· exact Or.inl h
theorem append_right (r : α → α → Prop) : ∀ {s₁ s₂} (t), Lex r s₁ s₂ → Lex r s₁ (s₂ ++ t)
| _, _, _, nil => nil
| _, _, _, cons h => cons (append_right r _ h)
| _, _, _, rel r => rel r
theorem append_left (R : α → α → Prop) {t₁ t₂} (h : Lex R t₁ t₂) : ∀ s, Lex R (s ++ t₁) (s ++ t₂)
| [] => h
| _ :: l => cons (append_left R h l)
theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) : ∀ l₁ l₂, Lex r l₁ l₂ → Lex s l₁ l₂
| _, _, nil => nil
| _, _, cons h => cons (imp H _ _ h)
| _, _, rel r => rel (H _ _ r)
theorem to_ne : ∀ {l₁ l₂ : List α}, Lex (· ≠ ·) l₁ l₂ → l₁ ≠ l₂
| _, _, cons h, e => to_ne h (List.cons.inj e).2
| _, _, rel r, e => r (List.cons.inj e).1
theorem _root_.Decidable.List.Lex.ne_iff [DecidableEq α] {l₁ l₂ : List α}
(H : length l₁ ≤ length l₂) : Lex (· ≠ ·) l₁ l₂ ↔ l₁ ≠ l₂ :=
⟨to_ne, fun h => by
induction' l₁ with a l₁ IH generalizing l₂ <;> cases' l₂ with b l₂
· contradiction
· apply nil
· exact (not_lt_of_ge H).elim (succ_pos _)
· by_cases ab : a = b
· subst b
apply cons
exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h)
· exact rel ab ⟩
theorem ne_iff {l₁ l₂ : List α} (H : length l₁ ≤ length l₂) : Lex (· ≠ ·) l₁ l₂ ↔ l₁ ≠ l₂ := by
classical
exact Decidable.List.Lex.ne_iff H
end Lex
--Note: this overrides an instance in core lean
instance LT' [LT α] : LT (List α) :=
⟨Lex (· < ·)⟩
theorem nil_lt_cons [LT α] (a : α) (l : List α) : [] < a :: l :=
Lex.nil
instance [LinearOrder α] : LinearOrder (List α) :=
linearOrderOfSTO (Lex (· < ·))
--Note: this overrides an instance in core lean
instance LE' [LinearOrder α] : LE (List α) :=
Preorder.toLE
theorem lt_iff_lex_lt [LinearOrder α] (l l' : List α) : lt l l' ↔ Lex (· < ·) l l' := by
constructor <;>
intro h
· induction h with
| nil b bs => exact Lex.nil
| @head a as b bs hab => apply Lex.rel; assumption
| @tail a as b bs hab hba _ ih =>
have heq : a = b := _root_.le_antisymm (le_of_not_lt hba) (le_of_not_lt hab)
subst b; apply Lex.cons; assumption
· induction h with
| @nil a as => apply lt.nil
| @cons a as bs _ ih => apply lt.tail <;> simp [ih]
| @rel a as b bs h => apply lt.head; assumption
@[simp]
theorem nil_le {α} [LinearOrder α] {l : List α} : [] ≤ l :=
match l with
| [] => le_rfl
| _ :: _ => le_of_lt <| nil_lt_cons _ _
theorem head_le_of_lt [Preorder α] {a a' : α} {l l' : List α} (h : (a' :: l') < (a :: l)) :
a' ≤ a :=
match h with
| .cons _ => le_rfl
| .rel h => h.le
theorem head!_le_of_lt [Preorder α] [Inhabited α] (l l' : List α) (h : l' < l) (hl' : l' ≠ []) :
l'.head! ≤ l.head! := by
replace h : List.Lex (· < ·) l' l := h
by_cases hl : l = []
· simp [hl] at h
· rw [← List.cons_head!_tail hl', ← List.cons_head!_tail hl] at h
exact head_le_of_lt h
theorem cons_le_cons [LinearOrder α] (a : α) {l l' : List α} (h : l' ≤ l) :
a :: l' ≤ a :: l := by
rw [le_iff_lt_or_eq] at h ⊢
exact h.imp .cons (congr_arg _)
end List
|
Data\List\MinMax.lean | /-
Copyright (c) 2019 Minchao Wu. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Minchao Wu, Chris Hughes, Mantas Bakšys
-/
import Mathlib.Data.List.Basic
import Mathlib.Order.MinMax
import Mathlib.Order.WithBot
/-!
# Minimum and maximum of lists
## Main definitions
The main definitions are `argmax`, `argmin`, `minimum` and `maximum` for lists.
`argmax f l` returns `some a`, where `a` of `l` that maximises `f a`. If there are `a b` such that
`f a = f b`, it returns whichever of `a` or `b` comes first in the list.
`argmax f [] = none`
`minimum l` returns a `WithTop α`, the smallest element of `l` for nonempty lists, and `⊤` for
`[]`
-/
namespace List
variable {α β : Type*}
section ArgAux
variable (r : α → α → Prop) [DecidableRel r] {l : List α} {o : Option α} {a m : α}
/-- Auxiliary definition for `argmax` and `argmin`. -/
def argAux (a : Option α) (b : α) : Option α :=
Option.casesOn a (some b) fun c => if r b c then some b else some c
@[simp]
theorem foldl_argAux_eq_none : l.foldl (argAux r) o = none ↔ l = [] ∧ o = none :=
List.reverseRecOn l (by simp) fun tl hd => by
simp only [foldl_append, foldl_cons, argAux, foldl_nil, append_eq_nil, and_false, false_and,
iff_false]
cases foldl (argAux r) o tl
· simp
· simp only [false_iff, not_and]
split_ifs <;> simp
private theorem foldl_argAux_mem (l) : ∀ a m : α, m ∈ foldl (argAux r) (some a) l → m ∈ a :: l :=
List.reverseRecOn l (by simp [eq_comm])
(by
intro tl hd ih a m
simp only [foldl_append, foldl_cons, foldl_nil, argAux]
cases hf : foldl (argAux r) (some a) tl
· simp (config := { contextual := true })
· dsimp only
split_ifs
· simp (config := { contextual := true })
· -- `finish [ih _ _ hf]` closes this goal
simp only [List.mem_cons] at ih
rcases ih _ _ hf with rfl | H
· simp (config := { contextual := true }) only [Option.mem_def, Option.some.injEq,
find?, eq_comm, mem_cons, mem_append, mem_singleton, true_or, implies_true]
· simp (config := { contextual := true }) [@eq_comm _ _ m, H])
@[simp]
theorem argAux_self (hr₀ : Irreflexive r) (a : α) : argAux r (some a) a = a :=
if_neg <| hr₀ _
theorem not_of_mem_foldl_argAux (hr₀ : Irreflexive r) (hr₁ : Transitive r) :
∀ {a m : α} {o : Option α}, a ∈ l → m ∈ foldl (argAux r) o l → ¬r a m := by
induction' l using List.reverseRecOn with tl a ih
· simp
intro b m o hb ho
rw [foldl_append, foldl_cons, foldl_nil, argAux] at ho
cases' hf : foldl (argAux r) o tl with c
· rw [hf] at ho
rw [foldl_argAux_eq_none] at hf
simp_all [hf.1, hf.2, hr₀ _]
rw [hf, Option.mem_def] at ho
dsimp only at ho
split_ifs at ho with hac <;> cases' mem_append.1 hb with h h <;>
injection ho with ho <;> subst ho
· exact fun hba => ih h hf (hr₁ hba hac)
· simp_all [hr₀ _]
· exact ih h hf
· simp_all
end ArgAux
section Preorder
variable [Preorder β] [@DecidableRel β (· < ·)] {f : α → β} {l : List α} {o : Option α} {a m : α}
/-- `argmax f l` returns `some a`, where `f a` is maximal among the elements of `l`, in the sense
that there is no `b ∈ l` with `f a < f b`. If `a`, `b` are such that `f a = f b`, it returns
whichever of `a` or `b` comes first in the list. `argmax f [] = none`. -/
def argmax (f : α → β) (l : List α) : Option α :=
l.foldl (argAux fun b c => f c < f b) none
/-- `argmin f l` returns `some a`, where `f a` is minimal among the elements of `l`, in the sense
that there is no `b ∈ l` with `f b < f a`. If `a`, `b` are such that `f a = f b`, it returns
whichever of `a` or `b` comes first in the list. `argmin f [] = none`. -/
def argmin (f : α → β) (l : List α) :=
l.foldl (argAux fun b c => f b < f c) none
@[simp]
theorem argmax_nil (f : α → β) : argmax f [] = none :=
rfl
@[simp]
theorem argmin_nil (f : α → β) : argmin f [] = none :=
rfl
@[simp]
theorem argmax_singleton {f : α → β} {a : α} : argmax f [a] = a :=
rfl
@[simp]
theorem argmin_singleton {f : α → β} {a : α} : argmin f [a] = a :=
rfl
theorem not_lt_of_mem_argmax : a ∈ l → m ∈ argmax f l → ¬f m < f a :=
not_of_mem_foldl_argAux _ (fun x h => lt_irrefl (f x) h)
(fun _ _ z hxy hyz => lt_trans (a := f z) hyz hxy)
theorem not_lt_of_mem_argmin : a ∈ l → m ∈ argmin f l → ¬f a < f m :=
not_of_mem_foldl_argAux _ (fun x h => lt_irrefl (f x) h)
(fun x _ _ hxy hyz => lt_trans (a := f x) hxy hyz)
theorem argmax_concat (f : α → β) (a : α) (l : List α) :
argmax f (l ++ [a]) =
Option.casesOn (argmax f l) (some a) fun c => if f c < f a then some a else some c := by
rw [argmax, argmax]; simp [argAux]
theorem argmin_concat (f : α → β) (a : α) (l : List α) :
argmin f (l ++ [a]) =
Option.casesOn (argmin f l) (some a) fun c => if f a < f c then some a else some c :=
@argmax_concat _ βᵒᵈ _ _ _ _ _
theorem argmax_mem : ∀ {l : List α} {m : α}, m ∈ argmax f l → m ∈ l
| [], m => by simp
| hd :: tl, m => by simpa [argmax, argAux] using foldl_argAux_mem _ tl hd m
theorem argmin_mem : ∀ {l : List α} {m : α}, m ∈ argmin f l → m ∈ l :=
@argmax_mem _ βᵒᵈ _ _ _
@[simp]
theorem argmax_eq_none : l.argmax f = none ↔ l = [] := by simp [argmax]
@[simp]
theorem argmin_eq_none : l.argmin f = none ↔ l = [] :=
@argmax_eq_none _ βᵒᵈ _ _ _ _
end Preorder
section LinearOrder
variable [LinearOrder β] {f : α → β} {l : List α} {o : Option α} {a m : α}
theorem le_of_mem_argmax : a ∈ l → m ∈ argmax f l → f a ≤ f m := fun ha hm =>
le_of_not_lt <| not_lt_of_mem_argmax ha hm
theorem le_of_mem_argmin : a ∈ l → m ∈ argmin f l → f m ≤ f a :=
@le_of_mem_argmax _ βᵒᵈ _ _ _ _ _
theorem argmax_cons (f : α → β) (a : α) (l : List α) :
argmax f (a :: l) =
Option.casesOn (argmax f l) (some a) fun c => if f a < f c then some c else some a :=
List.reverseRecOn l rfl fun hd tl ih => by
rw [← cons_append, argmax_concat, ih, argmax_concat]
cases' h : argmax f hd with m
· simp [h]
dsimp
rw [← apply_ite, ← apply_ite]
dsimp
split_ifs <;> try rfl
· exact absurd (lt_trans ‹f a < f m› ‹_›) ‹_›
· cases (‹f a < f tl›.lt_or_lt _).elim ‹_› ‹_›
theorem argmin_cons (f : α → β) (a : α) (l : List α) :
argmin f (a :: l) =
Option.casesOn (argmin f l) (some a) fun c => if f c < f a then some c else some a :=
@argmax_cons α βᵒᵈ _ _ _ _
variable [DecidableEq α]
theorem index_of_argmax :
∀ {l : List α} {m : α}, m ∈ argmax f l → ∀ {a}, a ∈ l → f m ≤ f a → l.indexOf m ≤ l.indexOf a
| [], m, _, _, _, _ => by simp
| hd :: tl, m, hm, a, ha, ham => by
simp only [indexOf_cons, argmax_cons, Option.mem_def] at hm ⊢
cases h : argmax f tl
· rw [h] at hm
simp_all
rw [h] at hm
dsimp only at hm
simp only [cond_eq_if, beq_iff_eq]
obtain ha | ha := ha <;> split_ifs at hm <;> injection hm with hm <;> subst hm
· cases not_le_of_lt ‹_› ‹_›
· rw [if_pos rfl]
· rw [if_neg, if_neg]
· exact Nat.succ_le_succ (index_of_argmax h (by assumption) ham)
· exact ne_of_apply_ne f (lt_of_lt_of_le ‹_› ‹_›).ne
· exact ne_of_apply_ne _ ‹f hd < f _›.ne
· rw [if_pos rfl]
exact Nat.zero_le _
theorem index_of_argmin :
∀ {l : List α} {m : α}, m ∈ argmin f l → ∀ {a}, a ∈ l → f a ≤ f m → l.indexOf m ≤ l.indexOf a :=
@index_of_argmax _ βᵒᵈ _ _ _
theorem mem_argmax_iff :
m ∈ argmax f l ↔
m ∈ l ∧ (∀ a ∈ l, f a ≤ f m) ∧ ∀ a ∈ l, f m ≤ f a → l.indexOf m ≤ l.indexOf a :=
⟨fun hm => ⟨argmax_mem hm, fun a ha => le_of_mem_argmax ha hm, fun _ => index_of_argmax hm⟩,
by
rintro ⟨hml, ham, hma⟩
cases' harg : argmax f l with n
· simp_all
· have :=
_root_.le_antisymm (hma n (argmax_mem harg) (le_of_mem_argmax hml harg))
(index_of_argmax harg hml (ham _ (argmax_mem harg)))
rw [(indexOf_inj hml (argmax_mem harg)).1 this, Option.mem_def]⟩
theorem argmax_eq_some_iff :
argmax f l = some m ↔
m ∈ l ∧ (∀ a ∈ l, f a ≤ f m) ∧ ∀ a ∈ l, f m ≤ f a → l.indexOf m ≤ l.indexOf a :=
mem_argmax_iff
theorem mem_argmin_iff :
m ∈ argmin f l ↔
m ∈ l ∧ (∀ a ∈ l, f m ≤ f a) ∧ ∀ a ∈ l, f a ≤ f m → l.indexOf m ≤ l.indexOf a :=
@mem_argmax_iff _ βᵒᵈ _ _ _ _ _
theorem argmin_eq_some_iff :
argmin f l = some m ↔
m ∈ l ∧ (∀ a ∈ l, f m ≤ f a) ∧ ∀ a ∈ l, f a ≤ f m → l.indexOf m ≤ l.indexOf a :=
mem_argmin_iff
end LinearOrder
section MaximumMinimum
section Preorder
variable [Preorder α] [@DecidableRel α (· < ·)] {l : List α} {a m : α}
/-- `maximum l` returns a `WithBot α`, the largest element of `l` for nonempty lists, and `⊥` for
`[]` -/
def maximum (l : List α) : WithBot α :=
argmax id l
/-- `minimum l` returns a `WithTop α`, the smallest element of `l` for nonempty lists, and `⊤` for
`[]` -/
def minimum (l : List α) : WithTop α :=
argmin id l
@[simp]
theorem maximum_nil : maximum ([] : List α) = ⊥ :=
rfl
@[simp]
theorem minimum_nil : minimum ([] : List α) = ⊤ :=
rfl
@[simp]
theorem maximum_singleton (a : α) : maximum [a] = a :=
rfl
@[simp]
theorem minimum_singleton (a : α) : minimum [a] = a :=
rfl
theorem maximum_mem {l : List α} {m : α} : (maximum l : WithTop α) = m → m ∈ l :=
argmax_mem
theorem minimum_mem {l : List α} {m : α} : (minimum l : WithBot α) = m → m ∈ l :=
argmin_mem
@[simp]
theorem maximum_eq_bot {l : List α} : l.maximum = ⊥ ↔ l = [] :=
argmax_eq_none
@[simp, deprecated maximum_eq_bot "Don't mix Option and WithBot" (since := "2024-05-27")]
theorem maximum_eq_none {l : List α} : l.maximum = none ↔ l = [] := maximum_eq_bot
@[simp]
theorem minimum_eq_top {l : List α} : l.minimum = ⊤ ↔ l = [] :=
argmin_eq_none
@[simp, deprecated minimum_eq_top "Don't mix Option and WithTop" (since := "2024-05-27")]
theorem minimum_eq_none {l : List α} : l.minimum = none ↔ l = [] := minimum_eq_top
theorem not_lt_maximum_of_mem : a ∈ l → (maximum l : WithBot α) = m → ¬m < a :=
not_lt_of_mem_argmax
theorem minimum_not_lt_of_mem : a ∈ l → (minimum l : WithTop α) = m → ¬a < m :=
not_lt_of_mem_argmin
theorem not_lt_maximum_of_mem' (ha : a ∈ l) : ¬maximum l < (a : WithBot α) := by
cases h : l.maximum
· simp_all
· simp [not_lt_maximum_of_mem ha h, not_false_iff]
theorem not_lt_minimum_of_mem' (ha : a ∈ l) : ¬(a : WithTop α) < minimum l :=
@not_lt_maximum_of_mem' αᵒᵈ _ _ _ _ ha
end Preorder
section LinearOrder
variable [LinearOrder α] {l : List α} {a m : α}
theorem maximum_concat (a : α) (l : List α) : maximum (l ++ [a]) = max (maximum l) a := by
simp only [maximum, argmax_concat, id]
cases argmax id l
· exact (max_eq_right bot_le).symm
· simp [WithBot.some_eq_coe, max_def_lt, WithBot.coe_lt_coe]
theorem le_maximum_of_mem : a ∈ l → (maximum l : WithBot α) = m → a ≤ m :=
le_of_mem_argmax
theorem minimum_le_of_mem : a ∈ l → (minimum l : WithTop α) = m → m ≤ a :=
le_of_mem_argmin
theorem le_maximum_of_mem' (ha : a ∈ l) : (a : WithBot α) ≤ maximum l :=
le_of_not_lt <| not_lt_maximum_of_mem' ha
theorem minimum_le_of_mem' (ha : a ∈ l) : minimum l ≤ (a : WithTop α) :=
@le_maximum_of_mem' αᵒᵈ _ _ _ ha
theorem minimum_concat (a : α) (l : List α) : minimum (l ++ [a]) = min (minimum l) a :=
@maximum_concat αᵒᵈ _ _ _
theorem maximum_cons (a : α) (l : List α) : maximum (a :: l) = max ↑a (maximum l) :=
List.reverseRecOn l (by simp [@max_eq_left (WithBot α) _ _ _ bot_le]) fun tl hd ih => by
rw [← cons_append, maximum_concat, ih, maximum_concat, max_assoc]
theorem minimum_cons (a : α) (l : List α) : minimum (a :: l) = min ↑a (minimum l) :=
@maximum_cons αᵒᵈ _ _ _
theorem maximum_le_of_forall_le {b : WithBot α} (h : ∀ a ∈ l, a ≤ b) : l.maximum ≤ b := by
induction l with
| nil => simp
| cons a l ih =>
simp only [maximum_cons, max_le_iff, WithBot.coe_le_coe]
exact ⟨h a (by simp), ih fun a w => h a (mem_cons.mpr (Or.inr w))⟩
theorem le_minimum_of_forall_le {b : WithTop α} (h : ∀ a ∈ l, b ≤ a) : b ≤ l.minimum :=
maximum_le_of_forall_le (α := αᵒᵈ) h
theorem maximum_eq_coe_iff : maximum l = m ↔ m ∈ l ∧ ∀ a ∈ l, a ≤ m := by
rw [maximum, ← WithBot.some_eq_coe, argmax_eq_some_iff]
simp only [id_eq, and_congr_right_iff, and_iff_left_iff_imp]
intro _ h a hal hma
rw [_root_.le_antisymm hma (h a hal)]
theorem minimum_eq_coe_iff : minimum l = m ↔ m ∈ l ∧ ∀ a ∈ l, m ≤ a :=
@maximum_eq_coe_iff αᵒᵈ _ _ _
theorem coe_le_maximum_iff : a ≤ l.maximum ↔ ∃ b, b ∈ l ∧ a ≤ b := by
induction l with
| nil => simp
| cons h t ih =>
simp [maximum_cons, ih]
theorem minimum_le_coe_iff : l.minimum ≤ a ↔ ∃ b, b ∈ l ∧ b ≤ a :=
coe_le_maximum_iff (α := αᵒᵈ)
theorem maximum_ne_bot_of_ne_nil (h : l ≠ []) : l.maximum ≠ ⊥ :=
match l, h with | _ :: _, _ => by simp [maximum_cons]
theorem minimum_ne_top_of_ne_nil (h : l ≠ []) : l.minimum ≠ ⊤ :=
@maximum_ne_bot_of_ne_nil αᵒᵈ _ _ h
theorem maximum_ne_bot_of_length_pos (h : 0 < l.length) : l.maximum ≠ ⊥ :=
match l, h with | _ :: _, _ => by simp [maximum_cons]
theorem minimum_ne_top_of_length_pos (h : 0 < l.length) : l.minimum ≠ ⊤ :=
maximum_ne_bot_of_length_pos (α := αᵒᵈ) h
/-- The maximum value in a non-empty `List`. -/
def maximum_of_length_pos (h : 0 < l.length) : α :=
WithBot.unbot l.maximum (maximum_ne_bot_of_length_pos h)
/-- The minimum value in a non-empty `List`. -/
def minimum_of_length_pos (h : 0 < l.length) : α :=
maximum_of_length_pos (α := αᵒᵈ) h
@[simp]
lemma coe_maximum_of_length_pos (h : 0 < l.length) :
(l.maximum_of_length_pos h : α) = l.maximum :=
WithBot.coe_unbot _ _
@[simp]
lemma coe_minimum_of_length_pos (h : 0 < l.length) :
(l.minimum_of_length_pos h : α) = l.minimum :=
WithTop.coe_untop _ _
@[simp]
theorem le_maximum_of_length_pos_iff {b : α} (h : 0 < l.length) :
b ≤ maximum_of_length_pos h ↔ b ≤ l.maximum :=
WithBot.le_unbot_iff _
@[simp]
theorem minimum_of_length_pos_le_iff {b : α} (h : 0 < l.length) :
minimum_of_length_pos h ≤ b ↔ l.minimum ≤ b :=
le_maximum_of_length_pos_iff (α := αᵒᵈ) h
theorem maximum_of_length_pos_mem (h : 0 < l.length) :
maximum_of_length_pos h ∈ l := by
apply maximum_mem
simp only [coe_maximum_of_length_pos]
theorem minimum_of_length_pos_mem (h : 0 < l.length) :
minimum_of_length_pos h ∈ l :=
maximum_of_length_pos_mem (α := αᵒᵈ) h
theorem le_maximum_of_length_pos_of_mem (h : a ∈ l) (w : 0 < l.length) :
a ≤ l.maximum_of_length_pos w := by
simp only [le_maximum_of_length_pos_iff]
exact le_maximum_of_mem' h
theorem minimum_of_length_pos_le_of_mem (h : a ∈ l) (w : 0 < l.length) :
l.minimum_of_length_pos w ≤ a :=
le_maximum_of_length_pos_of_mem (α := αᵒᵈ) h w
theorem getElem_le_maximum_of_length_pos {i : ℕ} (w : i < l.length) (h := (Nat.zero_lt_of_lt w)) :
l[i] ≤ l.maximum_of_length_pos h := by
apply le_maximum_of_length_pos_of_mem
exact get_mem l i w
theorem minimum_of_length_pos_le_getElem {i : ℕ} (w : i < l.length) (h := (Nat.zero_lt_of_lt w)) :
l.minimum_of_length_pos h ≤ l[i] :=
getElem_le_maximum_of_length_pos (α := αᵒᵈ) w
lemma getD_maximum?_eq_unbot'_maximum (l : List α) (d : α) :
l.maximum?.getD d = l.maximum.unbot' d := by
cases hy : l.maximum with
| bot => simp [List.maximum_eq_bot.mp hy]
| coe y =>
rw [List.maximum_eq_coe_iff] at hy
simp only [WithBot.unbot'_coe]
cases hz : l.maximum? with
| none => simp [List.maximum?_eq_none_iff.mp hz] at hy
| some z =>
have : Antisymm (α := α) (· ≤ ·) := ⟨_root_.le_antisymm⟩
rw [List.maximum?_eq_some_iff] at hz
· rw [Option.getD_some]
exact _root_.le_antisymm (hy.right _ hz.left) (hz.right _ hy.left)
all_goals simp [le_total]
lemma getD_minimum?_eq_untop'_minimum (l : List α) (d : α) :
l.minimum?.getD d = l.minimum.untop' d :=
getD_maximum?_eq_unbot'_maximum (α := αᵒᵈ) _ _
end LinearOrder
end MaximumMinimum
section Fold
variable [LinearOrder α]
section OrderBot
variable [OrderBot α] {l : List α}
@[simp]
theorem foldr_max_of_ne_nil (h : l ≠ []) : ↑(l.foldr max ⊥) = l.maximum := by
induction' l with hd tl IH
· contradiction
· rw [maximum_cons, foldr, WithBot.coe_max]
by_cases h : tl = []
· simp [h]
· simp [IH h]
theorem max_le_of_forall_le (l : List α) (a : α) (h : ∀ x ∈ l, x ≤ a) : l.foldr max ⊥ ≤ a := by
induction' l with y l IH
· simp
· simpa [h y (mem_cons_self _ _)] using IH fun x hx => h x <| mem_cons_of_mem _ hx
theorem le_max_of_le {l : List α} {a x : α} (hx : x ∈ l) (h : a ≤ x) : a ≤ l.foldr max ⊥ := by
induction' l with y l IH
· exact absurd hx (not_mem_nil _)
· obtain hl | hl := hx
· simp only [foldr, foldr_cons]
exact le_max_of_le_left h
· exact le_max_of_le_right (IH (by assumption))
end OrderBot
section OrderTop
variable [OrderTop α] {l : List α}
@[simp]
theorem foldr_min_of_ne_nil (h : l ≠ []) : ↑(l.foldr min ⊤) = l.minimum :=
@foldr_max_of_ne_nil αᵒᵈ _ _ _ h
theorem le_min_of_forall_le (l : List α) (a : α) (h : ∀ x ∈ l, a ≤ x) : a ≤ l.foldr min ⊤ :=
@max_le_of_forall_le αᵒᵈ _ _ _ _ h
theorem min_le_of_le (l : List α) (a : α) {x : α} (hx : x ∈ l) (h : x ≤ a) : l.foldr min ⊤ ≤ a :=
@le_max_of_le αᵒᵈ _ _ _ _ _ hx h
end OrderTop
end Fold
end List
|
Data\List\NatAntidiagonal.lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import Mathlib.Data.List.Nodup
/-!
# Antidiagonals in ℕ × ℕ as lists
This file defines the antidiagonals of ℕ × ℕ as lists: the `n`-th antidiagonal is the list 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
Files `Data.Multiset.NatAntidiagonal` and `Data.Finset.NatAntidiagonal` successively turn the
`List` definition we have here into `Multiset` and `Finset`.
-/
open List Function Nat
namespace List
namespace Nat
/-- The antidiagonal of a natural number `n` is the list of pairs `(i, j)` such that `i + j = n`. -/
def antidiagonal (n : ℕ) : List (ℕ × ℕ) :=
(range (n + 1)).map fun i ↦ (i, n - i)
/-- A pair (i, j) is contained in the antidiagonal of `n` if and only if `i + j = n`. -/
@[simp]
theorem mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := by
rw [antidiagonal, mem_map]; constructor
· rintro ⟨i, hi, rfl⟩
rw [mem_range, Nat.lt_succ_iff] at hi
exact Nat.add_sub_cancel' hi
· rintro rfl
refine ⟨x.fst, ?_, ?_⟩
· rw [mem_range]
omega
· exact Prod.ext rfl (by simp only [Nat.add_sub_cancel_left])
/-- The length of the antidiagonal of `n` is `n + 1`. -/
@[simp]
theorem length_antidiagonal (n : ℕ) : (antidiagonal n).length = n + 1 := by
rw [antidiagonal, length_map, length_range]
/-- The antidiagonal of `0` is the list `[(0, 0)]` -/
@[simp]
theorem antidiagonal_zero : antidiagonal 0 = [(0, 0)] :=
rfl
/-- The antidiagonal of `n` does not contain duplicate entries. -/
theorem nodup_antidiagonal (n : ℕ) : Nodup (antidiagonal n) :=
(nodup_range _).map ((@LeftInverse.injective ℕ (ℕ × ℕ) Prod.fst fun i ↦ (i, n - i)) fun _ ↦ rfl)
@[simp]
theorem antidiagonal_succ {n : ℕ} :
antidiagonal (n + 1) = (0, n + 1) :: (antidiagonal n).map (Prod.map Nat.succ id) := by
simp only [antidiagonal, range_succ_eq_map, map_cons, true_and_iff, Nat.add_succ_sub_one,
Nat.add_zero, id, eq_self_iff_true, Nat.sub_zero, map_map, Prod.map_mk]
apply congr rfl (congr rfl _)
ext; simp
theorem antidiagonal_succ' {n : ℕ} :
antidiagonal (n + 1) = (antidiagonal n).map (Prod.map id Nat.succ) ++ [(n + 1, 0)] := by
simp only [antidiagonal, range_succ, Nat.add_sub_cancel_left, map_append, append_assoc,
Nat.sub_self, singleton_append, map_map, map]
congr 1
apply map_congr_left
simp (config := { contextual := true }) [le_of_lt, Nat.sub_add_comm]
theorem antidiagonal_succ_succ' {n : ℕ} :
antidiagonal (n + 2) =
(0, n + 2) :: (antidiagonal n).map (Prod.map Nat.succ Nat.succ) ++ [(n + 2, 0)] := by
rw [antidiagonal_succ']
simp only [antidiagonal_succ, map_cons, Prod.map_apply, id_eq, map_map, cons_append, cons.injEq,
append_cancel_right_eq, true_and]
ext
simp
theorem map_swap_antidiagonal {n : ℕ} :
(antidiagonal n).map Prod.swap = (antidiagonal n).reverse := by
rw [antidiagonal, map_map, ← List.map_reverse, range_eq_range', reverse_range', ←
range_eq_range', map_map]
apply map_congr_left
simp (config := { contextual := true }) [Nat.sub_sub_self, Nat.lt_succ_iff]
end Nat
end List
|
Data\List\Nodup.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kenny Lau
-/
import Mathlib.Data.List.Forall2
import Mathlib.Data.Set.Pairwise.Basic
import Mathlib.Init.Data.Fin.Basic
/-!
# Lists with no duplicates
`List.Nodup` is defined in `Data/List/Basic`. In this file we prove various properties of this
predicate.
-/
universe u v
open Nat Function
variable {α : Type u} {β : Type v} {l l₁ l₂ : List α} {r : α → α → Prop} {a b : α}
namespace List
protected theorem Pairwise.nodup {l : List α} {r : α → α → Prop} [IsIrrefl α r] (h : Pairwise r l) :
Nodup l :=
h.imp ne_of_irrefl
theorem rel_nodup {r : α → β → Prop} (hr : Relator.BiUnique r) : (Forall₂ r ⇒ (· ↔ ·)) Nodup Nodup
| _, _, Forall₂.nil => by simp only [nodup_nil]
| _, _, Forall₂.cons hab h => by
simpa only [nodup_cons] using
Relator.rel_and (Relator.rel_not (rel_mem hr hab h)) (rel_nodup hr h)
protected theorem Nodup.cons (ha : a ∉ l) (hl : Nodup l) : Nodup (a :: l) :=
nodup_cons.2 ⟨ha, hl⟩
theorem nodup_singleton (a : α) : Nodup [a] :=
pairwise_singleton _ _
theorem Nodup.of_cons (h : Nodup (a :: l)) : Nodup l :=
(nodup_cons.1 h).2
theorem Nodup.not_mem (h : (a :: l).Nodup) : a ∉ l :=
(nodup_cons.1 h).1
theorem not_nodup_cons_of_mem : a ∈ l → ¬Nodup (a :: l) :=
imp_not_comm.1 Nodup.not_mem
theorem not_nodup_pair (a : α) : ¬Nodup [a, a] :=
not_nodup_cons_of_mem <| mem_singleton_self _
theorem nodup_iff_sublist {l : List α} : Nodup l ↔ ∀ a, ¬[a, a] <+ l :=
⟨fun d a h => not_nodup_pair a (d.sublist h),
by
induction' l with a l IH <;> intro h; · exact nodup_nil
exact (IH fun a s => h a <| sublist_cons_of_sublist _ s).cons fun al =>
h a <| (singleton_sublist.2 al).cons_cons _⟩
theorem nodup_iff_injective_getElem {l : List α} :
Nodup l ↔ Function.Injective (fun i : Fin l.length => l[i.1]) :=
pairwise_iff_getElem.trans
⟨fun h i j hg => by
cases' i with i hi; cases' j with j hj
rcases lt_trichotomy i j with (hij | rfl | hji)
· exact (h i j hi hj hij hg).elim
· rfl
· exact (h j i hj hi hji hg.symm).elim,
fun hinj i j hi hj hij h => Nat.ne_of_lt hij (Fin.val_eq_of_eq (@hinj ⟨i, hi⟩ ⟨j, hj⟩ h))⟩
-- Porting note (#10756): new theorem
theorem nodup_iff_injective_get {l : List α} :
Nodup l ↔ Function.Injective l.get := by
rw [nodup_iff_injective_getElem]
change _ ↔ Injective (fun i => l.get i)
simp
set_option linter.deprecated false in
@[deprecated nodup_iff_injective_get (since := "2023-01-10")]
theorem nodup_iff_nthLe_inj {l : List α} :
Nodup l ↔ ∀ i j h₁ h₂, nthLe l i h₁ = nthLe l j h₂ → i = j :=
nodup_iff_injective_get.trans
⟨fun hinj _ _ _ _ h => congr_arg Fin.val (hinj h),
fun hinj i j h => Fin.eq_of_veq (hinj i j i.2 j.2 h)⟩
theorem Nodup.get_inj_iff {l : List α} (h : Nodup l) {i j : Fin l.length} :
l.get i = l.get j ↔ i = j :=
(nodup_iff_injective_get.1 h).eq_iff
theorem Nodup.getElem_inj_iff {l : List α} (h : Nodup l)
{i : Nat} {hi : i < l.length} {j : Nat} {hj : j < l.length} :
l[i] = l[j] ↔ i = j := by
have := @Nodup.get_inj_iff _ _ h ⟨i, hi⟩ ⟨j, hj⟩
simpa
set_option linter.deprecated false in
@[deprecated Nodup.get_inj_iff (since := "2023-01-10")]
theorem Nodup.nthLe_inj_iff {l : List α} (h : Nodup l) {i j : ℕ} (hi : i < l.length)
(hj : j < l.length) : l.nthLe i hi = l.nthLe j hj ↔ i = j :=
⟨nodup_iff_nthLe_inj.mp h _ _ _ _, by simp (config := { contextual := true })⟩
theorem nodup_iff_getElem?_ne_getElem? {l : List α} :
l.Nodup ↔ ∀ i j : ℕ, i < j → j < l.length → l[i]? ≠ l[j]? := by
rw [Nodup, pairwise_iff_getElem]
constructor
· intro h i j hij hj
rw [getElem?_eq_getElem (lt_trans hij hj), getElem?_eq_getElem hj, Ne, Option.some_inj]
exact h _ _ _ _ hij
· intro h i j hi hj hij
rw [Ne, ← Option.some_inj, ← getElem?_eq_getElem, ← getElem?_eq_getElem]
exact h i j hij hj
theorem nodup_iff_get?_ne_get? {l : List α} :
l.Nodup ↔ ∀ i j : ℕ, i < j → j < l.length → l.get? i ≠ l.get? j := by
simp [nodup_iff_getElem?_ne_getElem?]
theorem Nodup.ne_singleton_iff {l : List α} (h : Nodup l) (x : α) :
l ≠ [x] ↔ l = [] ∨ ∃ y ∈ l, y ≠ x := by
induction' l with hd tl hl
· simp
· specialize hl h.of_cons
by_cases hx : tl = [x]
· simpa [hx, and_comm, and_or_left] using h
· rw [← Ne, hl] at hx
rcases hx with (rfl | ⟨y, hy, hx⟩)
· simp
· suffices ∃ y ∈ hd :: tl, y ≠ x by simpa [ne_nil_of_mem hy]
exact ⟨y, mem_cons_of_mem _ hy, hx⟩
theorem not_nodup_of_get_eq_of_ne (xs : List α) (n m : Fin xs.length)
(h : xs.get n = xs.get m) (hne : n ≠ m) : ¬Nodup xs := by
rw [nodup_iff_injective_get]
exact fun hinj => hne (hinj h)
theorem indexOf_getElem [DecidableEq α] {l : List α} (H : Nodup l) (i : Nat) (h : i < l.length) :
indexOf l[i] l = i :=
suffices (⟨indexOf l[i] l, indexOf_lt_length.2 (get_mem _ _ _)⟩ : Fin l.length) = ⟨i, h⟩
from Fin.val_eq_of_eq this
nodup_iff_injective_get.1 H (by simp)
-- This is incorrectly named and should be `indexOf_get`;
-- this already exists, so will require a deprecation dance.
theorem get_indexOf [DecidableEq α] {l : List α} (H : Nodup l) (i : Fin l.length) :
indexOf (get l i) l = i := by
simp [indexOf_getElem, H]
theorem nodup_iff_count_le_one [DecidableEq α] {l : List α} : Nodup l ↔ ∀ a, count a l ≤ 1 :=
nodup_iff_sublist.trans <|
forall_congr' fun a =>
have : replicate 2 a <+ l ↔ 1 < count a l := (le_count_iff_replicate_sublist ..).symm
(not_congr this).trans not_lt
theorem nodup_iff_count_eq_one [DecidableEq α] : Nodup l ↔ ∀ a ∈ l, count a l = 1 :=
nodup_iff_count_le_one.trans <| forall_congr' fun _ =>
⟨fun H h => H.antisymm (count_pos_iff_mem.mpr h),
fun H => if h : _ then (H h).le else (count_eq_zero.mpr h).trans_le (Nat.zero_le 1)⟩
@[simp]
theorem count_eq_one_of_mem [DecidableEq α] {a : α} {l : List α} (d : Nodup l) (h : a ∈ l) :
count a l = 1 :=
_root_.le_antisymm (nodup_iff_count_le_one.1 d a) (Nat.succ_le_of_lt (count_pos_iff_mem.2 h))
theorem count_eq_of_nodup [DecidableEq α] {a : α} {l : List α} (d : Nodup l) :
count a l = if a ∈ l then 1 else 0 := by
split_ifs with h
· exact count_eq_one_of_mem d h
· exact count_eq_zero_of_not_mem h
theorem Nodup.of_append_left : Nodup (l₁ ++ l₂) → Nodup l₁ :=
Nodup.sublist (sublist_append_left l₁ l₂)
theorem Nodup.of_append_right : Nodup (l₁ ++ l₂) → Nodup l₂ :=
Nodup.sublist (sublist_append_right l₁ l₂)
theorem nodup_append {l₁ l₂ : List α} :
Nodup (l₁ ++ l₂) ↔ Nodup l₁ ∧ Nodup l₂ ∧ Disjoint l₁ l₂ := by
simp only [Nodup, pairwise_append, disjoint_iff_ne]
theorem disjoint_of_nodup_append {l₁ l₂ : List α} (d : Nodup (l₁ ++ l₂)) : Disjoint l₁ l₂ :=
(nodup_append.1 d).2.2
theorem Nodup.append (d₁ : Nodup l₁) (d₂ : Nodup l₂) (dj : Disjoint l₁ l₂) : Nodup (l₁ ++ l₂) :=
nodup_append.2 ⟨d₁, d₂, dj⟩
theorem nodup_append_comm {l₁ l₂ : List α} : Nodup (l₁ ++ l₂) ↔ Nodup (l₂ ++ l₁) := by
simp only [nodup_append, and_left_comm, disjoint_comm]
theorem nodup_middle {a : α} {l₁ l₂ : List α} :
Nodup (l₁ ++ a :: l₂) ↔ Nodup (a :: (l₁ ++ l₂)) := by
simp only [nodup_append, not_or, and_left_comm, and_assoc, nodup_cons, mem_append,
disjoint_cons_right]
theorem Nodup.of_map (f : α → β) {l : List α} : Nodup (map f l) → Nodup l :=
(Pairwise.of_map f) fun _ _ => mt <| congr_arg f
theorem Nodup.map_on {f : α → β} (H : ∀ x ∈ l, ∀ y ∈ l, f x = f y → x = y) (d : Nodup l) :
(map f l).Nodup :=
Pairwise.map _ (fun a b ⟨ma, mb, n⟩ e => n (H a ma b mb e)) (Pairwise.and_mem.1 d)
theorem inj_on_of_nodup_map {f : α → β} {l : List α} (d : Nodup (map f l)) :
∀ ⦃x⦄, x ∈ l → ∀ ⦃y⦄, y ∈ l → f x = f y → x = y := by
induction' l with hd tl ih
· simp
· simp only [map, nodup_cons, mem_map, not_exists, not_and, ← Ne.eq_def] at d
simp only [mem_cons]
rintro _ (rfl | h₁) _ (rfl | h₂) h₃
· rfl
· apply (d.1 _ h₂ h₃.symm).elim
· apply (d.1 _ h₁ h₃).elim
· apply ih d.2 h₁ h₂ h₃
theorem nodup_map_iff_inj_on {f : α → β} {l : List α} (d : Nodup l) :
Nodup (map f l) ↔ ∀ x ∈ l, ∀ y ∈ l, f x = f y → x = y :=
⟨inj_on_of_nodup_map, fun h => d.map_on h⟩
protected theorem Nodup.map {f : α → β} (hf : Injective f) : Nodup l → Nodup (map f l) :=
Nodup.map_on fun _ _ _ _ h => hf h
theorem nodup_map_iff {f : α → β} {l : List α} (hf : Injective f) : Nodup (map f l) ↔ Nodup l :=
⟨Nodup.of_map _, Nodup.map hf⟩
@[simp]
theorem nodup_attach {l : List α} : Nodup (attach l) ↔ Nodup l :=
⟨fun h => attach_map_subtype_val l ▸ h.map fun _ _ => Subtype.eq, fun h =>
Nodup.of_map Subtype.val ((attach_map_subtype_val l).symm ▸ h)⟩
alias ⟨Nodup.of_attach, Nodup.attach⟩ := nodup_attach
-- Porting note: commented out
--attribute [protected] nodup.attach
theorem Nodup.pmap {p : α → Prop} {f : ∀ a, p a → β} {l : List α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : Nodup l) : Nodup (pmap f l H) := by
rw [pmap_eq_map_attach]
exact h.attach.map fun ⟨a, ha⟩ ⟨b, hb⟩ h => by congr; exact hf a (H _ ha) b (H _ hb) h
theorem Nodup.filter (p : α → Bool) {l} : Nodup l → Nodup (filter p l) := by
simpa using Pairwise.filter (fun a ↦ p a)
@[simp]
theorem nodup_reverse {l : List α} : Nodup (reverse l) ↔ Nodup l :=
pairwise_reverse.trans <| by simp only [Nodup, Ne, eq_comm]
theorem Nodup.erase_getElem [DecidableEq α] {l : List α} (hl : l.Nodup)
(i : Nat) (h : i < l.length) : l.erase l[i] = l.eraseIdx ↑i := by
induction l generalizing i with
| nil => simp
| cons a l IH =>
cases i with
| zero => simp
| succ i =>
rw [nodup_cons] at hl
rw [erase_cons_tail]
· simp [IH hl.2]
· rw [beq_iff_eq]
simp only [getElem_cons_succ]
simp only [length_cons, succ_eq_add_one, Nat.add_lt_add_iff_right] at h
exact mt (· ▸ l.getElem_mem i h) hl.1
theorem Nodup.erase_get [DecidableEq α] {l : List α} (hl : l.Nodup) (i : Fin l.length) :
l.erase (l.get i) = l.eraseIdx ↑i := by
simp [erase_getElem, hl]
theorem Nodup.diff [DecidableEq α] : l₁.Nodup → (l₁.diff l₂).Nodup :=
Nodup.sublist <| diff_sublist _ _
theorem nodup_join {L : List (List α)} :
Nodup (join L) ↔ (∀ l ∈ L, Nodup l) ∧ Pairwise Disjoint L := by
simp only [Nodup, pairwise_join, disjoint_left.symm, forall_mem_ne]
theorem nodup_bind {l₁ : List α} {f : α → List β} :
Nodup (l₁.bind f) ↔
(∀ x ∈ l₁, Nodup (f x)) ∧ Pairwise (fun a b : α => Disjoint (f a) (f b)) l₁ := by
simp only [List.bind, nodup_join, pairwise_map, and_comm, and_left_comm, mem_map, exists_imp,
and_imp]
rw [show (∀ (l : List β) (x : α), f x = l → x ∈ l₁ → Nodup l) ↔ ∀ x : α, x ∈ l₁ → Nodup (f x)
from forall_swap.trans <| forall_congr' fun _ => forall_eq']
protected theorem Nodup.product {l₂ : List β} (d₁ : l₁.Nodup) (d₂ : l₂.Nodup) :
(l₁ ×ˢ l₂).Nodup :=
nodup_bind.2
⟨fun a _ => d₂.map <| LeftInverse.injective fun b => (rfl : (a, b).2 = b),
d₁.imp fun {a₁ a₂} n x h₁ h₂ => by
rcases mem_map.1 h₁ with ⟨b₁, _, rfl⟩
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩
exact n rfl⟩
theorem Nodup.sigma {σ : α → Type*} {l₂ : ∀ a , List (σ a)} (d₁ : Nodup l₁)
(d₂ : ∀ a , Nodup (l₂ a)) : (l₁.sigma l₂).Nodup :=
nodup_bind.2
⟨fun a _ => (d₂ a).map fun b b' h => by injection h with _ h,
d₁.imp fun {a₁ a₂} n x h₁ h₂ => by
rcases mem_map.1 h₁ with ⟨b₁, _, rfl⟩
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩
exact n rfl⟩
protected theorem Nodup.filterMap {f : α → Option β} (h : ∀ a a' b, b ∈ f a → b ∈ f a' → a = a') :
Nodup l → Nodup (filterMap f l) :=
(Pairwise.filterMap f) @fun a a' n b bm b' bm' e => n <| h a a' b' (by rw [← e]; exact bm) bm'
protected theorem Nodup.concat (h : a ∉ l) (h' : l.Nodup) : (l.concat a).Nodup := by
rw [concat_eq_append]; exact h'.append (nodup_singleton _) (disjoint_singleton.2 h)
protected theorem Nodup.insert [DecidableEq α] (h : l.Nodup) : (l.insert a).Nodup :=
if h' : a ∈ l then by rw [insert_of_mem h']; exact h
else by rw [insert_of_not_mem h', nodup_cons]; constructor <;> assumption
theorem Nodup.union [DecidableEq α] (l₁ : List α) (h : Nodup l₂) : (l₁ ∪ l₂).Nodup := by
induction' l₁ with a l₁ ih generalizing l₂
· exact h
· exact (ih h).insert
theorem Nodup.inter [DecidableEq α] (l₂ : List α) : Nodup l₁ → Nodup (l₁ ∩ l₂) :=
Nodup.filter _
theorem Nodup.diff_eq_filter [DecidableEq α] :
∀ {l₁ l₂ : List α} (_ : l₁.Nodup), l₁.diff l₂ = l₁.filter (· ∉ l₂)
| l₁, [], _ => by simp
| l₁, a :: l₂, hl₁ => by
rw [diff_cons, (hl₁.erase _).diff_eq_filter, hl₁.erase_eq_filter, filter_filter]
simp only [decide_not, Bool.not_eq_true', decide_eq_false_iff_not, bne_iff_ne, ne_eq, and_comm,
Bool.decide_and, mem_cons, not_or]
theorem Nodup.mem_diff_iff [DecidableEq α] (hl₁ : l₁.Nodup) : a ∈ l₁.diff l₂ ↔ a ∈ l₁ ∧ a ∉ l₂ := by
rw [hl₁.diff_eq_filter, mem_filter, decide_eq_true_iff]
protected theorem Nodup.set :
∀ {l : List α} {n : ℕ} {a : α} (_ : l.Nodup) (_ : a ∉ l), (l.set n a).Nodup
| [], _, _, _, _ => nodup_nil
| _ :: _, 0, _, hl, ha => nodup_cons.2 ⟨mt (mem_cons_of_mem _) ha, (nodup_cons.1 hl).2⟩
| _ :: _, _ + 1, _, hl, ha =>
nodup_cons.2
⟨fun h =>
(mem_or_eq_of_mem_set h).elim (nodup_cons.1 hl).1 fun hba => ha (hba ▸ mem_cons_self _ _),
hl.of_cons.set (mt (mem_cons_of_mem _) ha)⟩
theorem Nodup.map_update [DecidableEq α] {l : List α} (hl : l.Nodup) (f : α → β) (x : α) (y : β) :
l.map (Function.update f x y) =
if x ∈ l then (l.map f).set (l.indexOf x) y else l.map f := by
induction' l with hd tl ihl; · simp
rw [nodup_cons] at hl
simp only [mem_cons, map, ihl hl.2]
by_cases H : hd = x
· subst hd
simp [set, hl.1]
· simp [Ne.symm H, H, set, ← apply_ite (cons (f hd))]
theorem Nodup.pairwise_of_forall_ne {l : List α} {r : α → α → Prop} (hl : l.Nodup)
(h : ∀ a ∈ l, ∀ b ∈ l, a ≠ b → r a b) : l.Pairwise r := by
rw [pairwise_iff_forall_sublist]
intro a b hab
if heq : a = b then
cases heq; have := nodup_iff_sublist.mp hl _ hab; contradiction
else
apply h <;> try (apply hab.subset; simp)
exact heq
theorem Nodup.pairwise_of_set_pairwise {l : List α} {r : α → α → Prop} (hl : l.Nodup)
(h : { x | x ∈ l }.Pairwise r) : l.Pairwise r :=
hl.pairwise_of_forall_ne h
@[simp]
theorem Nodup.pairwise_coe [IsSymm α r] (hl : l.Nodup) :
{ a | a ∈ l }.Pairwise r ↔ l.Pairwise r := by
induction' l with a l ih
· simp
rw [List.nodup_cons] at hl
have : ∀ b ∈ l, ¬a = b → r a b ↔ r a b := fun b hb =>
imp_iff_right (ne_of_mem_of_not_mem hb hl.1).symm
simp [Set.setOf_or, Set.pairwise_insert_of_symmetric (@symm_of _ r _), ih hl.2, and_comm,
forall₂_congr this]
theorem Nodup.take_eq_filter_mem [DecidableEq α] :
∀ {l : List α} {n : ℕ} (_ : l.Nodup), l.take n = l.filter (l.take n).elem
| [], n, _ => by simp
| b::l, 0, _ => by simp
| b::l, n+1, hl => by
rw [take_cons, Nodup.take_eq_filter_mem (Nodup.of_cons hl), List.filter_cons_of_pos (by simp)]
congr 1
refine List.filter_congr ?_
intro x hx
have : x ≠ b := fun h => (nodup_cons.1 hl).1 (h ▸ hx)
simp (config := {contextual := true}) [List.mem_filter, this, hx]
end List
theorem Option.toList_nodup : ∀ o : Option α, o.toList.Nodup
| none => List.nodup_nil
| some x => List.nodup_singleton x
|
Data\List\NodupEquivFin.lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import Mathlib.Data.List.Duplicate
import Mathlib.Data.List.Sort
/-!
# Equivalence between `Fin (length l)` and elements of a list
Given a list `l`,
* if `l` has no duplicates, then `List.Nodup.getEquiv` is the equivalence between
`Fin (length l)` and `{x // x ∈ l}` sending `i` to `⟨get l i, _⟩` with the inverse
sending `⟨x, hx⟩` to `⟨indexOf x l, _⟩`;
* if `l` has no duplicates and contains every element of a type `α`, then
`List.Nodup.getEquivOfForallMemList` defines an equivalence between `Fin (length l)` and `α`;
if `α` does not have decidable equality, then
there is a bijection `List.Nodup.getBijectionOfForallMemList`;
* if `l` is sorted w.r.t. `(<)`, then `List.Sorted.getIso` is the same bijection reinterpreted
as an `OrderIso`.
-/
namespace List
variable {α : Type*}
namespace Nodup
/-- If `l` lists all the elements of `α` without duplicates, then `List.get` defines
a bijection `Fin l.length → α`. See `List.Nodup.getEquivOfForallMemList`
for a version giving an equivalence when there is decidable equality. -/
@[simps]
def getBijectionOfForallMemList (l : List α) (nd : l.Nodup) (h : ∀ x : α, x ∈ l) :
{ f : Fin l.length → α // Function.Bijective f } :=
⟨fun i => l.get i, fun _ _ h => nd.get_inj_iff.1 h,
fun x =>
let ⟨i, hl⟩ := List.mem_iff_get.1 (h x)
⟨i, hl⟩⟩
variable [DecidableEq α]
/-- If `l` has no duplicates, then `List.get` defines an equivalence between `Fin (length l)` and
the set of elements of `l`. -/
@[simps]
def getEquiv (l : List α) (H : Nodup l) : Fin (length l) ≃ { x // x ∈ l } where
toFun i := ⟨get l i, get_mem l i i.2⟩
invFun x := ⟨indexOf (↑x) l, indexOf_lt_length.2 x.2⟩
left_inv i := by simp only [List.get_indexOf, eq_self_iff_true, Fin.eta, Subtype.coe_mk, H]
right_inv x := by simp
/-- If `l` lists all the elements of `α` without duplicates, then `List.get` defines
an equivalence between `Fin l.length` and `α`.
See `List.Nodup.getBijectionOfForallMemList` for a version without
decidable equality. -/
@[simps]
def getEquivOfForallMemList (l : List α) (nd : l.Nodup) (h : ∀ x : α, x ∈ l) :
Fin l.length ≃ α where
toFun i := l.get i
invFun a := ⟨_, indexOf_lt_length.2 (h a)⟩
left_inv i := by simp [List.indexOf_getElem, nd]
right_inv a := by simp
end Nodup
namespace Sorted
variable [Preorder α] {l : List α}
theorem get_mono (h : l.Sorted (· ≤ ·)) : Monotone l.get := fun _ _ => h.rel_get_of_le
theorem get_strictMono (h : l.Sorted (· < ·)) : StrictMono l.get := fun _ _ => h.rel_get_of_lt
variable [DecidableEq α]
/-- If `l` is a list sorted w.r.t. `(<)`, then `List.get` defines an order isomorphism between
`Fin (length l)` and the set of elements of `l`. -/
def getIso (l : List α) (H : Sorted (· < ·) l) : Fin (length l) ≃o { x // x ∈ l } where
toEquiv := H.nodup.getEquiv l
map_rel_iff' := H.get_strictMono.le_iff_le
variable (H : Sorted (· < ·) l) {x : { x // x ∈ l }} {i : Fin l.length}
@[simp]
theorem coe_getIso_apply : (H.getIso l i : α) = get l i :=
rfl
@[simp]
theorem coe_getIso_symm_apply : ((H.getIso l).symm x : ℕ) = indexOf (↑x) l :=
rfl
end Sorted
section Sublist
/-- If there is `f`, an order-preserving embedding of `ℕ` into `ℕ` such that
any element of `l` found at index `ix` can be found at index `f ix` in `l'`,
then `Sublist l l'`.
-/
theorem sublist_of_orderEmbedding_get?_eq {l l' : List α} (f : ℕ ↪o ℕ)
(hf : ∀ ix : ℕ, l.get? ix = l'.get? (f ix)) : l <+ l' := by
induction' l with hd tl IH generalizing l' f
· simp
have : some hd = _ := hf 0
rw [eq_comm, List.get?_eq_some] at this
obtain ⟨w, h⟩ := this
let f' : ℕ ↪o ℕ :=
OrderEmbedding.ofMapLEIff (fun i => f (i + 1) - (f 0 + 1)) fun a b => by
dsimp only
rw [Nat.sub_le_sub_iff_right, OrderEmbedding.le_iff_le, Nat.succ_le_succ_iff]
rw [Nat.succ_le_iff, OrderEmbedding.lt_iff_lt]
exact b.succ_pos
simp only [get_eq_getElem] at h
simp only [get?_eq_getElem?] at hf IH
have : ∀ ix, tl[ix]? = (l'.drop (f 0 + 1))[f' ix]? := by
intro ix
rw [List.getElem?_drop, OrderEmbedding.coe_ofMapLEIff, Nat.add_sub_cancel', ← hf]
simp only [getElem?_cons_succ]
rw [Nat.succ_le_iff, OrderEmbedding.lt_iff_lt]
exact ix.succ_pos
rw [← List.take_append_drop (f 0 + 1) l', ← List.singleton_append]
apply List.Sublist.append _ (IH _ this)
rw [List.singleton_sublist, ← h, l'.getElem_take _ (Nat.lt_succ_self _)]
apply List.get_mem
/-- A `l : List α` is `Sublist l l'` for `l' : List α` iff
there is `f`, an order-preserving embedding of `ℕ` into `ℕ` such that
any element of `l` found at index `ix` can be found at index `f ix` in `l'`.
-/
theorem sublist_iff_exists_orderEmbedding_get?_eq {l l' : List α} :
l <+ l' ↔ ∃ f : ℕ ↪o ℕ, ∀ ix : ℕ, l.get? ix = l'.get? (f ix) := by
constructor
· intro H
induction' H with xs ys y _H IH xs ys x _H IH
· simp
· obtain ⟨f, hf⟩ := IH
refine ⟨f.trans (OrderEmbedding.ofStrictMono (· + 1) fun _ => by simp), ?_⟩
simpa using hf
· obtain ⟨f, hf⟩ := IH
refine
⟨OrderEmbedding.ofMapLEIff (fun ix : ℕ => if ix = 0 then 0 else (f ix.pred).succ) ?_, ?_⟩
· rintro ⟨_ | a⟩ ⟨_ | b⟩ <;> simp [Nat.succ_le_succ_iff]
· rintro ⟨_ | i⟩
· simp
· simpa using hf _
· rintro ⟨f, hf⟩
exact sublist_of_orderEmbedding_get?_eq f hf
/-- A `l : List α` is `Sublist l l'` for `l' : List α` iff
there is `f`, an order-preserving embedding of `Fin l.length` into `Fin l'.length` such that
any element of `l` found at index `ix` can be found at index `f ix` in `l'`.
-/
theorem sublist_iff_exists_fin_orderEmbedding_get_eq {l l' : List α} :
l <+ l' ↔
∃ f : Fin l.length ↪o Fin l'.length,
∀ ix : Fin l.length, l.get ix = l'.get (f ix) := by
rw [sublist_iff_exists_orderEmbedding_get?_eq]
constructor
· rintro ⟨f, hf⟩
have h : ∀ {i : ℕ}, i < l.length → f i < l'.length := by
intro i hi
specialize hf i
rw [get?_eq_get hi, eq_comm, get?_eq_some] at hf
obtain ⟨h, -⟩ := hf
exact h
refine ⟨OrderEmbedding.ofMapLEIff (fun ix => ⟨f ix, h ix.is_lt⟩) ?_, ?_⟩
· simp
· intro i
apply Option.some_injective
simpa [getElem?_eq_getElem i.2, getElem?_eq_getElem (h i.2)] using hf i
· rintro ⟨f, hf⟩
refine
⟨OrderEmbedding.ofStrictMono (fun i => if hi : i < l.length then f ⟨i, hi⟩ else i + l'.length)
?_,
?_⟩
· intro i j h
dsimp only
split_ifs with hi hj hj
· rwa [Fin.val_fin_lt, f.lt_iff_lt]
· have := (f ⟨i, hi⟩).is_lt
omega
· exact absurd (h.trans hj) hi
· simpa using h
· intro i
simp only [OrderEmbedding.coe_ofStrictMono]
split_ifs with hi
· rw [get?_eq_get hi, get?_eq_get, ← hf]
· rw [get?_eq_none.mpr, get?_eq_none.mpr]
· simp
· simpa using hi
/-- An element `x : α` of `l : List α` is a duplicate iff it can be found
at two distinct indices `n m : ℕ` inside the list `l`.
-/
theorem duplicate_iff_exists_distinct_get {l : List α} {x : α} :
l.Duplicate x ↔
∃ (n m : Fin l.length) (_ : n < m),
x = l.get n ∧ x = l.get m := by
classical
rw [duplicate_iff_two_le_count, le_count_iff_replicate_sublist,
sublist_iff_exists_fin_orderEmbedding_get_eq]
constructor
· rintro ⟨f, hf⟩
refine ⟨f ⟨0, by simp⟩, f ⟨1, by simp⟩, f.lt_iff_lt.2 (Nat.zero_lt_one), ?_⟩
rw [← hf, ← hf]; simp
· rintro ⟨n, m, hnm, h, h'⟩
refine ⟨OrderEmbedding.ofStrictMono (fun i => if (i : ℕ) = 0 then n else m) ?_, ?_⟩
· rintro ⟨⟨_ | i⟩, hi⟩ ⟨⟨_ | j⟩, hj⟩
· simp
· simp [hnm]
· simp
· simp only [Nat.lt_succ_iff, Nat.succ_le_succ_iff, replicate, length, Nat.le_zero] at hi hj
simp [hi, hj]
· rintro ⟨⟨_ | i⟩, hi⟩
· simpa using h
· simpa using h'
set_option linter.deprecated false in
/-- An element `x : α` of `l : List α` is a duplicate iff it can be found
at two distinct indices `n m : ℕ` inside the list `l`.
-/
@[deprecated duplicate_iff_exists_distinct_get (since := "2023-01-19")]
theorem duplicate_iff_exists_distinct_nthLe {l : List α} {x : α} :
l.Duplicate x ↔
∃ (n : ℕ) (hn : n < l.length) (m : ℕ) (hm : m < l.length) (_ : n < m),
x = l.nthLe n hn ∧ x = l.nthLe m hm :=
duplicate_iff_exists_distinct_get.trans
⟨fun ⟨n, m, h⟩ => ⟨n.1, n.2, m.1, m.2, h⟩,
fun ⟨n, hn, m, hm, h⟩ => ⟨⟨n, hn⟩, ⟨m, hm⟩, h⟩⟩
end Sublist
end List
|
Data\List\OfFn.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.Fin.Tuple.Basic
import Mathlib.Data.List.Basic
/-!
# Lists from functions
Theorems and lemmas for dealing with `List.ofFn`, which converts a function on `Fin n` to a list
of length `n`.
## Main Statements
The main statements pertain to lists generated using `List.ofFn`
- `List.length_ofFn`, which tells us the length of such a list
- `List.get?_ofFn`, which tells us the nth element of such a list
- `List.equivSigmaTuple`, which is an `Equiv` between lists and the functions that generate them
via `List.ofFn`.
-/
assert_not_exists Monoid
universe u
variable {α : Type u}
open Nat
namespace List
@[simp]
theorem length_ofFn_go {n} (f : Fin n → α) (i j h) : length (ofFn.go f i j h) = i := by
induction i generalizing j <;> simp_all [ofFn.go]
/-- The length of a list converted from a function is the size of the domain. -/
@[simp]
theorem length_ofFn {n} (f : Fin n → α) : length (ofFn f) = n := by
simp [ofFn, length_ofFn_go]
theorem getElem_ofFn_go {n} (f : Fin n → α) (i j h) (k) (hk : k < (ofFn.go f i j h).length) :
(ofFn.go f i j h)[k] = f ⟨j + k, by simp at hk; omega⟩ := by
let i+1 := i
cases k <;> simp [ofFn.go, getElem_ofFn_go (i := i)]
congr 2; omega
theorem get_ofFn_go {n} (f : Fin n → α) (i j h) (k) (hk) :
get (ofFn.go f i j h) ⟨k, hk⟩ = f ⟨j + k, by simp at hk; omega⟩ := by
simp [getElem_ofFn_go]
@[simp]
theorem getElem_ofFn {n} (f : Fin n → α) (i : Nat) (h : i < (ofFn f).length) :
(ofFn f)[i] = f ⟨i, by simp_all⟩ := by
simp [ofFn, getElem_ofFn_go]
theorem get_ofFn {n} (f : Fin n → α) (i) : get (ofFn f) i = f (Fin.cast (by simp) i) := by
simp; congr
/-- The `n`th element of a list -/
@[simp]
theorem getElem?_ofFn {n} (f : Fin n → α) (i) : (ofFn f)[i]? = ofFnNthVal f i :=
if h : i < (ofFn f).length
then by
rw [getElem?_eq_getElem h, getElem_ofFn]
· simp only [length_ofFn] at h; simp [ofFnNthVal, h]
else by
rw [ofFnNthVal, dif_neg] <;>
simpa using h
/-- The `n`th element of a list -/
theorem get?_ofFn {n} (f : Fin n → α) (i) : get? (ofFn f) i = ofFnNthVal f i := by
simp
set_option linter.deprecated false in
@[deprecated get_ofFn (since := "2023-01-17")]
theorem nthLe_ofFn {n} (f : Fin n → α) (i : Fin n) :
nthLe (ofFn f) i ((length_ofFn f).symm ▸ i.2) = f i := by
simp [nthLe]
set_option linter.deprecated false in
@[simp, deprecated get_ofFn (since := "2023-01-17")]
theorem nthLe_ofFn' {n} (f : Fin n → α) {i : ℕ} (h : i < (ofFn f).length) :
nthLe (ofFn f) i h = f ⟨i, length_ofFn f ▸ h⟩ :=
nthLe_ofFn f ⟨i, length_ofFn f ▸ h⟩
@[simp]
theorem map_ofFn {β : Type*} {n : ℕ} (f : Fin n → α) (g : α → β) :
map g (ofFn f) = ofFn (g ∘ f) :=
ext_get (by simp) fun i h h' => by simp
-- Porting note: we don't have Array' in mathlib4
-- /-- Arrays converted to lists are the same as `of_fn` on the indexing function of the array. -/
-- theorem array_eq_of_fn {n} (a : Array' n α) : a.toList = ofFn a.read :=
-- by
-- suffices ∀ {m h l}, DArray.revIterateAux a (fun i => cons) m h l =
-- ofFnAux (DArray.read a) m h l
-- from this
-- intros; induction' m with m IH generalizing l; · rfl
-- simp only [DArray.revIterateAux, of_fn_aux, IH]
@[congr]
theorem ofFn_congr {m n : ℕ} (h : m = n) (f : Fin m → α) :
ofFn f = ofFn fun i : Fin n => f (Fin.cast h.symm i) := by
subst h
simp_rw [Fin.cast_refl, id]
/-- `ofFn` on an empty domain is the empty list. -/
@[simp]
theorem ofFn_zero (f : Fin 0 → α) : ofFn f = [] :=
ext_get (by simp) (fun i hi₁ hi₂ => by contradiction)
@[simp]
theorem ofFn_succ {n} (f : Fin (succ n) → α) : ofFn f = f 0 :: ofFn fun i => f i.succ :=
ext_get (by simp) (fun i hi₁ hi₂ => by
cases i
· simp
· simp)
theorem ofFn_succ' {n} (f : Fin (succ n) → α) :
ofFn f = (ofFn fun i => f (Fin.castSucc i)).concat (f (Fin.last _)) := by
induction' n with n IH
· rw [ofFn_zero, concat_nil, ofFn_succ, ofFn_zero]
rfl
· rw [ofFn_succ, IH, ofFn_succ, concat_cons, Fin.castSucc_zero]
congr
@[simp]
theorem ofFn_eq_nil_iff {n : ℕ} {f : Fin n → α} : ofFn f = [] ↔ n = 0 := by
cases n <;> simp only [ofFn_zero, ofFn_succ, eq_self_iff_true, Nat.succ_ne_zero]
theorem last_ofFn {n : ℕ} (f : Fin n → α) (h : ofFn f ≠ [])
(hn : n - 1 < n := Nat.pred_lt <| ofFn_eq_nil_iff.not.mp h) :
getLast (ofFn f) h = f ⟨n - 1, hn⟩ := by simp [getLast_eq_getElem]
theorem last_ofFn_succ {n : ℕ} (f : Fin n.succ → α)
(h : ofFn f ≠ [] := mt ofFn_eq_nil_iff.mp (Nat.succ_ne_zero _)) :
getLast (ofFn f) h = f (Fin.last _) :=
last_ofFn f h
/-- Note this matches the convention of `List.ofFn_succ'`, putting the `Fin m` elements first. -/
theorem ofFn_add {m n} (f : Fin (m + n) → α) :
List.ofFn f =
(List.ofFn fun i => f (Fin.castAdd n i)) ++ List.ofFn fun j => f (Fin.natAdd m j) := by
induction' n with n IH
· rw [ofFn_zero, append_nil, Fin.castAdd_zero, Fin.cast_refl]
rfl
· rw [ofFn_succ', ofFn_succ', IH, append_concat]
rfl
@[simp]
theorem ofFn_fin_append {m n} (a : Fin m → α) (b : Fin n → α) :
List.ofFn (Fin.append a b) = List.ofFn a ++ List.ofFn b := by
simp_rw [ofFn_add, Fin.append_left, Fin.append_right]
/-- This breaks a list of `m*n` items into `m` groups each containing `n` elements. -/
theorem ofFn_mul {m n} (f : Fin (m * n) → α) :
List.ofFn f = List.join (List.ofFn fun i : Fin m => List.ofFn fun j : Fin n => f ⟨i * n + j,
calc
↑i * n + j < (i + 1) * n :=
(Nat.add_lt_add_left j.prop _).trans_eq (by rw [Nat.add_mul, Nat.one_mul])
_ ≤ _ := Nat.mul_le_mul_right _ i.prop⟩) := by
induction' m with m IH
· simp [ofFn_zero, Nat.zero_mul, ofFn_zero, join]
· simp_rw [ofFn_succ', succ_mul]
simp [join_concat, ofFn_add, IH]
rfl
/-- This breaks a list of `m*n` items into `n` groups each containing `m` elements. -/
theorem ofFn_mul' {m n} (f : Fin (m * n) → α) :
List.ofFn f = List.join (List.ofFn fun i : Fin n => List.ofFn fun j : Fin m => f ⟨m * i + j,
calc
m * i + j < m * (i + 1) :=
(Nat.add_lt_add_left j.prop _).trans_eq (by rw [Nat.mul_add, Nat.mul_one])
_ ≤ _ := Nat.mul_le_mul_left _ i.prop⟩) := by simp_rw [m.mul_comm, ofFn_mul, Fin.cast_mk]
@[simp]
theorem ofFn_get : ∀ l : List α, (ofFn (get l)) = l
| [] => by rw [ofFn_zero]
| a :: l => by
rw [ofFn_succ]
congr
exact ofFn_get l
@[simp]
theorem ofFn_getElem : ∀ l : List α, (ofFn (fun i : Fin l.length => l[(i : Nat)])) = l
| [] => by rw [ofFn_zero]
| a :: l => by
rw [ofFn_succ]
congr
exact ofFn_get l
@[simp]
theorem ofFn_getElem_eq_map {β : Type*} (l : List α) (f : α → β) :
ofFn (fun i : Fin l.length => f <| l[(i : Nat)]) = l.map f := by
rw [← Function.comp_def, ← map_ofFn, ofFn_getElem]
@[deprecated ofFn_getElem_eq_map (since := "2024-06-12")]
theorem ofFn_get_eq_map {β : Type*} (l : List α) (f : α → β) : ofFn (f <| l.get ·) = l.map f := by
simp
set_option linter.deprecated false in
@[deprecated ofFn_get (since := "2023-01-17")]
theorem ofFn_nthLe : ∀ l : List α, (ofFn fun i => nthLe l i i.2) = l :=
ofFn_get
-- not registered as a simp lemma, as otherwise it fires before `forall_mem_ofFn_iff` which
-- is much more useful
theorem mem_ofFn {n} (f : Fin n → α) (a : α) : a ∈ ofFn f ↔ a ∈ Set.range f := by
simp only [mem_iff_get, Set.mem_range, get_ofFn]
exact ⟨fun ⟨i, hi⟩ => ⟨Fin.cast (by simp) i, hi⟩, fun ⟨i, hi⟩ => ⟨Fin.cast (by simp) i, hi⟩⟩
@[simp]
theorem forall_mem_ofFn_iff {n : ℕ} {f : Fin n → α} {P : α → Prop} :
(∀ i ∈ ofFn f, P i) ↔ ∀ j : Fin n, P (f j) := by simp only [mem_ofFn, Set.forall_mem_range]
@[simp]
theorem ofFn_const : ∀ (n : ℕ) (c : α), (ofFn fun _ : Fin n => c) = replicate n c
| 0, c => by rw [ofFn_zero, replicate_zero]
| n+1, c => by rw [replicate, ← ofFn_const n]; simp
@[simp]
theorem ofFn_fin_repeat {m} (a : Fin m → α) (n : ℕ) :
List.ofFn (Fin.repeat n a) = (List.replicate n (List.ofFn a)).join := by
simp_rw [ofFn_mul, ← ofFn_const, Fin.repeat, Fin.modNat, Nat.add_comm,
Nat.add_mul_mod_self_right, Nat.mod_eq_of_lt (Fin.is_lt _)]
@[simp]
theorem pairwise_ofFn {R : α → α → Prop} {n} {f : Fin n → α} :
(ofFn f).Pairwise R ↔ ∀ ⦃i j⦄, i < j → R (f i) (f j) := by
simp only [pairwise_iff_get, (Fin.rightInverse_cast (length_ofFn f)).surjective.forall, get_ofFn,
← Fin.not_le, Fin.cast_le_cast]
/-- Lists are equivalent to the sigma type of tuples of a given length. -/
@[simps]
def equivSigmaTuple : List α ≃ Σn, Fin n → α where
toFun l := ⟨l.length, l.get⟩
invFun f := List.ofFn f.2
left_inv := List.ofFn_get
right_inv := fun ⟨_, f⟩ =>
Fin.sigma_eq_of_eq_comp_cast (length_ofFn _) <| funext fun i => get_ofFn f i
/-- A recursor for lists that expands a list into a function mapping to its elements.
This can be used with `induction l using List.ofFnRec`. -/
@[elab_as_elim]
def ofFnRec {C : List α → Sort*} (h : ∀ (n) (f : Fin n → α), C (List.ofFn f)) (l : List α) : C l :=
cast (congr_arg C l.ofFn_get) <|
h l.length l.get
@[simp]
theorem ofFnRec_ofFn {C : List α → Sort*} (h : ∀ (n) (f : Fin n → α), C (List.ofFn f)) {n : ℕ}
(f : Fin n → α) : @ofFnRec _ C h (List.ofFn f) = h _ f := by
-- Porting note: Old proof was
-- equivSigmaTuple.rightInverse_symm.cast_eq (fun s => h s.1 s.2) ⟨n, f⟩
have := (@equivSigmaTuple α).rightInverse_symm
dsimp [equivSigmaTuple] at this
have := this.cast_eq (fun s => h s.1 s.2) ⟨n, f⟩
dsimp only at this
rw [ofFnRec, ← this]
theorem exists_iff_exists_tuple {P : List α → Prop} :
(∃ l : List α, P l) ↔ ∃ (n : _) (f : Fin n → α), P (List.ofFn f) :=
equivSigmaTuple.symm.surjective.exists.trans Sigma.exists
theorem forall_iff_forall_tuple {P : List α → Prop} :
(∀ l : List α, P l) ↔ ∀ (n) (f : Fin n → α), P (List.ofFn f) :=
equivSigmaTuple.symm.surjective.forall.trans Sigma.forall
/-- `Fin.sigma_eq_iff_eq_comp_cast` may be useful to work with the RHS of this expression. -/
theorem ofFn_inj' {m n : ℕ} {f : Fin m → α} {g : Fin n → α} :
ofFn f = ofFn g ↔ (⟨m, f⟩ : Σn, Fin n → α) = ⟨n, g⟩ :=
Iff.symm <| equivSigmaTuple.symm.injective.eq_iff.symm
/-- Note we can only state this when the two functions are indexed by defeq `n`. -/
theorem ofFn_injective {n : ℕ} : Function.Injective (ofFn : (Fin n → α) → List α) := fun f g h =>
eq_of_heq <| by rw [ofFn_inj'] at h; cases h; rfl
/-- A special case of `List.ofFn_inj` for when the two functions are indexed by defeq `n`. -/
@[simp]
theorem ofFn_inj {n : ℕ} {f g : Fin n → α} : ofFn f = ofFn g ↔ f = g :=
ofFn_injective.eq_iff
end List
|
Data\List\Pairwise.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Logic.Pairwise
import Mathlib.Logic.Relation
import Mathlib.Data.List.Basic
/-!
# Pairwise relations on a list
This file provides basic results about `List.Pairwise` and `List.pwFilter` (definitions are in
`Data.List.Defs`).
`Pairwise r [a 0, ..., a (n - 1)]` means `∀ i j, i < j → r (a i) (a j)`. For example,
`Pairwise (≠) l` means that all elements of `l` are distinct, and `Pairwise (<) l` means that `l`
is strictly increasing.
`pwFilter r l` is the list obtained by iteratively adding each element of `l` that doesn't break
the pairwiseness of the list we have so far. It thus yields `l'` a maximal sublist of `l` such that
`Pairwise r l'`.
## Tags
sorted, nodup
-/
open Nat Function
namespace List
variable {α β : Type*} {R S T : α → α → Prop} {a : α} {l : List α}
mk_iff_of_inductive_prop List.Pairwise List.pairwise_iff
/-! ### Pairwise -/
theorem Pairwise.forall_of_forall (H : Symmetric R) (H₁ : ∀ x ∈ l, R x x) (H₂ : l.Pairwise R) :
∀ ⦃x⦄, x ∈ l → ∀ ⦃y⦄, y ∈ l → R x y :=
H₂.forall_of_forall_of_flip H₁ <| by rwa [H.flip_eq]
theorem Pairwise.forall (hR : Symmetric R) (hl : l.Pairwise R) :
∀ ⦃a⦄, a ∈ l → ∀ ⦃b⦄, b ∈ l → a ≠ b → R a b := by
apply Pairwise.forall_of_forall
· exact fun a b h hne => hR (h hne.symm)
· exact fun _ _ hx => (hx rfl).elim
· exact hl.imp (@fun a b h _ => by exact h)
theorem Pairwise.set_pairwise (hl : Pairwise R l) (hr : Symmetric R) : { x | x ∈ l }.Pairwise R :=
hl.forall hr
-- Porting note: Duplicate of `pairwise_map` but with `f` explicit.
@[deprecated (since := "2024-02-25")] theorem pairwise_map' (f : β → α) :
∀ {l : List β}, Pairwise R (map f l) ↔ Pairwise (fun a b : β => R (f a) (f b)) l
| [] => by simp only [map, Pairwise.nil]
| b :: l => by
simp only [map, pairwise_cons, mem_map, forall_exists_index, and_imp,
forall_apply_eq_imp_iff₂, pairwise_map]
theorem pairwise_pmap {p : β → Prop} {f : ∀ b, p b → α} {l : List β} (h : ∀ x ∈ l, p x) :
Pairwise R (l.pmap f h) ↔
Pairwise (fun b₁ b₂ => ∀ (h₁ : p b₁) (h₂ : p b₂), R (f b₁ h₁) (f b₂ h₂)) l := by
induction' l with a l ihl
· simp
obtain ⟨_, hl⟩ : p a ∧ ∀ b, b ∈ l → p b := by simpa using h
simp only [ihl hl, pairwise_cons, exists₂_imp, pmap, and_congr_left_iff, mem_pmap]
refine fun _ => ⟨fun H b hb _ hpb => H _ _ hb rfl, ?_⟩
rintro H _ b hb rfl
exact H b hb _ _
theorem Pairwise.pmap {l : List α} (hl : Pairwise R l) {p : α → Prop} {f : ∀ a, p a → β}
(h : ∀ x ∈ l, p x) {S : β → β → Prop}
(hS : ∀ ⦃x⦄ (hx : p x) ⦃y⦄ (hy : p y), R x y → S (f x hx) (f y hy)) :
Pairwise S (l.pmap f h) := by
refine (pairwise_pmap h).2 (Pairwise.imp_of_mem ?_ hl)
intros; apply hS; assumption
theorem pairwise_of_forall_mem_list {l : List α} {r : α → α → Prop} (h : ∀ a ∈ l, ∀ b ∈ l, r a b) :
l.Pairwise r := by
rw [pairwise_iff_forall_sublist]
intro a b hab
apply h <;> (apply hab.subset; simp)
theorem pairwise_of_reflexive_of_forall_ne {l : List α} {r : α → α → Prop} (hr : Reflexive r)
(h : ∀ a ∈ l, ∀ b ∈ l, a ≠ b → r a b) : l.Pairwise r := by
rw [pairwise_iff_forall_sublist]
intro a b hab
if heq : a = b then
cases heq; apply hr
else
apply h <;> try (apply hab.subset; simp)
exact heq
set_option linter.deprecated false in
@[deprecated pairwise_iff_get (since := "2023-01-10")]
theorem pairwise_iff_nthLe {R} {l : List α} : Pairwise R l ↔
∀ (i j) (h₁ : j < length l) (h₂ : i < j), R (nthLe l i (lt_trans h₂ h₁)) (nthLe l j h₁) :=
pairwise_iff_get.trans
⟨fun h i j _ h₂ => h ⟨i, _⟩ ⟨j, _⟩ h₂,
fun h i j hij => h i j _ hij⟩
/-! ### Pairwise filtering -/
variable [DecidableRel R]
alias ⟨_, Pairwise.pwFilter⟩ := pwFilter_eq_self
-- Porting note: commented out
-- attribute [protected] List.Pairwise.pwFilter
end List
|
Data\List\Palindrome.lean | /-
Copyright (c) 2020 Google LLC. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Wong
-/
import Mathlib.Data.List.Basic
/-!
# Palindromes
This module defines *palindromes*, lists which are equal to their reverse.
The main result is the `Palindrome` inductive type, and its associated `Palindrome.rec` induction
principle. Also provided are conversions to and from other equivalent definitions.
## References
* [Pierre Castéran, *On palindromes*][casteran]
[casteran]: https://www.labri.fr/perso/casteran/CoqArt/inductive-prop-chap/palindrome.html
## Tags
palindrome, reverse, induction
-/
variable {α β : Type*}
namespace List
/-- `Palindrome l` asserts that `l` is a palindrome. This is defined inductively:
* The empty list is a palindrome;
* A list with one element is a palindrome;
* Adding the same element to both ends of a palindrome results in a bigger palindrome.
-/
inductive Palindrome : List α → Prop
| nil : Palindrome []
| singleton : ∀ x, Palindrome [x]
| cons_concat : ∀ (x) {l}, Palindrome l → Palindrome (x :: (l ++ [x]))
namespace Palindrome
variable {l : List α}
theorem reverse_eq {l : List α} (p : Palindrome l) : reverse l = l := by
induction p <;> try (exact rfl)
simpa
theorem of_reverse_eq {l : List α} : reverse l = l → Palindrome l := by
refine bidirectionalRecOn l (fun _ => Palindrome.nil) (fun a _ => Palindrome.singleton a) ?_
intro x l y hp hr
rw [reverse_cons, reverse_append] at hr
rw [head_eq_of_cons_eq hr]
have : Palindrome l := hp (append_inj_left' (tail_eq_of_cons_eq hr) rfl)
exact Palindrome.cons_concat x this
theorem iff_reverse_eq {l : List α} : Palindrome l ↔ reverse l = l :=
Iff.intro reverse_eq of_reverse_eq
theorem append_reverse (l : List α) : Palindrome (l ++ reverse l) := by
apply of_reverse_eq
rw [reverse_append, reverse_reverse]
protected theorem map (f : α → β) (p : Palindrome l) : Palindrome (map f l) :=
of_reverse_eq <| by rw [← map_reverse, p.reverse_eq]
instance [DecidableEq α] (l : List α) : Decidable (Palindrome l) :=
decidable_of_iff' _ iff_reverse_eq
end Palindrome
end List
|
Data\List\Perm.lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro
-/
import Mathlib.Data.List.Count
import Mathlib.Data.List.Dedup
import Mathlib.Data.List.Duplicate
import Mathlib.Data.List.InsertNth
import Mathlib.Data.List.Lattice
import Mathlib.Data.List.Permutation
import Mathlib.Data.Nat.Factorial.Basic
/-!
# List Permutations
This file introduces the `List.Perm` relation, which is true if two lists are permutations of one
another.
## Notation
The notation `~` is used for permutation equivalence.
-/
-- Make sure we don't import algebra
assert_not_exists Monoid
open Nat
namespace List
variable {α β : Type*} {l l₁ l₂ : List α} {a : α}
instance : Trans (@List.Perm α) (@List.Perm α) List.Perm where
trans := @List.Perm.trans α
open Perm (swap)
attribute [refl] Perm.refl
lemma perm_rfl : l ~ l := Perm.refl _
-- Porting note: used rec_on in mathlib3; lean4 eqn compiler still doesn't like it
attribute [symm] Perm.symm
attribute [trans] Perm.trans
theorem Perm.subset_congr_left {l₁ l₂ l₃ : List α} (h : l₁ ~ l₂) : l₁ ⊆ l₃ ↔ l₂ ⊆ l₃ :=
⟨h.symm.subset.trans, h.subset.trans⟩
theorem Perm.subset_congr_right {l₁ l₂ l₃ : List α} (h : l₁ ~ l₂) : l₃ ⊆ l₁ ↔ l₃ ⊆ l₂ :=
⟨fun h' => h'.trans h.subset, fun h' => h'.trans h.symm.subset⟩
section Rel
open Relator
variable {γ : Type*} {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
local infixr:80 " ∘r " => Relation.Comp
theorem perm_comp_perm : (Perm ∘r Perm : List α → List α → Prop) = Perm := by
funext a c; apply propext
constructor
· exact fun ⟨b, hab, hba⟩ => Perm.trans hab hba
· exact fun h => ⟨a, Perm.refl a, h⟩
theorem perm_comp_forall₂ {l u v} (hlu : Perm l u) (huv : Forall₂ r u v) :
(Forall₂ r ∘r Perm) l v := by
induction hlu generalizing v with
| nil => cases huv; exact ⟨[], Forall₂.nil, Perm.nil⟩
| cons u _hlu ih =>
cases' huv with _ b _ v hab huv'
rcases ih huv' with ⟨l₂, h₁₂, h₂₃⟩
exact ⟨b :: l₂, Forall₂.cons hab h₁₂, h₂₃.cons _⟩
| swap a₁ a₂ h₂₃ =>
cases' huv with _ b₁ _ l₂ h₁ hr₂₃
cases' hr₂₃ with _ b₂ _ l₂ h₂ h₁₂
exact ⟨b₂ :: b₁ :: l₂, Forall₂.cons h₂ (Forall₂.cons h₁ h₁₂), Perm.swap _ _ _⟩
| trans _ _ ih₁ ih₂ =>
rcases ih₂ huv with ⟨lb₂, hab₂, h₂₃⟩
rcases ih₁ hab₂ with ⟨lb₁, hab₁, h₁₂⟩
exact ⟨lb₁, hab₁, Perm.trans h₁₂ h₂₃⟩
theorem forall₂_comp_perm_eq_perm_comp_forall₂ : Forall₂ r ∘r Perm = Perm ∘r Forall₂ r := by
funext l₁ l₃; apply propext
constructor
· intro h
rcases h with ⟨l₂, h₁₂, h₂₃⟩
have : Forall₂ (flip r) l₂ l₁ := h₁₂.flip
rcases perm_comp_forall₂ h₂₃.symm this with ⟨l', h₁, h₂⟩
exact ⟨l', h₂.symm, h₁.flip⟩
· exact fun ⟨l₂, h₁₂, h₂₃⟩ => perm_comp_forall₂ h₁₂ h₂₃
theorem rel_perm_imp (hr : RightUnique r) : (Forall₂ r ⇒ Forall₂ r ⇒ (· → ·)) Perm Perm :=
fun a b h₁ c d h₂ h =>
have : (flip (Forall₂ r) ∘r Perm ∘r Forall₂ r) b d := ⟨a, h₁, c, h, h₂⟩
have : ((flip (Forall₂ r) ∘r Forall₂ r) ∘r Perm) b d := by
rwa [← forall₂_comp_perm_eq_perm_comp_forall₂, ← Relation.comp_assoc] at this
let ⟨b', ⟨c', hbc, hcb⟩, hbd⟩ := this
have : b' = b := right_unique_forall₂' hr hcb hbc
this ▸ hbd
theorem rel_perm (hr : BiUnique r) : (Forall₂ r ⇒ Forall₂ r ⇒ (· ↔ ·)) Perm Perm :=
fun _a _b hab _c _d hcd =>
Iff.intro (rel_perm_imp hr.2 hab hcd) (rel_perm_imp hr.left.flip hab.flip hcd.flip)
end Rel
section Subperm
attribute [refl] Subperm.refl
attribute [trans] Subperm.trans
end Subperm
lemma subperm_iff : l₁ <+~ l₂ ↔ ∃ l, l ~ l₂ ∧ l₁ <+ l := by
refine ⟨?_, fun ⟨l, h₁, h₂⟩ ↦ h₂.subperm.trans h₁.subperm⟩
rintro ⟨l, h₁, h₂⟩
obtain ⟨l', h₂⟩ := h₂.exists_perm_append
exact ⟨l₁ ++ l', (h₂.trans (h₁.append_right _)).symm, (prefix_append _ _).sublist⟩
@[simp] lemma subperm_singleton_iff : l <+~ [a] ↔ l = [] ∨ l = [a] := by
constructor
· rw [subperm_iff]
rintro ⟨s, hla, h⟩
rwa [perm_singleton.mp hla, sublist_singleton] at h
· rintro (rfl | rfl)
exacts [nil_subperm, Subperm.refl _]
attribute [simp] nil_subperm
@[simp]
theorem subperm_nil : List.Subperm l [] ↔ l = [] :=
⟨fun h ↦ length_eq_zero.1 <| Nat.le_zero.1 h.length_le, by rintro rfl; rfl⟩
lemma subperm_cons_self : l <+~ a :: l := ⟨l, Perm.refl _, sublist_cons_self _ _⟩
lemma count_eq_count_filter_add [DecidableEq α] (P : α → Prop) [DecidablePred P]
(l : List α) (a : α) :
count a l = count a (l.filter P) + count a (l.filter (¬ P ·)) := by
convert countP_eq_countP_filter_add l _ P
simp only [decide_not]
theorem Perm.foldl_eq {f : β → α → β} {l₁ l₂ : List α} (rcomm : RightCommutative f) (p : l₁ ~ l₂) :
∀ b, foldl f b l₁ = foldl f b l₂ :=
p.foldl_eq' fun x _hx y _hy z => rcomm z x y
theorem Perm.foldr_eq {f : α → β → β} {l₁ l₂ : List α} (lcomm : LeftCommutative f) (p : l₁ ~ l₂) :
∀ b, foldr f b l₁ = foldr f b l₂ := by
intro b
induction p using Perm.recOnSwap' generalizing b with
| nil => rfl
| cons _ _ r => simp [r b]
| swap' _ _ _ r => simp only [foldr_cons]; rw [lcomm, r b]
| trans _ _ r₁ r₂ => exact Eq.trans (r₁ b) (r₂ b)
section
variable {op : α → α → α} [IA : Std.Associative op] [IC : Std.Commutative op]
local notation a " * " b => op a b
local notation l " <*> " a => foldl op a l
theorem Perm.fold_op_eq {l₁ l₂ : List α} {a : α} (h : l₁ ~ l₂) : (l₁ <*> a) = l₂ <*> a :=
h.foldl_eq (right_comm _ IC.comm IA.assoc) _
end
theorem perm_option_to_list {o₁ o₂ : Option α} : o₁.toList ~ o₂.toList ↔ o₁ = o₂ := by
refine ⟨fun p => ?_, fun e => e ▸ Perm.refl _⟩
cases' o₁ with a <;> cases' o₂ with b; · rfl
· cases p.length_eq
· cases p.length_eq
· exact Option.mem_toList.1 (p.symm.subset <| by simp)
alias ⟨subperm.of_cons, subperm.cons⟩ := subperm_cons
-- Porting note: commented out
--attribute [protected] subperm.cons
theorem cons_subperm_of_mem {a : α} {l₁ l₂ : List α} (d₁ : Nodup l₁) (h₁ : a ∉ l₁) (h₂ : a ∈ l₂)
(s : l₁ <+~ l₂) : a :: l₁ <+~ l₂ := by
rcases s with ⟨l, p, s⟩
induction s generalizing l₁ with
| slnil => cases h₂
| @cons r₁ r₂ b s' ih =>
simp? at h₂ says simp only [mem_cons] at h₂
cases' h₂ with e m
· subst b
exact ⟨a :: r₁, p.cons a, s'.cons₂ _⟩
· rcases ih d₁ h₁ m p with ⟨t, p', s'⟩
exact ⟨t, p', s'.cons _⟩
| @cons₂ r₁ r₂ b _ ih =>
have bm : b ∈ l₁ := p.subset <| mem_cons_self _ _
have am : a ∈ r₂ := by
simp only [find?, mem_cons] at h₂
exact h₂.resolve_left fun e => h₁ <| e.symm ▸ bm
rcases append_of_mem bm with ⟨t₁, t₂, rfl⟩
have st : t₁ ++ t₂ <+ t₁ ++ b :: t₂ := by simp
rcases ih (d₁.sublist st) (mt (fun x => st.subset x) h₁) am
(Perm.cons_inv <| p.trans perm_middle) with
⟨t, p', s'⟩
exact
⟨b :: t, (p'.cons b).trans <| (swap _ _ _).trans (perm_middle.symm.cons a), s'.cons₂ _⟩
protected theorem Nodup.subperm (d : Nodup l₁) (H : l₁ ⊆ l₂) : l₁ <+~ l₂ :=
subperm_of_subset d H
section
variable [DecidableEq α]
theorem Perm.bagInter_right {l₁ l₂ : List α} (t : List α) (h : l₁ ~ l₂) :
l₁.bagInter t ~ l₂.bagInter t := by
induction' h with x _ _ _ _ x y _ _ _ _ _ _ ih_1 ih_2 generalizing t; · simp
· by_cases x ∈ t <;> simp [*, Perm.cons]
· by_cases h : x = y
· simp [h]
by_cases xt : x ∈ t <;> by_cases yt : y ∈ t
· simp [xt, yt, mem_erase_of_ne h, mem_erase_of_ne (Ne.symm h), erase_comm, swap]
· simp [xt, yt, mt mem_of_mem_erase, Perm.cons]
· simp [xt, yt, mt mem_of_mem_erase, Perm.cons]
· simp [xt, yt]
· exact (ih_1 _).trans (ih_2 _)
theorem Perm.bagInter_left (l : List α) {t₁ t₂ : List α} (p : t₁ ~ t₂) :
l.bagInter t₁ = l.bagInter t₂ := by
induction' l with a l IH generalizing t₁ t₂ p; · simp
by_cases h : a ∈ t₁
· simp [h, p.subset h, IH (p.erase _)]
· simp [h, mt p.mem_iff.2 h, IH p]
theorem Perm.bagInter {l₁ l₂ t₁ t₂ : List α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) :
l₁.bagInter t₁ ~ l₂.bagInter t₂ :=
ht.bagInter_left l₂ ▸ hl.bagInter_right _
theorem perm_replicate_append_replicate {l : List α} {a b : α} {m n : ℕ} (h : a ≠ b) :
l ~ replicate m a ++ replicate n b ↔ count a l = m ∧ count b l = n ∧ l ⊆ [a, b] := by
rw [perm_iff_count, ← Decidable.and_forall_ne a, ← Decidable.and_forall_ne b]
suffices l ⊆ [a, b] ↔ ∀ c, c ≠ b → c ≠ a → c ∉ l by
simp (config := { contextual := true }) [count_replicate, h, this, count_eq_zero, Ne.symm]
trans ∀ c, c ∈ l → c = b ∨ c = a
· simp [subset_def, or_comm]
· exact forall_congr' fun _ => by rw [← and_imp, ← not_or, not_imp_not]
theorem Perm.dedup {l₁ l₂ : List α} (p : l₁ ~ l₂) : dedup l₁ ~ dedup l₂ :=
perm_iff_count.2 fun a =>
if h : a ∈ l₁ then by
simp [h, nodup_dedup, p.subset h]
else by
simp [h, count_eq_zero_of_not_mem, mt p.mem_iff.2]
theorem Perm.inter_append {l t₁ t₂ : List α} (h : Disjoint t₁ t₂) :
l ∩ (t₁ ++ t₂) ~ l ∩ t₁ ++ l ∩ t₂ := by
induction l with
| nil => simp
| cons x xs l_ih =>
by_cases h₁ : x ∈ t₁
· have h₂ : x ∉ t₂ := h h₁
simp [*]
by_cases h₂ : x ∈ t₂
· simp only [*, inter_cons_of_not_mem, false_or_iff, mem_append, inter_cons_of_mem,
not_false_iff]
refine Perm.trans (Perm.cons _ l_ih) ?_
change [x] ++ xs ∩ t₁ ++ xs ∩ t₂ ~ xs ∩ t₁ ++ ([x] ++ xs ∩ t₂)
rw [← List.append_assoc]
solve_by_elim [Perm.append_right, perm_append_comm]
· simp [*]
end
theorem Perm.bind_left (l : List α) {f g : α → List β} (h : ∀ a ∈ l, f a ~ g a) :
l.bind f ~ l.bind g :=
Perm.join_congr <| by
rwa [List.forall₂_map_right_iff, List.forall₂_map_left_iff, List.forall₂_same]
theorem bind_append_perm (l : List α) (f g : α → List β) :
l.bind f ++ l.bind g ~ l.bind fun x => f x ++ g x := by
induction' l with a l IH
· simp
simp only [bind_cons, append_assoc]
refine (Perm.trans ?_ (IH.append_left _)).append_left _
rw [← append_assoc, ← append_assoc]
exact perm_append_comm.append_right _
theorem map_append_bind_perm (l : List α) (f : α → β) (g : α → List β) :
l.map f ++ l.bind g ~ l.bind fun x => f x :: g x := by
simpa [← map_eq_bind] using bind_append_perm l (fun x => [f x]) g
theorem Perm.product_right {l₁ l₂ : List α} (t₁ : List β) (p : l₁ ~ l₂) :
product l₁ t₁ ~ product l₂ t₁ :=
p.bind_right _
theorem Perm.product_left (l : List α) {t₁ t₂ : List β} (p : t₁ ~ t₂) :
product l t₁ ~ product l t₂ :=
(Perm.bind_left _) fun _ _ => p.map _
theorem Perm.product {l₁ l₂ : List α} {t₁ t₂ : List β} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) :
product l₁ t₁ ~ product l₂ t₂ :=
(p₁.product_right t₁).trans (p₂.product_left l₂)
theorem perm_lookmap (f : α → Option α) {l₁ l₂ : List α}
(H : Pairwise (fun a b => ∀ c ∈ f a, ∀ d ∈ f b, a = b ∧ c = d) l₁) (p : l₁ ~ l₂) :
lookmap f l₁ ~ lookmap f l₂ := by
induction' p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ _ IH₁ IH₂; · simp
· cases h : f a
· simpa [h] using IH (pairwise_cons.1 H).2
· simp [lookmap_cons_some _ _ h, p]
· cases' h₁ : f a with c <;> cases' h₂ : f b with d
· simpa [h₁, h₂] using swap _ _ _
· simpa [h₁, lookmap_cons_some _ _ h₂] using swap _ _ _
· simpa [lookmap_cons_some _ _ h₁, h₂] using swap _ _ _
· rcases (pairwise_cons.1 H).1 _ (mem_cons.2 (Or.inl rfl)) _ h₂ _ h₁ with ⟨rfl, rfl⟩
exact Perm.refl _
· refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff ?_).1 H))
intro x y h c hc d hd
rw [@eq_comm _ y, @eq_comm _ c]
apply h d hd c hc
theorem Perm.take_inter [DecidableEq α] {xs ys : List α} (n : ℕ) (h : xs ~ ys)
(h' : ys.Nodup) : xs.take n ~ ys.inter (xs.take n) := by
simp only [List.inter]
exact Perm.trans (show xs.take n ~ xs.filter (xs.take n).elem by
conv_lhs => rw [Nodup.take_eq_filter_mem ((Perm.nodup_iff h).2 h')])
(Perm.filter _ h)
theorem Perm.drop_inter [DecidableEq α] {xs ys : List α} (n : ℕ) (h : xs ~ ys) (h' : ys.Nodup) :
xs.drop n ~ ys.inter (xs.drop n) := by
by_cases h'' : n ≤ xs.length
· let n' := xs.length - n
have h₀ : n = xs.length - n' := by rwa [Nat.sub_sub_self]
have h₁ : n' ≤ xs.length := Nat.sub_le ..
have h₂ : xs.drop n = (xs.reverse.take n').reverse := by
rw [take_reverse h₁, h₀, reverse_reverse]
rw [h₂]
apply (reverse_perm _).trans
rw [inter_reverse]
apply Perm.take_inter _ _ h'
apply (reverse_perm _).trans; assumption
· have : drop n xs = [] := by
apply eq_nil_of_length_eq_zero
rw [length_drop, Nat.sub_eq_zero_iff_le]
apply le_of_not_ge h''
simp [this, List.inter]
theorem Perm.dropSlice_inter [DecidableEq α] {xs ys : List α} (n m : ℕ) (h : xs ~ ys)
(h' : ys.Nodup) : List.dropSlice n m xs ~ ys ∩ List.dropSlice n m xs := by
simp only [dropSlice_eq]
have : n ≤ n + m := Nat.le_add_right _ _
have h₂ := h.nodup_iff.2 h'
apply Perm.trans _ (Perm.inter_append _).symm
· exact Perm.append (Perm.take_inter _ h h') (Perm.drop_inter _ h h')
· exact disjoint_take_drop h₂ this
-- enumerating permutations
section Permutations
theorem perm_of_mem_permutationsAux :
∀ {ts is l : List α}, l ∈ permutationsAux ts is → l ~ ts ++ is := by
show ∀ (ts is l : List α), l ∈ permutationsAux ts is → l ~ ts ++ is
refine permutationsAux.rec (by simp) ?_
introv IH1 IH2 m
rw [permutationsAux_cons, permutations, mem_foldr_permutationsAux2] at m
rcases m with (m | ⟨l₁, l₂, m, _, rfl⟩)
· exact (IH1 _ m).trans perm_middle
· have p : l₁ ++ l₂ ~ is := by
simp only [mem_cons] at m
cases' m with e m
· simp [e]
exact is.append_nil ▸ IH2 _ m
exact ((perm_middle.trans (p.cons _)).append_right _).trans (perm_append_comm.cons _)
theorem perm_of_mem_permutations {l₁ l₂ : List α} (h : l₁ ∈ permutations l₂) : l₁ ~ l₂ :=
(eq_or_mem_of_mem_cons h).elim (fun e => e ▸ Perm.refl _) fun m =>
append_nil l₂ ▸ perm_of_mem_permutationsAux m
theorem length_permutationsAux :
∀ ts is : List α, length (permutationsAux ts is) + is.length ! = (length ts + length is)! := by
refine permutationsAux.rec (by simp) ?_
intro t ts is IH1 IH2
have IH2 : length (permutationsAux is nil) + 1 = is.length ! := by simpa using IH2
simp only [factorial, Nat.mul_comm, add_eq] at IH1
rw [permutationsAux_cons,
length_foldr_permutationsAux2' _ _ _ _ _ fun l m => (perm_of_mem_permutations m).length_eq,
permutations, length, length, IH2, Nat.succ_add, Nat.factorial_succ, Nat.mul_comm (_ + 1),
← Nat.succ_eq_add_one, ← IH1, Nat.add_comm (_ * _), Nat.add_assoc, Nat.mul_succ, Nat.mul_comm]
theorem length_permutations (l : List α) : length (permutations l) = (length l)! :=
length_permutationsAux l []
theorem mem_permutations_of_perm_lemma {is l : List α}
(H : l ~ [] ++ is → (∃ (ts' : _) (_ : ts' ~ []), l = ts' ++ is) ∨ l ∈ permutationsAux is []) :
l ~ is → l ∈ permutations is := by simpa [permutations, perm_nil] using H
theorem mem_permutationsAux_of_perm :
∀ {ts is l : List α},
l ~ is ++ ts → (∃ (is' : _) (_ : is' ~ is), l = is' ++ ts) ∨ l ∈ permutationsAux ts is := by
show ∀ (ts is l : List α),
l ~ is ++ ts → (∃ (is' : _) (_ : is' ~ is), l = is' ++ ts) ∨ l ∈ permutationsAux ts is
refine permutationsAux.rec (by simp) ?_
intro t ts is IH1 IH2 l p
rw [permutationsAux_cons, mem_foldr_permutationsAux2]
rcases IH1 _ (p.trans perm_middle) with (⟨is', p', e⟩ | m)
· clear p
subst e
rcases append_of_mem (p'.symm.subset (mem_cons_self _ _)) with ⟨l₁, l₂, e⟩
subst is'
have p := (perm_middle.symm.trans p').cons_inv
cases' l₂ with a l₂'
· exact Or.inl ⟨l₁, by simpa using p⟩
· exact Or.inr (Or.inr ⟨l₁, a :: l₂', mem_permutations_of_perm_lemma (IH2 _) p, by simp⟩)
· exact Or.inr (Or.inl m)
@[simp]
theorem mem_permutations {s t : List α} : s ∈ permutations t ↔ s ~ t :=
⟨perm_of_mem_permutations, mem_permutations_of_perm_lemma mem_permutationsAux_of_perm⟩
-- Porting note: temporary theorem to solve diamond issue
private theorem DecEq_eq [DecidableEq α] :
List.instBEq = @instBEqOfDecidableEq (List α) instDecidableEqList :=
congr_arg BEq.mk <| by
funext l₁ l₂
show (l₁ == l₂) = _
rw [Bool.eq_iff_iff, @beq_iff_eq _ (_), decide_eq_true_iff]
theorem perm_permutations'Aux_comm (a b : α) (l : List α) :
(permutations'Aux a l).bind (permutations'Aux b) ~
(permutations'Aux b l).bind (permutations'Aux a) := by
induction' l with c l ih
· simp [swap]
simp only [permutations'Aux, bind_cons, map_cons, map_map, cons_append]
apply Perm.swap'
have :
∀ a b,
(map (cons c) (permutations'Aux a l)).bind (permutations'Aux b) ~
map (cons b ∘ cons c) (permutations'Aux a l) ++
map (cons c) ((permutations'Aux a l).bind (permutations'Aux b)) := by
intros a' b'
simp only [bind_map, permutations'Aux]
show List.bind (permutations'Aux _ l) (fun a => ([b' :: c :: a] ++
map (cons c) (permutations'Aux _ a))) ~ _
refine (bind_append_perm _ (fun x => [b' :: c :: x]) _).symm.trans ?_
rw [← map_eq_bind, ← map_bind]
exact Perm.refl _
refine (((this _ _).append_left _).trans ?_).trans ((this _ _).append_left _).symm
rw [← append_assoc, ← append_assoc]
exact perm_append_comm.append (ih.map _)
theorem Perm.permutations' {s t : List α} (p : s ~ t) : permutations' s ~ permutations' t := by
induction' p with a s t _ IH a b l s t u _ _ IH₁ IH₂; · simp
· exact IH.bind_right _
· dsimp
rw [bind_assoc, bind_assoc]
apply Perm.bind_left
intro l' _
apply perm_permutations'Aux_comm
· exact IH₁.trans IH₂
theorem permutations_perm_permutations' (ts : List α) : ts.permutations ~ ts.permutations' := by
obtain ⟨n, h⟩ : ∃ n, length ts < n := ⟨_, Nat.lt_succ_self _⟩
induction' n with n IH generalizing ts; · cases h
refine List.reverseRecOn ts (fun _ => ?_) (fun ts t _ h => ?_) h; · simp [permutations]
rw [← concat_eq_append, length_concat, Nat.succ_lt_succ_iff] at h
have IH₂ := (IH ts.reverse (by rwa [length_reverse])).trans (reverse_perm _).permutations'
simp only [permutations_append, foldr_permutationsAux2, permutationsAux_nil,
permutationsAux_cons, append_nil]
refine
(perm_append_comm.trans ((IH₂.bind_right _).append ((IH _ h).map _))).trans
(Perm.trans ?_ perm_append_comm.permutations')
rw [map_eq_bind, singleton_append, permutations']
refine (bind_append_perm _ _ _).trans ?_
refine Perm.of_eq ?_
congr
funext _
rw [permutations'Aux_eq_permutationsAux2, permutationsAux2_append]
@[simp]
theorem mem_permutations' {s t : List α} : s ∈ permutations' t ↔ s ~ t :=
(permutations_perm_permutations' _).symm.mem_iff.trans mem_permutations
theorem Perm.permutations {s t : List α} (h : s ~ t) : permutations s ~ permutations t :=
(permutations_perm_permutations' _).trans <|
h.permutations'.trans (permutations_perm_permutations' _).symm
@[simp]
theorem perm_permutations_iff {s t : List α} : permutations s ~ permutations t ↔ s ~ t :=
⟨fun h => mem_permutations.1 <| h.mem_iff.1 <| mem_permutations.2 (Perm.refl _),
Perm.permutations⟩
@[simp]
theorem perm_permutations'_iff {s t : List α} : permutations' s ~ permutations' t ↔ s ~ t :=
⟨fun h => mem_permutations'.1 <| h.mem_iff.1 <| mem_permutations'.2 (Perm.refl _),
Perm.permutations'⟩
theorem getElem_permutations'Aux (s : List α) (x : α) (n : ℕ)
(hn : n < length (permutations'Aux x s)) :
(permutations'Aux x s)[n] = s.insertNth n x := by
induction' s with y s IH generalizing n
· simp only [length, Nat.zero_add, Nat.lt_one_iff] at hn
simp [hn]
· cases n
· simp [get]
· simpa [get] using IH _ _
theorem get_permutations'Aux (s : List α) (x : α) (n : ℕ)
(hn : n < length (permutations'Aux x s)) :
(permutations'Aux x s).get ⟨n, hn⟩ = s.insertNth n x := by
simp [getElem_permutations'Aux]
set_option linter.deprecated false in
@[deprecated get_permutations'Aux (since := "2024-04-23")]
theorem nthLe_permutations'Aux (s : List α) (x : α) (n : ℕ)
(hn : n < length (permutations'Aux x s)) :
(permutations'Aux x s).nthLe n hn = s.insertNth n x :=
get_permutations'Aux s x n hn
theorem count_permutations'Aux_self [DecidableEq α] (l : List α) (x : α) :
count (x :: l) (permutations'Aux x l) = length (takeWhile (x = ·) l) + 1 := by
induction' l with y l IH generalizing x
· simp [takeWhile, count]
· rw [permutations'Aux, count_cons_self]
by_cases hx : x = y
· subst hx
simpa [takeWhile, Nat.succ_inj', DecEq_eq] using IH _
· rw [takeWhile]
simp only [mem_map, cons.injEq, Ne.symm hx, false_and, and_false, exists_false,
not_false_iff, count_eq_zero_of_not_mem, Nat.zero_add, hx, decide_False, length_nil]
@[simp]
theorem length_permutations'Aux (s : List α) (x : α) :
length (permutations'Aux x s) = length s + 1 := by
induction' s with y s IH
· simp
· simpa using IH
@[deprecated (since := "2024-06-12")]
theorem permutations'Aux_get_zero (s : List α) (x : α)
(hn : 0 < length (permutations'Aux x s) := (by simp)) :
(permutations'Aux x s).get ⟨0, hn⟩ = x :: s :=
get_permutations'Aux _ _ _ _
theorem injective_permutations'Aux (x : α) : Function.Injective (permutations'Aux x) := by
intro s t h
apply insertNth_injective s.length x
have hl : s.length = t.length := by simpa using congr_arg length h
rw [← get_permutations'Aux s x s.length (by simp),
← get_permutations'Aux t x s.length (by simp [hl])]
simp only [get_eq_getElem, h, hl]
theorem nodup_permutations'Aux_of_not_mem (s : List α) (x : α) (hx : x ∉ s) :
Nodup (permutations'Aux x s) := by
induction' s with y s IH
· simp
· simp only [not_or, mem_cons] at hx
simp only [permutations'Aux, nodup_cons, mem_map, cons.injEq, exists_eq_right_right, not_and]
refine ⟨fun _ => Ne.symm hx.left, ?_⟩
rw [nodup_map_iff]
· exact IH hx.right
· simp
set_option linter.deprecated false in
theorem nodup_permutations'Aux_iff {s : List α} {x : α} : Nodup (permutations'Aux x s) ↔ x ∉ s := by
refine ⟨fun h => ?_, nodup_permutations'Aux_of_not_mem _ _⟩
intro H
obtain ⟨k, hk, hk'⟩ := nthLe_of_mem H
rw [nodup_iff_nthLe_inj] at h
refine k.succ_ne_self.symm $ h k (k + 1) ?_ ?_ ?_
· simpa [Nat.lt_succ_iff] using hk.le
· simpa using hk
rw [nthLe_permutations'Aux, nthLe_permutations'Aux]
have hl : length (insertNth k x s) = length (insertNth (k + 1) x s) := by
rw [length_insertNth _ _ hk.le, length_insertNth _ _ (Nat.succ_le_of_lt hk)]
refine ext_nthLe hl fun n hn hn' => ?_
rcases lt_trichotomy n k with (H | rfl | H)
· rw [nthLe_insertNth_of_lt _ _ _ _ H (H.trans hk),
nthLe_insertNth_of_lt _ _ _ _ (H.trans (Nat.lt_succ_self _))]
· rw [nthLe_insertNth_self _ _ _ hk.le, nthLe_insertNth_of_lt _ _ _ _ (Nat.lt_succ_self _) hk,
hk']
· rcases (Nat.succ_le_of_lt H).eq_or_lt with (rfl | H')
· rw [nthLe_insertNth_self _ _ _ (Nat.succ_le_of_lt hk)]
convert hk' using 1
exact nthLe_insertNth_add_succ _ _ _ 0 _
· obtain ⟨m, rfl⟩ := Nat.exists_eq_add_of_lt H'
erw [length_insertNth _ _ hk.le, Nat.succ_lt_succ_iff, Nat.succ_add] at hn
rw [nthLe_insertNth_add_succ]
· convert nthLe_insertNth_add_succ s x k m.succ (by simpa using hn) using 2
· simp [Nat.add_assoc, Nat.add_left_comm]
· simp [Nat.add_left_comm, Nat.add_comm]
· simpa [Nat.succ_add] using hn
set_option linter.deprecated false in
theorem nodup_permutations (s : List α) (hs : Nodup s) : Nodup s.permutations := by
rw [(permutations_perm_permutations' s).nodup_iff]
induction' hs with x l h h' IH
· simp
· rw [permutations']
rw [nodup_bind]
constructor
· intro ys hy
rw [mem_permutations'] at hy
rw [nodup_permutations'Aux_iff, hy.mem_iff]
exact fun H => h x H rfl
· refine IH.pairwise_of_forall_ne fun as ha bs hb H => ?_
rw [disjoint_iff_ne]
rintro a ha' b hb' rfl
obtain ⟨⟨n, hn⟩, hn'⟩ := get_of_mem ha'
obtain ⟨⟨m, hm⟩, hm'⟩ := get_of_mem hb'
rw [mem_permutations'] at ha hb
have hl : as.length = bs.length := (ha.trans hb.symm).length_eq
simp only [Nat.lt_succ_iff, length_permutations'Aux] at hn hm
rw [← nthLe, nthLe_permutations'Aux] at hn' hm'
have hx :
nthLe (insertNth n x as) m (by rwa [length_insertNth _ _ hn, Nat.lt_succ_iff, hl]) = x := by
simp [hn', ← hm', hm]
have hx' :
nthLe (insertNth m x bs) n (by rwa [length_insertNth _ _ hm, Nat.lt_succ_iff, ← hl]) =
x := by
simp [hm', ← hn', hn]
rcases lt_trichotomy n m with (ht | ht | ht)
· suffices x ∈ bs by exact h x (hb.subset this) rfl
rw [← hx', nthLe_insertNth_of_lt _ _ _ _ ht (ht.trans_le hm)]
exact nthLe_mem _ _ _
· simp only [ht] at hm' hn'
rw [← hm'] at hn'
exact H (insertNth_injective _ _ hn')
· suffices x ∈ as by exact h x (ha.subset this) rfl
rw [← hx, nthLe_insertNth_of_lt _ _ _ _ ht (ht.trans_le hn)]
exact nthLe_mem _ _ _
lemma permutations_take_two (x y : α) (s : List α) :
(x :: y :: s).permutations.take 2 = [x :: y :: s, y :: x :: s] := by
induction s <;> simp only [take, permutationsAux, permutationsAux.rec, permutationsAux2, id_eq]
@[simp]
theorem nodup_permutations_iff {s : List α} : Nodup s.permutations ↔ Nodup s := by
refine ⟨?_, nodup_permutations s⟩
contrapose
rw [← exists_duplicate_iff_not_nodup]
intro ⟨x, hs⟩
rw [duplicate_iff_sublist] at hs
obtain ⟨l, ht⟩ := List.Sublist.exists_perm_append hs
rw [List.Perm.nodup_iff (List.Perm.permutations ht), ← exists_duplicate_iff_not_nodup]
use x :: x :: l
rw [List.duplicate_iff_sublist, ← permutations_take_two]
exact take_sublist 2 _
-- TODO: `count s s.permutations = (zipWith count s s.tails).prod`
end Permutations
end List
|
Data\List\Permutation.lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import Mathlib.Data.List.Join
/-!
# Permutations of a list
In this file we prove properties about `List.Permutations`, a list of all permutations of a list. It
is defined in `Data.List.Defs`.
## Order of the permutations
Designed for performance, the order in which the permutations appear in `List.Permutations` is
rather intricate and not very amenable to induction. That's why we also provide `List.Permutations'`
as a less efficient but more straightforward way of listing permutations.
### `List.Permutations`
TODO. In the meantime, you can try decrypting the docstrings.
### `List.Permutations'`
The list of partitions is built by recursion. The permutations of `[]` are `[[]]`. Then, the
permutations of `a :: l` are obtained by taking all permutations of `l` in order and adding `a` in
all positions. Hence, to build `[0, 1, 2, 3].permutations'`, it does
* `[[]]`
* `[[3]]`
* `[[2, 3], [3, 2]]]`
* `[[1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 3, 2], [3, 1, 2], [3, 2, 1]]`
* `[[0, 1, 2, 3], [1, 0, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0],`
`[0, 2, 1, 3], [2, 0, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0],`
`[0, 2, 3, 1], [2, 0, 3, 1], [2, 3, 0, 1], [2, 3, 1, 0],`
`[0, 1, 3, 2], [1, 0, 3, 2], [1, 3, 0, 2], [1, 3, 2, 0],`
`[0, 3, 1, 2], [3, 0, 1, 2], [3, 1, 0, 2], [3, 1, 2, 0],`
`[0, 3, 2, 1], [3, 0, 2, 1], [3, 2, 0, 1], [3, 2, 1, 0]]`
## TODO
Show that `l.Nodup → l.permutations.Nodup`. See `Data.Fintype.List`.
-/
-- Make sure we don't import algebra
assert_not_exists Monoid
open Nat
variable {α β : Type*}
namespace List
theorem permutationsAux2_fst (t : α) (ts : List α) (r : List β) :
∀ (ys : List α) (f : List α → β), (permutationsAux2 t ts r ys f).1 = ys ++ ts
| [], f => rfl
| y :: ys, f => by simp [permutationsAux2, permutationsAux2_fst t _ _ ys]
@[simp]
theorem permutationsAux2_snd_nil (t : α) (ts : List α) (r : List β) (f : List α → β) :
(permutationsAux2 t ts r [] f).2 = r :=
rfl
@[simp]
theorem permutationsAux2_snd_cons (t : α) (ts : List α) (r : List β) (y : α) (ys : List α)
(f : List α → β) :
(permutationsAux2 t ts r (y :: ys) f).2 =
f (t :: y :: ys ++ ts) :: (permutationsAux2 t ts r ys fun x : List α => f (y :: x)).2 := by
simp [permutationsAux2, permutationsAux2_fst t _ _ ys]
/-- The `r` argument to `permutationsAux2` is the same as appending. -/
theorem permutationsAux2_append (t : α) (ts : List α) (r : List β) (ys : List α) (f : List α → β) :
(permutationsAux2 t ts nil ys f).2 ++ r = (permutationsAux2 t ts r ys f).2 := by
induction ys generalizing f <;> simp [*]
/-- The `ts` argument to `permutationsAux2` can be folded into the `f` argument. -/
theorem permutationsAux2_comp_append {t : α} {ts ys : List α} {r : List β} (f : List α → β) :
((permutationsAux2 t [] r ys) fun x => f (x ++ ts)).2 = (permutationsAux2 t ts r ys f).2 := by
induction' ys with ys_hd _ ys_ih generalizing f
· simp
· simp [ys_ih fun xs => f (ys_hd :: xs)]
theorem map_permutationsAux2' {α' β'} (g : α → α') (g' : β → β') (t : α) (ts ys : List α)
(r : List β) (f : List α → β) (f' : List α' → β') (H : ∀ a, g' (f a) = f' (map g a)) :
map g' (permutationsAux2 t ts r ys f).2 =
(permutationsAux2 (g t) (map g ts) (map g' r) (map g ys) f').2 := by
induction' ys with ys_hd _ ys_ih generalizing f f'
· simp
· simp only [map, permutationsAux2_snd_cons, cons_append, cons.injEq]
rw [ys_ih, permutationsAux2_fst]
· refine ⟨?_, rfl⟩
simp only [← map_cons, ← map_append]; apply H
· intro a; apply H
/-- The `f` argument to `permutationsAux2` when `r = []` can be eliminated. -/
theorem map_permutationsAux2 (t : α) (ts : List α) (ys : List α) (f : List α → β) :
(permutationsAux2 t ts [] ys id).2.map f = (permutationsAux2 t ts [] ys f).2 := by
rw [map_permutationsAux2' id, map_id, map_id]
· rfl
simp
/-- An expository lemma to show how all of `ts`, `r`, and `f` can be eliminated from
`permutationsAux2`.
`(permutationsAux2 t [] [] ys id).2`, which appears on the RHS, is a list whose elements are
produced by inserting `t` into every non-terminal position of `ys` in order. As an example:
```lean
#eval permutationsAux2 1 [] [] [2, 3, 4] id
-- [[1, 2, 3, 4], [2, 1, 3, 4], [2, 3, 1, 4]]
```
-/
theorem permutationsAux2_snd_eq (t : α) (ts : List α) (r : List β) (ys : List α) (f : List α → β) :
(permutationsAux2 t ts r ys f).2 =
((permutationsAux2 t [] [] ys id).2.map fun x => f (x ++ ts)) ++ r := by
rw [← permutationsAux2_append, map_permutationsAux2, permutationsAux2_comp_append]
theorem map_map_permutationsAux2 {α'} (g : α → α') (t : α) (ts ys : List α) :
map (map g) (permutationsAux2 t ts [] ys id).2 =
(permutationsAux2 (g t) (map g ts) [] (map g ys) id).2 :=
map_permutationsAux2' _ _ _ _ _ _ _ _ fun _ => rfl
theorem map_map_permutations'Aux (f : α → β) (t : α) (ts : List α) :
map (map f) (permutations'Aux t ts) = permutations'Aux (f t) (map f ts) := by
induction' ts with a ts ih
· rfl
· simp only [permutations'Aux, map_cons, map_map, ← ih, cons.injEq, true_and, Function.comp_def]
theorem permutations'Aux_eq_permutationsAux2 (t : α) (ts : List α) :
permutations'Aux t ts = (permutationsAux2 t [] [ts ++ [t]] ts id).2 := by
induction' ts with a ts ih; · rfl
simp only [permutations'Aux, ih, cons_append, permutationsAux2_snd_cons, append_nil, id_eq,
cons.injEq, true_and]
simp (config := { singlePass := true }) only [← permutationsAux2_append]
simp [map_permutationsAux2]
theorem mem_permutationsAux2 {t : α} {ts : List α} {ys : List α} {l l' : List α} :
l' ∈ (permutationsAux2 t ts [] ys (l ++ ·)).2 ↔
∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l' = l ++ l₁ ++ t :: l₂ ++ ts := by
induction' ys with y ys ih generalizing l
· simp (config := { contextual := true })
rw [permutationsAux2_snd_cons,
show (fun x : List α => l ++ y :: x) = (l ++ [y] ++ ·) by funext _; simp, mem_cons, ih]
constructor
· rintro (rfl | ⟨l₁, l₂, l0, rfl, rfl⟩)
· exact ⟨[], y :: ys, by simp⟩
· exact ⟨y :: l₁, l₂, l0, by simp⟩
· rintro ⟨_ | ⟨y', l₁⟩, l₂, l0, ye, rfl⟩
· simp [ye]
· simp only [cons_append] at ye
rcases ye with ⟨rfl, rfl⟩
exact Or.inr ⟨l₁, l₂, l0, by simp⟩
theorem mem_permutationsAux2' {t : α} {ts : List α} {ys : List α} {l : List α} :
l ∈ (permutationsAux2 t ts [] ys id).2 ↔
∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l = l₁ ++ t :: l₂ ++ ts := by
rw [show @id (List α) = ([] ++ ·) by funext _; rfl]; apply mem_permutationsAux2
theorem length_permutationsAux2 (t : α) (ts : List α) (ys : List α) (f : List α → β) :
length (permutationsAux2 t ts [] ys f).2 = length ys := by
induction ys generalizing f <;> simp [*]
theorem foldr_permutationsAux2 (t : α) (ts : List α) (r L : List (List α)) :
foldr (fun y r => (permutationsAux2 t ts r y id).2) r L =
(L.bind fun y => (permutationsAux2 t ts [] y id).2) ++ r := by
induction' L with l L ih
· rfl
· simp_rw [foldr_cons, ih, bind_cons, append_assoc, permutationsAux2_append]
theorem mem_foldr_permutationsAux2 {t : α} {ts : List α} {r L : List (List α)} {l' : List α} :
l' ∈ foldr (fun y r => (permutationsAux2 t ts r y id).2) r L ↔
l' ∈ r ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ L ∧ l₂ ≠ [] ∧ l' = l₁ ++ t :: l₂ ++ ts := by
have :
(∃ a : List α,
a ∈ L ∧ ∃ l₁ l₂ : List α, ¬l₂ = nil ∧ a = l₁ ++ l₂ ∧ l' = l₁ ++ t :: (l₂ ++ ts)) ↔
∃ l₁ l₂ : List α, ¬l₂ = nil ∧ l₁ ++ l₂ ∈ L ∧ l' = l₁ ++ t :: (l₂ ++ ts) :=
⟨fun ⟨_, aL, l₁, l₂, l0, e, h⟩ => ⟨l₁, l₂, l0, e ▸ aL, h⟩, fun ⟨l₁, l₂, l0, aL, h⟩ =>
⟨_, aL, l₁, l₂, l0, rfl, h⟩⟩
rw [foldr_permutationsAux2]
simp only [mem_permutationsAux2', ← this, or_comm, and_left_comm, mem_append, mem_bind,
append_assoc, cons_append, exists_prop]
theorem length_foldr_permutationsAux2 (t : α) (ts : List α) (r L : List (List α)) :
length (foldr (fun y r => (permutationsAux2 t ts r y id).2) r L) =
Nat.sum (map length L) + length r := by
simp [foldr_permutationsAux2, (· ∘ ·), length_permutationsAux2, length_bind']
theorem length_foldr_permutationsAux2' (t : α) (ts : List α) (r L : List (List α)) (n)
(H : ∀ l ∈ L, length l = n) :
length (foldr (fun y r => (permutationsAux2 t ts r y id).2) r L) = n * length L + length r := by
rw [length_foldr_permutationsAux2, (_ : Nat.sum (map length L) = n * length L)]
induction' L with l L ih
· simp
have sum_map : Nat.sum (map length L) = n * length L := ih fun l m => H l (mem_cons_of_mem _ m)
have length_l : length l = n := H _ (mem_cons_self _ _)
simp [sum_map, length_l, Nat.mul_add, Nat.add_comm, mul_succ]
@[simp]
theorem permutationsAux_nil (is : List α) : permutationsAux [] is = [] := by
rw [permutationsAux, permutationsAux.rec]
@[simp]
theorem permutationsAux_cons (t : α) (ts is : List α) :
permutationsAux (t :: ts) is =
foldr (fun y r => (permutationsAux2 t ts r y id).2) (permutationsAux ts (t :: is))
(permutations is) := by
rw [permutationsAux, permutationsAux.rec]; rfl
@[simp]
theorem permutations_nil : permutations ([] : List α) = [[]] := by
rw [permutations, permutationsAux_nil]
theorem map_permutationsAux (f : α → β) :
∀ ts is :
List α, map (map f) (permutationsAux ts is) = permutationsAux (map f ts) (map f is) := by
refine permutationsAux.rec (by simp) ?_
introv IH1 IH2; rw [map] at IH2
simp only [foldr_permutationsAux2, map_append, map, map_map_permutationsAux2, permutations,
bind_map, IH1, append_assoc, permutationsAux_cons, bind_cons, ← IH2, map_bind]
theorem map_permutations (f : α → β) (ts : List α) :
map (map f) (permutations ts) = permutations (map f ts) := by
rw [permutations, permutations, map, map_permutationsAux, map]
theorem map_permutations' (f : α → β) (ts : List α) :
map (map f) (permutations' ts) = permutations' (map f ts) := by
induction' ts with t ts ih <;> [rfl; simp [← ih, map_bind, ← map_map_permutations'Aux, bind_map]]
theorem permutationsAux_append (is is' ts : List α) :
permutationsAux (is ++ ts) is' =
(permutationsAux is is').map (· ++ ts) ++ permutationsAux ts (is.reverse ++ is') := by
induction' is with t is ih generalizing is'; · simp
simp only [foldr_permutationsAux2, ih, map_bind, cons_append, permutationsAux_cons, map_append,
reverse_cons, append_assoc, singleton_append]
congr 2
funext _
rw [map_permutationsAux2]
simp (config := { singlePass := true }) only [← permutationsAux2_comp_append]
simp only [id, append_assoc]
theorem permutations_append (is ts : List α) :
permutations (is ++ ts) = (permutations is).map (· ++ ts) ++ permutationsAux ts is.reverse := by
simp [permutations, permutationsAux_append]
end List
|
Data\List\Pi.lean | /-
Copyright (c) 2023 Yuyang Zhao. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yuyang Zhao
-/
import Mathlib.Data.Multiset.Pi
/-!
# The cartesian product of lists
## Main definitions
* `List.pi`: Cartesian product of lists indexed by a list.
-/
namespace List
namespace Pi
variable {ι : Type*} [DecidableEq ι] {α : ι → Sort*}
/-- Given `α : ι → Sort*`, `Pi.nil α` is the trivial dependent function out of the empty list. -/
def nil (α : ι → Sort*) : (∀ i ∈ ([] : List ι), α i) :=
nofun
variable {i : ι} {l : List ι}
/-- Given `f` a function whose domain is `i :: l`, get its value at `i`. -/
def head (f : ∀ j ∈ i :: l, α j) : α i :=
f i (mem_cons_self _ _)
/-- Given `f` a function whose domain is `i :: l`, produce a function whose domain
is restricted to `l`. -/
def tail (f : ∀ j ∈ i :: l, α j) : ∀ j ∈ l, α j :=
fun j hj ↦ f j (mem_cons_of_mem _ hj)
variable (i l)
/-- Given `α : ι → Sort*`, a list `l` and a term `i`, as well as a term `a : α i` and a
function `f` such that `f j : α j` for all `j` in `l`, `Pi.cons a f` is a function `g` such
that `g k : α k` for all `k` in `i :: l`. -/
def cons (a : α i) (f : ∀ j ∈ l, α j) : ∀ j ∈ i :: l, α j :=
Multiset.Pi.cons (α := ι) l _ a f
variable {i l}
lemma cons_def (a : α i) (f : ∀ j ∈ l, α j) : cons _ _ a f =
fun j hj ↦ if h : j = i then h.symm.rec a else f j <| (mem_cons.1 hj).resolve_left h :=
rfl
@[simp] lemma _root_.Multiset.Pi.cons_coe {l : List ι} (a : α i) (f : ∀ j ∈ l, α j) :
Multiset.Pi.cons l _ a f = cons _ _ a f :=
rfl
@[simp] lemma cons_eta (f : ∀ j ∈ i :: l, α j) :
cons _ _ (head f) (tail f) = f :=
Multiset.Pi.cons_eta (α := ι) (m := l) f
lemma cons_map (a : α i) (f : ∀ j ∈ l, α j)
{α' : ι → Sort*} (φ : ∀ ⦃j⦄, α j → α' j) :
cons _ _ (φ a) (fun j hj ↦ φ (f j hj)) = (fun j hj ↦ φ ((cons _ _ a f) j hj)) :=
Multiset.Pi.cons_map _ _ _
lemma forall_rel_cons_ext {r : ∀ ⦃i⦄, α i → α i → Prop} {a₁ a₂ : α i} {f₁ f₂ : ∀ j ∈ l, α j}
(ha : r a₁ a₂) (hf : ∀ (i : ι) (hi : i ∈ l), r (f₁ i hi) (f₂ i hi)) :
∀ j hj, r (cons _ _ a₁ f₁ j hj) (cons _ _ a₂ f₂ j hj) :=
Multiset.Pi.forall_rel_cons_ext (α := ι) (m := l) ha hf
end Pi
variable {ι : Type*} [DecidableEq ι] {α : ι → Type*}
/-- `pi xs f` creates the list of functions `g` such that, for `x ∈ xs`, `g x ∈ f x` -/
def pi : ∀ l : List ι, (∀ i, List (α i)) → List (∀ i, i ∈ l → α i)
| [], _ => [List.Pi.nil α]
| i :: l, fs => (fs i).bind (fun b ↦ (pi l fs).map (List.Pi.cons _ _ b))
@[simp] lemma pi_nil (t : ∀ i, List (α i)) :
pi [] t = [Pi.nil α] :=
rfl
@[simp] lemma pi_cons (i : ι) (l : List ι) (t : ∀ j, List (α j)) :
pi (i :: l) t = ((t i).bind fun b ↦ (pi l t).map <| Pi.cons _ _ b) :=
rfl
lemma _root_.Multiset.pi_coe (l : List ι) (fs : ∀ i, List (α i)) :
(l : Multiset ι).pi (fs ·) = (↑(pi l fs) : Multiset (∀ i ∈ l, α i)) := by
induction' l with i l ih
· change Multiset.pi 0 _ = _
simp only [Multiset.coe_singleton, Multiset.pi_zero, pi_nil, Multiset.singleton_inj]
ext i hi
simp at hi
· change Multiset.pi (i ::ₘ ↑l) _ = _
simp [ih, Multiset.coe_bind, - Multiset.cons_coe]
lemma mem_pi {l : List ι} (fs : ∀ i, List (α i)) :
∀ f : ∀ i ∈ l, α i, (f ∈ pi l fs) ↔ (∀ i (hi : i ∈ l), f i hi ∈ fs i) := by
intros f
convert @Multiset.mem_pi ι _ α ↑l (fs ·) f using 1
rw [Multiset.pi_coe]
rfl
end List
|
Data\List\Prime.lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jens Wagemaker, Anne Baanen
-/
import Mathlib.Algebra.Associated.Basic
import Mathlib.Algebra.BigOperators.Group.List
import Mathlib.Data.List.Perm
/-!
# Products of lists of prime elements.
This file contains some theorems relating `Prime` and products of `List`s.
-/
open List
section CommMonoidWithZero
variable {M : Type*} [CommMonoidWithZero M]
/-- Prime `p` divides the product of a list `L` iff it divides some `a ∈ L` -/
theorem Prime.dvd_prod_iff {p : M} {L : List M} (pp : Prime p) : p ∣ L.prod ↔ ∃ a ∈ L, p ∣ a := by
constructor
· intro h
induction' L with L_hd L_tl L_ih
· rw [prod_nil] at h
exact absurd h pp.not_dvd_one
· rw [prod_cons] at h
cases' pp.dvd_or_dvd h with hd hd
· exact ⟨L_hd, mem_cons_self L_hd L_tl, hd⟩
· obtain ⟨x, hx1, hx2⟩ := L_ih hd
exact ⟨x, mem_cons_of_mem L_hd hx1, hx2⟩
· exact fun ⟨a, ha1, ha2⟩ => dvd_trans ha2 (dvd_prod ha1)
theorem Prime.not_dvd_prod {p : M} {L : List M} (pp : Prime p) (hL : ∀ a ∈ L, ¬p ∣ a) :
¬p ∣ L.prod :=
mt (Prime.dvd_prod_iff pp).1 <| not_exists.2 fun a => not_and.2 (hL a)
end CommMonoidWithZero
section CancelCommMonoidWithZero
variable {M : Type*} [CancelCommMonoidWithZero M] [Unique (Units M)]
theorem mem_list_primes_of_dvd_prod {p : M} (hp : Prime p) {L : List M} (hL : ∀ q ∈ L, Prime q)
(hpL : p ∣ L.prod) : p ∈ L := by
obtain ⟨x, hx1, hx2⟩ := hp.dvd_prod_iff.mp hpL
rwa [(prime_dvd_prime_iff_eq hp (hL x hx1)).mp hx2]
theorem perm_of_prod_eq_prod :
∀ {l₁ l₂ : List M}, l₁.prod = l₂.prod → (∀ p ∈ l₁, Prime p) → (∀ p ∈ l₂, Prime p) → Perm l₁ l₂
| [], [], _, _, _ => Perm.nil
| [], a :: l, h₁, _, h₃ =>
have ha : a ∣ 1 := @prod_nil M _ ▸ h₁.symm ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _
absurd ha (Prime.not_dvd_one (h₃ a (mem_cons_self _ _)))
| a :: l, [], h₁, h₂, _ =>
have ha : a ∣ 1 := @prod_nil M _ ▸ h₁ ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _
absurd ha (Prime.not_dvd_one (h₂ a (mem_cons_self _ _)))
| a :: l₁, b :: l₂, h, hl₁, hl₂ => by
classical
have hl₁' : ∀ p ∈ l₁, Prime p := fun p hp => hl₁ p (mem_cons_of_mem _ hp)
have hl₂' : ∀ p ∈ (b :: l₂).erase a, Prime p := fun p hp => hl₂ p (mem_of_mem_erase hp)
have ha : a ∈ b :: l₂ :=
mem_list_primes_of_dvd_prod (hl₁ a (mem_cons_self _ _)) hl₂
(h ▸ by rw [prod_cons]; exact dvd_mul_right _ _)
have hb : b :: l₂ ~ a :: (b :: l₂).erase a := perm_cons_erase ha
have hl : prod l₁ = prod ((b :: l₂).erase a) :=
(mul_right_inj' (hl₁ a (mem_cons_self _ _)).ne_zero).1 <| by
rwa [← prod_cons, ← prod_cons, ← hb.prod_eq]
exact Perm.trans ((perm_of_prod_eq_prod hl hl₁' hl₂').cons _) hb.symm
end CancelCommMonoidWithZero
|
Data\List\ProdSigma.lean | /-
Copyright (c) 2015 Leonardo de Moura. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
-/
import Mathlib.Data.List.Basic
import Mathlib.Data.Sigma.Basic
import Batteries.Data.Nat.Lemmas
/-!
# Lists in product and sigma types
This file proves basic properties of `List.product` and `List.sigma`, which are list constructions
living in `Prod` and `Sigma` types respectively. Their definitions can be found in
[`Data.List.Defs`](./defs). Beware, this is not about `List.prod`, the multiplicative product.
-/
variable {α β : Type*}
namespace List
/-! ### product -/
@[simp]
theorem nil_product (l : List β) : (@nil α) ×ˢ l = [] :=
rfl
@[simp]
theorem product_cons (a : α) (l₁ : List α) (l₂ : List β) :
(a :: l₁) ×ˢ l₂ = map (fun b => (a, b)) l₂ ++ (l₁ ×ˢ l₂) :=
rfl
@[simp]
theorem product_nil : ∀ l : List α, l ×ˢ (@nil β) = []
| [] => rfl
| _ :: l => by simp [product_cons, product_nil l]
@[simp]
theorem mem_product {l₁ : List α} {l₂ : List β} {a : α} {b : β} :
(a, b) ∈ l₁ ×ˢ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ := by
simp_all [SProd.sprod, product, mem_bind, mem_map, Prod.ext_iff, exists_prop, and_left_comm,
exists_and_left, exists_eq_left, exists_eq_right]
theorem length_product (l₁ : List α) (l₂ : List β) :
length (l₁ ×ˢ l₂) = length l₁ * length l₂ := by
induction' l₁ with x l₁ IH
· exact (Nat.zero_mul _).symm
· simp only [length, product_cons, length_append, IH, Nat.add_mul, Nat.one_mul, length_map,
Nat.add_comm]
/-! ### sigma -/
variable {σ : α → Type*}
@[simp]
theorem nil_sigma (l : ∀ a, List (σ a)) : (@nil α).sigma l = [] :=
rfl
@[simp]
theorem sigma_cons (a : α) (l₁ : List α) (l₂ : ∀ a, List (σ a)) :
(a :: l₁).sigma l₂ = map (Sigma.mk a) (l₂ a) ++ l₁.sigma l₂ :=
rfl
@[simp]
theorem sigma_nil : ∀ l : List α, (l.sigma fun a => @nil (σ a)) = []
| [] => rfl
| _ :: l => by simp [sigma_cons, sigma_nil l]
@[simp]
theorem mem_sigma {l₁ : List α} {l₂ : ∀ a, List (σ a)} {a : α} {b : σ a} :
Sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a := by
simp [List.sigma, mem_bind, mem_map, exists_prop, exists_and_left, and_left_comm,
exists_eq_left, heq_iff_eq, exists_eq_right]
/-- See `List.length_sigma` for the corresponding statement using `List.sum`. -/
theorem length_sigma' (l₁ : List α) (l₂ : ∀ a, List (σ a)) :
length (l₁.sigma l₂) = Nat.sum (l₁.map fun a ↦ length (l₂ a)) := by
induction' l₁ with x l₁ IH
· rfl
· simp only [map, sigma_cons, length_append, length_map, IH, Nat.sum_cons]
end List
|
Data\List\Range.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kenny Lau, Scott Morrison
-/
import Mathlib.Data.List.Chain
import Mathlib.Data.List.Nodup
import Mathlib.Data.List.Pairwise
import Batteries.Data.Nat.Lemmas
/-!
# Ranges of naturals as lists
This file shows basic results about `List.iota`, `List.range`, `List.range'`
and defines `List.finRange`.
`finRange n` is the list of elements of `Fin n`.
`iota n = [n, n - 1, ..., 1]` and `range n = [0, ..., n - 1]` are basic list constructions used for
tactics. `range' a b = [a, ..., a + b - 1]` is there to help prove properties about them.
Actual maths should use `List.Ico` instead.
-/
universe u
open Nat
namespace List
variable {α : Type u}
set_option linter.deprecated false in
@[simp]
theorem nthLe_range' {n m step} (i) (H : i < (range' n m step).length) :
nthLe (range' n m step) i H = n + step * i := get_range' i H
set_option linter.deprecated false in
theorem nthLe_range'_1 {n m} (i) (H : i < (range' n m).length) :
nthLe (range' n m) i H = n + i := by simp
theorem chain'_range_succ (r : ℕ → ℕ → Prop) (n : ℕ) :
Chain' r (range n.succ) ↔ ∀ m < n, r m m.succ := by
rw [range_succ]
induction' n with n hn
· simp
· rw [range_succ]
simp only [append_assoc, singleton_append, chain'_append_cons_cons, chain'_singleton,
and_true_iff]
rw [hn, forall_lt_succ]
theorem chain_range_succ (r : ℕ → ℕ → Prop) (n a : ℕ) :
Chain r a (range n.succ) ↔ r a 0 ∧ ∀ m < n, r m m.succ := by
rw [range_succ_eq_map, chain_cons, and_congr_right_iff, ← chain'_range_succ, range_succ_eq_map]
exact fun _ => Iff.rfl
/-- All elements of `Fin n`, from `0` to `n-1`. The corresponding finset is `Finset.univ`. -/
def finRange (n : ℕ) : List (Fin n) :=
(range n).pmap Fin.mk fun _ => List.mem_range.1
@[simp]
theorem finRange_zero : finRange 0 = [] :=
rfl
@[simp]
theorem mem_finRange {n : ℕ} (a : Fin n) : a ∈ finRange n :=
mem_pmap.2
⟨a.1, mem_range.2 a.2, by
cases a
rfl⟩
theorem nodup_finRange (n : ℕ) : (finRange n).Nodup :=
(Pairwise.pmap (nodup_range n) _) fun _ _ _ _ => @Fin.ne_of_vne _ ⟨_, _⟩ ⟨_, _⟩
@[simp]
theorem length_finRange (n : ℕ) : (finRange n).length = n := by
rw [finRange, length_pmap, length_range]
@[simp]
theorem finRange_eq_nil {n : ℕ} : finRange n = [] ↔ n = 0 := by
rw [← length_eq_zero, length_finRange]
theorem pairwise_lt_finRange (n : ℕ) : Pairwise (· < ·) (finRange n) :=
(List.pairwise_lt_range n).pmap (by simp) (by simp)
theorem pairwise_le_finRange (n : ℕ) : Pairwise (· ≤ ·) (finRange n) :=
(List.pairwise_le_range n).pmap (by simp) (by simp)
set_option linter.deprecated false in
@[simp]
theorem nthLe_range {n} (i) (H : i < (range n).length) : nthLe (range n) i H = i :=
get_range i H
@[simp]
theorem getElem_finRange {n : ℕ} {i : ℕ} (h) :
(finRange n)[i] = ⟨i, length_finRange n ▸ h⟩ := by
simp only [finRange, getElem_range, getElem_pmap]
-- Porting note (#10756): new theorem
theorem get_finRange {n : ℕ} {i : ℕ} (h) :
(finRange n).get ⟨i, h⟩ = ⟨i, length_finRange n ▸ h⟩ := by
simp
@[simp]
theorem finRange_map_get (l : List α) : (finRange l.length).map l.get = l :=
List.ext_get (by simp) (by simp)
set_option linter.deprecated false in
@[simp]
theorem nthLe_finRange {n : ℕ} {i : ℕ} (h) :
(finRange n).nthLe i h = ⟨i, length_finRange n ▸ h⟩ :=
get_finRange h
@[simp] theorem indexOf_finRange {k : ℕ} (i : Fin k) : (finRange k).indexOf i = i := by
have : (finRange k).indexOf i < (finRange k).length := indexOf_lt_length.mpr (by simp)
have h₁ : (finRange k).get ⟨(finRange k).indexOf i, this⟩ = i := indexOf_get this
have h₂ : (finRange k).get ⟨i, by simp⟩ = i := get_finRange _
simpa using (Nodup.get_inj_iff (nodup_finRange k)).mp (Eq.trans h₁ h₂.symm)
section Ranges
/-- From `l : List ℕ`, construct `l.ranges : List (List ℕ)` such that
`l.ranges.map List.length = l` and `l.ranges.join = range l.sum`
* Example: `[1,2,3].ranges = [[0],[1,2],[3,4,5]]` -/
def ranges : List ℕ → List (List ℕ)
| [] => nil
| a::l => range a::(ranges l).map (map (a + ·))
/-- The members of `l.ranges` are pairwise disjoint -/
theorem ranges_disjoint (l : List ℕ) :
Pairwise Disjoint (ranges l) := by
induction l with
| nil => exact Pairwise.nil
| cons a l hl =>
simp only [ranges, pairwise_cons]
constructor
· intro s hs
obtain ⟨s', _, rfl⟩ := mem_map.mp hs
intro u hu
rw [mem_map]
rintro ⟨v, _, rfl⟩
rw [mem_range] at hu
omega
· rw [pairwise_map]
apply Pairwise.imp _ hl
intro u v
apply disjoint_map
exact fun u v => Nat.add_left_cancel
/-- The lengths of the members of `l.ranges` are those given by `l` -/
theorem ranges_length (l : List ℕ) :
l.ranges.map length = l := by
induction l with
| nil => simp only [ranges, map_nil]
| cons a l hl => -- (a :: l)
simp only [map, length_range, map_map, cons.injEq, true_and]
conv_rhs => rw [← hl]
apply map_congr_left
intro s _
simp only [Function.comp_apply, length_map]
/-- See `List.ranges_join` for the version about `List.sum`. -/
lemma ranges_join' : ∀ l : List ℕ, l.ranges.join = range (Nat.sum l)
| [] => rfl
| a :: l => by simp only [sum_cons, join, ← map_join, ranges_join', range_add]
/-- Any entry of any member of `l.ranges` is strictly smaller than `Nat.sum l`.
See `List.mem_mem_ranges_iff_lt_sum` for the version about `List.sum`. -/
lemma mem_mem_ranges_iff_lt_natSum (l : List ℕ) {n : ℕ} :
(∃ s ∈ l.ranges, n ∈ s) ↔ n < Nat.sum l := by
rw [← mem_range, ← ranges_join', mem_join]
/-- The members of `l.ranges` have no duplicate -/
theorem ranges_nodup {l s : List ℕ} (hs : s ∈ ranges l) : s.Nodup :=
(List.pairwise_join.mp $ by rw [ranges_join']; exact nodup_range _).1 s hs
end Ranges
end List
|
Data\List\ReduceOption.lean | /-
Copyright (c) 2020 Yakov Pechersky. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky
-/
import Mathlib.Data.List.Basic
/-!
# Properties of `List.reduceOption`
In this file we prove basic lemmas about `List.reduceOption`.
-/
namespace List
variable {α β : Type*}
@[simp]
theorem reduceOption_cons_of_some (x : α) (l : List (Option α)) :
reduceOption (some x :: l) = x :: l.reduceOption := by
simp only [reduceOption, filterMap, id, eq_self_iff_true, and_self_iff]
@[simp]
theorem reduceOption_cons_of_none (l : List (Option α)) :
reduceOption (none :: l) = l.reduceOption := by simp only [reduceOption, filterMap, id]
@[simp]
theorem reduceOption_nil : @reduceOption α [] = [] :=
rfl
@[simp]
theorem reduceOption_map {l : List (Option α)} {f : α → β} :
reduceOption (map (Option.map f) l) = map f (reduceOption l) := by
induction' l with hd tl hl
· simp only [reduceOption_nil, map_nil]
· cases hd <;>
simpa [true_and_iff, Option.map_some', map, eq_self_iff_true,
reduceOption_cons_of_some] using hl
theorem reduceOption_append (l l' : List (Option α)) :
(l ++ l').reduceOption = l.reduceOption ++ l'.reduceOption :=
filterMap_append l l' id
theorem reduceOption_length_eq {l : List (Option α)} :
l.reduceOption.length = (l.filter Option.isSome).length := by
induction' l with hd tl hl
· simp_rw [reduceOption_nil, filter_nil, length]
· cases hd <;> simp [hl]
theorem length_eq_reduceOption_length_add_filter_none {l : List (Option α)} :
l.length = l.reduceOption.length + (l.filter Option.isNone).length := by
simp_rw [reduceOption_length_eq, l.length_eq_length_filter_add Option.isSome, Option.bnot_isSome]
theorem reduceOption_length_le (l : List (Option α)) : l.reduceOption.length ≤ l.length := by
rw [length_eq_reduceOption_length_add_filter_none]
apply Nat.le_add_right
theorem reduceOption_length_eq_iff {l : List (Option α)} :
l.reduceOption.length = l.length ↔ ∀ x ∈ l, Option.isSome x := by
rw [reduceOption_length_eq, List.filter_length_eq_length]
theorem reduceOption_length_lt_iff {l : List (Option α)} :
l.reduceOption.length < l.length ↔ none ∈ l := by
rw [Nat.lt_iff_le_and_ne, and_iff_right (reduceOption_length_le l), Ne,
reduceOption_length_eq_iff]
induction l <;> simp
rw [@eq_comm _ none, ← Option.not_isSome_iff_eq_none, Decidable.imp_iff_not_or]
theorem reduceOption_singleton (x : Option α) : [x].reduceOption = x.toList := by cases x <;> rfl
theorem reduceOption_concat (l : List (Option α)) (x : Option α) :
(l.concat x).reduceOption = l.reduceOption ++ x.toList := by
induction' l with hd tl hl generalizing x
· cases x <;> simp [Option.toList]
· simp only [concat_eq_append, reduceOption_append] at hl
cases hd <;> simp [hl, reduceOption_append]
theorem reduceOption_concat_of_some (l : List (Option α)) (x : α) :
(l.concat (some x)).reduceOption = l.reduceOption.concat x := by
simp only [reduceOption_nil, concat_eq_append, reduceOption_append, reduceOption_cons_of_some]
theorem reduceOption_mem_iff {l : List (Option α)} {x : α} : x ∈ l.reduceOption ↔ some x ∈ l := by
simp only [reduceOption, id, mem_filterMap, exists_eq_right]
theorem reduceOption_get?_iff {l : List (Option α)} {x : α} :
(∃ i, l.get? i = some (some x)) ↔ ∃ i, l.reduceOption.get? i = some x := by
rw [← mem_iff_get?, ← mem_iff_get?, reduceOption_mem_iff]
end List
|
Data\List\Rotate.lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Yakov Pechersky
-/
import Mathlib.Data.List.Nodup
import Mathlib.Data.Nat.Defs
import Mathlib.Data.List.Infix
/-!
# List rotation
This file proves basic results about `List.rotate`, the list rotation.
## Main declarations
* `List.IsRotated l₁ l₂`: States that `l₁` is a rotated version of `l₂`.
* `List.cyclicPermutations l`: The list of all cyclic permutants of `l`, up to the length of `l`.
## Tags
rotated, rotation, permutation, cycle
-/
universe u
variable {α : Type u}
open Nat Function
namespace List
theorem rotate_mod (l : List α) (n : ℕ) : l.rotate (n % l.length) = l.rotate n := by simp [rotate]
@[simp]
theorem rotate_nil (n : ℕ) : ([] : List α).rotate n = [] := by simp [rotate]
@[simp]
theorem rotate_zero (l : List α) : l.rotate 0 = l := by simp [rotate]
-- Porting note: removing simp, simp can prove it
theorem rotate'_nil (n : ℕ) : ([] : List α).rotate' n = [] := by cases n <;> rfl
@[simp]
theorem rotate'_zero (l : List α) : l.rotate' 0 = l := by cases l <;> rfl
theorem rotate'_cons_succ (l : List α) (a : α) (n : ℕ) :
(a :: l : List α).rotate' n.succ = (l ++ [a]).rotate' n := by simp [rotate']
@[simp]
theorem length_rotate' : ∀ (l : List α) (n : ℕ), (l.rotate' n).length = l.length
| [], _ => by simp
| a :: l, 0 => rfl
| a :: l, n + 1 => by rw [List.rotate', length_rotate' (l ++ [a]) n]; simp
theorem rotate'_eq_drop_append_take :
∀ {l : List α} {n : ℕ}, n ≤ l.length → l.rotate' n = l.drop n ++ l.take n
| [], n, h => by simp [drop_append_of_le_length h]
| l, 0, h => by simp [take_append_of_le_length h]
| a :: l, n + 1, h => by
have hnl : n ≤ l.length := le_of_succ_le_succ h
have hnl' : n ≤ (l ++ [a]).length := by
rw [length_append, length_cons, List.length]; exact le_of_succ_le h
rw [rotate'_cons_succ, rotate'_eq_drop_append_take hnl', drop, take,
drop_append_of_le_length hnl, take_append_of_le_length hnl]; simp
theorem rotate'_rotate' : ∀ (l : List α) (n m : ℕ), (l.rotate' n).rotate' m = l.rotate' (n + m)
| a :: l, 0, m => by simp
| [], n, m => by simp
| a :: l, n + 1, m => by
rw [rotate'_cons_succ, rotate'_rotate' _ n, Nat.add_right_comm, ← rotate'_cons_succ,
Nat.succ_eq_add_one]
@[simp]
theorem rotate'_length (l : List α) : rotate' l l.length = l := by
rw [rotate'_eq_drop_append_take le_rfl]; simp
@[simp]
theorem rotate'_length_mul (l : List α) : ∀ n : ℕ, l.rotate' (l.length * n) = l
| 0 => by simp
| n + 1 =>
calc
l.rotate' (l.length * (n + 1)) =
(l.rotate' (l.length * n)).rotate' (l.rotate' (l.length * n)).length := by
simp [-rotate'_length, Nat.mul_succ, rotate'_rotate']
_ = l := by rw [rotate'_length, rotate'_length_mul l n]
theorem rotate'_mod (l : List α) (n : ℕ) : l.rotate' (n % l.length) = l.rotate' n :=
calc
l.rotate' (n % l.length) =
(l.rotate' (n % l.length)).rotate' ((l.rotate' (n % l.length)).length * (n / l.length)) :=
by rw [rotate'_length_mul]
_ = l.rotate' n := by rw [rotate'_rotate', length_rotate', Nat.mod_add_div]
theorem rotate_eq_rotate' (l : List α) (n : ℕ) : l.rotate n = l.rotate' n :=
if h : l.length = 0 then by simp_all [length_eq_zero]
else by
rw [← rotate'_mod,
rotate'_eq_drop_append_take (le_of_lt (Nat.mod_lt _ (Nat.pos_of_ne_zero h)))]
simp [rotate]
theorem rotate_cons_succ (l : List α) (a : α) (n : ℕ) :
(a :: l : List α).rotate (n + 1) = (l ++ [a]).rotate n := by
rw [rotate_eq_rotate', rotate_eq_rotate', rotate'_cons_succ]
@[simp]
theorem mem_rotate : ∀ {l : List α} {a : α} {n : ℕ}, a ∈ l.rotate n ↔ a ∈ l
| [], _, n => by simp
| a :: l, _, 0 => by simp
| a :: l, _, n + 1 => by simp [rotate_cons_succ, mem_rotate, or_comm]
@[simp]
theorem length_rotate (l : List α) (n : ℕ) : (l.rotate n).length = l.length := by
rw [rotate_eq_rotate', length_rotate']
@[simp]
theorem rotate_replicate (a : α) (n : ℕ) (k : ℕ) : (replicate n a).rotate k = replicate n a :=
eq_replicate.2 ⟨by rw [length_rotate, length_replicate], fun b hb =>
eq_of_mem_replicate <| mem_rotate.1 hb⟩
theorem rotate_eq_drop_append_take {l : List α} {n : ℕ} :
n ≤ l.length → l.rotate n = l.drop n ++ l.take n := by
rw [rotate_eq_rotate']; exact rotate'_eq_drop_append_take
theorem rotate_eq_drop_append_take_mod {l : List α} {n : ℕ} :
l.rotate n = l.drop (n % l.length) ++ l.take (n % l.length) := by
rcases l.length.zero_le.eq_or_lt with hl | hl
· simp [eq_nil_of_length_eq_zero hl.symm]
rw [← rotate_eq_drop_append_take (n.mod_lt hl).le, rotate_mod]
@[simp]
theorem rotate_append_length_eq (l l' : List α) : (l ++ l').rotate l.length = l' ++ l := by
rw [rotate_eq_rotate']
induction l generalizing l'
· simp
· simp_all [rotate']
theorem rotate_rotate (l : List α) (n m : ℕ) : (l.rotate n).rotate m = l.rotate (n + m) := by
rw [rotate_eq_rotate', rotate_eq_rotate', rotate_eq_rotate', rotate'_rotate']
@[simp]
theorem rotate_length (l : List α) : rotate l l.length = l := by
rw [rotate_eq_rotate', rotate'_length]
@[simp]
theorem rotate_length_mul (l : List α) (n : ℕ) : l.rotate (l.length * n) = l := by
rw [rotate_eq_rotate', rotate'_length_mul]
theorem rotate_perm (l : List α) (n : ℕ) : l.rotate n ~ l := by
rw [rotate_eq_rotate']
induction' n with n hn generalizing l
· simp
· cases' l with hd tl
· simp
· rw [rotate'_cons_succ]
exact (hn _).trans (perm_append_singleton _ _)
@[simp]
theorem nodup_rotate {l : List α} {n : ℕ} : Nodup (l.rotate n) ↔ Nodup l :=
(rotate_perm l n).nodup_iff
@[simp]
theorem rotate_eq_nil_iff {l : List α} {n : ℕ} : l.rotate n = [] ↔ l = [] := by
induction' n with n hn generalizing l
· simp
· cases' l with hd tl
· simp
· simp [rotate_cons_succ, hn]
@[simp]
theorem nil_eq_rotate_iff {l : List α} {n : ℕ} : [] = l.rotate n ↔ [] = l := by
rw [eq_comm, rotate_eq_nil_iff, eq_comm]
@[simp]
theorem rotate_singleton (x : α) (n : ℕ) : [x].rotate n = [x] :=
rotate_replicate x 1 n
theorem zipWith_rotate_distrib {β γ : Type*} (f : α → β → γ) (l : List α) (l' : List β) (n : ℕ)
(h : l.length = l'.length) :
(zipWith f l l').rotate n = zipWith f (l.rotate n) (l'.rotate n) := by
rw [rotate_eq_drop_append_take_mod, rotate_eq_drop_append_take_mod,
rotate_eq_drop_append_take_mod, h, zipWith_append, ← drop_zipWith, ←
take_zipWith, List.length_zipWith, h, min_self]
rw [length_drop, length_drop, h]
attribute [local simp] rotate_cons_succ
-- Porting note: removing @[simp], simp can prove it
theorem zipWith_rotate_one {β : Type*} (f : α → α → β) (x y : α) (l : List α) :
zipWith f (x :: y :: l) ((x :: y :: l).rotate 1) = f x y :: zipWith f (y :: l) (l ++ [x]) := by
simp
theorem getElem?_rotate {l : List α} {n m : ℕ} (hml : m < l.length) :
(l.rotate n)[m]? = l[(m + n) % l.length]? := by
rw [rotate_eq_drop_append_take_mod]
rcases lt_or_le m (l.drop (n % l.length)).length with hm | hm
· rw [getElem?_append hm, getElem?_drop, ← add_mod_mod]
rw [length_drop, Nat.lt_sub_iff_add_lt] at hm
rw [mod_eq_of_lt hm, Nat.add_comm]
· have hlt : n % length l < length l := mod_lt _ (m.zero_le.trans_lt hml)
rw [getElem?_append_right hm, getElem?_take, length_drop]
· congr 1
rw [length_drop] at hm
have hm' := Nat.sub_le_iff_le_add'.1 hm
have : n % length l + m - length l < length l := by
rw [Nat.sub_lt_iff_lt_add' hm']
exact Nat.add_lt_add hlt hml
conv_rhs => rw [Nat.add_comm m, ← mod_add_mod, mod_eq_sub_mod hm', mod_eq_of_lt this]
rw [← Nat.add_right_inj, ← Nat.add_sub_assoc, Nat.add_sub_sub_cancel, Nat.add_sub_cancel',
Nat.add_comm]
exacts [hm', hlt.le, hm]
· rwa [Nat.sub_lt_iff_lt_add hm, length_drop, Nat.sub_add_cancel hlt.le]
theorem getElem_rotate (l : List α) (n : ℕ) (k : Nat) (h : k < (l.rotate n).length) :
(l.rotate n)[k] =
l[(k + n) % l.length]'(mod_lt _ (length_rotate l n ▸ k.zero_le.trans_lt h)) := by
rw [← Option.some_inj, ← getElem?_eq_getElem, ← getElem?_eq_getElem, getElem?_rotate]
exact h.trans_eq (length_rotate _ _)
theorem get?_rotate {l : List α} {n m : ℕ} (hml : m < l.length) :
(l.rotate n).get? m = l.get? ((m + n) % l.length) := by
simp only [get?_eq_getElem?, length_rotate, hml, getElem?_eq_getElem, getElem_rotate]
rw [← getElem?_eq_getElem]
-- Porting note (#10756): new lemma
theorem get_rotate (l : List α) (n : ℕ) (k : Fin (l.rotate n).length) :
(l.rotate n).get k =
l.get ⟨(k + n) % l.length, mod_lt _ (length_rotate l n ▸ k.1.zero_le.trans_lt k.2)⟩ := by
simp [getElem_rotate]
theorem head?_rotate {l : List α} {n : ℕ} (h : n < l.length) : head? (l.rotate n) = l[n]? := by
rw [← get?_zero, get?_rotate (n.zero_le.trans_lt h), Nat.zero_add, Nat.mod_eq_of_lt h,
get?_eq_getElem?]
-- Porting note: moved down from its original location below `get_rotate` so that the
-- non-deprecated lemma does not use the deprecated version
set_option linter.deprecated false in
@[deprecated get_rotate (since := "2023-01-13")]
theorem nthLe_rotate (l : List α) (n k : ℕ) (hk : k < (l.rotate n).length) :
(l.rotate n).nthLe k hk =
l.nthLe ((k + n) % l.length) (mod_lt _ (length_rotate l n ▸ k.zero_le.trans_lt hk)) :=
get_rotate l n ⟨k, hk⟩
set_option linter.deprecated false in
theorem nthLe_rotate_one (l : List α) (k : ℕ) (hk : k < (l.rotate 1).length) :
(l.rotate 1).nthLe k hk =
l.nthLe ((k + 1) % l.length) (mod_lt _ (length_rotate l 1 ▸ k.zero_le.trans_lt hk)) :=
nthLe_rotate l 1 k hk
/-- A version of `List.get_rotate` that represents `List.get l` in terms of
`List.get (List.rotate l n)`, not vice versa. Can be used instead of rewriting `List.get_rotate`
from right to left. -/
theorem get_eq_get_rotate (l : List α) (n : ℕ) (k : Fin l.length) :
l.get k = (l.rotate n).get ⟨(l.length - n % l.length + k) % l.length,
(Nat.mod_lt _ (k.1.zero_le.trans_lt k.2)).trans_eq (length_rotate _ _).symm⟩ := by
rw [get_rotate]
refine congr_arg l.get (Fin.eq_of_val_eq ?_)
simp only [mod_add_mod]
rw [← add_mod_mod, Nat.add_right_comm, Nat.sub_add_cancel, add_mod_left, mod_eq_of_lt]
exacts [k.2, (mod_lt _ (k.1.zero_le.trans_lt k.2)).le]
set_option linter.deprecated false in
/-- A variant of `List.nthLe_rotate` useful for rewrites from right to left. -/
@[deprecated get_eq_get_rotate (since := "2023-03-26")]
theorem nthLe_rotate' (l : List α) (n k : ℕ) (hk : k < l.length) :
(l.rotate n).nthLe ((l.length - n % l.length + k) % l.length)
((Nat.mod_lt _ (k.zero_le.trans_lt hk)).trans_le (length_rotate _ _).ge) =
l.nthLe k hk :=
(get_eq_get_rotate l n ⟨k, hk⟩).symm
theorem rotate_eq_self_iff_eq_replicate [hα : Nonempty α] :
∀ {l : List α}, (∀ n, l.rotate n = l) ↔ ∃ a, l = replicate l.length a
| [] => by simp
| a :: l => ⟨fun h => ⟨a, ext_getElem (length_replicate _ _).symm fun n h₁ h₂ => by
rw [getElem_replicate, ← Option.some_inj, ← getElem?_eq_getElem, ← head?_rotate h₁, h,
head?_cons]⟩,
fun ⟨b, hb⟩ n => by rw [hb, rotate_replicate]⟩
theorem rotate_one_eq_self_iff_eq_replicate [Nonempty α] {l : List α} :
l.rotate 1 = l ↔ ∃ a : α, l = List.replicate l.length a :=
⟨fun h =>
rotate_eq_self_iff_eq_replicate.mp fun n =>
Nat.rec l.rotate_zero (fun n hn => by rwa [Nat.succ_eq_add_one, ← l.rotate_rotate, hn]) n,
fun h => rotate_eq_self_iff_eq_replicate.mpr h 1⟩
theorem rotate_injective (n : ℕ) : Function.Injective fun l : List α => l.rotate n := by
rintro l l' (h : l.rotate n = l'.rotate n)
have hle : l.length = l'.length := (l.length_rotate n).symm.trans (h.symm ▸ l'.length_rotate n)
rw [rotate_eq_drop_append_take_mod, rotate_eq_drop_append_take_mod] at h
obtain ⟨hd, ht⟩ := append_inj h (by simp_all)
rw [← take_append_drop _ l, ht, hd, take_append_drop]
@[simp]
theorem rotate_eq_rotate {l l' : List α} {n : ℕ} : l.rotate n = l'.rotate n ↔ l = l' :=
(rotate_injective n).eq_iff
theorem rotate_eq_iff {l l' : List α} {n : ℕ} :
l.rotate n = l' ↔ l = l'.rotate (l'.length - n % l'.length) := by
rw [← @rotate_eq_rotate _ l _ n, rotate_rotate, ← rotate_mod l', add_mod]
rcases l'.length.zero_le.eq_or_lt with hl | hl
· rw [eq_nil_of_length_eq_zero hl.symm, rotate_nil]
· rcases (Nat.zero_le (n % l'.length)).eq_or_lt with hn | hn
· simp [← hn]
· rw [mod_eq_of_lt (Nat.sub_lt hl hn), Nat.sub_add_cancel, mod_self, rotate_zero]
exact (Nat.mod_lt _ hl).le
@[simp]
theorem rotate_eq_singleton_iff {l : List α} {n : ℕ} {x : α} : l.rotate n = [x] ↔ l = [x] := by
rw [rotate_eq_iff, rotate_singleton]
@[simp]
theorem singleton_eq_rotate_iff {l : List α} {n : ℕ} {x : α} : [x] = l.rotate n ↔ [x] = l := by
rw [eq_comm, rotate_eq_singleton_iff, eq_comm]
theorem reverse_rotate (l : List α) (n : ℕ) :
(l.rotate n).reverse = l.reverse.rotate (l.length - n % l.length) := by
rw [← length_reverse l, ← rotate_eq_iff]
induction' n with n hn generalizing l
· simp
· cases' l with hd tl
· simp
· rw [rotate_cons_succ, ← rotate_rotate, hn]
simp
theorem rotate_reverse (l : List α) (n : ℕ) :
l.reverse.rotate n = (l.rotate (l.length - n % l.length)).reverse := by
rw [← reverse_reverse l]
simp_rw [reverse_rotate, reverse_reverse, rotate_eq_iff, rotate_rotate, length_rotate,
length_reverse]
rw [← length_reverse l]
let k := n % l.reverse.length
cases' hk' : k with k'
· simp_all! [k, length_reverse, ← rotate_rotate]
· cases' l with x l
· simp
· rw [Nat.mod_eq_of_lt, Nat.sub_add_cancel, rotate_length]
· exact Nat.sub_le _ _
· exact Nat.sub_lt (by simp) (by simp_all! [k])
theorem map_rotate {β : Type*} (f : α → β) (l : List α) (n : ℕ) :
map f (l.rotate n) = (map f l).rotate n := by
induction' n with n hn IH generalizing l
· simp
· cases' l with hd tl
· simp
· simp [hn]
theorem Nodup.rotate_congr {l : List α} (hl : l.Nodup) (hn : l ≠ []) (i j : ℕ)
(h : l.rotate i = l.rotate j) : i % l.length = j % l.length := by
rw [← rotate_mod l i, ← rotate_mod l j] at h
simpa only [head?_rotate, mod_lt, length_pos_of_ne_nil hn, getElem?_eq_getElem, Option.some_inj,
hl.getElem_inj_iff, Fin.ext_iff] using congr_arg head? h
theorem Nodup.rotate_congr_iff {l : List α} (hl : l.Nodup) {i j : ℕ} :
l.rotate i = l.rotate j ↔ i % l.length = j % l.length ∨ l = [] := by
rcases eq_or_ne l [] with rfl | hn
· simp
· simp only [hn, or_false]
refine ⟨hl.rotate_congr hn _ _, fun h ↦ ?_⟩
rw [← rotate_mod, h, rotate_mod]
theorem Nodup.rotate_eq_self_iff {l : List α} (hl : l.Nodup) {n : ℕ} :
l.rotate n = l ↔ n % l.length = 0 ∨ l = [] := by
rw [← zero_mod, ← hl.rotate_congr_iff, rotate_zero]
section IsRotated
variable (l l' : List α)
/-- `IsRotated l₁ l₂` or `l₁ ~r l₂` asserts that `l₁` and `l₂` are cyclic permutations
of each other. This is defined by claiming that `∃ n, l.rotate n = l'`. -/
def IsRotated : Prop :=
∃ n, l.rotate n = l'
@[inherit_doc List.IsRotated]
infixr:1000 " ~r " => IsRotated
variable {l l'}
@[refl]
theorem IsRotated.refl (l : List α) : l ~r l :=
⟨0, by simp⟩
@[symm]
theorem IsRotated.symm (h : l ~r l') : l' ~r l := by
obtain ⟨n, rfl⟩ := h
cases' l with hd tl
· exists 0
· use (hd :: tl).length * n - n
rw [rotate_rotate, Nat.add_sub_cancel', rotate_length_mul]
exact Nat.le_mul_of_pos_left _ (by simp)
theorem isRotated_comm : l ~r l' ↔ l' ~r l :=
⟨IsRotated.symm, IsRotated.symm⟩
@[simp]
protected theorem IsRotated.forall (l : List α) (n : ℕ) : l.rotate n ~r l :=
IsRotated.symm ⟨n, rfl⟩
@[trans]
theorem IsRotated.trans : ∀ {l l' l'' : List α}, l ~r l' → l' ~r l'' → l ~r l''
| _, _, _, ⟨n, rfl⟩, ⟨m, rfl⟩ => ⟨n + m, by rw [rotate_rotate]⟩
theorem IsRotated.eqv : Equivalence (@IsRotated α) :=
Equivalence.mk IsRotated.refl IsRotated.symm IsRotated.trans
/-- The relation `List.IsRotated l l'` forms a `Setoid` of cycles. -/
def IsRotated.setoid (α : Type*) : Setoid (List α) where
r := IsRotated
iseqv := IsRotated.eqv
theorem IsRotated.perm (h : l ~r l') : l ~ l' :=
Exists.elim h fun _ hl => hl ▸ (rotate_perm _ _).symm
theorem IsRotated.nodup_iff (h : l ~r l') : Nodup l ↔ Nodup l' :=
h.perm.nodup_iff
theorem IsRotated.mem_iff (h : l ~r l') {a : α} : a ∈ l ↔ a ∈ l' :=
h.perm.mem_iff
@[simp]
theorem isRotated_nil_iff : l ~r [] ↔ l = [] :=
⟨fun ⟨n, hn⟩ => by simpa using hn, fun h => h ▸ by rfl⟩
@[simp]
theorem isRotated_nil_iff' : [] ~r l ↔ [] = l := by
rw [isRotated_comm, isRotated_nil_iff, eq_comm]
@[simp]
theorem isRotated_singleton_iff {x : α} : l ~r [x] ↔ l = [x] :=
⟨fun ⟨n, hn⟩ => by simpa using hn, fun h => h ▸ by rfl⟩
@[simp]
theorem isRotated_singleton_iff' {x : α} : [x] ~r l ↔ [x] = l := by
rw [isRotated_comm, isRotated_singleton_iff, eq_comm]
theorem isRotated_concat (hd : α) (tl : List α) : (tl ++ [hd]) ~r (hd :: tl) :=
IsRotated.symm ⟨1, by simp⟩
theorem isRotated_append : (l ++ l') ~r (l' ++ l) :=
⟨l.length, by simp⟩
theorem IsRotated.reverse (h : l ~r l') : l.reverse ~r l'.reverse := by
obtain ⟨n, rfl⟩ := h
exact ⟨_, (reverse_rotate _ _).symm⟩
theorem isRotated_reverse_comm_iff : l.reverse ~r l' ↔ l ~r l'.reverse := by
constructor <;>
· intro h
simpa using h.reverse
@[simp]
theorem isRotated_reverse_iff : l.reverse ~r l'.reverse ↔ l ~r l' := by
simp [isRotated_reverse_comm_iff]
theorem isRotated_iff_mod : l ~r l' ↔ ∃ n ≤ l.length, l.rotate n = l' := by
refine ⟨fun h => ?_, fun ⟨n, _, h⟩ => ⟨n, h⟩⟩
obtain ⟨n, rfl⟩ := h
cases' l with hd tl
· simp
· refine ⟨n % (hd :: tl).length, ?_, rotate_mod _ _⟩
refine (Nat.mod_lt _ ?_).le
simp
theorem isRotated_iff_mem_map_range : l ~r l' ↔ l' ∈ (List.range (l.length + 1)).map l.rotate := by
simp_rw [mem_map, mem_range, isRotated_iff_mod]
exact
⟨fun ⟨n, hn, h⟩ => ⟨n, Nat.lt_succ_of_le hn, h⟩,
fun ⟨n, hn, h⟩ => ⟨n, Nat.le_of_lt_succ hn, h⟩⟩
-- Porting note: @[congr] only works for equality.
-- @[congr]
theorem IsRotated.map {β : Type*} {l₁ l₂ : List α} (h : l₁ ~r l₂) (f : α → β) :
map f l₁ ~r map f l₂ := by
obtain ⟨n, rfl⟩ := h
rw [map_rotate]
use n
/-- List of all cyclic permutations of `l`.
The `cyclicPermutations` of a nonempty list `l` will always contain `List.length l` elements.
This implies that under certain conditions, there are duplicates in `List.cyclicPermutations l`.
The `n`th entry is equal to `l.rotate n`, proven in `List.get_cyclicPermutations`.
The proof that every cyclic permutant of `l` is in the list is `List.mem_cyclicPermutations_iff`.
cyclicPermutations [1, 2, 3, 2, 4] =
[[1, 2, 3, 2, 4], [2, 3, 2, 4, 1], [3, 2, 4, 1, 2],
[2, 4, 1, 2, 3], [4, 1, 2, 3, 2]] -/
def cyclicPermutations : List α → List (List α)
| [] => [[]]
| l@(_ :: _) => dropLast (zipWith (· ++ ·) (tails l) (inits l))
@[simp]
theorem cyclicPermutations_nil : cyclicPermutations ([] : List α) = [[]] :=
rfl
theorem cyclicPermutations_cons (x : α) (l : List α) :
cyclicPermutations (x :: l) = dropLast (zipWith (· ++ ·) (tails (x :: l)) (inits (x :: l))) :=
rfl
theorem cyclicPermutations_of_ne_nil (l : List α) (h : l ≠ []) :
cyclicPermutations l = dropLast (zipWith (· ++ ·) (tails l) (inits l)) := by
obtain ⟨hd, tl, rfl⟩ := exists_cons_of_ne_nil h
exact cyclicPermutations_cons _ _
theorem length_cyclicPermutations_cons (x : α) (l : List α) :
length (cyclicPermutations (x :: l)) = length l + 1 := by simp [cyclicPermutations_cons]
@[simp]
theorem length_cyclicPermutations_of_ne_nil (l : List α) (h : l ≠ []) :
length (cyclicPermutations l) = length l := by simp [cyclicPermutations_of_ne_nil _ h]
@[simp]
theorem cyclicPermutations_ne_nil : ∀ l : List α, cyclicPermutations l ≠ []
| a::l, h => by simpa using congr_arg length h
@[simp]
theorem getElem_cyclicPermutations (l : List α) (n : Nat) (h : n < length (cyclicPermutations l)) :
(cyclicPermutations l)[n] = l.rotate n := by
cases l with
| nil => simp
| cons a l =>
simp only [cyclicPermutations_cons, getElem_dropLast, getElem_zipWith, getElem_tails,
getElem_inits]
rw [rotate_eq_drop_append_take (by simpa using h.le)]
theorem get_cyclicPermutations (l : List α) (n : Fin (length (cyclicPermutations l))) :
(cyclicPermutations l).get n = l.rotate n := by
simp
@[simp]
theorem head_cyclicPermutations (l : List α) :
(cyclicPermutations l).head (cyclicPermutations_ne_nil l) = l := by
have h : 0 < length (cyclicPermutations l) := length_pos_of_ne_nil (cyclicPermutations_ne_nil _)
rw [← get_mk_zero h, get_cyclicPermutations, Fin.val_mk, rotate_zero]
@[simp]
theorem head?_cyclicPermutations (l : List α) : (cyclicPermutations l).head? = l := by
rw [head?_eq_head, head_cyclicPermutations]
theorem cyclicPermutations_injective : Function.Injective (@cyclicPermutations α) := fun l l' h ↦ by
simpa using congr_arg head? h
@[simp]
theorem cyclicPermutations_inj {l l' : List α} :
cyclicPermutations l = cyclicPermutations l' ↔ l = l' :=
cyclicPermutations_injective.eq_iff
theorem length_mem_cyclicPermutations (l : List α) (h : l' ∈ cyclicPermutations l) :
length l' = length l := by
obtain ⟨k, hk, rfl⟩ := get_of_mem h
simp
theorem mem_cyclicPermutations_self (l : List α) : l ∈ cyclicPermutations l := by
simpa using head_mem (cyclicPermutations_ne_nil l)
@[simp]
theorem cyclicPermutations_rotate (l : List α) (k : ℕ) :
(l.rotate k).cyclicPermutations = l.cyclicPermutations.rotate k := by
have : (l.rotate k).cyclicPermutations.length = length (l.cyclicPermutations.rotate k) := by
cases l
· simp
· rw [length_cyclicPermutations_of_ne_nil] <;> simp
refine ext_get this fun n hn hn' => ?_
rw [get_rotate, get_cyclicPermutations, rotate_rotate, ← rotate_mod, Nat.add_comm]
cases l <;> simp
@[simp]
theorem mem_cyclicPermutations_iff : l ∈ cyclicPermutations l' ↔ l ~r l' := by
constructor
· simp_rw [mem_iff_get, get_cyclicPermutations]
rintro ⟨k, rfl⟩
exact .forall _ _
· rintro ⟨k, rfl⟩
rw [cyclicPermutations_rotate, mem_rotate]
apply mem_cyclicPermutations_self
@[simp]
theorem cyclicPermutations_eq_nil_iff {l : List α} : cyclicPermutations l = [[]] ↔ l = [] :=
cyclicPermutations_injective.eq_iff' rfl
@[simp]
theorem cyclicPermutations_eq_singleton_iff {l : List α} {x : α} :
cyclicPermutations l = [[x]] ↔ l = [x] :=
cyclicPermutations_injective.eq_iff' rfl
/-- If a `l : List α` is `Nodup l`, then all of its cyclic permutants are distinct. -/
protected theorem Nodup.cyclicPermutations {l : List α} (hn : Nodup l) :
Nodup (cyclicPermutations l) := by
rcases eq_or_ne l [] with rfl | hl
· simp
· rw [nodup_iff_injective_get]
rintro ⟨i, hi⟩ ⟨j, hj⟩ h
simp only [length_cyclicPermutations_of_ne_nil l hl] at hi hj
simpa [hn.rotate_congr_iff, mod_eq_of_lt, *] using h
protected theorem IsRotated.cyclicPermutations {l l' : List α} (h : l ~r l') :
l.cyclicPermutations ~r l'.cyclicPermutations := by
obtain ⟨k, rfl⟩ := h
exact ⟨k, by simp⟩
@[simp]
theorem isRotated_cyclicPermutations_iff {l l' : List α} :
l.cyclicPermutations ~r l'.cyclicPermutations ↔ l ~r l' := by
simp only [IsRotated, ← cyclicPermutations_rotate, cyclicPermutations_inj]
section Decidable
variable [DecidableEq α]
instance isRotatedDecidable (l l' : List α) : Decidable (l ~r l') :=
decidable_of_iff' _ isRotated_iff_mem_map_range
instance {l l' : List α} : Decidable (@Setoid.r _ (IsRotated.setoid α) l l') :=
List.isRotatedDecidable _ _
end Decidable
end IsRotated
end List
|
Data\List\Sections.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.List.Forall2
/-!
# List sections
This file proves some stuff about `List.sections` (definition in `Data.List.Defs`). A section of a
list of lists `[l₁, ..., lₙ]` is a list whose `i`-th element comes from the `i`-th list.
-/
open Nat Function
namespace List
variable {α β : Type*}
theorem mem_sections {L : List (List α)} {f} : f ∈ sections L ↔ Forall₂ (· ∈ ·) f L := by
refine ⟨fun h => ?_, fun h => ?_⟩
· induction L generalizing f
· cases mem_singleton.1 h
exact Forall₂.nil
simp only [sections, bind_eq_bind, mem_bind, mem_map] at h
rcases h with ⟨_, _, _, _, rfl⟩
simp only [*, forall₂_cons, true_and_iff]
· induction' h with a l f L al fL fs
· simp only [sections, mem_singleton]
simp only [sections, bind_eq_bind, mem_bind, mem_map]
exact ⟨f, fs, a, al, rfl⟩
theorem mem_sections_length {L : List (List α)} {f} (h : f ∈ sections L) : length f = length L :=
(mem_sections.1 h).length_eq
theorem rel_sections {r : α → β → Prop} :
(Forall₂ (Forall₂ r) ⇒ Forall₂ (Forall₂ r)) sections sections
| _, _, Forall₂.nil => Forall₂.cons Forall₂.nil Forall₂.nil
| _, _, Forall₂.cons h₀ h₁ =>
rel_bind (rel_sections h₁) fun _ _ hl => rel_map (fun _ _ ha => Forall₂.cons ha hl) h₀
end List
|
Data\List\Sigma.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Sean Leather
-/
import Mathlib.Data.List.Perm
import Mathlib.Data.List.Pairwise
/-!
# Utilities for lists of sigmas
This file includes several ways of interacting with `List (Sigma β)`, treated as a key-value store.
If `α : Type*` and `β : α → Type*`, then we regard `s : Sigma β` as having key `s.1 : α` and value
`s.2 : β s.1`. Hence, `List (Sigma β)` behaves like a key-value store.
## Main Definitions
- `List.keys` extracts the list of keys.
- `List.NodupKeys` determines if the store has duplicate keys.
- `List.lookup`/`lookup_all` accesses the value(s) of a particular key.
- `List.kreplace` replaces the first value with a given key by a given value.
- `List.kerase` removes a value.
- `List.kinsert` inserts a value.
- `List.kunion` computes the union of two stores.
- `List.kextract` returns a value with a given key and the rest of the values.
-/
universe u v
namespace List
variable {α : Type u} {β : α → Type v} {l l₁ l₂ : List (Sigma β)}
/-! ### `keys` -/
/-- List of keys from a list of key-value pairs -/
def keys : List (Sigma β) → List α :=
map Sigma.fst
@[simp]
theorem keys_nil : @keys α β [] = [] :=
rfl
@[simp]
theorem keys_cons {s} {l : List (Sigma β)} : (s :: l).keys = s.1 :: l.keys :=
rfl
theorem mem_keys_of_mem {s : Sigma β} {l : List (Sigma β)} : s ∈ l → s.1 ∈ l.keys :=
mem_map_of_mem Sigma.fst
theorem exists_of_mem_keys {a} {l : List (Sigma β)} (h : a ∈ l.keys) :
∃ b : β a, Sigma.mk a b ∈ l :=
let ⟨⟨_, b'⟩, m, e⟩ := exists_of_mem_map h
Eq.recOn e (Exists.intro b' m)
theorem mem_keys {a} {l : List (Sigma β)} : a ∈ l.keys ↔ ∃ b : β a, Sigma.mk a b ∈ l :=
⟨exists_of_mem_keys, fun ⟨_, h⟩ => mem_keys_of_mem h⟩
theorem not_mem_keys {a} {l : List (Sigma β)} : a ∉ l.keys ↔ ∀ b : β a, Sigma.mk a b ∉ l :=
(not_congr mem_keys).trans not_exists
theorem not_eq_key {a} {l : List (Sigma β)} : a ∉ l.keys ↔ ∀ s : Sigma β, s ∈ l → a ≠ s.1 :=
Iff.intro (fun h₁ s h₂ e => absurd (mem_keys_of_mem h₂) (by rwa [e] at h₁)) fun f h₁ =>
let ⟨b, h₂⟩ := exists_of_mem_keys h₁
f _ h₂ rfl
/-! ### `NodupKeys` -/
/-- Determines whether the store uses a key several times. -/
def NodupKeys (l : List (Sigma β)) : Prop :=
l.keys.Nodup
theorem nodupKeys_iff_pairwise {l} : NodupKeys l ↔ Pairwise (fun s s' : Sigma β => s.1 ≠ s'.1) l :=
pairwise_map
theorem NodupKeys.pairwise_ne {l} (h : NodupKeys l) :
Pairwise (fun s s' : Sigma β => s.1 ≠ s'.1) l :=
nodupKeys_iff_pairwise.1 h
@[simp]
theorem nodupKeys_nil : @NodupKeys α β [] :=
Pairwise.nil
@[simp]
theorem nodupKeys_cons {s : Sigma β} {l : List (Sigma β)} :
NodupKeys (s :: l) ↔ s.1 ∉ l.keys ∧ NodupKeys l := by simp [keys, NodupKeys]
theorem not_mem_keys_of_nodupKeys_cons {s : Sigma β} {l : List (Sigma β)} (h : NodupKeys (s :: l)) :
s.1 ∉ l.keys :=
(nodupKeys_cons.1 h).1
theorem nodupKeys_of_nodupKeys_cons {s : Sigma β} {l : List (Sigma β)} (h : NodupKeys (s :: l)) :
NodupKeys l :=
(nodupKeys_cons.1 h).2
theorem NodupKeys.eq_of_fst_eq {l : List (Sigma β)} (nd : NodupKeys l) {s s' : Sigma β} (h : s ∈ l)
(h' : s' ∈ l) : s.1 = s'.1 → s = s' :=
@Pairwise.forall_of_forall _ (fun s s' : Sigma β => s.1 = s'.1 → s = s') _
(fun _ _ H h => (H h.symm).symm) (fun _ _ _ => rfl)
((nodupKeys_iff_pairwise.1 nd).imp fun h h' => (h h').elim) _ h _ h'
theorem NodupKeys.eq_of_mk_mem {a : α} {b b' : β a} {l : List (Sigma β)} (nd : NodupKeys l)
(h : Sigma.mk a b ∈ l) (h' : Sigma.mk a b' ∈ l) : b = b' := by
cases nd.eq_of_fst_eq h h' rfl; rfl
theorem nodupKeys_singleton (s : Sigma β) : NodupKeys [s] :=
nodup_singleton _
theorem NodupKeys.sublist {l₁ l₂ : List (Sigma β)} (h : l₁ <+ l₂) : NodupKeys l₂ → NodupKeys l₁ :=
Nodup.sublist <| h.map _
protected theorem NodupKeys.nodup {l : List (Sigma β)} : NodupKeys l → Nodup l :=
Nodup.of_map _
theorem perm_nodupKeys {l₁ l₂ : List (Sigma β)} (h : l₁ ~ l₂) : NodupKeys l₁ ↔ NodupKeys l₂ :=
(h.map _).nodup_iff
theorem nodupKeys_join {L : List (List (Sigma β))} :
NodupKeys (join L) ↔ (∀ l ∈ L, NodupKeys l) ∧ Pairwise Disjoint (L.map keys) := by
rw [nodupKeys_iff_pairwise, pairwise_join, pairwise_map]
refine and_congr (forall₂_congr fun l _ => by simp [nodupKeys_iff_pairwise]) ?_
apply iff_of_eq; congr with (l₁ l₂)
simp [keys, disjoint_iff_ne]
theorem nodup_enum_map_fst (l : List α) : (l.enum.map Prod.fst).Nodup := by simp [List.nodup_range]
theorem mem_ext {l₀ l₁ : List (Sigma β)} (nd₀ : l₀.Nodup) (nd₁ : l₁.Nodup)
(h : ∀ x, x ∈ l₀ ↔ x ∈ l₁) : l₀ ~ l₁ :=
(perm_ext_iff_of_nodup nd₀ nd₁).2 h
variable [DecidableEq α]
/-! ### `dlookup` -/
-- Porting note: renaming to `dlookup` since `lookup` already exists
/-- `dlookup a l` is the first value in `l` corresponding to the key `a`,
or `none` if no such element exists. -/
def dlookup (a : α) : List (Sigma β) → Option (β a)
| [] => none
| ⟨a', b⟩ :: l => if h : a' = a then some (Eq.recOn h b) else dlookup a l
@[simp]
theorem dlookup_nil (a : α) : dlookup a [] = @none (β a) :=
rfl
@[simp]
theorem dlookup_cons_eq (l) (a : α) (b : β a) : dlookup a (⟨a, b⟩ :: l) = some b :=
dif_pos rfl
@[simp]
theorem dlookup_cons_ne (l) {a} : ∀ s : Sigma β, a ≠ s.1 → dlookup a (s :: l) = dlookup a l
| ⟨_, _⟩, h => dif_neg h.symm
theorem dlookup_isSome {a : α} : ∀ {l : List (Sigma β)}, (dlookup a l).isSome ↔ a ∈ l.keys
| [] => by simp
| ⟨a', b⟩ :: l => by
by_cases h : a = a'
· subst a'
simp
· simp [h, dlookup_isSome]
theorem dlookup_eq_none {a : α} {l : List (Sigma β)} : dlookup a l = none ↔ a ∉ l.keys := by
simp [← dlookup_isSome, Option.isNone_iff_eq_none]
theorem of_mem_dlookup {a : α} {b : β a} :
∀ {l : List (Sigma β)}, b ∈ dlookup a l → Sigma.mk a b ∈ l
| ⟨a', b'⟩ :: l, H => by
by_cases h : a = a'
· subst a'
simp? at H says simp only [dlookup_cons_eq, Option.mem_def, Option.some.injEq] at H
simp [H]
· simp only [ne_eq, h, not_false_iff, dlookup_cons_ne] at H
simp [of_mem_dlookup H]
theorem mem_dlookup {a} {b : β a} {l : List (Sigma β)} (nd : l.NodupKeys) (h : Sigma.mk a b ∈ l) :
b ∈ dlookup a l := by
cases' Option.isSome_iff_exists.mp (dlookup_isSome.mpr (mem_keys_of_mem h)) with b' h'
cases nd.eq_of_mk_mem h (of_mem_dlookup h')
exact h'
theorem map_dlookup_eq_find (a : α) :
∀ l : List (Sigma β), (dlookup a l).map (Sigma.mk a) = find? (fun s => a = s.1) l
| [] => rfl
| ⟨a', b'⟩ :: l => by
by_cases h : a = a'
· subst a'
simp
· simpa [h] using map_dlookup_eq_find a l
theorem mem_dlookup_iff {a : α} {b : β a} {l : List (Sigma β)} (nd : l.NodupKeys) :
b ∈ dlookup a l ↔ Sigma.mk a b ∈ l :=
⟨of_mem_dlookup, mem_dlookup nd⟩
theorem perm_dlookup (a : α) {l₁ l₂ : List (Sigma β)} (nd₁ : l₁.NodupKeys) (nd₂ : l₂.NodupKeys)
(p : l₁ ~ l₂) : dlookup a l₁ = dlookup a l₂ := by
ext b; simp only [mem_dlookup_iff nd₁, mem_dlookup_iff nd₂]; exact p.mem_iff
theorem lookup_ext {l₀ l₁ : List (Sigma β)} (nd₀ : l₀.NodupKeys) (nd₁ : l₁.NodupKeys)
(h : ∀ x y, y ∈ l₀.dlookup x ↔ y ∈ l₁.dlookup x) : l₀ ~ l₁ :=
mem_ext nd₀.nodup nd₁.nodup fun ⟨a, b⟩ => by
rw [← mem_dlookup_iff, ← mem_dlookup_iff, h] <;> assumption
/-! ### `lookupAll` -/
/-- `lookup_all a l` is the list of all values in `l` corresponding to the key `a`. -/
def lookupAll (a : α) : List (Sigma β) → List (β a)
| [] => []
| ⟨a', b⟩ :: l => if h : a' = a then Eq.recOn h b :: lookupAll a l else lookupAll a l
@[simp]
theorem lookupAll_nil (a : α) : lookupAll a [] = @nil (β a) :=
rfl
@[simp]
theorem lookupAll_cons_eq (l) (a : α) (b : β a) : lookupAll a (⟨a, b⟩ :: l) = b :: lookupAll a l :=
dif_pos rfl
@[simp]
theorem lookupAll_cons_ne (l) {a} : ∀ s : Sigma β, a ≠ s.1 → lookupAll a (s :: l) = lookupAll a l
| ⟨_, _⟩, h => dif_neg h.symm
theorem lookupAll_eq_nil {a : α} :
∀ {l : List (Sigma β)}, lookupAll a l = [] ↔ ∀ b : β a, Sigma.mk a b ∉ l
| [] => by simp
| ⟨a', b⟩ :: l => by
by_cases h : a = a'
· subst a'
simp only [lookupAll_cons_eq, mem_cons, Sigma.mk.inj_iff, heq_eq_eq, true_and, not_or,
false_iff, not_forall, not_and, not_not]
use b
simp
· simp [h, lookupAll_eq_nil]
theorem head?_lookupAll (a : α) : ∀ l : List (Sigma β), head? (lookupAll a l) = dlookup a l
| [] => by simp
| ⟨a', b⟩ :: l => by
by_cases h : a = a'
· subst h; simp
· rw [lookupAll_cons_ne, dlookup_cons_ne, head?_lookupAll a l] <;> assumption
theorem mem_lookupAll {a : α} {b : β a} :
∀ {l : List (Sigma β)}, b ∈ lookupAll a l ↔ Sigma.mk a b ∈ l
| [] => by simp
| ⟨a', b'⟩ :: l => by
by_cases h : a = a'
· subst h
simp [*, mem_lookupAll]
· simp [*, mem_lookupAll]
theorem lookupAll_sublist (a : α) : ∀ l : List (Sigma β), (lookupAll a l).map (Sigma.mk a) <+ l
| [] => by simp
| ⟨a', b'⟩ :: l => by
by_cases h : a = a'
· subst h
simp only [ne_eq, not_true, lookupAll_cons_eq, List.map]
exact (lookupAll_sublist a l).cons₂ _
· simp only [ne_eq, h, not_false_iff, lookupAll_cons_ne]
exact (lookupAll_sublist a l).cons _
theorem lookupAll_length_le_one (a : α) {l : List (Sigma β)} (h : l.NodupKeys) :
length (lookupAll a l) ≤ 1 := by
have := Nodup.sublist ((lookupAll_sublist a l).map _) h
rw [map_map] at this
rwa [← nodup_replicate, ← map_const]
theorem lookupAll_eq_dlookup (a : α) {l : List (Sigma β)} (h : l.NodupKeys) :
lookupAll a l = (dlookup a l).toList := by
rw [← head?_lookupAll]
have h1 := lookupAll_length_le_one a h; revert h1
rcases lookupAll a l with (_ | ⟨b, _ | ⟨c, l⟩⟩) <;> intro h1 <;> try rfl
exact absurd h1 (by simp)
theorem lookupAll_nodup (a : α) {l : List (Sigma β)} (h : l.NodupKeys) : (lookupAll a l).Nodup := by
(rw [lookupAll_eq_dlookup a h]; apply Option.toList_nodup)
theorem perm_lookupAll (a : α) {l₁ l₂ : List (Sigma β)} (nd₁ : l₁.NodupKeys) (nd₂ : l₂.NodupKeys)
(p : l₁ ~ l₂) : lookupAll a l₁ = lookupAll a l₂ := by
simp [lookupAll_eq_dlookup, nd₁, nd₂, perm_dlookup a nd₁ nd₂ p]
/-! ### `kreplace` -/
/-- Replaces the first value with key `a` by `b`. -/
def kreplace (a : α) (b : β a) : List (Sigma β) → List (Sigma β) :=
lookmap fun s => if a = s.1 then some ⟨a, b⟩ else none
theorem kreplace_of_forall_not (a : α) (b : β a) {l : List (Sigma β)}
(H : ∀ b : β a, Sigma.mk a b ∉ l) : kreplace a b l = l :=
lookmap_of_forall_not _ <| by
rintro ⟨a', b'⟩ h; dsimp; split_ifs
· subst a'
exact H _ h
· rfl
theorem kreplace_self {a : α} {b : β a} {l : List (Sigma β)} (nd : NodupKeys l)
(h : Sigma.mk a b ∈ l) : kreplace a b l = l := by
refine (lookmap_congr ?_).trans (lookmap_id' (Option.guard fun (s : Sigma β) => a = s.1) ?_ _)
· rintro ⟨a', b'⟩ h'
dsimp [Option.guard]
split_ifs
· subst a'
simp [nd.eq_of_mk_mem h h']
· rfl
· rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩
dsimp [Option.guard]
split_ifs
· simp
· rintro ⟨⟩
theorem keys_kreplace (a : α) (b : β a) : ∀ l : List (Sigma β), (kreplace a b l).keys = l.keys :=
lookmap_map_eq _ _ <| by
rintro ⟨a₁, b₂⟩ ⟨a₂, b₂⟩
dsimp
split_ifs with h <;> simp (config := { contextual := true }) [h]
theorem kreplace_nodupKeys (a : α) (b : β a) {l : List (Sigma β)} :
(kreplace a b l).NodupKeys ↔ l.NodupKeys := by simp [NodupKeys, keys_kreplace]
theorem Perm.kreplace {a : α} {b : β a} {l₁ l₂ : List (Sigma β)} (nd : l₁.NodupKeys) :
l₁ ~ l₂ → kreplace a b l₁ ~ kreplace a b l₂ :=
perm_lookmap _ <| by
refine nd.pairwise_ne.imp ?_
intro x y h z h₁ w h₂
split_ifs at h₁ h₂ with h_2 h_1 <;> cases h₁ <;> cases h₂
exact (h (h_2.symm.trans h_1)).elim
/-! ### `kerase` -/
/-- Remove the first pair with the key `a`. -/
def kerase (a : α) : List (Sigma β) → List (Sigma β) :=
eraseP fun s => a = s.1
-- Porting note (#10618): removing @[simp], `simp` can prove it
theorem kerase_nil {a} : @kerase _ β _ a [] = [] :=
rfl
@[simp]
theorem kerase_cons_eq {a} {s : Sigma β} {l : List (Sigma β)} (h : a = s.1) :
kerase a (s :: l) = l := by simp [kerase, h]
@[simp]
theorem kerase_cons_ne {a} {s : Sigma β} {l : List (Sigma β)} (h : a ≠ s.1) :
kerase a (s :: l) = s :: kerase a l := by simp [kerase, h]
@[simp]
theorem kerase_of_not_mem_keys {a} {l : List (Sigma β)} (h : a ∉ l.keys) : kerase a l = l := by
induction' l with _ _ ih <;> [rfl; (simp [not_or] at h; simp [h.1, ih h.2])]
theorem kerase_sublist (a : α) (l : List (Sigma β)) : kerase a l <+ l :=
eraseP_sublist _
theorem kerase_keys_subset (a) (l : List (Sigma β)) : (kerase a l).keys ⊆ l.keys :=
((kerase_sublist a l).map _).subset
theorem mem_keys_of_mem_keys_kerase {a₁ a₂} {l : List (Sigma β)} :
a₁ ∈ (kerase a₂ l).keys → a₁ ∈ l.keys :=
@kerase_keys_subset _ _ _ _ _ _
theorem exists_of_kerase {a : α} {l : List (Sigma β)} (h : a ∈ l.keys) :
∃ (b : β a) (l₁ l₂ : List (Sigma β)),
a ∉ l₁.keys ∧ l = l₁ ++ ⟨a, b⟩ :: l₂ ∧ kerase a l = l₁ ++ l₂ := by
induction l with
| nil => cases h
| cons hd tl ih =>
by_cases e : a = hd.1
· subst e
exact ⟨hd.2, [], tl, by simp, by cases hd; rfl, by simp⟩
· simp only [keys_cons, mem_cons] at h
cases' h with h h
· exact absurd h e
rcases ih h with ⟨b, tl₁, tl₂, h₁, h₂, h₃⟩
exact ⟨b, hd :: tl₁, tl₂, not_mem_cons_of_ne_of_not_mem e h₁, by (rw [h₂]; rfl), by
simp [e, h₃]⟩
@[simp]
theorem mem_keys_kerase_of_ne {a₁ a₂} {l : List (Sigma β)} (h : a₁ ≠ a₂) :
a₁ ∈ (kerase a₂ l).keys ↔ a₁ ∈ l.keys :=
(Iff.intro mem_keys_of_mem_keys_kerase) fun p =>
if q : a₂ ∈ l.keys then
match l, kerase a₂ l, exists_of_kerase q, p with
| _, _, ⟨_, _, _, _, rfl, rfl⟩, p => by simpa [keys, h] using p
else by simp [q, p]
theorem keys_kerase {a} {l : List (Sigma β)} : (kerase a l).keys = l.keys.erase a := by
rw [keys, kerase, erase_eq_eraseP, eraseP_map, Function.comp]
simp only [beq_eq_decide]
congr
funext
simp
theorem kerase_kerase {a a'} {l : List (Sigma β)} :
(kerase a' l).kerase a = (kerase a l).kerase a' := by
by_cases h : a = a'
· subst a'; rfl
induction' l with x xs
· rfl
· by_cases a' = x.1
· subst a'
simp [kerase_cons_ne h, kerase_cons_eq rfl]
by_cases h' : a = x.1
· subst a
simp [kerase_cons_eq rfl, kerase_cons_ne (Ne.symm h)]
· simp [kerase_cons_ne, *]
theorem NodupKeys.kerase (a : α) : NodupKeys l → (kerase a l).NodupKeys :=
NodupKeys.sublist <| kerase_sublist _ _
theorem Perm.kerase {a : α} {l₁ l₂ : List (Sigma β)} (nd : l₁.NodupKeys) :
l₁ ~ l₂ → kerase a l₁ ~ kerase a l₂ := by
apply Perm.eraseP
apply (nodupKeys_iff_pairwise.1 nd).imp
intros; simp_all
@[simp]
theorem not_mem_keys_kerase (a) {l : List (Sigma β)} (nd : l.NodupKeys) :
a ∉ (kerase a l).keys := by
induction l with
| nil => simp
| cons hd tl ih =>
simp? at nd says simp only [nodupKeys_cons] at nd
by_cases h : a = hd.1
· subst h
simp [nd.1]
· simp [h, ih nd.2]
@[simp]
theorem dlookup_kerase (a) {l : List (Sigma β)} (nd : l.NodupKeys) :
dlookup a (kerase a l) = none :=
dlookup_eq_none.mpr (not_mem_keys_kerase a nd)
@[simp]
theorem dlookup_kerase_ne {a a'} {l : List (Sigma β)} (h : a ≠ a') :
dlookup a (kerase a' l) = dlookup a l := by
induction l with
| nil => rfl
| cons hd tl ih =>
cases' hd with ah bh
by_cases h₁ : a = ah <;> by_cases h₂ : a' = ah
· substs h₁ h₂
cases Ne.irrefl h
· subst h₁
simp [h₂]
· subst h₂
simp [h]
· simp [h₁, h₂, ih]
theorem kerase_append_left {a} :
∀ {l₁ l₂ : List (Sigma β)}, a ∈ l₁.keys → kerase a (l₁ ++ l₂) = kerase a l₁ ++ l₂
| [], _, h => by cases h
| s :: l₁, l₂, h₁ => by
if h₂ : a = s.1 then simp [h₂]
else simp at h₁; cases' h₁ with h₁ h₁ <;> [exact absurd h₁ h₂; simp [h₂, kerase_append_left h₁]]
theorem kerase_append_right {a} :
∀ {l₁ l₂ : List (Sigma β)}, a ∉ l₁.keys → kerase a (l₁ ++ l₂) = l₁ ++ kerase a l₂
| [], _, _ => rfl
| _ :: l₁, l₂, h => by
simp only [keys_cons, mem_cons, not_or] at h
simp [h.1, kerase_append_right h.2]
theorem kerase_comm (a₁ a₂) (l : List (Sigma β)) :
kerase a₂ (kerase a₁ l) = kerase a₁ (kerase a₂ l) :=
if h : a₁ = a₂ then by simp [h]
else
if ha₁ : a₁ ∈ l.keys then
if ha₂ : a₂ ∈ l.keys then
match l, kerase a₁ l, exists_of_kerase ha₁, ha₂ with
| _, _, ⟨b₁, l₁, l₂, a₁_nin_l₁, rfl, rfl⟩, _ =>
if h' : a₂ ∈ l₁.keys then by
simp [kerase_append_left h',
kerase_append_right (mt (mem_keys_kerase_of_ne h).mp a₁_nin_l₁)]
else by
simp [kerase_append_right h', kerase_append_right a₁_nin_l₁,
@kerase_cons_ne _ _ _ a₂ ⟨a₁, b₁⟩ _ (Ne.symm h)]
else by simp [ha₂, mt mem_keys_of_mem_keys_kerase ha₂]
else by simp [ha₁, mt mem_keys_of_mem_keys_kerase ha₁]
theorem sizeOf_kerase [SizeOf (Sigma β)] (x : α)
(xs : List (Sigma β)) : SizeOf.sizeOf (List.kerase x xs) ≤ SizeOf.sizeOf xs := by
simp only [SizeOf.sizeOf, _sizeOf_1]
induction' xs with y ys
· simp
· by_cases x = y.1 <;> simp [*]
/-! ### `kinsert` -/
/-- Insert the pair `⟨a, b⟩` and erase the first pair with the key `a`. -/
def kinsert (a : α) (b : β a) (l : List (Sigma β)) : List (Sigma β) :=
⟨a, b⟩ :: kerase a l
@[simp]
theorem kinsert_def {a} {b : β a} {l : List (Sigma β)} : kinsert a b l = ⟨a, b⟩ :: kerase a l :=
rfl
theorem mem_keys_kinsert {a a'} {b' : β a'} {l : List (Sigma β)} :
a ∈ (kinsert a' b' l).keys ↔ a = a' ∨ a ∈ l.keys := by by_cases h : a = a' <;> simp [h]
theorem kinsert_nodupKeys (a) (b : β a) {l : List (Sigma β)} (nd : l.NodupKeys) :
(kinsert a b l).NodupKeys :=
nodupKeys_cons.mpr ⟨not_mem_keys_kerase a nd, nd.kerase a⟩
theorem Perm.kinsert {a} {b : β a} {l₁ l₂ : List (Sigma β)} (nd₁ : l₁.NodupKeys) (p : l₁ ~ l₂) :
kinsert a b l₁ ~ kinsert a b l₂ :=
(p.kerase nd₁).cons _
theorem dlookup_kinsert {a} {b : β a} (l : List (Sigma β)) :
dlookup a (kinsert a b l) = some b := by
simp only [kinsert, dlookup_cons_eq]
theorem dlookup_kinsert_ne {a a'} {b' : β a'} {l : List (Sigma β)} (h : a ≠ a') :
dlookup a (kinsert a' b' l) = dlookup a l := by simp [h]
/-! ### `kextract` -/
/-- Finds the first entry with a given key `a` and returns its value (as an `Option` because there
might be no entry with key `a`) alongside with the rest of the entries. -/
def kextract (a : α) : List (Sigma β) → Option (β a) × List (Sigma β)
| [] => (none, [])
| s :: l =>
if h : s.1 = a then (some (Eq.recOn h s.2), l)
else
let (b', l') := kextract a l
(b', s :: l')
@[simp]
theorem kextract_eq_dlookup_kerase (a : α) :
∀ l : List (Sigma β), kextract a l = (dlookup a l, kerase a l)
| [] => rfl
| ⟨a', b⟩ :: l => by
simp only [kextract]; dsimp; split_ifs with h
· subst a'
simp [kerase]
· simp [kextract, Ne.symm h, kextract_eq_dlookup_kerase a l, kerase]
/-! ### `dedupKeys` -/
/-- Remove entries with duplicate keys from `l : List (Sigma β)`. -/
def dedupKeys : List (Sigma β) → List (Sigma β) :=
List.foldr (fun x => kinsert x.1 x.2) []
theorem dedupKeys_cons {x : Sigma β} (l : List (Sigma β)) :
dedupKeys (x :: l) = kinsert x.1 x.2 (dedupKeys l) :=
rfl
theorem nodupKeys_dedupKeys (l : List (Sigma β)) : NodupKeys (dedupKeys l) := by
dsimp [dedupKeys]
generalize hl : nil = l'
have : NodupKeys l' := by
rw [← hl]
apply nodup_nil
clear hl
induction' l with x xs l_ih
· apply this
· cases x
simp only [foldr_cons, kinsert_def, nodupKeys_cons, ne_eq, not_true]
constructor
· simp only [keys_kerase]
apply l_ih.not_mem_erase
· exact l_ih.kerase _
theorem dlookup_dedupKeys (a : α) (l : List (Sigma β)) : dlookup a (dedupKeys l) = dlookup a l := by
induction' l with l_hd _ l_ih
· rfl
cases' l_hd with a' b
by_cases h : a = a'
· subst a'
rw [dedupKeys_cons, dlookup_kinsert, dlookup_cons_eq]
· rw [dedupKeys_cons, dlookup_kinsert_ne h, l_ih, dlookup_cons_ne]
exact h
theorem sizeOf_dedupKeys [SizeOf (Sigma β)]
(xs : List (Sigma β)) : SizeOf.sizeOf (dedupKeys xs) ≤ SizeOf.sizeOf xs := by
simp only [SizeOf.sizeOf, _sizeOf_1]
induction' xs with x xs
· simp [dedupKeys]
· simp only [dedupKeys_cons, kinsert_def, Nat.add_le_add_iff_left, Sigma.eta]
trans
· apply sizeOf_kerase
· assumption
/-! ### `kunion` -/
/-- `kunion l₁ l₂` is the append to l₁ of l₂ after, for each key in l₁, the
first matching pair in l₂ is erased. -/
def kunion : List (Sigma β) → List (Sigma β) → List (Sigma β)
| [], l₂ => l₂
| s :: l₁, l₂ => s :: kunion l₁ (kerase s.1 l₂)
@[simp]
theorem nil_kunion {l : List (Sigma β)} : kunion [] l = l :=
rfl
@[simp]
theorem kunion_nil : ∀ {l : List (Sigma β)}, kunion l [] = l
| [] => rfl
| _ :: l => by rw [kunion, kerase_nil, kunion_nil]
@[simp]
theorem kunion_cons {s} {l₁ l₂ : List (Sigma β)} :
kunion (s :: l₁) l₂ = s :: kunion l₁ (kerase s.1 l₂) :=
rfl
@[simp]
theorem mem_keys_kunion {a} {l₁ l₂ : List (Sigma β)} :
a ∈ (kunion l₁ l₂).keys ↔ a ∈ l₁.keys ∨ a ∈ l₂.keys := by
induction l₁ generalizing l₂ with
| nil => simp
| cons s l₁ ih => by_cases h : a = s.1 <;> [simp [h]; simp [h, ih]]
@[simp]
theorem kunion_kerase {a} :
∀ {l₁ l₂ : List (Sigma β)}, kunion (kerase a l₁) (kerase a l₂) = kerase a (kunion l₁ l₂)
| [], _ => rfl
| s :: _, l => by by_cases h : a = s.1 <;> simp [h, kerase_comm a s.1 l, kunion_kerase]
theorem NodupKeys.kunion (nd₁ : l₁.NodupKeys) (nd₂ : l₂.NodupKeys) : (kunion l₁ l₂).NodupKeys := by
induction l₁ generalizing l₂ with
| nil => simp only [nil_kunion, nd₂]
| cons s l₁ ih =>
simp? at nd₁ says simp only [nodupKeys_cons] at nd₁
simp [not_or, nd₁.1, nd₂, ih nd₁.2 (nd₂.kerase s.1)]
theorem Perm.kunion_right {l₁ l₂ : List (Sigma β)} (p : l₁ ~ l₂) (l) :
kunion l₁ l ~ kunion l₂ l := by
induction p generalizing l with
| nil => rfl
| cons hd _ ih =>
simp [ih (List.kerase _ _), Perm.cons]
| swap s₁ s₂ l => simp [kerase_comm, Perm.swap]
| trans _ _ ih₁₂ ih₂₃ => exact Perm.trans (ih₁₂ l) (ih₂₃ l)
theorem Perm.kunion_left :
∀ (l) {l₁ l₂ : List (Sigma β)}, l₁.NodupKeys → l₁ ~ l₂ → kunion l l₁ ~ kunion l l₂
| [], _, _, _, p => p
| s :: l, _, _, nd₁, p => ((p.kerase nd₁).kunion_left l <| nd₁.kerase s.1).cons s
theorem Perm.kunion {l₁ l₂ l₃ l₄ : List (Sigma β)} (nd₃ : l₃.NodupKeys) (p₁₂ : l₁ ~ l₂)
(p₃₄ : l₃ ~ l₄) : kunion l₁ l₃ ~ kunion l₂ l₄ :=
(p₁₂.kunion_right l₃).trans (p₃₄.kunion_left l₂ nd₃)
@[simp]
theorem dlookup_kunion_left {a} {l₁ l₂ : List (Sigma β)} (h : a ∈ l₁.keys) :
dlookup a (kunion l₁ l₂) = dlookup a l₁ := by
induction' l₁ with s _ ih generalizing l₂ <;> simp at h; cases' h with h h <;> cases' s with a'
· subst h
simp
· rw [kunion_cons]
by_cases h' : a = a'
· subst h'
simp
· simp [h', ih h]
@[simp]
theorem dlookup_kunion_right {a} {l₁ l₂ : List (Sigma β)} (h : a ∉ l₁.keys) :
dlookup a (kunion l₁ l₂) = dlookup a l₂ := by
induction l₁ generalizing l₂ with
| nil => simp
| cons _ _ ih => simp_all [not_or]
theorem mem_dlookup_kunion {a} {b : β a} {l₁ l₂ : List (Sigma β)} :
b ∈ dlookup a (kunion l₁ l₂) ↔ b ∈ dlookup a l₁ ∨ a ∉ l₁.keys ∧ b ∈ dlookup a l₂ := by
induction l₁ generalizing l₂ with
| nil => simp
| cons s _ ih =>
cases' s with a'
by_cases h₁ : a = a'
· subst h₁
simp
· let h₂ := @ih (kerase a' l₂)
simp? [h₁] at h₂ says
simp only [Option.mem_def, ne_eq, h₁, not_false_eq_true, dlookup_kerase_ne] at h₂
simp [h₁, h₂]
@[simp]
theorem dlookup_kunion_eq_some {a} {b : β a} {l₁ l₂ : List (Sigma β)} :
dlookup a (kunion l₁ l₂) = some b ↔
dlookup a l₁ = some b ∨ a ∉ l₁.keys ∧ dlookup a l₂ = some b :=
mem_dlookup_kunion
theorem mem_dlookup_kunion_middle {a} {b : β a} {l₁ l₂ l₃ : List (Sigma β)}
(h₁ : b ∈ dlookup a (kunion l₁ l₃)) (h₂ : a ∉ keys l₂) :
b ∈ dlookup a (kunion (kunion l₁ l₂) l₃) :=
match mem_dlookup_kunion.mp h₁ with
| Or.inl h => mem_dlookup_kunion.mpr (Or.inl (mem_dlookup_kunion.mpr (Or.inl h)))
| Or.inr h => mem_dlookup_kunion.mpr <| Or.inr ⟨mt mem_keys_kunion.mp (not_or.mpr ⟨h.1, h₂⟩), h.2⟩
end List
|
Data\List\Sort.lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import Mathlib.Data.List.OfFn
import Mathlib.Data.List.Nodup
import Mathlib.Data.List.Infix
import Mathlib.Order.Fin.Basic
/-!
# Sorting algorithms on lists
In this file we define `List.Sorted r l` to be an alias for `List.Pairwise r l`.
This alias is preferred in the case that `r` is a `<` or `≤`-like relation.
Then we define two sorting algorithms:
`List.insertionSort` and `List.mergeSort`, and prove their correctness.
-/
open List.Perm
universe u
namespace List
/-!
### The predicate `List.Sorted`
-/
section Sorted
variable {α : Type u} {r : α → α → Prop} {a : α} {l : List α}
/-- `Sorted r l` is the same as `List.Pairwise r l`, preferred in the case that `r`
is a `<` or `≤`-like relation (transitive and antisymmetric or asymmetric) -/
def Sorted :=
@Pairwise
instance decidableSorted [DecidableRel r] (l : List α) : Decidable (Sorted r l) :=
List.instDecidablePairwise _
protected theorem Sorted.le_of_lt [Preorder α] {l : List α} (h : l.Sorted (· < ·)) :
l.Sorted (· ≤ ·) :=
h.imp le_of_lt
protected theorem Sorted.lt_of_le [PartialOrder α] {l : List α} (h₁ : l.Sorted (· ≤ ·))
(h₂ : l.Nodup) : l.Sorted (· < ·) :=
h₁.imp₂ (fun _ _ => lt_of_le_of_ne) h₂
protected theorem Sorted.ge_of_gt [Preorder α] {l : List α} (h : l.Sorted (· > ·)) :
l.Sorted (· ≥ ·) :=
h.imp le_of_lt
protected theorem Sorted.gt_of_ge [PartialOrder α] {l : List α} (h₁ : l.Sorted (· ≥ ·))
(h₂ : l.Nodup) : l.Sorted (· > ·) :=
h₁.imp₂ (fun _ _ => lt_of_le_of_ne) <| by simp_rw [ne_comm]; exact h₂
@[simp]
theorem sorted_nil : Sorted r [] :=
Pairwise.nil
theorem Sorted.of_cons : Sorted r (a :: l) → Sorted r l :=
Pairwise.of_cons
theorem Sorted.tail {r : α → α → Prop} {l : List α} (h : Sorted r l) : Sorted r l.tail :=
Pairwise.tail h
theorem rel_of_sorted_cons {a : α} {l : List α} : Sorted r (a :: l) → ∀ b ∈ l, r a b :=
rel_of_pairwise_cons
theorem Sorted.head!_le [Inhabited α] [Preorder α] {a : α} {l : List α} (h : Sorted (· < ·) l)
(ha : a ∈ l) : l.head! ≤ a := by
rw [← List.cons_head!_tail (List.ne_nil_of_mem ha)] at h ha
cases ha
· exact le_rfl
· exact le_of_lt (rel_of_sorted_cons h a (by assumption))
theorem Sorted.le_head! [Inhabited α] [Preorder α] {a : α} {l : List α} (h : Sorted (· > ·) l)
(ha : a ∈ l) : a ≤ l.head! := by
rw [← List.cons_head!_tail (List.ne_nil_of_mem ha)] at h ha
cases ha
· exact le_rfl
· exact le_of_lt (rel_of_sorted_cons h a (by assumption))
@[simp]
theorem sorted_cons {a : α} {l : List α} : Sorted r (a :: l) ↔ (∀ b ∈ l, r a b) ∧ Sorted r l :=
pairwise_cons
protected theorem Sorted.nodup {r : α → α → Prop} [IsIrrefl α r] {l : List α} (h : Sorted r l) :
Nodup l :=
Pairwise.nodup h
theorem eq_of_perm_of_sorted [IsAntisymm α r] {l₁ l₂ : List α} (hp : l₁ ~ l₂) (hs₁ : Sorted r l₁)
(hs₂ : Sorted r l₂) : l₁ = l₂ := by
induction' hs₁ with a l₁ h₁ hs₁ IH generalizing l₂
· exact hp.nil_eq
· have : a ∈ l₂ := hp.subset (mem_cons_self _ _)
rcases append_of_mem this with ⟨u₂, v₂, rfl⟩
have hp' := (perm_cons a).1 (hp.trans perm_middle)
obtain rfl := IH hp' (hs₂.sublist <| by simp)
change a :: u₂ ++ v₂ = u₂ ++ ([a] ++ v₂)
rw [← append_assoc]
congr
have : ∀ x ∈ u₂, x = a := fun x m =>
antisymm ((pairwise_append.1 hs₂).2.2 _ m a (mem_cons_self _ _)) (h₁ _ (by simp [m]))
rw [(@eq_replicate _ a (length u₂ + 1) (a :: u₂)).2,
(@eq_replicate _ a (length u₂ + 1) (u₂ ++ [a])).2] <;>
constructor <;>
simp [iff_true_intro this, or_comm]
theorem sublist_of_subperm_of_sorted [IsAntisymm α r] {l₁ l₂ : List α} (hp : l₁ <+~ l₂)
(hs₁ : l₁.Sorted r) (hs₂ : l₂.Sorted r) : l₁ <+ l₂ := by
let ⟨_, h, h'⟩ := hp
rwa [← eq_of_perm_of_sorted h (hs₂.sublist h') hs₁]
@[simp 1100] -- Porting note: higher priority for linter
theorem sorted_singleton (a : α) : Sorted r [a] :=
pairwise_singleton _ _
theorem Sorted.rel_get_of_lt {l : List α} (h : l.Sorted r) {a b : Fin l.length} (hab : a < b) :
r (l.get a) (l.get b) :=
List.pairwise_iff_get.1 h _ _ hab
set_option linter.deprecated false in
@[deprecated Sorted.rel_get_of_lt (since := "2024-05-08")]
theorem Sorted.rel_nthLe_of_lt {l : List α} (h : l.Sorted r) {a b : ℕ} (ha : a < l.length)
(hb : b < l.length) (hab : a < b) : r (l.nthLe a ha) (l.nthLe b hb) :=
List.pairwise_iff_get.1 h ⟨a, ha⟩ ⟨b, hb⟩ hab
theorem Sorted.rel_get_of_le [IsRefl α r] {l : List α} (h : l.Sorted r) {a b : Fin l.length}
(hab : a ≤ b) : r (l.get a) (l.get b) := by
obtain rfl | hlt := Fin.eq_or_lt_of_le hab; exacts [refl _, h.rel_get_of_lt hlt]
set_option linter.deprecated false in
@[deprecated Sorted.rel_get_of_le (since := "2024-05-08")]
theorem Sorted.rel_nthLe_of_le [IsRefl α r] {l : List α} (h : l.Sorted r) {a b : ℕ}
(ha : a < l.length) (hb : b < l.length) (hab : a ≤ b) : r (l.nthLe a ha) (l.nthLe b hb) :=
h.rel_get_of_le hab
theorem Sorted.rel_of_mem_take_of_mem_drop {l : List α} (h : List.Sorted r l) {k : ℕ} {x y : α}
(hx : x ∈ List.take k l) (hy : y ∈ List.drop k l) : r x y := by
obtain ⟨iy, hiy, rfl⟩ := getElem_of_mem hy
obtain ⟨ix, hix, rfl⟩ := getElem_of_mem hx
rw [getElem_take', getElem_drop']
rw [length_take] at hix
exact h.rel_get_of_lt (Nat.lt_add_right _ (Nat.lt_min.mp hix).left)
end Sorted
section Monotone
variable {n : ℕ} {α : Type u} {f : Fin n → α}
theorem sorted_ofFn_iff {r : α → α → Prop} : (ofFn f).Sorted r ↔ ((· < ·) ⇒ r) f f := by
simp_rw [Sorted, pairwise_iff_get, get_ofFn, Relator.LiftFun]
exact Iff.symm (Fin.rightInverse_cast _).surjective.forall₂
variable [Preorder α]
/-- The list `List.ofFn f` is strictly sorted with respect to `(· ≤ ·)` if and only if `f` is
strictly monotone. -/
@[simp] theorem sorted_lt_ofFn_iff : (ofFn f).Sorted (· < ·) ↔ StrictMono f := sorted_ofFn_iff
/-- The list `List.ofFn f` is sorted with respect to `(· ≤ ·)` if and only if `f` is monotone. -/
@[simp] theorem sorted_le_ofFn_iff : (ofFn f).Sorted (· ≤ ·) ↔ Monotone f :=
sorted_ofFn_iff.trans monotone_iff_forall_lt.symm
/-- A tuple is monotone if and only if the list obtained from it is sorted. -/
@[deprecated sorted_le_ofFn_iff (since := "2023-01-10")]
theorem monotone_iff_ofFn_sorted : Monotone f ↔ (ofFn f).Sorted (· ≤ ·) := sorted_le_ofFn_iff.symm
/-- The list obtained from a monotone tuple is sorted. -/
alias ⟨_, _root_.Monotone.ofFn_sorted⟩ := sorted_le_ofFn_iff
end Monotone
section sort
variable {α : Type u} (r : α → α → Prop) [DecidableRel r]
local infixl:50 " ≼ " => r
/-! ### Insertion sort -/
section InsertionSort
/-- `orderedInsert a l` inserts `a` into `l` at such that
`orderedInsert a l` is sorted if `l` is. -/
@[simp]
def orderedInsert (a : α) : List α → List α
| [] => [a]
| b :: l => if a ≼ b then a :: b :: l else b :: orderedInsert a l
/-- `insertionSort l` returns `l` sorted using the insertion sort algorithm. -/
@[simp]
def insertionSort : List α → List α
| [] => []
| b :: l => orderedInsert r b (insertionSort l)
@[simp]
theorem orderedInsert_nil (a : α) : [].orderedInsert r a = [a] :=
rfl
theorem orderedInsert_length : ∀ (L : List α) (a : α), (L.orderedInsert r a).length = L.length + 1
| [], a => rfl
| hd :: tl, a => by
dsimp [orderedInsert]
split_ifs <;> simp [orderedInsert_length tl]
/-- An alternative definition of `orderedInsert` using `takeWhile` and `dropWhile`. -/
theorem orderedInsert_eq_take_drop (a : α) :
∀ l : List α,
l.orderedInsert r a = (l.takeWhile fun b => ¬a ≼ b) ++ a :: l.dropWhile fun b => ¬a ≼ b
| [] => rfl
| b :: l => by
dsimp only [orderedInsert]
split_ifs with h <;> simp [takeWhile, dropWhile, *, orderedInsert_eq_take_drop a l]
theorem insertionSort_cons_eq_take_drop (a : α) (l : List α) :
insertionSort r (a :: l) =
((insertionSort r l).takeWhile fun b => ¬a ≼ b) ++
a :: (insertionSort r l).dropWhile fun b => ¬a ≼ b :=
orderedInsert_eq_take_drop r a _
@[simp]
theorem mem_orderedInsert {a b : α} {l : List α} :
a ∈ orderedInsert r b l ↔ a = b ∨ a ∈ l :=
match l with
| [] => by simp [orderedInsert]
| x :: xs => by
rw [orderedInsert]
split_ifs
· simp [orderedInsert]
· rw [mem_cons, mem_cons, mem_orderedInsert, or_left_comm]
section Correctness
open Perm
theorem perm_orderedInsert (a) : ∀ l : List α, orderedInsert r a l ~ a :: l
| [] => Perm.refl _
| b :: l => by
by_cases h : a ≼ b
· simp [orderedInsert, h]
· simpa [orderedInsert, h] using ((perm_orderedInsert a l).cons _).trans (Perm.swap _ _ _)
theorem orderedInsert_count [DecidableEq α] (L : List α) (a b : α) :
count a (L.orderedInsert r b) = count a L + if b = a then 1 else 0 := by
rw [(L.perm_orderedInsert r b).count_eq, count_cons]
simp
theorem perm_insertionSort : ∀ l : List α, insertionSort r l ~ l
| [] => Perm.nil
| b :: l => by
simpa [insertionSort] using (perm_orderedInsert _ _ _).trans ((perm_insertionSort l).cons b)
variable {r}
/-- If `l` is already `List.Sorted` with respect to `r`, then `insertionSort` does not change
it. -/
theorem Sorted.insertionSort_eq : ∀ {l : List α}, Sorted r l → insertionSort r l = l
| [], _ => rfl
| [a], _ => rfl
| a :: b :: l, h => by
rw [insertionSort, Sorted.insertionSort_eq, orderedInsert, if_pos]
exacts [rel_of_sorted_cons h _ (mem_cons_self _ _), h.tail]
/-- For a reflexive relation, insert then erasing is the identity. -/
theorem erase_orderedInsert [DecidableEq α] [IsRefl α r] (x : α) (xs : List α) :
(xs.orderedInsert r x).erase x = xs := by
rw [orderedInsert_eq_take_drop, erase_append_right, List.erase_cons_head,
takeWhile_append_dropWhile]
intro h
replace h := mem_takeWhile_imp h
simp [refl x] at h
/-- Inserting then erasing an element that is absent is the identity. -/
theorem erase_orderedInsert_of_not_mem [DecidableEq α]
{x : α} {xs : List α} (hx : x ∉ xs) :
(xs.orderedInsert r x).erase x = xs := by
rw [orderedInsert_eq_take_drop, erase_append_right, List.erase_cons_head,
takeWhile_append_dropWhile]
exact mt ((takeWhile_prefix _).sublist.subset ·) hx
/-- For an antisymmetric relation, erasing then inserting is the identity. -/
theorem orderedInsert_erase [DecidableEq α] [IsAntisymm α r] (x : α) (xs : List α) (hx : x ∈ xs)
(hxs : Sorted r xs) :
(xs.erase x).orderedInsert r x = xs := by
induction xs generalizing x with
| nil => cases hx
| cons y ys ih =>
rw [sorted_cons] at hxs
obtain rfl | hxy := Decidable.eq_or_ne x y
· rw [erase_cons_head]
cases ys with
| nil => rfl
| cons z zs =>
rw [orderedInsert, if_pos (hxs.1 _ (.head zs))]
· rw [mem_cons] at hx
replace hx := hx.resolve_left hxy
rw [erase_cons_tail (not_beq_of_ne hxy.symm), orderedInsert, ih _ hx hxs.2, if_neg]
refine mt (fun hrxy => ?_) hxy
exact antisymm hrxy (hxs.1 _ hx)
theorem sublist_orderedInsert (x : α) (xs : List α) : xs <+ xs.orderedInsert r x := by
rw [orderedInsert_eq_take_drop]
refine Sublist.trans ?_ (.append_left (.cons _ (.refl _)) _)
rw [takeWhile_append_dropWhile]
section TotalAndTransitive
variable [IsTotal α r] [IsTrans α r]
theorem Sorted.orderedInsert (a : α) : ∀ l, Sorted r l → Sorted r (orderedInsert r a l)
| [], _ => sorted_singleton a
| b :: l, h => by
by_cases h' : a ≼ b
· -- Porting note: was
-- `simpa [orderedInsert, h', h] using fun b' bm => trans h' (rel_of_sorted_cons h _ bm)`
rw [List.orderedInsert, if_pos h', sorted_cons]
exact ⟨forall_mem_cons.2 ⟨h', fun c hc => _root_.trans h' (rel_of_sorted_cons h _ hc)⟩, h⟩
· suffices ∀ b' : α, b' ∈ List.orderedInsert r a l → r b b' by
simpa [orderedInsert, h', h.of_cons.orderedInsert a l]
intro b' bm
cases' (mem_orderedInsert r).mp bm with be bm
· subst b'
exact (total_of r _ _).resolve_left h'
· exact rel_of_sorted_cons h _ bm
variable (r)
/-- The list `List.insertionSort r l` is `List.Sorted` with respect to `r`. -/
theorem sorted_insertionSort : ∀ l, Sorted r (insertionSort r l)
| [] => sorted_nil
| a :: l => (sorted_insertionSort l).orderedInsert a _
end TotalAndTransitive
end Correctness
end InsertionSort
/-! ### Merge sort -/
section MergeSort
-- TODO(Jeremy): observation: if instead we write (a :: (split l).1, b :: (split l).2), the
-- equation compiler can't prove the third equation
/-- Split `l` into two lists of approximately equal length.
split [1, 2, 3, 4, 5] = ([1, 3, 5], [2, 4]) -/
@[simp]
def split : List α → List α × List α
| [] => ([], [])
| a :: l =>
let (l₁, l₂) := split l
(a :: l₂, l₁)
theorem split_cons_of_eq (a : α) {l l₁ l₂ : List α} (h : split l = (l₁, l₂)) :
split (a :: l) = (a :: l₂, l₁) := by rw [split, h]
theorem length_split_le :
∀ {l l₁ l₂ : List α}, split l = (l₁, l₂) → length l₁ ≤ length l ∧ length l₂ ≤ length l
| [], _, _, rfl => ⟨Nat.le_refl 0, Nat.le_refl 0⟩
| a :: l, l₁', l₂', h => by
cases' e : split l with l₁ l₂
injection (split_cons_of_eq _ e).symm.trans h; substs l₁' l₂'
cases' length_split_le e with h₁ h₂
exact ⟨Nat.succ_le_succ h₂, Nat.le_succ_of_le h₁⟩
theorem length_split_fst_le (l : List α) : length (split l).1 ≤ length l :=
(length_split_le rfl).1
theorem length_split_snd_le (l : List α) : length (split l).2 ≤ length l :=
(length_split_le rfl).2
theorem length_split_lt {a b} {l l₁ l₂ : List α} (h : split (a :: b :: l) = (l₁, l₂)) :
length l₁ < length (a :: b :: l) ∧ length l₂ < length (a :: b :: l) := by
cases' e : split l with l₁' l₂'
injection (split_cons_of_eq _ (split_cons_of_eq _ e)).symm.trans h; substs l₁ l₂
cases' length_split_le e with h₁ h₂
exact ⟨Nat.succ_le_succ (Nat.succ_le_succ h₁), Nat.succ_le_succ (Nat.succ_le_succ h₂)⟩
theorem perm_split : ∀ {l l₁ l₂ : List α}, split l = (l₁, l₂) → l ~ l₁ ++ l₂
| [], _, _, rfl => Perm.refl _
| a :: l, l₁', l₂', h => by
cases' e : split l with l₁ l₂
injection (split_cons_of_eq _ e).symm.trans h; substs l₁' l₂'
exact ((perm_split e).trans perm_append_comm).cons a
/-- Implementation of a merge sort algorithm to sort a list. -/
def mergeSort : List α → List α
| [] => []
| [a] => [a]
| a :: b :: l => by
-- Porting note: rewrote to make `mergeSort_cons_cons` proof easier
let ls := (split (a :: b :: l))
have := length_split_fst_le l
have := length_split_snd_le l
exact merge (r · ·) (mergeSort ls.1) (mergeSort ls.2)
termination_by l => length l
@[nolint unusedHavesSuffices] -- Porting note: false positive
theorem mergeSort_cons_cons {a b} {l l₁ l₂ : List α} (h : split (a :: b :: l) = (l₁, l₂)) :
mergeSort r (a :: b :: l) = merge (r · ·) (mergeSort r l₁) (mergeSort r l₂) := by
simp only [mergeSort, h]
section Correctness
theorem perm_mergeSort : ∀ l : List α, mergeSort r l ~ l
| [] => by simp [mergeSort]
| [a] => by simp [mergeSort]
| a :: b :: l => by
cases' e : split (a :: b :: l) with l₁ l₂
cases' length_split_lt e with h₁ h₂
rw [mergeSort_cons_cons r e]
apply (perm_merge (r · ·) _ _).trans
exact
((perm_mergeSort l₁).append (perm_mergeSort l₂)).trans (perm_split e).symm
termination_by l => length l
@[simp]
theorem length_mergeSort (l : List α) : (mergeSort r l).length = l.length :=
(perm_mergeSort r _).length_eq
section TotalAndTransitive
variable {r} [IsTotal α r] [IsTrans α r]
theorem Sorted.merge : ∀ {l l' : List α}, Sorted r l → Sorted r l' → Sorted r (merge (r · ·) l l')
| [], [], _, _ => by simp
| [], b :: l', _, h₂ => by simpa using h₂
| a :: l, [], h₁, _ => by simpa using h₁
| a :: l, b :: l', h₁, h₂ => by
by_cases h : a ≼ b
· suffices ∀ b' ∈ List.merge (r · ·) l (b :: l'), r a b' by
simpa [h, h₁.of_cons.merge h₂]
intro b' bm
rcases show b' = b ∨ b' ∈ l ∨ b' ∈ l' by
simpa [or_left_comm] using (perm_merge _ _ _).subset bm with
(be | bl | bl')
· subst b'
assumption
· exact rel_of_sorted_cons h₁ _ bl
· exact _root_.trans h (rel_of_sorted_cons h₂ _ bl')
· suffices ∀ b' ∈ List.merge (r · ·) (a :: l) l', r b b' by
simpa [h, h₁.merge h₂.of_cons]
intro b' bm
have ba : b ≼ a := (total_of r _ _).resolve_left h
have : b' = a ∨ b' ∈ l ∨ b' ∈ l' := by simpa using (perm_merge _ _ _).subset bm
rcases this with (be | bl | bl')
· subst b'
assumption
· exact _root_.trans ba (rel_of_sorted_cons h₁ _ bl)
· exact rel_of_sorted_cons h₂ _ bl'
variable (r)
theorem sorted_mergeSort : ∀ l : List α, Sorted r (mergeSort r l)
| [] => by simp [mergeSort]
| [a] => by simp [mergeSort]
| a :: b :: l => by
cases' e : split (a :: b :: l) with l₁ l₂
cases' length_split_lt e with h₁ h₂
rw [mergeSort_cons_cons r e]
exact (sorted_mergeSort l₁).merge (sorted_mergeSort l₂)
termination_by l => length l
theorem mergeSort_eq_self [IsAntisymm α r] {l : List α} : Sorted r l → mergeSort r l = l :=
eq_of_perm_of_sorted (perm_mergeSort _ _) (sorted_mergeSort _ _)
theorem mergeSort_eq_insertionSort [IsAntisymm α r] (l : List α) :
mergeSort r l = insertionSort r l :=
eq_of_perm_of_sorted ((perm_mergeSort r l).trans (perm_insertionSort r l).symm)
(sorted_mergeSort r l) (sorted_insertionSort r l)
end TotalAndTransitive
end Correctness
@[simp]
theorem mergeSort_nil : [].mergeSort r = [] := by rw [List.mergeSort]
@[simp]
theorem mergeSort_singleton (a : α) : [a].mergeSort r = [a] := by rw [List.mergeSort]
end MergeSort
end sort
-- try them out!
--#eval insertionSort (fun m n : ℕ => m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12]
--#eval mergeSort (fun m n : ℕ => m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12]
end List
|
Data\List\Sublists.lean | /-
Copyright (c) 2019 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.Nat.Choose.Basic
import Mathlib.Data.List.Perm
import Mathlib.Data.List.Range
/-! # sublists
`List.Sublists` gives a list of all (not necessarily contiguous) sublists of a list.
This file contains basic results on this function.
-/
/-
Porting note: various auxiliary definitions such as `sublists'_aux` were left out of the port
because they were only used to prove properties of `sublists`, and these proofs have changed.
-/
universe u v w
variable {α : Type u} {β : Type v} {γ : Type w}
open Nat
namespace List
/-! ### sublists -/
@[simp]
theorem sublists'_nil : sublists' (@nil α) = [[]] :=
rfl
@[simp]
theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] :=
rfl
-- Porting note: Not the same as `sublists'_aux` from Lean3
/-- Auxiliary helper definition for `sublists'` -/
def sublists'Aux (a : α) (r₁ r₂ : List (List α)) : List (List α) :=
r₁.foldl (init := r₂) fun r l => r ++ [a :: l]
theorem sublists'Aux_eq_array_foldl (a : α) : ∀ (r₁ r₂ : List (List α)),
sublists'Aux a r₁ r₂ = ((r₁.toArray).foldl (init := r₂.toArray)
(fun r l => r.push (a :: l))).toList := by
intro r₁ r₂
rw [sublists'Aux, Array.foldl_eq_foldl_data]
have := List.foldl_hom Array.toList (fun r l => r.push (a :: l))
(fun r l => r ++ [a :: l]) r₁ r₂.toArray (by simp)
simpa using this
theorem sublists'_eq_sublists'Aux (l : List α) :
sublists' l = l.foldr (fun a r => sublists'Aux a r r) [[]] := by
simp only [sublists', sublists'Aux_eq_array_foldl]
rw [← List.foldr_hom Array.toList]
· rfl
· intros _ _; congr <;> simp
theorem sublists'Aux_eq_map (a : α) (r₁ : List (List α)) : ∀ (r₂ : List (List α)),
sublists'Aux a r₁ r₂ = r₂ ++ map (cons a) r₁ :=
List.reverseRecOn r₁ (fun _ => by simp [sublists'Aux]) fun r₁ l ih r₂ => by
rw [map_append, map_singleton, ← append_assoc, ← ih, sublists'Aux, foldl_append, foldl]
simp [sublists'Aux]
-- Porting note: simp can prove `sublists'_singleton`
@[simp 900]
theorem sublists'_cons (a : α) (l : List α) :
sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) := by
simp [sublists'_eq_sublists'Aux, foldr_cons, sublists'Aux_eq_map]
@[simp]
theorem mem_sublists' {s t : List α} : s ∈ sublists' t ↔ s <+ t := by
induction' t with a t IH generalizing s
· simp only [sublists'_nil, mem_singleton]
exact ⟨fun h => by rw [h], eq_nil_of_sublist_nil⟩
simp only [sublists'_cons, mem_append, IH, mem_map]
constructor <;> intro h
· rcases h with (h | ⟨s, h, rfl⟩)
· exact sublist_cons_of_sublist _ h
· exact h.cons_cons _
· cases' h with _ _ _ h s _ _ h
· exact Or.inl h
· exact Or.inr ⟨s, h, rfl⟩
@[simp]
theorem length_sublists' : ∀ l : List α, length (sublists' l) = 2 ^ length l
| [] => rfl
| a :: l => by
simp_arith only [sublists'_cons, length_append, length_sublists' l,
length_map, length, Nat.pow_succ']
@[simp]
theorem sublists_nil : sublists (@nil α) = [[]] :=
rfl
@[simp]
theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] :=
rfl
-- Porting note: Not the same as `sublists_aux` from Lean3
/-- Auxiliary helper function for `sublists` -/
def sublistsAux (a : α) (r : List (List α)) : List (List α) :=
r.foldl (init := []) fun r l => r ++ [l, a :: l]
theorem sublistsAux_eq_array_foldl :
sublistsAux = fun (a : α) (r : List (List α)) =>
(r.toArray.foldl (init := #[])
fun r l => (r.push l).push (a :: l)).toList := by
funext a r
simp only [sublistsAux, Array.foldl_eq_foldl_data, Array.mkEmpty]
have := foldl_hom Array.toList (fun r l => (r.push l).push (a :: l))
(fun (r : List (List α)) l => r ++ [l, a :: l]) r #[]
(by simp)
simpa using this
theorem sublistsAux_eq_bind :
sublistsAux = fun (a : α) (r : List (List α)) => r.bind fun l => [l, a :: l] :=
funext fun a => funext fun r =>
List.reverseRecOn r
(by simp [sublistsAux])
(fun r l ih => by
rw [bind_append, ← ih, bind_singleton, sublistsAux, foldl_append]
simp [sublistsAux])
@[csimp] theorem sublists_eq_sublistsFast : @sublists = @sublistsFast := by
ext α l : 2
trans l.foldr sublistsAux [[]]
· rw [sublistsAux_eq_bind, sublists]
· simp only [sublistsFast, sublistsAux_eq_array_foldl, Array.foldr_eq_foldr_data]
rw [← foldr_hom Array.toList]
· rfl
· intros _ _; congr <;> simp
theorem sublists_append (l₁ l₂ : List α) :
sublists (l₁ ++ l₂) = (sublists l₂) >>= (fun x => (sublists l₁).map (· ++ x)) := by
simp only [sublists, foldr_append]
induction l₁ with
| nil => simp
| cons a l₁ ih =>
rw [foldr_cons, ih]
simp [List.bind, join_join, Function.comp]
theorem sublists_cons (a : α) (l : List α) :
sublists (a :: l) = sublists l >>= (fun x => [x, a :: x]) :=
show sublists ([a] ++ l) = _ by
rw [sublists_append]
simp only [sublists_singleton, map_cons, bind_eq_bind, nil_append, cons_append, map_nil]
@[simp]
theorem sublists_concat (l : List α) (a : α) :
sublists (l ++ [a]) = sublists l ++ map (fun x => x ++ [a]) (sublists l) := by
rw [sublists_append, sublists_singleton, bind_eq_bind, bind_cons, bind_cons, bind_nil,
map_id'' append_nil, append_nil]
theorem sublists_reverse (l : List α) : sublists (reverse l) = map reverse (sublists' l) := by
induction' l with hd tl ih <;> [rfl;
simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton,
map_eq_map, bind_eq_bind, map_map, bind_cons, append_nil, bind_nil, (· ∘ ·)]]
theorem sublists_eq_sublists' (l : List α) : sublists l = map reverse (sublists' (reverse l)) := by
rw [← sublists_reverse, reverse_reverse]
theorem sublists'_reverse (l : List α) : sublists' (reverse l) = map reverse (sublists l) := by
simp only [sublists_eq_sublists', map_map, map_id'' reverse_reverse, Function.comp]
theorem sublists'_eq_sublists (l : List α) : sublists' l = map reverse (sublists (reverse l)) := by
rw [← sublists'_reverse, reverse_reverse]
@[simp]
theorem mem_sublists {s t : List α} : s ∈ sublists t ↔ s <+ t := by
rw [← reverse_sublist, ← mem_sublists', sublists'_reverse,
mem_map_of_injective reverse_injective]
@[simp]
theorem length_sublists (l : List α) : length (sublists l) = 2 ^ length l := by
simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse]
theorem map_pure_sublist_sublists (l : List α) : map pure l <+ sublists l := by
induction' l using reverseRecOn with l a ih <;> simp only [map, map_append, sublists_concat]
· simp only [sublists_nil, sublist_cons_self]
exact ((append_sublist_append_left _).2 <|
singleton_sublist.2 <| mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by rfl⟩).trans
((append_sublist_append_right _).2 ih)
set_option linter.deprecated false in
@[deprecated map_pure_sublist_sublists (since := "2024-03-24")]
theorem map_ret_sublist_sublists (l : List α) : map List.ret l <+ sublists l :=
map_pure_sublist_sublists l
/-! ### sublistsLen -/
/-- Auxiliary function to construct the list of all sublists of a given length. Given an
integer `n`, a list `l`, a function `f` and an auxiliary list `L`, it returns the list made of
`f` applied to all sublists of `l` of length `n`, concatenated with `L`. -/
def sublistsLenAux : ℕ → List α → (List α → β) → List β → List β
| 0, _, f, r => f [] :: r
| _ + 1, [], _, r => r
| n + 1, a :: l, f, r => sublistsLenAux (n + 1) l f (sublistsLenAux n l (f ∘ List.cons a) r)
/-- The list of all sublists of a list `l` that are of length `n`. For instance, for
`l = [0, 1, 2, 3]` and `n = 2`, one gets
`[[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]]`. -/
def sublistsLen (n : ℕ) (l : List α) : List (List α) :=
sublistsLenAux n l id []
theorem sublistsLenAux_append :
∀ (n : ℕ) (l : List α) (f : List α → β) (g : β → γ) (r : List β) (s : List γ),
sublistsLenAux n l (g ∘ f) (r.map g ++ s) = (sublistsLenAux n l f r).map g ++ s
| 0, l, f, g, r, s => by unfold sublistsLenAux; simp
| n + 1, [], f, g, r, s => rfl
| n + 1, a :: l, f, g, r, s => by
unfold sublistsLenAux
simp only [show (g ∘ f) ∘ List.cons a = g ∘ f ∘ List.cons a by rfl, sublistsLenAux_append,
sublistsLenAux_append]
theorem sublistsLenAux_eq (l : List α) (n) (f : List α → β) (r) :
sublistsLenAux n l f r = (sublistsLen n l).map f ++ r := by
rw [sublistsLen, ← sublistsLenAux_append]; rfl
theorem sublistsLenAux_zero (l : List α) (f : List α → β) (r) :
sublistsLenAux 0 l f r = f [] :: r := by cases l <;> rfl
@[simp]
theorem sublistsLen_zero (l : List α) : sublistsLen 0 l = [[]] :=
sublistsLenAux_zero _ _ _
@[simp]
theorem sublistsLen_succ_nil (n) : sublistsLen (n + 1) (@nil α) = [] :=
rfl
@[simp]
theorem sublistsLen_succ_cons (n) (a : α) (l) :
sublistsLen (n + 1) (a :: l) = sublistsLen (n + 1) l ++ (sublistsLen n l).map (cons a) := by
rw [sublistsLen, sublistsLenAux, sublistsLenAux_eq, sublistsLenAux_eq, map_id,
append_nil]; rfl
theorem sublistsLen_one (l : List α) : sublistsLen 1 l = l.reverse.map ([·]) :=
l.rec (by rw [sublistsLen_succ_nil, reverse_nil, map_nil]) fun a s ih ↦ by
rw [sublistsLen_succ_cons, ih, reverse_cons, map_append, sublistsLen_zero]; rfl
@[simp]
theorem length_sublistsLen :
∀ (n) (l : List α), length (sublistsLen n l) = Nat.choose (length l) n
| 0, l => by simp
| _ + 1, [] => by simp
| n + 1, a :: l => by
rw [sublistsLen_succ_cons, length_append, length_sublistsLen (n+1) l,
length_map, length_sublistsLen n l, length_cons, Nat.choose_succ_succ, Nat.add_comm]
theorem sublistsLen_sublist_sublists' :
∀ (n) (l : List α), sublistsLen n l <+ sublists' l
| 0, l => by simp
| _ + 1, [] => nil_sublist _
| n + 1, a :: l => by
rw [sublistsLen_succ_cons, sublists'_cons]
exact (sublistsLen_sublist_sublists' _ _).append ((sublistsLen_sublist_sublists' _ _).map _)
theorem sublistsLen_sublist_of_sublist (n) {l₁ l₂ : List α} (h : l₁ <+ l₂) :
sublistsLen n l₁ <+ sublistsLen n l₂ := by
induction' n with n IHn generalizing l₁ l₂; · simp
induction' h with l₁ l₂ a _ IH l₁ l₂ a s IH; · rfl
· refine IH.trans ?_
rw [sublistsLen_succ_cons]
apply sublist_append_left
· simpa only [sublistsLen_succ_cons] using IH.append ((IHn s).map _)
theorem length_of_sublistsLen :
∀ {n} {l l' : List α}, l' ∈ sublistsLen n l → length l' = n
| 0, l, l', h => by simp_all
| n + 1, a :: l, l', h => by
rw [sublistsLen_succ_cons, mem_append, mem_map] at h
rcases h with (h | ⟨l', h, rfl⟩)
· exact length_of_sublistsLen h
· exact congr_arg (· + 1) (length_of_sublistsLen h)
theorem mem_sublistsLen_self {l l' : List α} (h : l' <+ l) :
l' ∈ sublistsLen (length l') l := by
induction' h with l₁ l₂ a s IH l₁ l₂ a s IH
· simp
· cases' l₁ with b l₁
· simp
· rw [length, sublistsLen_succ_cons]
exact mem_append_left _ IH
· rw [length, sublistsLen_succ_cons]
exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩)
@[simp]
theorem mem_sublistsLen {n} {l l' : List α} :
l' ∈ sublistsLen n l ↔ l' <+ l ∧ length l' = n :=
⟨fun h =>
⟨mem_sublists'.1 ((sublistsLen_sublist_sublists' _ _).subset h), length_of_sublistsLen h⟩,
fun ⟨h₁, h₂⟩ => h₂ ▸ mem_sublistsLen_self h₁⟩
theorem sublistsLen_of_length_lt {n} {l : List α} (h : l.length < n) : sublistsLen n l = [] :=
eq_nil_iff_forall_not_mem.mpr fun _ =>
mem_sublistsLen.not.mpr fun ⟨hs, hl⟩ => (h.trans_eq hl.symm).not_le (Sublist.length_le hs)
@[simp]
theorem sublistsLen_length : ∀ l : List α, sublistsLen l.length l = [l]
| [] => rfl
| a :: l => by
simp only [length, sublistsLen_succ_cons, sublistsLen_length, map,
sublistsLen_of_length_lt (lt_succ_self _), nil_append]
open Function
theorem Pairwise.sublists' {R} :
∀ {l : List α}, Pairwise R l → Pairwise (Lex (swap R)) (sublists' l)
| _, Pairwise.nil => pairwise_singleton _ _
| _, @Pairwise.cons _ _ a l H₁ H₂ => by
simp only [sublists'_cons, pairwise_append, pairwise_map, mem_sublists', mem_map, exists_imp,
and_imp]
refine ⟨H₂.sublists', H₂.sublists'.imp fun l₁ => Lex.cons l₁, ?_⟩
rintro l₁ sl₁ x l₂ _ rfl
cases' l₁ with b l₁; · constructor
exact Lex.rel (H₁ _ <| sl₁.subset <| mem_cons_self _ _)
theorem pairwise_sublists {R} {l : List α} (H : Pairwise R l) :
Pairwise (fun l₁ l₂ => Lex R (reverse l₁) (reverse l₂)) (sublists l) := by
have := (pairwise_reverse.2 H).sublists'
rwa [sublists'_reverse, pairwise_map] at this
@[simp]
theorem nodup_sublists {l : List α} : Nodup (sublists l) ↔ Nodup l :=
⟨fun h => (h.sublist (map_pure_sublist_sublists _)).of_map _, fun h =>
(pairwise_sublists h).imp @fun l₁ l₂ h => by simpa using h.to_ne⟩
@[simp]
theorem nodup_sublists' {l : List α} : Nodup (sublists' l) ↔ Nodup l := by
rw [sublists'_eq_sublists, nodup_map_iff reverse_injective, nodup_sublists, nodup_reverse]
alias ⟨nodup.of_sublists, nodup.sublists⟩ := nodup_sublists
alias ⟨nodup.of_sublists', nodup.sublists'⟩ := nodup_sublists'
-- Porting note: commented out
--attribute [protected] nodup.sublists nodup.sublists'
theorem nodup_sublistsLen (n : ℕ) {l : List α} (h : Nodup l) : (sublistsLen n l).Nodup := by
have : Pairwise (· ≠ ·) l.sublists' := Pairwise.imp
(fun h => Lex.to_ne (by convert h using 3; simp [swap, eq_comm])) h.sublists'
exact this.sublist (sublistsLen_sublist_sublists' _ _)
theorem sublists_map (f : α → β) : ∀ (l : List α),
sublists (map f l) = map (map f) (sublists l)
| [] => by simp
| a::l => by
rw [map_cons, sublists_cons, bind_eq_bind, sublists_map f l, sublists_cons,
bind_eq_bind, map_eq_bind, map_eq_bind]
induction sublists l <;> simp [*]
theorem sublists'_map (f : α → β) : ∀ (l : List α),
sublists' (map f l) = map (map f) (sublists' l)
| [] => by simp
| a::l => by simp [map_cons, sublists'_cons, sublists'_map f l, Function.comp]
-- Porting note: moved because it is now used to prove `sublists_cons_perm_append`
theorem sublists_perm_sublists' (l : List α) : sublists l ~ sublists' l := by
rw [← finRange_map_get l, sublists_map, sublists'_map]
apply Perm.map
apply (perm_ext_iff_of_nodup _ _).mpr
· simp
· exact nodup_sublists.mpr (nodup_finRange _)
· exact (nodup_sublists'.mpr (nodup_finRange _))
theorem sublists_cons_perm_append (a : α) (l : List α) :
sublists (a :: l) ~ sublists l ++ map (cons a) (sublists l) :=
Perm.trans (sublists_perm_sublists' _) <| by
rw [sublists'_cons]
exact Perm.append (sublists_perm_sublists' _).symm (Perm.map _ (sublists_perm_sublists' _).symm)
theorem revzip_sublists (l : List α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists → l₁ ++ l₂ ~ l := by
rw [revzip]
induction' l using List.reverseRecOn with l' a ih
· intro l₁ l₂ h
simp? at h says
simp only [sublists_nil, reverse_cons, reverse_nil, nil_append, zip_cons_cons, zip_nil_right,
mem_singleton, Prod.mk.injEq] at h
simp [h]
· intro l₁ l₂ h
rw [sublists_concat, reverse_append, zip_append (by simp), ← map_reverse, zip_map_right,
zip_map_left] at *
simp only [Prod.mk.inj_iff, mem_map, mem_append, Prod.map_mk, Prod.exists] at h
rcases h with (⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩)
· rw [← append_assoc]
exact (ih _ _ h).append_right _
· rw [append_assoc]
apply (perm_append_comm.append_left _).trans
rw [← append_assoc]
exact (ih _ _ h).append_right _
theorem revzip_sublists' (l : List α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists' → l₁ ++ l₂ ~ l := by
rw [revzip]
induction' l with a l IH <;> intro l₁ l₂ h
· simp_all only [sublists'_nil, reverse_cons, reverse_nil, nil_append, zip_cons_cons,
zip_nil_right, mem_singleton, Prod.mk.injEq, append_nil, Perm.refl]
· rw [sublists'_cons, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at *
<;> [simp only [mem_append, mem_map, Prod.map_apply, id_eq, Prod.mk.injEq, Prod.exists,
exists_eq_right_right] at h; simp]
rcases h with (⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', h, rfl⟩)
· exact perm_middle.trans ((IH _ _ h).cons _)
· exact (IH _ _ h).cons _
theorem range_bind_sublistsLen_perm (l : List α) :
((List.range (l.length + 1)).bind fun n => sublistsLen n l) ~ sublists' l := by
induction' l with h tl l_ih
· simp [range_succ]
· simp_rw [range_succ_eq_map, length, bind_cons, bind_map, sublistsLen_succ_cons, sublists'_cons,
List.sublistsLen_zero, List.singleton_append]
refine ((bind_append_perm (range (tl.length + 1)) _ _).symm.cons _).trans ?_
simp_rw [← List.map_bind, ← cons_append]
rw [← List.singleton_append, ← List.sublistsLen_zero tl]
refine Perm.append ?_ (l_ih.map _)
rw [List.range_succ, bind_append, bind_singleton,
sublistsLen_of_length_lt (Nat.lt_succ_self _), append_nil,
← List.bind_map Nat.succ fun n => sublistsLen n tl,
← bind_cons 0 _ fun n => sublistsLen n tl, ← range_succ_eq_map]
exact l_ih
end List
|
Data\List\Sym.lean | /-
Copyright (c) 2023 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import Mathlib.Data.Nat.Choose.Basic
import Mathlib.Data.Sym.Sym2
/-! # Unordered tuples of elements of a list
Defines `List.sym` and the specialized `List.sym2` for computing lists of all unordered n-tuples
from a given list. These are list versions of `Nat.multichoose`.
## Main declarations
* `List.sym`: `xs.sym n` is a list of all unordered n-tuples of elements from `xs`,
with multiplicity. The list's values are in `Sym α n`.
* `List.sym2`: `xs.sym2` is a list of all unordered pairs of elements from `xs`,
with multiplicity. The list's values are in `Sym2 α`.
## TODO
* Prove `protected theorem Perm.sym (n : ℕ) {xs ys : List α} (h : xs ~ ys) : xs.sym n ~ ys.sym n`
and lift the result to `Multiset` and `Finset`.
-/
namespace List
variable {α β : Type*}
section Sym2
/-- `xs.sym2` is a list of all unordered pairs of elements from `xs`.
If `xs` has no duplicates then neither does `xs.sym2`. -/
protected def sym2 : List α → List (Sym2 α)
| [] => []
| x :: xs => (x :: xs).map (fun y => s(x, y)) ++ xs.sym2
theorem sym2_map (f : α → β) (xs : List α) :
(xs.map f).sym2 = xs.sym2.map (Sym2.map f) := by
induction xs with
| nil => simp [List.sym2]
| cons x xs ih => simp [List.sym2, ih, Function.comp]
theorem mem_sym2_cons_iff {x : α} {xs : List α} {z : Sym2 α} :
z ∈ (x :: xs).sym2 ↔ z = s(x, x) ∨ (∃ y, y ∈ xs ∧ z = s(x, y)) ∨ z ∈ xs.sym2 := by
simp only [List.sym2, map_cons, cons_append, mem_cons, mem_append, mem_map]
simp only [eq_comm]
@[simp]
theorem sym2_eq_nil_iff {xs : List α} : xs.sym2 = [] ↔ xs = [] := by
cases xs <;> simp [List.sym2]
theorem left_mem_of_mk_mem_sym2 {xs : List α} {a b : α}
(h : s(a, b) ∈ xs.sym2) : a ∈ xs := by
induction xs with
| nil => exact (not_mem_nil _ h).elim
| cons x xs ih =>
rw [mem_cons]
rw [mem_sym2_cons_iff] at h
obtain (h | ⟨c, hc, h⟩ | h) := h
· rw [Sym2.eq_iff, ← and_or_left] at h
exact .inl h.1
· rw [Sym2.eq_iff] at h
obtain (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩) := h <;> simp [hc]
· exact .inr <| ih h
theorem right_mem_of_mk_mem_sym2 {xs : List α} {a b : α}
(h : s(a, b) ∈ xs.sym2) : b ∈ xs := by
rw [Sym2.eq_swap] at h
exact left_mem_of_mk_mem_sym2 h
theorem mk_mem_sym2 {xs : List α} {a b : α} (ha : a ∈ xs) (hb : b ∈ xs) :
s(a, b) ∈ xs.sym2 := by
induction xs with
| nil => simp at ha
| cons x xs ih =>
rw [mem_sym2_cons_iff]
rw [mem_cons] at ha hb
obtain (rfl | ha) := ha <;> obtain (rfl | hb) := hb
· left; rfl
· right; left; use b
· right; left; rw [Sym2.eq_swap]; use a
· right; right; exact ih ha hb
theorem mk_mem_sym2_iff {xs : List α} {a b : α} :
s(a, b) ∈ xs.sym2 ↔ a ∈ xs ∧ b ∈ xs := by
constructor
· intro h
exact ⟨left_mem_of_mk_mem_sym2 h, right_mem_of_mk_mem_sym2 h⟩
· rintro ⟨ha, hb⟩
exact mk_mem_sym2 ha hb
theorem mem_sym2_iff {xs : List α} {z : Sym2 α} :
z ∈ xs.sym2 ↔ ∀ y ∈ z, y ∈ xs := by
refine z.ind (fun a b => ?_)
simp [mk_mem_sym2_iff]
protected theorem Nodup.sym2 {xs : List α} (h : xs.Nodup) : xs.sym2.Nodup := by
induction xs with
| nil => simp only [List.sym2, nodup_nil]
| cons x xs ih =>
rw [List.sym2]
specialize ih h.of_cons
rw [nodup_cons] at h
refine Nodup.append (Nodup.cons ?notmem (h.2.map ?inj)) ih ?disj
case disj =>
intro z hz hz'
simp only [mem_cons, mem_map] at hz
obtain ⟨_, (rfl | _), rfl⟩ := hz
<;> simp [left_mem_of_mk_mem_sym2 hz'] at h
case notmem =>
intro h'
simp only [h.1, mem_map, Sym2.eq_iff, true_and, or_self, exists_eq_right] at h'
case inj =>
intro a b
simp only [Sym2.eq_iff, true_and]
rintro (rfl | ⟨rfl, rfl⟩) <;> rfl
theorem map_mk_sublist_sym2 (x : α) (xs : List α) (h : x ∈ xs) :
map (fun y ↦ s(x, y)) xs <+ xs.sym2 := by
induction xs with
| nil => simp
| cons x' xs ih =>
simp [List.sym2]
cases h with
| head =>
exact (sublist_append_left _ _).cons₂ _
| tail _ h =>
refine .cons _ ?_
rw [← singleton_append]
refine .append ?_ (ih h)
rw [singleton_sublist, mem_map]
exact ⟨_, h, Sym2.eq_swap⟩
theorem map_mk_disjoint_sym2 (x : α) (xs : List α) (h : x ∉ xs) :
(map (fun y ↦ s(x, y)) xs).Disjoint xs.sym2 := by
induction xs with
| nil => simp
| cons x' xs ih =>
simp only [mem_cons, not_or] at h
rw [List.sym2, map_cons, map_cons, disjoint_cons_left, disjoint_append_right,
disjoint_cons_right]
refine ⟨?_, ⟨?_, ?_⟩, ?_⟩
· refine not_mem_cons_of_ne_of_not_mem ?_ (not_mem_append ?_ ?_)
· simp [h.1]
· simp_rw [mem_map, not_exists, not_and]
intro x'' hx
simp_rw [Sym2.mk_eq_mk_iff, Prod.swap_prod_mk, Prod.mk.injEq, true_and]
rintro (⟨rfl, rfl⟩ | rfl)
· exact h.2 hx
· exact h.2 hx
· simp [mk_mem_sym2_iff, h.2]
· simp [h.1]
· intro z hx hy
rw [List.mem_map] at hx hy
obtain ⟨a, hx, rfl⟩ := hx
obtain ⟨b, hy, hx⟩ := hy
simp [Sym2.mk_eq_mk_iff, Ne.symm h.1] at hx
obtain ⟨rfl, rfl⟩ := hx
exact h.2 hy
· exact ih h.2
theorem dedup_sym2 [DecidableEq α] (xs : List α) : xs.sym2.dedup = xs.dedup.sym2 := by
induction xs with
| nil => simp only [List.sym2, dedup_nil]
| cons x xs ih =>
simp only [List.sym2, map_cons, cons_append]
obtain hm | hm := Decidable.em (x ∈ xs)
· rw [dedup_cons_of_mem hm, ← ih, dedup_cons_of_mem,
List.Subset.dedup_append_right (map_mk_sublist_sym2 _ _ hm).subset]
refine mem_append_of_mem_left _ ?_
rw [mem_map]
exact ⟨_, hm, Sym2.eq_swap⟩
· rw [dedup_cons_of_not_mem hm, List.sym2, map_cons, ← ih, dedup_cons_of_not_mem, cons_append,
List.Disjoint.dedup_append, dedup_map_of_injective]
· exact (Sym2.mkEmbedding _).injective
· exact map_mk_disjoint_sym2 x xs hm
· simp [hm, mem_sym2_iff]
protected theorem Perm.sym2 {xs ys : List α} (h : xs ~ ys) :
xs.sym2 ~ ys.sym2 := by
induction h with
| nil => rfl
| cons x h ih =>
simp only [List.sym2, map_cons, cons_append, perm_cons]
exact (h.map _).append ih
| swap x y xs =>
simp only [List.sym2, map_cons, cons_append]
conv => enter [1,2,1]; rw [Sym2.eq_swap]
-- Explicit permutation to speed up simps that follow.
refine Perm.trans (Perm.swap ..) (Perm.trans (Perm.cons _ ?_) (Perm.swap ..))
simp only [← Multiset.coe_eq_coe, ← Multiset.cons_coe,
← Multiset.coe_add, ← Multiset.singleton_add]
simp only [add_assoc, add_left_comm]
| trans _ _ ih1 ih2 => exact ih1.trans ih2
protected theorem Sublist.sym2 {xs ys : List α} (h : xs <+ ys) : xs.sym2 <+ ys.sym2 := by
induction h with
| slnil => apply slnil
| cons a h ih =>
simp only [List.sym2]
exact Sublist.append (nil_sublist _) ih
| cons₂ a h ih =>
simp only [List.sym2, map_cons, cons_append]
exact cons₂ _ (append (Sublist.map _ h) ih)
protected theorem Subperm.sym2 {xs ys : List α} (h : xs <+~ ys) : xs.sym2 <+~ ys.sym2 := by
obtain ⟨xs', hx, h⟩ := h
exact hx.sym2.symm.subperm.trans h.sym2.subperm
theorem length_sym2 {xs : List α} : xs.sym2.length = Nat.choose (xs.length + 1) 2 := by
induction xs with
| nil => rfl
| cons x xs ih =>
rw [List.sym2, length_append, length_map, length_cons,
Nat.choose_succ_succ, ← ih, Nat.choose_one_right]
end Sym2
section Sym
/-- `xs.sym n` is all unordered `n`-tuples from the list `xs` in some order. -/
protected def sym : (n : ℕ) → List α → List (Sym α n)
| 0, _ => [.nil]
| _, [] => []
| n + 1, x :: xs => ((x :: xs).sym n |>.map fun p => x ::ₛ p) ++ xs.sym (n + 1)
variable {xs ys : List α} {n : ℕ}
theorem sym_one_eq : xs.sym 1 = xs.map (· ::ₛ .nil) := by
induction xs with
| nil => simp only [List.sym, Nat.succ_eq_add_one, Nat.reduceAdd, map_nil]
| cons x xs ih =>
rw [map_cons, ← ih, List.sym, List.sym, map_singleton, singleton_append]
theorem sym2_eq_sym_two : xs.sym2.map (Sym2.equivSym α) = xs.sym 2 := by
induction xs with
| nil => simp only [List.sym, map_eq_nil, sym2_eq_nil_iff]
| cons x xs ih =>
rw [List.sym, ← ih, sym_one_eq, map_map, List.sym2, map_append, map_map]
rfl
theorem sym_map {β : Type*} (f : α → β) (n : ℕ) (xs : List α) :
(xs.map f).sym n = (xs.sym n).map (Sym.map f) :=
match n, xs with
| 0, _ => by simp only [List.sym]; rfl
| n + 1, [] => by simp [List.sym]
| n + 1, x :: xs => by
rw [map_cons, List.sym, ← map_cons, sym_map f n (x :: xs), sym_map f (n + 1) xs]
simp only [map_map, List.sym, map_append, append_cancel_right_eq]
congr
ext s
simp only [Function.comp_apply, Sym.map_cons]
protected theorem Sublist.sym (n : ℕ) {xs ys : List α} (h : xs <+ ys) : xs.sym n <+ ys.sym n :=
match n, h with
| 0, _ => by simp [List.sym]
| n + 1, .slnil => by simp only [refl]
| n + 1, .cons a h => by
rw [List.sym, ← nil_append (List.sym (n + 1) xs)]
apply Sublist.append (nil_sublist _)
exact h.sym (n + 1)
| n + 1, .cons₂ a h => by
rw [List.sym, List.sym]
apply Sublist.append
· exact ((cons₂ a h).sym n).map _
· exact h.sym (n + 1)
theorem sym_sublist_sym_cons {a : α} : xs.sym n <+ (a :: xs).sym n :=
(sublist_cons_self a xs).sym n
theorem mem_of_mem_of_mem_sym {n : ℕ} {xs : List α} {a : α} {z : Sym α n}
(ha : a ∈ z) (hz : z ∈ xs.sym n) : a ∈ xs :=
match n, xs with
| 0, xs => by
cases Sym.eq_nil_of_card_zero z
simp at ha
| n + 1, [] => by simp [List.sym] at hz
| n + 1, x :: xs => by
rw [List.sym, mem_append, mem_map] at hz
obtain ⟨z, hz, rfl⟩ | hz := hz
· rw [Sym.mem_cons] at ha
obtain rfl | ha := ha
· simp
· exact mem_of_mem_of_mem_sym ha hz
· rw [mem_cons]
right
exact mem_of_mem_of_mem_sym ha hz
theorem first_mem_of_cons_mem_sym {xs : List α} {n : ℕ} {a : α} {z : Sym α n}
(h : a ::ₛ z ∈ xs.sym (n + 1)) : a ∈ xs :=
mem_of_mem_of_mem_sym (Sym.mem_cons_self a z) h
protected theorem Nodup.sym (n : ℕ) {xs : List α} (h : xs.Nodup) : (xs.sym n).Nodup :=
match n, xs with
| 0, _ => by simp [List.sym]
| n + 1, [] => by simp [List.sym]
| n + 1, x :: xs => by
rw [List.sym]
refine Nodup.append (Nodup.map ?inj (Nodup.sym n h)) (Nodup.sym (n + 1) h.of_cons) ?disj
case inj =>
intro z z'
simp
case disj =>
intro z hz hz'
rw [mem_map] at hz
obtain ⟨z, _hz, rfl⟩ := hz
have := first_mem_of_cons_mem_sym hz'
simp only [nodup_cons, this, not_true_eq_false, false_and] at h
theorem length_sym {n : ℕ} {xs : List α} :
(xs.sym n).length = Nat.multichoose xs.length n :=
match n, xs with
| 0, _ => by rw [List.sym, Nat.multichoose]; rfl
| n + 1, [] => by simp [List.sym]
| n + 1, x :: xs => by
rw [List.sym, length_append, length_map, length_cons]
rw [@length_sym n (x :: xs), @length_sym (n + 1) xs]
rw [Nat.multichoose_succ_succ, length_cons, add_comm]
end Sym
end List
|
Data\List\TFAE.lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Simon Hudon
-/
import Batteries.Data.List.Lemmas
import Batteries.Tactic.Classical
import Mathlib.Tactic.TypeStar
/-!
# The Following Are Equivalent
This file allows to state that all propositions in a list are equivalent. It is used by
`Mathlib.Tactic.Tfae`.
`TFAE l` means `∀ x ∈ l, ∀ y ∈ l, x ↔ y`. This is equivalent to `Pairwise (↔) l`.
-/
namespace List
/-- TFAE: The Following (propositions) Are Equivalent.
The `tfae_have` and `tfae_finish` tactics can be useful in proofs with `TFAE` goals.
-/
def TFAE (l : List Prop) : Prop :=
∀ x ∈ l, ∀ y ∈ l, x ↔ y
theorem tfae_nil : TFAE [] :=
forall_mem_nil _
@[simp]
theorem tfae_singleton (p) : TFAE [p] := by simp [TFAE, -eq_iff_iff]
theorem tfae_cons_of_mem {a b} {l : List Prop} (h : b ∈ l) : TFAE (a :: l) ↔ (a ↔ b) ∧ TFAE l :=
⟨fun H => ⟨H a (by simp) b (Mem.tail a h),
fun p hp q hq => H _ (Mem.tail a hp) _ (Mem.tail a hq)⟩,
by
rintro ⟨ab, H⟩ p (_ | ⟨_, hp⟩) q (_ | ⟨_, hq⟩)
· rfl
· exact ab.trans (H _ h _ hq)
· exact (ab.trans (H _ h _ hp)).symm
· exact H _ hp _ hq⟩
theorem tfae_cons_cons {a b} {l : List Prop} : TFAE (a :: b :: l) ↔ (a ↔ b) ∧ TFAE (b :: l) :=
tfae_cons_of_mem (Mem.head _)
@[simp]
theorem tfae_cons_self {a} {l : List Prop} : TFAE (a :: a :: l) ↔ TFAE (a :: l) := by
simp [tfae_cons_cons]
theorem tfae_of_forall (b : Prop) (l : List Prop) (h : ∀ a ∈ l, a ↔ b) : TFAE l :=
fun _a₁ h₁ _a₂ h₂ => (h _ h₁).trans (h _ h₂).symm
theorem tfae_of_cycle {a b} {l : List Prop} (h_chain : List.Chain (· → ·) a (b :: l))
(h_last : getLastD l b → a) : TFAE (a :: b :: l) := by
induction l generalizing a b with
| nil => simp_all [tfae_cons_cons, iff_def]
| cons c l IH =>
simp only [tfae_cons_cons, getLastD_cons, tfae_singleton, and_true, chain_cons, Chain.nil] at *
rcases h_chain with ⟨ab, ⟨bc, ch⟩⟩
have := IH ⟨bc, ch⟩ (ab ∘ h_last)
exact ⟨⟨ab, h_last ∘ (this.2 c (.head _) _ (getLastD_mem_cons _ _)).1 ∘ bc⟩, this⟩
theorem TFAE.out {l} (h : TFAE l) (n₁ n₂) {a b} (h₁ : List.get? l n₁ = some a := by rfl)
(h₂ : List.get? l n₂ = some b := by rfl) : a ↔ b :=
h _ (List.get?_mem h₁) _ (List.get?_mem h₂)
/-- If `P₁ x ↔ ... ↔ Pₙ x` for all `x`, then `(∀ x, P₁ x) ↔ ... ↔ (∀ x, Pₙ x)`.
Note: in concrete cases, Lean has trouble finding the list `[P₁, ..., Pₙ]` from the list
`[(∀ x, P₁ x), ..., (∀ x, Pₙ x)]`, but simply providing a list of underscores with the right
length makes it happier.
Example:
```lean
example (P₁ P₂ P₃ : ℕ → Prop) (H : ∀ n, [P₁ n, P₂ n, P₃ n].TFAE) :
[∀ n, P₁ n, ∀ n, P₂ n, ∀ n, P₃ n].TFAE :=
forall_tfae [_, _, _] H
```
-/
theorem forall_tfae {α : Type*} (l : List (α → Prop)) (H : ∀ a : α, (l.map (fun p ↦ p a)).TFAE) :
(l.map (fun p ↦ ∀ a, p a)).TFAE := by
simp only [TFAE, List.forall_mem_map]
intros p₁ hp₁ p₂ hp₂
exact forall_congr' fun a ↦ H a (p₁ a) (mem_map_of_mem (fun p ↦ p a) hp₁)
(p₂ a) (mem_map_of_mem (fun p ↦ p a) hp₂)
/-- If `P₁ x ↔ ... ↔ Pₙ x` for all `x`, then `(∃ x, P₁ x) ↔ ... ↔ (∃ x, Pₙ x)`.
Note: in concrete cases, Lean has trouble finding the list `[P₁, ..., Pₙ]` from the list
`[(∃ x, P₁ x), ..., (∃ x, Pₙ x)]`, but simply providing a list of underscores with the right
length makes it happier.
Example:
```lean
example (P₁ P₂ P₃ : ℕ → Prop) (H : ∀ n, [P₁ n, P₂ n, P₃ n].TFAE) :
[∃ n, P₁ n, ∃ n, P₂ n, ∃ n, P₃ n].TFAE :=
exists_tfae [_, _, _] H
```
-/
theorem exists_tfae {α : Type*} (l : List (α → Prop)) (H : ∀ a : α, (l.map (fun p ↦ p a)).TFAE) :
(l.map (fun p ↦ ∃ a, p a)).TFAE := by
simp only [TFAE, List.forall_mem_map]
intros p₁ hp₁ p₂ hp₂
exact exists_congr fun a ↦ H a (p₁ a) (mem_map_of_mem (fun p ↦ p a) hp₁)
(p₂ a) (mem_map_of_mem (fun p ↦ p a) hp₂)
theorem tfae_not_iff {l : List Prop} : TFAE (l.map Not) ↔ TFAE l := by
classical
simp only [TFAE, mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂,
Decidable.not_iff_not]
alias ⟨_, TFAE.not⟩ := tfae_not_iff
end List
|
Data\List\ToFinsupp.lean | /-
Copyright (c) 2022 Yakov Pechersky. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky
-/
import Mathlib.Data.Finsupp.Defs
import Mathlib.Data.List.GetD
/-!
# Lists as finsupp
## Main definitions
- `List.toFinsupp`: Interpret a list as a finitely supported function, where the indexing type is
`ℕ`, and the values are either the elements of the list (accessing by indexing) or `0` outside of
the list.
## Main theorems
- `List.toFinsupp_eq_sum_map_enum_single`: A `l : List M` over `M` an `AddMonoid`, when interpreted
as a finitely supported function, is equal to the sum of `Finsupp.single` produced by mapping over
`List.enum l`.
## Implementation details
The functions defined here rely on a decidability predicate that each element in the list
can be decidably determined to be not equal to zero or that one can decide one is out of the
bounds of a list. For concretely defined lists that are made up of elements of decidable terms,
this holds. More work will be needed to support lists over non-dec-eq types like `ℝ`, where the
elements are beyond the dec-eq terms of casted values from `ℕ, ℤ, ℚ`.
-/
namespace List
variable {M : Type*} [Zero M] (l : List M) [DecidablePred (getD l · 0 ≠ 0)] (n : ℕ)
/-- Indexing into a `l : List M`, as a finitely-supported function,
where the support are all the indices within the length of the list
that index to a non-zero value. Indices beyond the end of the list are sent to 0.
This is a computable version of the `Finsupp.onFinset` construction.
-/
def toFinsupp : ℕ →₀ M where
toFun i := getD l i 0
support := (Finset.range l.length).filter fun i => getD l i 0 ≠ 0
mem_support_toFun n := by
simp only [Ne, Finset.mem_filter, Finset.mem_range, and_iff_right_iff_imp]
contrapose!
exact getD_eq_default _ _
@[norm_cast]
theorem coe_toFinsupp : (l.toFinsupp : ℕ → M) = (l.getD · 0) :=
rfl
@[simp, norm_cast]
theorem toFinsupp_apply (i : ℕ) : (l.toFinsupp : ℕ → M) i = l.getD i 0 :=
rfl
theorem toFinsupp_support :
l.toFinsupp.support = (Finset.range l.length).filter (getD l · 0 ≠ 0) :=
rfl
theorem toFinsupp_apply_lt (hn : n < l.length) : l.toFinsupp n = l.get ⟨n, hn⟩ :=
getD_eq_get _ _ _
theorem toFinsupp_apply_fin (n : Fin l.length) : l.toFinsupp n = l.get n :=
getD_eq_get _ _ _
set_option linter.deprecated false in
@[deprecated (since := "2023-04-10")]
theorem toFinsupp_apply_lt' (hn : n < l.length) : l.toFinsupp n = l.nthLe n hn :=
getD_eq_get _ _ _
theorem toFinsupp_apply_le (hn : l.length ≤ n) : l.toFinsupp n = 0 :=
getD_eq_default _ _ hn
@[simp]
theorem toFinsupp_nil [DecidablePred fun i => getD ([] : List M) i 0 ≠ 0] :
toFinsupp ([] : List M) = 0 := by
ext
simp
theorem toFinsupp_singleton (x : M) [DecidablePred (getD [x] · 0 ≠ 0)] :
toFinsupp [x] = Finsupp.single 0 x := by
ext ⟨_ | i⟩ <;> simp [Finsupp.single_apply, (Nat.zero_lt_succ _).ne]
@[deprecated "This lemma is unused, and can be proved by `simp`." (since := "2024-06-12")]
theorem toFinsupp_cons_apply_zero (x : M) (xs : List M)
[DecidablePred (getD (x::xs) · 0 ≠ 0)] : (x::xs).toFinsupp 0 = x :=
rfl
@[deprecated "This lemma is unused, and can be proved by `simp`." (since := "2024-06-12")]
theorem toFinsupp_cons_apply_succ (x : M) (xs : List M) (n : ℕ)
[DecidablePred (getD (x::xs) · 0 ≠ 0)] [DecidablePred (getD xs · 0 ≠ 0)] :
(x::xs).toFinsupp n.succ = xs.toFinsupp n :=
rfl
theorem toFinsupp_append {R : Type*} [AddZeroClass R] (l₁ l₂ : List R)
[DecidablePred (getD (l₁ ++ l₂) · 0 ≠ 0)] [DecidablePred (getD l₁ · 0 ≠ 0)]
[DecidablePred (getD l₂ · 0 ≠ 0)] :
toFinsupp (l₁ ++ l₂) =
toFinsupp l₁ + (toFinsupp l₂).embDomain (addLeftEmbedding l₁.length) := by
ext n
simp only [toFinsupp_apply, Finsupp.add_apply]
cases lt_or_le n l₁.length with
| inl h =>
rw [getD_append _ _ _ _ h, Finsupp.embDomain_notin_range, add_zero]
rintro ⟨k, rfl : length l₁ + k = n⟩
omega
| inr h =>
rcases Nat.exists_eq_add_of_le h with ⟨k, rfl⟩
rw [getD_append_right _ _ _ _ h, Nat.add_sub_cancel_left, getD_eq_default _ _ h, zero_add]
exact Eq.symm (Finsupp.embDomain_apply _ _ _)
theorem toFinsupp_cons_eq_single_add_embDomain {R : Type*} [AddZeroClass R] (x : R) (xs : List R)
[DecidablePred (getD (x::xs) · 0 ≠ 0)] [DecidablePred (getD xs · 0 ≠ 0)] :
toFinsupp (x::xs) =
Finsupp.single 0 x + (toFinsupp xs).embDomain ⟨Nat.succ, Nat.succ_injective⟩ := by
classical
convert toFinsupp_append [x] xs using 3
· exact (toFinsupp_singleton x).symm
· ext n
exact add_comm n 1
theorem toFinsupp_concat_eq_toFinsupp_add_single {R : Type*} [AddZeroClass R] (x : R) (xs : List R)
[DecidablePred fun i => getD (xs ++ [x]) i 0 ≠ 0] [DecidablePred fun i => getD xs i 0 ≠ 0] :
toFinsupp (xs ++ [x]) = toFinsupp xs + Finsupp.single xs.length x := by
classical rw [toFinsupp_append, toFinsupp_singleton, Finsupp.embDomain_single,
addLeftEmbedding_apply, add_zero]
theorem toFinsupp_eq_sum_map_enum_single {R : Type*} [AddMonoid R] (l : List R)
[DecidablePred (getD l · 0 ≠ 0)] :
toFinsupp l = (l.enum.map fun nr : ℕ × R => Finsupp.single nr.1 nr.2).sum := by
/- Porting note (#11215): TODO: `induction` fails to substitute `l = []` in
`[DecidablePred (getD l · 0 ≠ 0)]`, so we manually do some `revert`/`intro` as a workaround -/
revert l; intro l
induction l using List.reverseRecOn with
| nil => exact toFinsupp_nil
| append_singleton x xs ih =>
classical simp [toFinsupp_concat_eq_toFinsupp_add_single, enum_append, ih]
end List
|
Data\List\Zip.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kenny Lau
-/
import Mathlib.Data.List.Forall2
/-!
# zip & unzip
This file provides results about `List.zipWith`, `List.zip` and `List.unzip` (definitions are in
core Lean).
`zipWith f l₁ l₂` applies `f : α → β → γ` pointwise to a list `l₁ : List α` and `l₂ : List β`. It
applies, until one of the lists is exhausted. For example,
`zipWith f [0, 1, 2] [6.28, 31] = [f 0 6.28, f 1 31]`.
`zip` is `zipWith` applied to `Prod.mk`. For example,
`zip [a₁, a₂] [b₁, b₂, b₃] = [(a₁, b₁), (a₂, b₂)]`.
`unzip` undoes `zip`. For example, `unzip [(a₁, b₁), (a₂, b₂)] = ([a₁, a₂], [b₁, b₂])`.
-/
-- Make sure we don't import algebra
assert_not_exists Monoid
universe u
open Nat
namespace List
variable {α : Type u} {β γ δ ε : Type*}
@[simp]
theorem zip_swap : ∀ (l₁ : List α) (l₂ : List β), (zip l₁ l₂).map Prod.swap = zip l₂ l₁
| [], l₂ => zip_nil_right.symm
| l₁, [] => by rw [zip_nil_right]; rfl
| a :: l₁, b :: l₂ => by
simp only [zip_cons_cons, map_cons, zip_swap l₁ l₂, Prod.swap_prod_mk]
theorem forall_zipWith {f : α → β → γ} {p : γ → Prop} :
∀ {l₁ : List α} {l₂ : List β}, length l₁ = length l₂ →
(Forall p (zipWith f l₁ l₂) ↔ Forall₂ (fun x y => p (f x y)) l₁ l₂)
| [], [], _ => by simp
| a :: l₁, b :: l₂, h => by
simp only [length_cons, succ_inj'] at h
simp [forall_zipWith h]
theorem unzip_swap (l : List (α × β)) : unzip (l.map Prod.swap) = (unzip l).swap := by
simp only [unzip_eq_map, map_map]
rfl
@[congr]
theorem zipWith_congr (f g : α → β → γ) (la : List α) (lb : List β)
(h : List.Forall₂ (fun a b => f a b = g a b) la lb) : zipWith f la lb = zipWith g la lb := by
induction' h with a b as bs hfg _ ih
· rfl
· exact congr_arg₂ _ hfg ih
theorem zipWith_zipWith_left (f : δ → γ → ε) (g : α → β → δ) :
∀ (la : List α) (lb : List β) (lc : List γ),
zipWith f (zipWith g la lb) lc = zipWith3 (fun a b c => f (g a b) c) la lb lc
| [], _, _ => rfl
| _ :: _, [], _ => rfl
| _ :: _, _ :: _, [] => rfl
| _ :: as, _ :: bs, _ :: cs => congr_arg (cons _) <| zipWith_zipWith_left f g as bs cs
theorem zipWith_zipWith_right (f : α → δ → ε) (g : β → γ → δ) :
∀ (la : List α) (lb : List β) (lc : List γ),
zipWith f la (zipWith g lb lc) = zipWith3 (fun a b c => f a (g b c)) la lb lc
| [], _, _ => rfl
| _ :: _, [], _ => rfl
| _ :: _, _ :: _, [] => rfl
| _ :: as, _ :: bs, _ :: cs => congr_arg (cons _) <| zipWith_zipWith_right f g as bs cs
@[simp]
theorem zipWith3_same_left (f : α → α → β → γ) :
∀ (la : List α) (lb : List β), zipWith3 f la la lb = zipWith (fun a b => f a a b) la lb
| [], _ => rfl
| _ :: _, [] => rfl
| _ :: as, _ :: bs => congr_arg (cons _) <| zipWith3_same_left f as bs
@[simp]
theorem zipWith3_same_mid (f : α → β → α → γ) :
∀ (la : List α) (lb : List β), zipWith3 f la lb la = zipWith (fun a b => f a b a) la lb
| [], _ => rfl
| _ :: _, [] => rfl
| _ :: as, _ :: bs => congr_arg (cons _) <| zipWith3_same_mid f as bs
@[simp]
theorem zipWith3_same_right (f : α → β → β → γ) :
∀ (la : List α) (lb : List β), zipWith3 f la lb lb = zipWith (fun a b => f a b b) la lb
| [], _ => rfl
| _ :: _, [] => rfl
| _ :: as, _ :: bs => congr_arg (cons _) <| zipWith3_same_right f as bs
instance (f : α → α → β) [IsSymmOp α β f] : IsSymmOp (List α) (List β) (zipWith f) :=
⟨zipWith_comm_of_comm f IsSymmOp.symm_op⟩
@[simp]
theorem length_revzip (l : List α) : length (revzip l) = length l := by
simp only [revzip, length_zip, length_reverse, min_self]
@[simp]
theorem unzip_revzip (l : List α) : (revzip l).unzip = (l, l.reverse) :=
unzip_zip (length_reverse l).symm
@[simp]
theorem revzip_map_fst (l : List α) : (revzip l).map Prod.fst = l := by
rw [← unzip_fst, unzip_revzip]
@[simp]
theorem revzip_map_snd (l : List α) : (revzip l).map Prod.snd = l.reverse := by
rw [← unzip_snd, unzip_revzip]
theorem reverse_revzip (l : List α) : reverse l.revzip = revzip l.reverse := by
rw [← zip_unzip (revzip l).reverse]
simp [unzip_eq_map, revzip, map_reverse, map_fst_zip, map_snd_zip]
theorem revzip_swap (l : List α) : (revzip l).map Prod.swap = revzip l.reverse := by simp [revzip]
@[deprecated (since := "2024-07-29")] alias getElem?_zip_with := getElem?_zipWith'
theorem get?_zipWith' (f : α → β → γ) (l₁ : List α) (l₂ : List β) (i : ℕ) :
(zipWith f l₁ l₂).get? i = ((l₁.get? i).map f).bind fun g => (l₂.get? i).map g := by
simp [getElem?_zipWith']
@[deprecated (since := "2024-07-29")] alias get?_zip_with := get?_zipWith'
@[deprecated (since := "2024-07-29")] alias getElem?_zip_with_eq_some := getElem?_zipWith_eq_some
theorem get?_zipWith_eq_some (f : α → β → γ) (l₁ : List α) (l₂ : List β) (z : γ) (i : ℕ) :
(zipWith f l₁ l₂).get? i = some z ↔
∃ x y, l₁.get? i = some x ∧ l₂.get? i = some y ∧ f x y = z := by
simp [getElem?_zipWith_eq_some]
@[deprecated (since := "2024-07-29")] alias get?_zip_with_eq_some := get?_zipWith_eq_some
theorem get?_zip_eq_some (l₁ : List α) (l₂ : List β) (z : α × β) (i : ℕ) :
(zip l₁ l₂).get? i = some z ↔ l₁.get? i = some z.1 ∧ l₂.get? i = some z.2 := by
simp [getElem?_zip_eq_some]
@[deprecated getElem_zipWith (since := "2024-06-12")]
theorem get_zipWith {f : α → β → γ} {l : List α} {l' : List β} {i : Fin (zipWith f l l').length} :
(zipWith f l l').get i =
f (l.get ⟨i, lt_length_left_of_zipWith i.isLt⟩)
(l'.get ⟨i, lt_length_right_of_zipWith i.isLt⟩) := by
simp
set_option linter.deprecated false in
@[simp, deprecated get_zipWith (since := "2024-05-09")]
theorem nthLe_zipWith {f : α → β → γ} {l : List α} {l' : List β} {i : ℕ}
{h : i < (zipWith f l l').length} :
(zipWith f l l').nthLe i h =
f (l.nthLe i (lt_length_left_of_zipWith h)) (l'.nthLe i (lt_length_right_of_zipWith h)) :=
get_zipWith (i := ⟨i, h⟩)
@[deprecated getElem_zip (since := "2024-06-12")]
theorem get_zip {l : List α} {l' : List β} {i : Fin (zip l l').length} :
(zip l l').get i =
(l.get ⟨i, lt_length_left_of_zip i.isLt⟩, l'.get ⟨i, lt_length_right_of_zip i.isLt⟩) := by
simp
set_option linter.deprecated false in
@[simp, deprecated get_zip (since := "2024-05-09")]
theorem nthLe_zip {l : List α} {l' : List β} {i : ℕ} {h : i < (zip l l').length} :
(zip l l').nthLe i h =
(l.nthLe i (lt_length_left_of_zip h), l'.nthLe i (lt_length_right_of_zip h)) :=
nthLe_zipWith
theorem mem_zip_inits_tails {l : List α} {init tail : List α} :
(init, tail) ∈ zip l.inits l.tails ↔ init ++ tail = l := by
induction' l with hd tl ih generalizing init tail <;> simp_rw [tails, inits, zip_cons_cons]
· simp
· constructor <;> rw [mem_cons, zip_map_left, mem_map, Prod.exists]
· rintro (⟨rfl, rfl⟩ | ⟨_, _, h, rfl, rfl⟩)
· simp
· simp [ih.mp h]
· cases' init with hd' tl'
· rintro rfl
simp
· intro h
right
use tl', tail
simp_all
theorem map_uncurry_zip_eq_zipWith (f : α → β → γ) (l : List α) (l' : List β) :
map (Function.uncurry f) (l.zip l') = zipWith f l l' := by
rw [zip]
induction' l with hd tl hl generalizing l'
· simp
· cases' l' with hd' tl'
· simp
· simp [hl]
end List
|
Data\List\EditDistance\Bounds.lean | /-
Copyright (c) 2023 Kim Liesinger. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kim Liesinger
-/
import Mathlib.Algebra.Order.Monoid.Canonical.Defs
import Mathlib.Data.List.Infix
import Mathlib.Data.List.MinMax
import Mathlib.Data.List.EditDistance.Defs
/-!
# Lower bounds for Levenshtein distances
We show that there is some suffix `L'` of `L` such
that the Levenshtein distance from `L'` to `M` gives a lower bound
for the Levenshtein distance from `L` to `m :: M`.
This allows us to use the intermediate steps of a Levenshtein distance calculation
to produce lower bounds on the final result.
-/
variable {α β δ : Type*} {C : Levenshtein.Cost α β δ} [CanonicallyLinearOrderedAddCommMonoid δ]
theorem suffixLevenshtein_minimum_le_levenshtein_cons (xs : List α) (y ys) :
(suffixLevenshtein C xs ys).1.minimum ≤ levenshtein C xs (y :: ys) := by
induction xs with
| nil =>
simp only [suffixLevenshtein_nil', levenshtein_nil_cons,
List.minimum_singleton, WithTop.coe_le_coe]
exact le_add_of_nonneg_left (by simp)
| cons x xs ih =>
suffices
(suffixLevenshtein C (x :: xs) ys).1.minimum ≤ (C.delete x + levenshtein C xs (y :: ys)) ∧
(suffixLevenshtein C (x :: xs) ys).1.minimum ≤ (C.insert y + levenshtein C (x :: xs) ys) ∧
(suffixLevenshtein C (x :: xs) ys).1.minimum ≤ (C.substitute x y + levenshtein C xs ys) by
simpa [suffixLevenshtein_eq_tails_map]
refine ⟨?_, ?_, ?_⟩
· calc
_ ≤ (suffixLevenshtein C xs ys).1.minimum := by
simp [suffixLevenshtein_cons₁_fst, List.minimum_cons]
_ ≤ ↑(levenshtein C xs (y :: ys)) := ih
_ ≤ _ := by simp
· calc
(suffixLevenshtein C (x :: xs) ys).1.minimum ≤ (levenshtein C (x :: xs) ys) := by
simp [suffixLevenshtein_cons₁_fst, List.minimum_cons]
_ ≤ _ := by simp
· calc
(suffixLevenshtein C (x :: xs) ys).1.minimum ≤ (levenshtein C xs ys) := by
simp only [suffixLevenshtein_cons₁_fst, List.minimum_cons]
apply min_le_of_right_le
cases xs
· simp [suffixLevenshtein_nil']
· simp [suffixLevenshtein_cons₁, List.minimum_cons]
_ ≤ _ := by simp
theorem le_suffixLevenshtein_cons_minimum (xs : List α) (y ys) :
(suffixLevenshtein C xs ys).1.minimum ≤ (suffixLevenshtein C xs (y :: ys)).1.minimum := by
apply List.le_minimum_of_forall_le
simp only [suffixLevenshtein_eq_tails_map]
simp only [List.mem_map, List.mem_tails, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂]
intro a suff
refine (?_ : _ ≤ _).trans (suffixLevenshtein_minimum_le_levenshtein_cons _ _ _)
simp only [suffixLevenshtein_eq_tails_map]
apply List.le_minimum_of_forall_le
intro b m
replace m : ∃ a_1, a_1 <:+ a ∧ levenshtein C a_1 ys = b := by simpa using m
obtain ⟨a', suff', rfl⟩ := m
apply List.minimum_le_of_mem'
simp only [List.mem_map, List.mem_tails]
suffices ∃ a, a <:+ xs ∧ levenshtein C a ys = levenshtein C a' ys by simpa
exact ⟨a', suff'.trans suff, rfl⟩
theorem le_suffixLevenshtein_append_minimum (xs : List α) (ys₁ ys₂) :
(suffixLevenshtein C xs ys₂).1.minimum ≤ (suffixLevenshtein C xs (ys₁ ++ ys₂)).1.minimum := by
induction ys₁ with
| nil => exact le_refl _
| cons y ys₁ ih => exact ih.trans (le_suffixLevenshtein_cons_minimum _ _ _)
theorem suffixLevenshtein_minimum_le_levenshtein_append (xs ys₁ ys₂) :
(suffixLevenshtein C xs ys₂).1.minimum ≤ levenshtein C xs (ys₁ ++ ys₂) := by
cases ys₁ with
| nil => exact List.minimum_le_of_mem' (List.get_mem _ _ _)
| cons y ys₁ =>
exact (le_suffixLevenshtein_append_minimum _ _ _).trans
(suffixLevenshtein_minimum_le_levenshtein_cons _ _ _)
theorem le_levenshtein_cons (xs : List α) (y ys) :
∃ xs', xs' <:+ xs ∧ levenshtein C xs' ys ≤ levenshtein C xs (y :: ys) := by
simpa [suffixLevenshtein_eq_tails_map, List.minimum_le_coe_iff] using
suffixLevenshtein_minimum_le_levenshtein_cons (δ := δ) xs y ys
theorem le_levenshtein_append (xs : List α) (ys₁ ys₂) :
∃ xs', xs' <:+ xs ∧ levenshtein C xs' ys₂ ≤ levenshtein C xs (ys₁ ++ ys₂) := by
simpa [suffixLevenshtein_eq_tails_map, List.minimum_le_coe_iff] using
suffixLevenshtein_minimum_le_levenshtein_append (δ := δ) xs ys₁ ys₂
|
Data\List\EditDistance\Defs.lean | /-
Copyright (c) 2023 Kim Liesinger. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kim Liesinger
-/
import Mathlib.Algebra.Group.Defs
/-!
# Levenshtein distances
We define the Levenshtein edit distance `levenshtein C xy ys` between two `List α`,
with a customizable cost structure `C` for the `delete`, `insert`, and `substitute` operations.
As an auxiliary function, we define `suffixLevenshtein C xs ys`, which gives the list of distances
from each suffix of `xs` to `ys`.
This is defined by recursion on `ys`, using the internal function `Levenshtein.impl`,
which computes `suffixLevenshtein C xs (y :: ys)` using `xs`, `y`, and `suffixLevenshtein C xs ys`.
(This corresponds to the usual algorithm
using the last two rows of the matrix of distances between suffixes.)
After setting up these definitions, we prove lemmas specifying their behaviour,
particularly
```
theorem suffixLevenshtein_eq_tails_map :
(suffixLevenshtein C xs ys).1 = xs.tails.map fun xs' => levenshtein C xs' ys := ...
```
and
```
theorem levenshtein_cons_cons :
levenshtein C (x :: xs) (y :: ys) =
min (C.delete x + levenshtein C xs (y :: ys))
(min (C.insert y + levenshtein C (x :: xs) ys)
(C.substitute x y + levenshtein C xs ys)) := ...
```
-/
variable {α β δ : Type*} [AddZeroClass δ] [Min δ]
namespace Levenshtein
/-- A cost structure for Levenshtein edit distance. -/
structure Cost (α β δ : Type*) where
/-- Cost to delete an element from a list. -/
delete : α → δ
/-- Cost in insert an element into a list. -/
insert : β → δ
/-- Cost to substitute one element for another in a list. -/
substitute : α → β → δ
/-- The default cost structure, for which all operations cost `1`. -/
@[simps]
def defaultCost [DecidableEq α] : Cost α α ℕ where
delete _ := 1
insert _ := 1
substitute a b := if a = b then 0 else 1
instance [DecidableEq α] : Inhabited (Cost α α ℕ) := ⟨defaultCost⟩
/--
Cost structure given by a function.
Delete and insert cost the same, and substitution costs the greater value.
-/
@[simps]
def weightCost (f : α → ℕ) : Cost α α ℕ where
delete a := f a
insert b := f b
substitute a b := max (f a) (f b)
/--
Cost structure for strings, where cost is the length of the token.
-/
@[simps!]
def stringLengthCost : Cost String String ℕ := weightCost String.length
/--
Cost structure for strings, where cost is the log base 2 length of the token.
-/
@[simps!]
def stringLogLengthCost : Cost String String ℕ := weightCost fun s => Nat.log2 (s.length + 1)
variable (C : Cost α β δ)
/--
(Implementation detail for `levenshtein`)
Given a list `xs` and the Levenshtein distances from each suffix of `xs` to some other list `ys`,
compute the Levenshtein distances from each suffix of `xs` to `y :: ys`.
(Note that we don't actually need to know `ys` itself here, so it is not an argument.)
The return value is a list of length `x.length + 1`,
and it is convenient for the recursive calls that we bundle this list
with a proof that it is non-empty.
-/
def impl
(xs : List α) (y : β) (d : {r : List δ // 0 < r.length}) : {r : List δ // 0 < r.length} :=
let ⟨ds, w⟩ := d
xs.zip (ds.zip ds.tail) |>.foldr
(init := ⟨[C.insert y + ds.getLast (List.length_pos.mp w)], by simp⟩)
(fun ⟨x, d₀, d₁⟩ ⟨r, w⟩ =>
⟨min (C.delete x + r[0]) (min (C.insert y + d₀) (C.substitute x y + d₁)) :: r, by simp⟩)
variable {C}
variable (x : α) (xs : List α) (y : β) (d : δ) (ds : List δ) (w : 0 < (d :: ds).length)
-- Note this lemma has an unspecified proof `w'` on the right-hand-side,
-- which will become an extra goal when rewriting.
theorem impl_cons (w' : 0 < List.length ds) :
impl C (x :: xs) y ⟨d :: ds, w⟩ =
let ⟨r, w⟩ := impl C xs y ⟨ds, w'⟩
⟨min (C.delete x + r[0]) (min (C.insert y + d) (C.substitute x y + ds[0])) :: r, by simp⟩ :=
match ds, w' with | _ :: _, _ => rfl
-- Note this lemma has two unspecified proofs: `h` appears on the left-hand-side
-- and should be found by matching, but `w'` will become an extra goal when rewriting.
theorem impl_cons_fst_zero (h : 0 < (impl C (x :: xs) y ⟨d :: ds, w⟩).val.length)
(w' : 0 < List.length ds) : (impl C (x :: xs) y ⟨d :: ds, w⟩).1[0] =
let ⟨r, w⟩ := impl C xs y ⟨ds, w'⟩
min (C.delete x + r[0]) (min (C.insert y + d) (C.substitute x y + ds[0])) :=
match ds, w' with | _ :: _, _ => rfl
theorem impl_length (d : {r : List δ // 0 < r.length}) (w : d.1.length = xs.length + 1) :
(impl C xs y d).1.length = xs.length + 1 := by
induction xs generalizing d with
| nil => rfl
| cons x xs ih =>
dsimp [impl]
match d, w with
| ⟨d₁ :: d₂ :: ds, _⟩, w =>
dsimp
congr 1
exact ih ⟨d₂ :: ds, (by simp)⟩ (by simpa using w)
end Levenshtein
open Levenshtein
variable (C : Cost α β δ)
/--
`suffixLevenshtein C xs ys` computes the Levenshtein distance
(using the cost functions provided by a `C : Cost α β δ`)
from each suffix of the list `xs` to the list `ys`.
The first element of this list is the Levenshtein distance from `xs` to `ys`.
Note that if the cost functions do not satisfy the inequalities
* `C.delete a + C.insert b ≥ C.substitute a b`
* `C.substitute a b + C.substitute b c ≥ C.substitute a c`
(or if any values are negative)
then the edit distances calculated here may not agree with the general
geodesic distance on the edit graph.
-/
def suffixLevenshtein (xs : List α) (ys : List β) : {r : List δ // 0 < r.length} :=
ys.foldr
(impl C xs)
(xs.foldr (init := ⟨[0], by simp⟩) (fun a ⟨r, w⟩ => ⟨(C.delete a + r[0]) :: r, by simp⟩))
variable {C}
theorem suffixLevenshtein_length (xs : List α) (ys : List β) :
(suffixLevenshtein C xs ys).1.length = xs.length + 1 := by
induction ys with
| nil =>
dsimp [suffixLevenshtein]
induction xs with
| nil => rfl
| cons _ xs ih =>
simp_all
| cons y ys ih =>
dsimp [suffixLevenshtein]
rw [impl_length]
exact ih
-- This is only used in keeping track of estimates.
theorem suffixLevenshtein_eq (xs : List α) (y ys) :
impl C xs y (suffixLevenshtein C xs ys) = suffixLevenshtein C xs (y :: ys) := by
rfl
variable (C)
/--
`levenshtein C xs ys` computes the Levenshtein distance
(using the cost functions provided by a `C : Cost α β δ`)
from the list `xs` to the list `ys`.
Note that if the cost functions do not satisfy the inequalities
* `C.delete a + C.insert b ≥ C.substitute a b`
* `C.substitute a b + C.substitute b c ≥ C.substitute a c`
(or if any values are negative)
then the edit distance calculated here may not agree with the general
geodesic distance on the edit graph.
-/
def levenshtein (xs : List α) (ys : List β) : δ :=
let ⟨r, w⟩ := suffixLevenshtein C xs ys
r[0]
variable {C}
theorem suffixLevenshtein_nil_nil : (suffixLevenshtein C [] []).1 = [0] := by
rfl
-- Not sure if this belongs in the main `List` API, or can stay local.
theorem List.eq_of_length_one (x : List α) (w : x.length = 1) :
have : 0 < x.length := lt_of_lt_of_eq Nat.zero_lt_one w.symm
x = [x[0]] := by
match x, w with
| [r], _ => rfl
theorem suffixLevenshtein_nil' (ys : List β) :
(suffixLevenshtein C [] ys).1 = [levenshtein C [] ys] :=
List.eq_of_length_one _ (suffixLevenshtein_length [] _)
theorem suffixLevenshtein_cons₂ (xs : List α) (y ys) :
suffixLevenshtein C xs (y :: ys) = (impl C xs) y (suffixLevenshtein C xs ys) :=
rfl
theorem suffixLevenshtein_cons₁_aux {α} {x y : { l : List α // 0 < l.length }}
(w₀ : x.1[0]'x.2 = y.1[0]'y.2) (w : x.1.tail = y.1.tail) : x = y := by
match x, y with
| ⟨hx :: tx, _⟩, ⟨hy :: ty, _⟩ => simp_all
theorem suffixLevenshtein_cons₁
(x : α) (xs ys) :
suffixLevenshtein C (x :: xs) ys =
⟨levenshtein C (x :: xs) ys ::
(suffixLevenshtein C xs ys).1, by simp⟩ := by
induction ys with
| nil =>
dsimp [levenshtein, suffixLevenshtein]
| cons y ys ih =>
apply suffixLevenshtein_cons₁_aux
· rfl
· rw [suffixLevenshtein_cons₂ (x :: xs), ih, impl_cons]
· rfl
· simp [suffixLevenshtein_length]
theorem suffixLevenshtein_cons₁_fst (x : α) (xs ys) :
(suffixLevenshtein C (x :: xs) ys).1 =
levenshtein C (x :: xs) ys ::
(suffixLevenshtein C xs ys).1 := by
simp [suffixLevenshtein_cons₁]
theorem suffixLevenshtein_cons_cons_fst_get_zero
(x : α) (xs y ys) (w : 0 < (suffixLevenshtein C (x :: xs) (y :: ys)).val.length) :
(suffixLevenshtein C (x :: xs) (y :: ys)).1[0]'w =
let ⟨dx, _⟩ := suffixLevenshtein C xs (y :: ys)
let ⟨dy, _⟩ := suffixLevenshtein C (x :: xs) ys
let ⟨dxy, _⟩ := suffixLevenshtein C xs ys
min
(C.delete x + dx[0])
(min
(C.insert y + dy[0])
(C.substitute x y + dxy[0])) := by
conv =>
lhs
dsimp only [suffixLevenshtein_cons₂]
simp only [suffixLevenshtein_cons₁]
rw [impl_cons_fst_zero]
rfl
theorem suffixLevenshtein_eq_tails_map (xs ys) :
(suffixLevenshtein C xs ys).1 = xs.tails.map fun xs' => levenshtein C xs' ys := by
induction xs with
| nil =>
simp only [List.map, suffixLevenshtein_nil']
| cons x xs ih =>
simp only [List.map, suffixLevenshtein_cons₁, ih]
@[simp]
theorem levenshtein_nil_nil : levenshtein C [] [] = 0 := by
simp [levenshtein, suffixLevenshtein]
@[simp]
theorem levenshtein_nil_cons (y) (ys) :
levenshtein C [] (y :: ys) = C.insert y + levenshtein C [] ys := by
dsimp (config := { unfoldPartialApp := true }) [levenshtein, suffixLevenshtein, impl]
congr
rw [List.getLast_eq_getElem]
congr
rw [show (List.length _) = 1 from _]
induction ys <;> simp
@[simp]
theorem levenshtein_cons_nil (x : α) (xs : List α) :
levenshtein C (x :: xs) [] = C.delete x + levenshtein C xs [] :=
rfl
@[simp]
theorem levenshtein_cons_cons
(x : α) (xs : List α) (y : β) (ys : List β) :
levenshtein C (x :: xs) (y :: ys) =
min (C.delete x + levenshtein C xs (y :: ys))
(min (C.insert y + levenshtein C (x :: xs) ys)
(C.substitute x y + levenshtein C xs ys)) :=
suffixLevenshtein_cons_cons_fst_get_zero ..
|
Data\List\EditDistance\Estimator.lean | /-
Copyright (c) 2023 Kim Liesinger. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kim Liesinger
-/
import Mathlib.Data.List.EditDistance.Bounds
import Mathlib.Order.Estimator
/-!
# `Estimator` for Levenshtein distance.
The usual algorithm for computing Levenshtein distances
provides successively better lower bounds for the Levenshtein distance as it runs,
as proved in `Mathlib.Data.List.EditDistance.Bounds`.
In this file we package that fact as an instance of
```
Estimator (Thunk.mk fun _ => levenshtein C xs ys) (LevenshteinEstimator C xs ys)
```
allowing us to use the `Estimator` framework for Levenshtein distances.
This is then used in the implementation of `rewrite_search`
to avoid needing the entire edit distance calculation in unlikely search paths.
-/
variable {α : Type*} {β δ : Type} [CanonicallyLinearOrderedAddCommMonoid δ]
(C : Levenshtein.Cost α β δ) (xs : List α) (ys : List β)
/--
Data showing that the Levenshtein distance from `xs` to `ys`
is bounded below by the minimum Levenshtein distance between some suffix of `xs`
and a particular suffix of `ys`.
This bound is (non-strict) monotone as we take longer suffixes of `ys`.
This is an auxiliary definition for the later `LevenshteinEstimator`:
this variant constructs a lower bound for the pair consisting of
the Levenshtein distance from `xs` to `ys`,
along with the length of `ys`.
-/
structure LevenshteinEstimator' : Type where
/-- The prefix of `ys` that is not is not involved in the bound, in reverse order. -/
pre_rev : List β
/-- The suffix of `ys`, such that the distance from `xs` to `ys` is bounded below
by the minimum distance from any suffix of `xs` to this suffix. -/
suff : List β
/-- Witness that `ys` has been decomposed into a prefix and suffix. -/
split : pre_rev.reverse ++ suff = ys
/-- The distances from each suffix of `xs` to `suff`. -/
distances : {r : List δ // 0 < r.length}
/-- Witness that `distances` are correct. -/
distances_eq : distances = suffixLevenshtein C xs suff
/-- The current bound on the pair (distance from `xs` to `ys`, length of `ys`). -/
bound : δ × ℕ
/-- Predicate describing the current bound. -/
bound_eq : bound = match pre_rev with
| [] => (distances.1[0]'(distances.2), ys.length)
| _ => (List.minimum_of_length_pos distances.2, suff.length)
instance : EstimatorData (Thunk.mk fun _ => (levenshtein C xs ys, ys.length))
(LevenshteinEstimator' C xs ys) where
bound e := e.bound
improve e := match e.pre_rev, e.split with
| [], _ => none
| y :: ys, split => some
{ pre_rev := ys
suff := y :: e.suff
split := by simpa using split
distances := Levenshtein.impl C xs y e.distances
distances_eq := e.distances_eq ▸ suffixLevenshtein_eq xs y e.suff
bound := _
bound_eq := rfl }
instance estimator' :
Estimator (Thunk.mk fun _ => (levenshtein C xs ys, ys.length))
(LevenshteinEstimator' C xs ys) where
bound_le e := match e.pre_rev, e.split, e.bound_eq with
| [], split, eq => by
simp only [List.reverse_nil, List.nil_append] at split
rw [e.distances_eq] at eq
simp only [← List.get_eq_getElem] at eq
rw [split] at eq
exact eq.le
| y :: t, split, eq => by
rw [e.distances_eq] at eq
simp only at eq
dsimp [EstimatorData.bound]
rw [eq]
simp only [← split]
constructor
· simp only [List.minimum_of_length_pos_le_iff]
exact suffixLevenshtein_minimum_le_levenshtein_append _ _ _
· exact List.length_le_of_sublist (List.sublist_append_right _ _)
improve_spec e := by
dsimp [EstimatorData.improve]
match e.pre_rev, e.split, e.bound_eq, e.distances_eq with
| [], split, eq, _ =>
simp only [List.reverse_nil, List.nil_append] at split
rw [e.distances_eq] at eq
simp only [← List.get_eq_getElem] at eq
rw [split] at eq
exact eq
| [y], split, b_eq, d_eq =>
simp only [EstimatorData.bound, Prod.lt_iff, List.reverse_nil, List.nil_append]
right
have b_eq :
e.bound = (List.minimum_of_length_pos e.distances.property, List.length e.suff) := by
simpa using b_eq
rw [b_eq]
constructor
· refine (?_ : _ ≤ _).trans (List.minimum_of_length_pos_le_getElem _)
simp only [List.minimum_of_length_pos_le_iff, List.coe_minimum_of_length_pos, d_eq]
apply le_suffixLevenshtein_cons_minimum
· simp [← split]
| y₁ :: y₂ :: t, split, b_eq, d_eq =>
simp only [EstimatorData.bound, Prod.lt_iff]
right
have b_eq :
e.bound = (List.minimum_of_length_pos e.distances.property, List.length e.suff) := by
simpa using b_eq
rw [b_eq]
constructor
· simp only [d_eq, List.minimum_of_length_pos_le_iff, List.coe_minimum_of_length_pos]
apply le_suffixLevenshtein_cons_minimum
· exact Nat.lt.base _
/-- An estimator for Levenshtein distances. -/
def LevenshteinEstimator : Type _ :=
Estimator.fst (Thunk.mk fun _ => (levenshtein C xs ys, ys.length)) (LevenshteinEstimator' C xs ys)
instance [∀ a : δ × ℕ, WellFoundedGT { x // x ≤ a }] :
Estimator (Thunk.mk fun _ => levenshtein C xs ys) (LevenshteinEstimator C xs ys) :=
Estimator.fstInst (Thunk.mk fun _ => _) (Thunk.mk fun _ => _) (estimator' C xs ys)
/-- The initial estimator for Levenshtein distances. -/
instance (C : Levenshtein.Cost α β δ) (xs : List α) (ys : List β) :
Bot (LevenshteinEstimator C xs ys) where
bot :=
{ inner :=
{ pre_rev := ys.reverse
suff := []
split := by simp
distances_eq := rfl
bound_eq := rfl } }
|
Data\Matrix\Auto.lean | /-
Copyright (c) 2022 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import Mathlib.Algebra.Expr
import Mathlib.Data.Matrix.Reflection
/-! # Automatically generated lemmas for working with concrete matrices
In Mathlib3, this file contained "magic" lemmas which autogenerate to the correct size of matrix.
For instance, `Matrix.of_mul_of_fin` could be used as:
```lean
example {α} [AddCommMonoid α] [Mul α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁₁ b₁₂ b₂₁ b₂₂ : α) :
!![a₁₁, a₁₂;
a₂₁, a₂₂] * !![b₁₁, b₁₂;
b₂₁, b₂₂] = !![a₁₁ * b₁₁ + a₁₂ * b₂₁, a₁₁ * b₁₂ + a₁₂ * b₂₂;
a₂₁ * b₁₁ + a₂₂ * b₂₁, a₂₁ * b₁₂ + a₂₂ * b₂₂] := by
rw [of_mul_of_fin]
```
Porting note: these magic lemmas have been skipped for now, though the plumbing lemmas in
`Mathlib.Data.Matrix.Reflection` are still available
-/
|
Data\Matrix\Basic.lean | /-
Copyright (c) 2018 Ellen Arlt. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin, Lu-Ming Zhang
-/
import Mathlib.Algebra.Algebra.Opposite
import Mathlib.Algebra.Algebra.Pi
import Mathlib.Algebra.BigOperators.Pi
import Mathlib.Algebra.BigOperators.Ring
import Mathlib.Algebra.BigOperators.RingEquiv
import Mathlib.Algebra.Module.Pi
import Mathlib.Algebra.Star.BigOperators
import Mathlib.Algebra.Star.Module
import Mathlib.Algebra.Star.Pi
import Mathlib.Data.Fintype.BigOperators
import Mathlib.GroupTheory.GroupAction.BigOperators
/-!
# Matrices
This file defines basic properties of matrices.
Matrices with rows indexed by `m`, columns indexed by `n`, and entries of type `α` are represented
with `Matrix m n α`. For the typical approach of counting rows and columns,
`Matrix (Fin m) (Fin n) α` can be used.
## Notation
The locale `Matrix` gives the following notation:
* `⬝ᵥ` for `Matrix.dotProduct`
* `*ᵥ` for `Matrix.mulVec`
* `ᵥ*` for `Matrix.vecMul`
* `ᵀ` for `Matrix.transpose`
* `ᴴ` for `Matrix.conjTranspose`
## Implementation notes
For convenience, `Matrix m n α` is defined as `m → n → α`, as this allows elements of the matrix
to be accessed with `A i j`. However, it is not advisable to _construct_ matrices using terms of the
form `fun i j ↦ _` or even `(fun i j ↦ _ : Matrix m n α)`, as these are not recognized by Lean
as having the right type. Instead, `Matrix.of` should be used.
## TODO
Under various conditions, multiplication of infinite matrices makes sense.
These have not yet been implemented.
-/
universe u u' v w
/-- `Matrix m n R` is the type of matrices with entries in `R`, whose rows are indexed by `m`
and whose columns are indexed by `n`. -/
def Matrix (m : Type u) (n : Type u') (α : Type v) : Type max u u' v :=
m → n → α
variable {l m n o : Type*} {m' : o → Type*} {n' : o → Type*}
variable {R : Type*} {S : Type*} {α : Type v} {β : Type w} {γ : Type*}
namespace Matrix
section Ext
variable {M N : Matrix m n α}
theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N :=
⟨fun h => funext fun i => funext <| h i, fun h => by simp [h]⟩
@[ext]
theorem ext : (∀ i j, M i j = N i j) → M = N :=
ext_iff.mp
end Ext
/-- Cast a function into a matrix.
The two sides of the equivalence are definitionally equal types. We want to use an explicit cast
to distinguish the types because `Matrix` has different instances to pi types (such as `Pi.mul`,
which performs elementwise multiplication, vs `Matrix.mul`).
If you are defining a matrix, in terms of its entries, use `of (fun i j ↦ _)`. The
purpose of this approach is to ensure that terms of the form `(fun i j ↦ _) * (fun i j ↦ _)` do not
appear, as the type of `*` can be misleading.
Porting note: In Lean 3, it is also safe to use pattern matching in a definition as `| i j := _`,
which can only be unfolded when fully-applied. leanprover/lean4#2042 means this does not
(currently) work in Lean 4.
-/
def of : (m → n → α) ≃ Matrix m n α :=
Equiv.refl _
@[simp]
theorem of_apply (f : m → n → α) (i j) : of f i j = f i j :=
rfl
@[simp]
theorem of_symm_apply (f : Matrix m n α) (i j) : of.symm f i j = f i j :=
rfl
/-- `M.map f` is the matrix obtained by applying `f` to each entry of the matrix `M`.
This is available in bundled forms as:
* `AddMonoidHom.mapMatrix`
* `LinearMap.mapMatrix`
* `RingHom.mapMatrix`
* `AlgHom.mapMatrix`
* `Equiv.mapMatrix`
* `AddEquiv.mapMatrix`
* `LinearEquiv.mapMatrix`
* `RingEquiv.mapMatrix`
* `AlgEquiv.mapMatrix`
-/
def map (M : Matrix m n α) (f : α → β) : Matrix m n β :=
of fun i j => f (M i j)
@[simp]
theorem map_apply {M : Matrix m n α} {f : α → β} {i : m} {j : n} : M.map f i j = f (M i j) :=
rfl
@[simp]
theorem map_id (M : Matrix m n α) : M.map id = M := by
ext
rfl
@[simp]
theorem map_id' (M : Matrix m n α) : M.map (·) = M := map_id M
@[simp]
theorem map_map {M : Matrix m n α} {β γ : Type*} {f : α → β} {g : β → γ} :
(M.map f).map g = M.map (g ∘ f) := by
ext
rfl
theorem map_injective {f : α → β} (hf : Function.Injective f) :
Function.Injective fun M : Matrix m n α => M.map f := fun _ _ h =>
ext fun i j => hf <| ext_iff.mpr h i j
/-- The transpose of a matrix. -/
def transpose (M : Matrix m n α) : Matrix n m α :=
of fun x y => M y x
-- TODO: set as an equation lemma for `transpose`, see mathlib4#3024
@[simp]
theorem transpose_apply (M : Matrix m n α) (i j) : transpose M i j = M j i :=
rfl
@[inherit_doc]
scoped postfix:1024 "ᵀ" => Matrix.transpose
/-- The conjugate transpose of a matrix defined in term of `star`. -/
def conjTranspose [Star α] (M : Matrix m n α) : Matrix n m α :=
M.transpose.map star
@[inherit_doc]
scoped postfix:1024 "ᴴ" => Matrix.conjTranspose
instance inhabited [Inhabited α] : Inhabited (Matrix m n α) :=
inferInstanceAs <| Inhabited <| m → n → α
-- Porting note: new, Lean3 found this automatically
instance decidableEq [DecidableEq α] [Fintype m] [Fintype n] : DecidableEq (Matrix m n α) :=
Fintype.decidablePiFintype
instance {n m} [Fintype m] [DecidableEq m] [Fintype n] [DecidableEq n] (α) [Fintype α] :
Fintype (Matrix m n α) := inferInstanceAs (Fintype (m → n → α))
instance {n m} [Finite m] [Finite n] (α) [Finite α] :
Finite (Matrix m n α) := inferInstanceAs (Finite (m → n → α))
instance add [Add α] : Add (Matrix m n α) :=
Pi.instAdd
instance addSemigroup [AddSemigroup α] : AddSemigroup (Matrix m n α) :=
Pi.addSemigroup
instance addCommSemigroup [AddCommSemigroup α] : AddCommSemigroup (Matrix m n α) :=
Pi.addCommSemigroup
instance zero [Zero α] : Zero (Matrix m n α) :=
Pi.instZero
instance addZeroClass [AddZeroClass α] : AddZeroClass (Matrix m n α) :=
Pi.addZeroClass
instance addMonoid [AddMonoid α] : AddMonoid (Matrix m n α) :=
Pi.addMonoid
instance addCommMonoid [AddCommMonoid α] : AddCommMonoid (Matrix m n α) :=
Pi.addCommMonoid
instance neg [Neg α] : Neg (Matrix m n α) :=
Pi.instNeg
instance sub [Sub α] : Sub (Matrix m n α) :=
Pi.instSub
instance addGroup [AddGroup α] : AddGroup (Matrix m n α) :=
Pi.addGroup
instance addCommGroup [AddCommGroup α] : AddCommGroup (Matrix m n α) :=
Pi.addCommGroup
instance unique [Unique α] : Unique (Matrix m n α) :=
Pi.unique
instance subsingleton [Subsingleton α] : Subsingleton (Matrix m n α) :=
inferInstanceAs <| Subsingleton <| m → n → α
instance nonempty [Nonempty m] [Nonempty n] [Nontrivial α] : Nontrivial (Matrix m n α) :=
Function.nontrivial
instance smul [SMul R α] : SMul R (Matrix m n α) :=
Pi.instSMul
instance smulCommClass [SMul R α] [SMul S α] [SMulCommClass R S α] :
SMulCommClass R S (Matrix m n α) :=
Pi.smulCommClass
instance isScalarTower [SMul R S] [SMul R α] [SMul S α] [IsScalarTower R S α] :
IsScalarTower R S (Matrix m n α) :=
Pi.isScalarTower
instance isCentralScalar [SMul R α] [SMul Rᵐᵒᵖ α] [IsCentralScalar R α] :
IsCentralScalar R (Matrix m n α) :=
Pi.isCentralScalar
instance mulAction [Monoid R] [MulAction R α] : MulAction R (Matrix m n α) :=
Pi.mulAction _
instance distribMulAction [Monoid R] [AddMonoid α] [DistribMulAction R α] :
DistribMulAction R (Matrix m n α) :=
Pi.distribMulAction _
instance module [Semiring R] [AddCommMonoid α] [Module R α] : Module R (Matrix m n α) :=
Pi.module _ _ _
section
#adaptation_note
/--
After https://github.com/leanprover/lean4/pull/4481
the `simpNF` linter incorrectly claims this lemma can't be applied by `simp`.
-/
@[simp, nolint simpNF]
theorem zero_apply [Zero α] (i : m) (j : n) : (0 : Matrix m n α) i j = 0 := rfl
@[simp]
theorem add_apply [Add α] (A B : Matrix m n α) (i : m) (j : n) :
(A + B) i j = (A i j) + (B i j) := rfl
@[simp]
theorem smul_apply [SMul β α] (r : β) (A : Matrix m n α) (i : m) (j : n) :
(r • A) i j = r • (A i j) := rfl
@[simp]
theorem sub_apply [Sub α] (A B : Matrix m n α) (i : m) (j : n) :
(A - B) i j = (A i j) - (B i j) := rfl
@[simp]
theorem neg_apply [Neg α] (A : Matrix m n α) (i : m) (j : n) :
(-A) i j = -(A i j) := rfl
end
/-! simp-normal form pulls `of` to the outside. -/
@[simp]
theorem of_zero [Zero α] : of (0 : m → n → α) = 0 :=
rfl
@[simp]
theorem of_add_of [Add α] (f g : m → n → α) : of f + of g = of (f + g) :=
rfl
@[simp]
theorem of_sub_of [Sub α] (f g : m → n → α) : of f - of g = of (f - g) :=
rfl
@[simp]
theorem neg_of [Neg α] (f : m → n → α) : -of f = of (-f) :=
rfl
@[simp]
theorem smul_of [SMul R α] (r : R) (f : m → n → α) : r • of f = of (r • f) :=
rfl
@[simp]
protected theorem map_zero [Zero α] [Zero β] (f : α → β) (h : f 0 = 0) :
(0 : Matrix m n α).map f = 0 := by
ext
simp [h]
protected theorem map_add [Add α] [Add β] (f : α → β) (hf : ∀ a₁ a₂, f (a₁ + a₂) = f a₁ + f a₂)
(M N : Matrix m n α) : (M + N).map f = M.map f + N.map f :=
ext fun _ _ => hf _ _
protected theorem map_sub [Sub α] [Sub β] (f : α → β) (hf : ∀ a₁ a₂, f (a₁ - a₂) = f a₁ - f a₂)
(M N : Matrix m n α) : (M - N).map f = M.map f - N.map f :=
ext fun _ _ => hf _ _
theorem map_smul [SMul R α] [SMul R β] (f : α → β) (r : R) (hf : ∀ a, f (r • a) = r • f a)
(M : Matrix m n α) : (r • M).map f = r • M.map f :=
ext fun _ _ => hf _
/-- The scalar action via `Mul.toSMul` is transformed by the same map as the elements
of the matrix, when `f` preserves multiplication. -/
theorem map_smul' [Mul α] [Mul β] (f : α → β) (r : α) (A : Matrix n n α)
(hf : ∀ a₁ a₂, f (a₁ * a₂) = f a₁ * f a₂) : (r • A).map f = f r • A.map f :=
ext fun _ _ => hf _ _
/-- The scalar action via `mul.toOppositeSMul` is transformed by the same map as the
elements of the matrix, when `f` preserves multiplication. -/
theorem map_op_smul' [Mul α] [Mul β] (f : α → β) (r : α) (A : Matrix n n α)
(hf : ∀ a₁ a₂, f (a₁ * a₂) = f a₁ * f a₂) :
(MulOpposite.op r • A).map f = MulOpposite.op (f r) • A.map f :=
ext fun _ _ => hf _ _
theorem _root_.IsSMulRegular.matrix [SMul R S] {k : R} (hk : IsSMulRegular S k) :
IsSMulRegular (Matrix m n S) k :=
IsSMulRegular.pi fun _ => IsSMulRegular.pi fun _ => hk
theorem _root_.IsLeftRegular.matrix [Mul α] {k : α} (hk : IsLeftRegular k) :
IsSMulRegular (Matrix m n α) k :=
hk.isSMulRegular.matrix
instance subsingleton_of_empty_left [IsEmpty m] : Subsingleton (Matrix m n α) :=
⟨fun M N => by
ext i
exact isEmptyElim i⟩
instance subsingleton_of_empty_right [IsEmpty n] : Subsingleton (Matrix m n α) :=
⟨fun M N => by
ext i j
exact isEmptyElim j⟩
end Matrix
open Matrix
namespace Matrix
section Diagonal
variable [DecidableEq n]
/-- `diagonal d` is the square matrix such that `(diagonal d) i i = d i` and `(diagonal d) i j = 0`
if `i ≠ j`.
Note that bundled versions exist as:
* `Matrix.diagonalAddMonoidHom`
* `Matrix.diagonalLinearMap`
* `Matrix.diagonalRingHom`
* `Matrix.diagonalAlgHom`
-/
def diagonal [Zero α] (d : n → α) : Matrix n n α :=
of fun i j => if i = j then d i else 0
-- TODO: set as an equation lemma for `diagonal`, see mathlib4#3024
theorem diagonal_apply [Zero α] (d : n → α) (i j) : diagonal d i j = if i = j then d i else 0 :=
rfl
@[simp]
theorem diagonal_apply_eq [Zero α] (d : n → α) (i : n) : (diagonal d) i i = d i := by
simp [diagonal]
@[simp]
theorem diagonal_apply_ne [Zero α] (d : n → α) {i j : n} (h : i ≠ j) : (diagonal d) i j = 0 := by
simp [diagonal, h]
theorem diagonal_apply_ne' [Zero α] (d : n → α) {i j : n} (h : j ≠ i) : (diagonal d) i j = 0 :=
diagonal_apply_ne d h.symm
@[simp]
theorem diagonal_eq_diagonal_iff [Zero α] {d₁ d₂ : n → α} :
diagonal d₁ = diagonal d₂ ↔ ∀ i, d₁ i = d₂ i :=
⟨fun h i => by simpa using congr_arg (fun m : Matrix n n α => m i i) h, fun h => by
rw [show d₁ = d₂ from funext h]⟩
theorem diagonal_injective [Zero α] : Function.Injective (diagonal : (n → α) → Matrix n n α) :=
fun d₁ d₂ h => funext fun i => by simpa using Matrix.ext_iff.mpr h i i
@[simp]
theorem diagonal_zero [Zero α] : (diagonal fun _ => 0 : Matrix n n α) = 0 := by
ext
simp [diagonal]
@[simp]
theorem diagonal_transpose [Zero α] (v : n → α) : (diagonal v)ᵀ = diagonal v := by
ext i j
by_cases h : i = j
· simp [h, transpose]
· simp [h, transpose, diagonal_apply_ne' _ h]
@[simp]
theorem diagonal_add [AddZeroClass α] (d₁ d₂ : n → α) :
diagonal d₁ + diagonal d₂ = diagonal fun i => d₁ i + d₂ i := by
ext i j
by_cases h : i = j <;>
simp [h]
@[simp]
theorem diagonal_smul [Zero α] [SMulZeroClass R α] (r : R) (d : n → α) :
diagonal (r • d) = r • diagonal d := by
ext i j
by_cases h : i = j <;> simp [h]
@[simp]
theorem diagonal_neg [NegZeroClass α] (d : n → α) :
-diagonal d = diagonal fun i => -d i := by
ext i j
by_cases h : i = j <;>
simp [h]
@[simp]
theorem diagonal_sub [SubNegZeroMonoid α] (d₁ d₂ : n → α) :
diagonal d₁ - diagonal d₂ = diagonal fun i => d₁ i - d₂ i := by
ext i j
by_cases h : i = j <;>
simp [h]
instance [Zero α] [NatCast α] : NatCast (Matrix n n α) where
natCast m := diagonal fun _ => m
@[norm_cast]
theorem diagonal_natCast [Zero α] [NatCast α] (m : ℕ) : diagonal (fun _ : n => (m : α)) = m := rfl
@[norm_cast]
theorem diagonal_natCast' [Zero α] [NatCast α] (m : ℕ) : diagonal ((m : n → α)) = m := rfl
-- See note [no_index around OfNat.ofNat]
theorem diagonal_ofNat [Zero α] [NatCast α] (m : ℕ) [m.AtLeastTwo] :
diagonal (fun _ : n => no_index (OfNat.ofNat m : α)) = OfNat.ofNat m := rfl
-- See note [no_index around OfNat.ofNat]
theorem diagonal_ofNat' [Zero α] [NatCast α] (m : ℕ) [m.AtLeastTwo] :
diagonal (no_index (OfNat.ofNat m : n → α)) = OfNat.ofNat m := rfl
instance [Zero α] [IntCast α] : IntCast (Matrix n n α) where
intCast m := diagonal fun _ => m
@[norm_cast]
theorem diagonal_intCast [Zero α] [IntCast α] (m : ℤ) : diagonal (fun _ : n => (m : α)) = m := rfl
@[norm_cast]
theorem diagonal_intCast' [Zero α] [IntCast α] (m : ℤ) : diagonal ((m : n → α)) = m := rfl
variable (n α)
/-- `Matrix.diagonal` as an `AddMonoidHom`. -/
@[simps]
def diagonalAddMonoidHom [AddZeroClass α] : (n → α) →+ Matrix n n α where
toFun := diagonal
map_zero' := diagonal_zero
map_add' x y := (diagonal_add x y).symm
variable (R)
/-- `Matrix.diagonal` as a `LinearMap`. -/
@[simps]
def diagonalLinearMap [Semiring R] [AddCommMonoid α] [Module R α] : (n → α) →ₗ[R] Matrix n n α :=
{ diagonalAddMonoidHom n α with map_smul' := diagonal_smul }
variable {n α R}
@[simp]
theorem diagonal_map [Zero α] [Zero β] {f : α → β} (h : f 0 = 0) {d : n → α} :
(diagonal d).map f = diagonal fun m => f (d m) := by
ext
simp only [diagonal_apply, map_apply]
split_ifs <;> simp [h]
protected theorem map_natCast [AddMonoidWithOne α] [AddMonoidWithOne β]
{f : α → β} (h : f 0 = 0) (d : ℕ) :
(d : Matrix n n α).map f = diagonal (fun _ => f d) :=
diagonal_map h
-- See note [no_index around OfNat.ofNat]
protected theorem map_ofNat [AddMonoidWithOne α] [AddMonoidWithOne β]
{f : α → β} (h : f 0 = 0) (d : ℕ) [d.AtLeastTwo] :
(no_index (OfNat.ofNat d) : Matrix n n α).map f = diagonal (fun _ => f (OfNat.ofNat d)) :=
diagonal_map h
protected theorem map_intCast [AddGroupWithOne α] [AddGroupWithOne β]
{f : α → β} (h : f 0 = 0) (d : ℤ) :
(d : Matrix n n α).map f = diagonal (fun _ => f d) :=
diagonal_map h
@[simp]
theorem diagonal_conjTranspose [AddMonoid α] [StarAddMonoid α] (v : n → α) :
(diagonal v)ᴴ = diagonal (star v) := by
rw [conjTranspose, diagonal_transpose, diagonal_map (star_zero _)]
rfl
section One
variable [Zero α] [One α]
instance one : One (Matrix n n α) :=
⟨diagonal fun _ => 1⟩
@[simp]
theorem diagonal_one : (diagonal fun _ => 1 : Matrix n n α) = 1 :=
rfl
theorem one_apply {i j} : (1 : Matrix n n α) i j = if i = j then 1 else 0 :=
rfl
@[simp]
theorem one_apply_eq (i) : (1 : Matrix n n α) i i = 1 :=
diagonal_apply_eq _ i
@[simp]
theorem one_apply_ne {i j} : i ≠ j → (1 : Matrix n n α) i j = 0 :=
diagonal_apply_ne _
theorem one_apply_ne' {i j} : j ≠ i → (1 : Matrix n n α) i j = 0 :=
diagonal_apply_ne' _
@[simp]
theorem map_one [Zero β] [One β] (f : α → β) (h₀ : f 0 = 0) (h₁ : f 1 = 1) :
(1 : Matrix n n α).map f = (1 : Matrix n n β) := by
ext
simp only [one_apply, map_apply]
split_ifs <;> simp [h₀, h₁]
-- Porting note: added implicit argument `(f := fun_ => α)`, why is that needed?
theorem one_eq_pi_single {i j} : (1 : Matrix n n α) i j = Pi.single (f := fun _ => α) i 1 j := by
simp only [one_apply, Pi.single_apply, eq_comm]
lemma zero_le_one_elem [Preorder α] [ZeroLEOneClass α] (i j : n) :
0 ≤ (1 : Matrix n n α) i j := by
by_cases hi : i = j
· subst hi
simp
· simp [hi]
lemma zero_le_one_row [Preorder α] [ZeroLEOneClass α] (i : n) :
0 ≤ (1 : Matrix n n α) i :=
zero_le_one_elem i
end One
instance instAddMonoidWithOne [AddMonoidWithOne α] : AddMonoidWithOne (Matrix n n α) where
natCast_zero := show diagonal _ = _ by
rw [Nat.cast_zero, diagonal_zero]
natCast_succ n := show diagonal _ = diagonal _ + _ by
rw [Nat.cast_succ, ← diagonal_add, diagonal_one]
instance instAddGroupWithOne [AddGroupWithOne α] : AddGroupWithOne (Matrix n n α) where
intCast_ofNat n := show diagonal _ = diagonal _ by
rw [Int.cast_natCast]
intCast_negSucc n := show diagonal _ = -(diagonal _) by
rw [Int.cast_negSucc, diagonal_neg]
__ := addGroup
__ := instAddMonoidWithOne
instance instAddCommMonoidWithOne [AddCommMonoidWithOne α] :
AddCommMonoidWithOne (Matrix n n α) where
__ := addCommMonoid
__ := instAddMonoidWithOne
instance instAddCommGroupWithOne [AddCommGroupWithOne α] :
AddCommGroupWithOne (Matrix n n α) where
__ := addCommGroup
__ := instAddGroupWithOne
end Diagonal
section Diag
/-- The diagonal of a square matrix. -/
-- @[simp] -- Porting note: simpNF does not like this.
def diag (A : Matrix n n α) (i : n) : α :=
A i i
-- Porting note: new, because of removed `simp` above.
-- TODO: set as an equation lemma for `diag`, see mathlib4#3024
@[simp]
theorem diag_apply (A : Matrix n n α) (i) : diag A i = A i i :=
rfl
@[simp]
theorem diag_diagonal [DecidableEq n] [Zero α] (a : n → α) : diag (diagonal a) = a :=
funext <| @diagonal_apply_eq _ _ _ _ a
@[simp]
theorem diag_transpose (A : Matrix n n α) : diag Aᵀ = diag A :=
rfl
@[simp]
theorem diag_zero [Zero α] : diag (0 : Matrix n n α) = 0 :=
rfl
@[simp]
theorem diag_add [Add α] (A B : Matrix n n α) : diag (A + B) = diag A + diag B :=
rfl
@[simp]
theorem diag_sub [Sub α] (A B : Matrix n n α) : diag (A - B) = diag A - diag B :=
rfl
@[simp]
theorem diag_neg [Neg α] (A : Matrix n n α) : diag (-A) = -diag A :=
rfl
@[simp]
theorem diag_smul [SMul R α] (r : R) (A : Matrix n n α) : diag (r • A) = r • diag A :=
rfl
@[simp]
theorem diag_one [DecidableEq n] [Zero α] [One α] : diag (1 : Matrix n n α) = 1 :=
diag_diagonal _
variable (n α)
/-- `Matrix.diag` as an `AddMonoidHom`. -/
@[simps]
def diagAddMonoidHom [AddZeroClass α] : Matrix n n α →+ n → α where
toFun := diag
map_zero' := diag_zero
map_add' := diag_add
variable (R)
/-- `Matrix.diag` as a `LinearMap`. -/
@[simps]
def diagLinearMap [Semiring R] [AddCommMonoid α] [Module R α] : Matrix n n α →ₗ[R] n → α :=
{ diagAddMonoidHom n α with map_smul' := diag_smul }
variable {n α R}
theorem diag_map {f : α → β} {A : Matrix n n α} : diag (A.map f) = f ∘ diag A :=
rfl
@[simp]
theorem diag_conjTranspose [AddMonoid α] [StarAddMonoid α] (A : Matrix n n α) :
diag Aᴴ = star (diag A) :=
rfl
@[simp]
theorem diag_list_sum [AddMonoid α] (l : List (Matrix n n α)) : diag l.sum = (l.map diag).sum :=
map_list_sum (diagAddMonoidHom n α) l
@[simp]
theorem diag_multiset_sum [AddCommMonoid α] (s : Multiset (Matrix n n α)) :
diag s.sum = (s.map diag).sum :=
map_multiset_sum (diagAddMonoidHom n α) s
@[simp]
theorem diag_sum {ι} [AddCommMonoid α] (s : Finset ι) (f : ι → Matrix n n α) :
diag (∑ i ∈ s, f i) = ∑ i ∈ s, diag (f i) :=
map_sum (diagAddMonoidHom n α) f s
end Diag
section DotProduct
variable [Fintype m] [Fintype n]
/-- `dotProduct v w` is the sum of the entrywise products `v i * w i` -/
def dotProduct [Mul α] [AddCommMonoid α] (v w : m → α) : α :=
∑ i, v i * w i
/- The precedence of 72 comes immediately after ` • ` for `SMul.smul`,
so that `r₁ • a ⬝ᵥ r₂ • b` is parsed as `(r₁ • a) ⬝ᵥ (r₂ • b)` here. -/
@[inherit_doc]
scoped infixl:72 " ⬝ᵥ " => Matrix.dotProduct
theorem dotProduct_assoc [NonUnitalSemiring α] (u : m → α) (w : n → α) (v : Matrix m n α) :
(fun j => u ⬝ᵥ fun i => v i j) ⬝ᵥ w = u ⬝ᵥ fun i => v i ⬝ᵥ w := by
simpa [dotProduct, Finset.mul_sum, Finset.sum_mul, mul_assoc] using Finset.sum_comm
theorem dotProduct_comm [AddCommMonoid α] [CommSemigroup α] (v w : m → α) : v ⬝ᵥ w = w ⬝ᵥ v := by
simp_rw [dotProduct, mul_comm]
@[simp]
theorem dotProduct_pUnit [AddCommMonoid α] [Mul α] (v w : PUnit → α) : v ⬝ᵥ w = v ⟨⟩ * w ⟨⟩ := by
simp [dotProduct]
section MulOneClass
variable [MulOneClass α] [AddCommMonoid α]
theorem dotProduct_one (v : n → α) : v ⬝ᵥ 1 = ∑ i, v i := by simp [(· ⬝ᵥ ·)]
theorem one_dotProduct (v : n → α) : 1 ⬝ᵥ v = ∑ i, v i := by simp [(· ⬝ᵥ ·)]
end MulOneClass
section NonUnitalNonAssocSemiring
variable [NonUnitalNonAssocSemiring α] (u v w : m → α) (x y : n → α)
@[simp]
theorem dotProduct_zero : v ⬝ᵥ 0 = 0 := by simp [dotProduct]
@[simp]
theorem dotProduct_zero' : (v ⬝ᵥ fun _ => 0) = 0 :=
dotProduct_zero v
@[simp]
theorem zero_dotProduct : 0 ⬝ᵥ v = 0 := by simp [dotProduct]
@[simp]
theorem zero_dotProduct' : (fun _ => (0 : α)) ⬝ᵥ v = 0 :=
zero_dotProduct v
@[simp]
theorem add_dotProduct : (u + v) ⬝ᵥ w = u ⬝ᵥ w + v ⬝ᵥ w := by
simp [dotProduct, add_mul, Finset.sum_add_distrib]
@[simp]
theorem dotProduct_add : u ⬝ᵥ (v + w) = u ⬝ᵥ v + u ⬝ᵥ w := by
simp [dotProduct, mul_add, Finset.sum_add_distrib]
@[simp]
theorem sum_elim_dotProduct_sum_elim : Sum.elim u x ⬝ᵥ Sum.elim v y = u ⬝ᵥ v + x ⬝ᵥ y := by
simp [dotProduct]
/-- Permuting a vector on the left of a dot product can be transferred to the right. -/
@[simp]
theorem comp_equiv_symm_dotProduct (e : m ≃ n) : u ∘ e.symm ⬝ᵥ x = u ⬝ᵥ x ∘ e :=
(e.sum_comp _).symm.trans <|
Finset.sum_congr rfl fun _ _ => by simp only [Function.comp, Equiv.symm_apply_apply]
/-- Permuting a vector on the right of a dot product can be transferred to the left. -/
@[simp]
theorem dotProduct_comp_equiv_symm (e : n ≃ m) : u ⬝ᵥ x ∘ e.symm = u ∘ e ⬝ᵥ x := by
simpa only [Equiv.symm_symm] using (comp_equiv_symm_dotProduct u x e.symm).symm
/-- Permuting vectors on both sides of a dot product is a no-op. -/
@[simp]
theorem comp_equiv_dotProduct_comp_equiv (e : m ≃ n) : x ∘ e ⬝ᵥ y ∘ e = x ⬝ᵥ y := by
-- Porting note: was `simp only` with all three lemmas
rw [← dotProduct_comp_equiv_symm]; simp only [Function.comp, Equiv.apply_symm_apply]
end NonUnitalNonAssocSemiring
section NonUnitalNonAssocSemiringDecidable
variable [DecidableEq m] [NonUnitalNonAssocSemiring α] (u v w : m → α)
@[simp]
theorem diagonal_dotProduct (i : m) : diagonal v i ⬝ᵥ w = v i * w i := by
have : ∀ j ≠ i, diagonal v i j * w j = 0 := fun j hij => by
simp [diagonal_apply_ne' _ hij]
convert Finset.sum_eq_single i (fun j _ => this j) _ using 1 <;> simp
@[simp]
theorem dotProduct_diagonal (i : m) : v ⬝ᵥ diagonal w i = v i * w i := by
have : ∀ j ≠ i, v j * diagonal w i j = 0 := fun j hij => by
simp [diagonal_apply_ne' _ hij]
convert Finset.sum_eq_single i (fun j _ => this j) _ using 1 <;> simp
@[simp]
theorem dotProduct_diagonal' (i : m) : (v ⬝ᵥ fun j => diagonal w j i) = v i * w i := by
have : ∀ j ≠ i, v j * diagonal w j i = 0 := fun j hij => by
simp [diagonal_apply_ne _ hij]
convert Finset.sum_eq_single i (fun j _ => this j) _ using 1 <;> simp
@[simp]
theorem single_dotProduct (x : α) (i : m) : Pi.single i x ⬝ᵥ v = x * v i := by
-- Porting note: (implicit arg) added `(f := fun _ => α)`
have : ∀ j ≠ i, Pi.single (f := fun _ => α) i x j * v j = 0 := fun j hij => by
simp [Pi.single_eq_of_ne hij]
convert Finset.sum_eq_single i (fun j _ => this j) _ using 1 <;> simp
@[simp]
theorem dotProduct_single (x : α) (i : m) : v ⬝ᵥ Pi.single i x = v i * x := by
-- Porting note: (implicit arg) added `(f := fun _ => α)`
have : ∀ j ≠ i, v j * Pi.single (f := fun _ => α) i x j = 0 := fun j hij => by
simp [Pi.single_eq_of_ne hij]
convert Finset.sum_eq_single i (fun j _ => this j) _ using 1 <;> simp
end NonUnitalNonAssocSemiringDecidable
section NonAssocSemiring
variable [NonAssocSemiring α]
@[simp]
theorem one_dotProduct_one : (1 : n → α) ⬝ᵥ 1 = Fintype.card n := by
simp [dotProduct]
end NonAssocSemiring
section NonUnitalNonAssocRing
variable [NonUnitalNonAssocRing α] (u v w : m → α)
@[simp]
theorem neg_dotProduct : -v ⬝ᵥ w = -(v ⬝ᵥ w) := by simp [dotProduct]
@[simp]
theorem dotProduct_neg : v ⬝ᵥ -w = -(v ⬝ᵥ w) := by simp [dotProduct]
lemma neg_dotProduct_neg : -v ⬝ᵥ -w = v ⬝ᵥ w := by
rw [neg_dotProduct, dotProduct_neg, neg_neg]
@[simp]
theorem sub_dotProduct : (u - v) ⬝ᵥ w = u ⬝ᵥ w - v ⬝ᵥ w := by simp [sub_eq_add_neg]
@[simp]
theorem dotProduct_sub : u ⬝ᵥ (v - w) = u ⬝ᵥ v - u ⬝ᵥ w := by simp [sub_eq_add_neg]
end NonUnitalNonAssocRing
section DistribMulAction
variable [Monoid R] [Mul α] [AddCommMonoid α] [DistribMulAction R α]
@[simp]
theorem smul_dotProduct [IsScalarTower R α α] (x : R) (v w : m → α) :
x • v ⬝ᵥ w = x • (v ⬝ᵥ w) := by simp [dotProduct, Finset.smul_sum, smul_mul_assoc]
@[simp]
theorem dotProduct_smul [SMulCommClass R α α] (x : R) (v w : m → α) :
v ⬝ᵥ x • w = x • (v ⬝ᵥ w) := by simp [dotProduct, Finset.smul_sum, mul_smul_comm]
end DistribMulAction
section StarRing
variable [NonUnitalSemiring α] [StarRing α] (v w : m → α)
theorem star_dotProduct_star : star v ⬝ᵥ star w = star (w ⬝ᵥ v) := by simp [dotProduct]
theorem star_dotProduct : star v ⬝ᵥ w = star (star w ⬝ᵥ v) := by simp [dotProduct]
theorem dotProduct_star : v ⬝ᵥ star w = star (w ⬝ᵥ star v) := by simp [dotProduct]
end StarRing
end DotProduct
open Matrix
/-- `M * N` is the usual product of matrices `M` and `N`, i.e. we have that
`(M * N) i k` is the dot product of the `i`-th row of `M` by the `k`-th column of `N`.
This is currently only defined when `m` is finite. -/
-- We want to be lower priority than `instHMul`, but without this we can't have operands with
-- implicit dimensions.
@[default_instance 100]
instance [Fintype m] [Mul α] [AddCommMonoid α] :
HMul (Matrix l m α) (Matrix m n α) (Matrix l n α) where
hMul M N := fun i k => (fun j => M i j) ⬝ᵥ fun j => N j k
theorem mul_apply [Fintype m] [Mul α] [AddCommMonoid α] {M : Matrix l m α} {N : Matrix m n α}
{i k} : (M * N) i k = ∑ j, M i j * N j k :=
rfl
instance [Fintype n] [Mul α] [AddCommMonoid α] : Mul (Matrix n n α) where mul M N := M * N
theorem mul_apply' [Fintype m] [Mul α] [AddCommMonoid α] {M : Matrix l m α} {N : Matrix m n α}
{i k} : (M * N) i k = (fun j => M i j) ⬝ᵥ fun j => N j k :=
rfl
theorem sum_apply [AddCommMonoid α] (i : m) (j : n) (s : Finset β) (g : β → Matrix m n α) :
(∑ c ∈ s, g c) i j = ∑ c ∈ s, g c i j :=
(congr_fun (s.sum_apply i g) j).trans (s.sum_apply j _)
theorem two_mul_expl {R : Type*} [CommRing R] (A B : Matrix (Fin 2) (Fin 2) R) :
(A * B) 0 0 = A 0 0 * B 0 0 + A 0 1 * B 1 0 ∧
(A * B) 0 1 = A 0 0 * B 0 1 + A 0 1 * B 1 1 ∧
(A * B) 1 0 = A 1 0 * B 0 0 + A 1 1 * B 1 0 ∧
(A * B) 1 1 = A 1 0 * B 0 1 + A 1 1 * B 1 1 := by
refine ⟨?_, ?_, ?_, ?_⟩ <;>
· rw [Matrix.mul_apply, Finset.sum_fin_eq_sum_range, Finset.sum_range_succ, Finset.sum_range_succ]
simp
section AddCommMonoid
variable [AddCommMonoid α] [Mul α]
@[simp]
theorem smul_mul [Fintype n] [Monoid R] [DistribMulAction R α] [IsScalarTower R α α] (a : R)
(M : Matrix m n α) (N : Matrix n l α) : (a • M) * N = a • (M * N) := by
ext
apply smul_dotProduct a
@[simp]
theorem mul_smul [Fintype n] [Monoid R] [DistribMulAction R α] [SMulCommClass R α α]
(M : Matrix m n α) (a : R) (N : Matrix n l α) : M * (a • N) = a • (M * N) := by
ext
apply dotProduct_smul
end AddCommMonoid
section NonUnitalNonAssocSemiring
variable [NonUnitalNonAssocSemiring α]
@[simp]
protected theorem mul_zero [Fintype n] (M : Matrix m n α) : M * (0 : Matrix n o α) = 0 := by
ext
apply dotProduct_zero
@[simp]
protected theorem zero_mul [Fintype m] (M : Matrix m n α) : (0 : Matrix l m α) * M = 0 := by
ext
apply zero_dotProduct
protected theorem mul_add [Fintype n] (L : Matrix m n α) (M N : Matrix n o α) :
L * (M + N) = L * M + L * N := by
ext
apply dotProduct_add
protected theorem add_mul [Fintype m] (L M : Matrix l m α) (N : Matrix m n α) :
(L + M) * N = L * N + M * N := by
ext
apply add_dotProduct
instance nonUnitalNonAssocSemiring [Fintype n] : NonUnitalNonAssocSemiring (Matrix n n α) :=
{ Matrix.addCommMonoid with
mul_zero := Matrix.mul_zero
zero_mul := Matrix.zero_mul
left_distrib := Matrix.mul_add
right_distrib := Matrix.add_mul }
@[simp]
theorem diagonal_mul [Fintype m] [DecidableEq m] (d : m → α) (M : Matrix m n α) (i j) :
(diagonal d * M) i j = d i * M i j :=
diagonal_dotProduct _ _ _
@[simp]
theorem mul_diagonal [Fintype n] [DecidableEq n] (d : n → α) (M : Matrix m n α) (i j) :
(M * diagonal d) i j = M i j * d j := by
rw [← diagonal_transpose]
apply dotProduct_diagonal
@[simp]
theorem diagonal_mul_diagonal [Fintype n] [DecidableEq n] (d₁ d₂ : n → α) :
diagonal d₁ * diagonal d₂ = diagonal fun i => d₁ i * d₂ i := by
ext i j
by_cases h : i = j <;>
simp [h]
theorem diagonal_mul_diagonal' [Fintype n] [DecidableEq n] (d₁ d₂ : n → α) :
diagonal d₁ * diagonal d₂ = diagonal fun i => d₁ i * d₂ i :=
diagonal_mul_diagonal _ _
theorem smul_eq_diagonal_mul [Fintype m] [DecidableEq m] (M : Matrix m n α) (a : α) :
a • M = (diagonal fun _ => a) * M := by
ext
simp
theorem op_smul_eq_mul_diagonal [Fintype n] [DecidableEq n] (M : Matrix m n α) (a : α) :
MulOpposite.op a • M = M * (diagonal fun _ : n => a) := by
ext
simp
/-- Left multiplication by a matrix, as an `AddMonoidHom` from matrices to matrices. -/
@[simps]
def addMonoidHomMulLeft [Fintype m] (M : Matrix l m α) : Matrix m n α →+ Matrix l n α where
toFun x := M * x
map_zero' := Matrix.mul_zero _
map_add' := Matrix.mul_add _
/-- Right multiplication by a matrix, as an `AddMonoidHom` from matrices to matrices. -/
@[simps]
def addMonoidHomMulRight [Fintype m] (M : Matrix m n α) : Matrix l m α →+ Matrix l n α where
toFun x := x * M
map_zero' := Matrix.zero_mul _
map_add' _ _ := Matrix.add_mul _ _ _
protected theorem sum_mul [Fintype m] (s : Finset β) (f : β → Matrix l m α) (M : Matrix m n α) :
(∑ a ∈ s, f a) * M = ∑ a ∈ s, f a * M :=
map_sum (addMonoidHomMulRight M) f s
protected theorem mul_sum [Fintype m] (s : Finset β) (f : β → Matrix m n α) (M : Matrix l m α) :
(M * ∑ a ∈ s, f a) = ∑ a ∈ s, M * f a :=
map_sum (addMonoidHomMulLeft M) f s
/-- This instance enables use with `smul_mul_assoc`. -/
instance Semiring.isScalarTower [Fintype n] [Monoid R] [DistribMulAction R α]
[IsScalarTower R α α] : IsScalarTower R (Matrix n n α) (Matrix n n α) :=
⟨fun r m n => Matrix.smul_mul r m n⟩
/-- This instance enables use with `mul_smul_comm`. -/
instance Semiring.smulCommClass [Fintype n] [Monoid R] [DistribMulAction R α]
[SMulCommClass R α α] : SMulCommClass R (Matrix n n α) (Matrix n n α) :=
⟨fun r m n => (Matrix.mul_smul m r n).symm⟩
end NonUnitalNonAssocSemiring
section NonAssocSemiring
variable [NonAssocSemiring α]
@[simp]
protected theorem one_mul [Fintype m] [DecidableEq m] (M : Matrix m n α) :
(1 : Matrix m m α) * M = M := by
ext
rw [← diagonal_one, diagonal_mul, one_mul]
@[simp]
protected theorem mul_one [Fintype n] [DecidableEq n] (M : Matrix m n α) :
M * (1 : Matrix n n α) = M := by
ext
rw [← diagonal_one, mul_diagonal, mul_one]
instance nonAssocSemiring [Fintype n] [DecidableEq n] : NonAssocSemiring (Matrix n n α) :=
{ Matrix.nonUnitalNonAssocSemiring, Matrix.instAddCommMonoidWithOne with
one := 1
one_mul := Matrix.one_mul
mul_one := Matrix.mul_one }
@[simp]
theorem map_mul [Fintype n] {L : Matrix m n α} {M : Matrix n o α} [NonAssocSemiring β]
{f : α →+* β} : (L * M).map f = L.map f * M.map f := by
ext
simp [mul_apply, map_sum]
theorem smul_one_eq_diagonal [DecidableEq m] (a : α) :
a • (1 : Matrix m m α) = diagonal fun _ => a := by
simp_rw [← diagonal_one, ← diagonal_smul, Pi.smul_def, smul_eq_mul, mul_one]
theorem op_smul_one_eq_diagonal [DecidableEq m] (a : α) :
MulOpposite.op a • (1 : Matrix m m α) = diagonal fun _ => a := by
simp_rw [← diagonal_one, ← diagonal_smul, Pi.smul_def, op_smul_eq_mul, one_mul]
variable (α n)
/-- `Matrix.diagonal` as a `RingHom`. -/
@[simps]
def diagonalRingHom [Fintype n] [DecidableEq n] : (n → α) →+* Matrix n n α :=
{ diagonalAddMonoidHom n α with
toFun := diagonal
map_one' := diagonal_one
map_mul' := fun _ _ => (diagonal_mul_diagonal' _ _).symm }
end NonAssocSemiring
section NonUnitalSemiring
variable [NonUnitalSemiring α] [Fintype m] [Fintype n]
protected theorem mul_assoc (L : Matrix l m α) (M : Matrix m n α) (N : Matrix n o α) :
L * M * N = L * (M * N) := by
ext
apply dotProduct_assoc
instance nonUnitalSemiring : NonUnitalSemiring (Matrix n n α) :=
{ Matrix.nonUnitalNonAssocSemiring with mul_assoc := Matrix.mul_assoc }
end NonUnitalSemiring
section Semiring
variable [Semiring α]
instance semiring [Fintype n] [DecidableEq n] : Semiring (Matrix n n α) :=
{ Matrix.nonUnitalSemiring, Matrix.nonAssocSemiring with }
end Semiring
section NonUnitalNonAssocRing
variable [NonUnitalNonAssocRing α] [Fintype n]
@[simp]
protected theorem neg_mul (M : Matrix m n α) (N : Matrix n o α) : (-M) * N = -(M * N) := by
ext
apply neg_dotProduct
@[simp]
protected theorem mul_neg (M : Matrix m n α) (N : Matrix n o α) : M * (-N) = -(M * N) := by
ext
apply dotProduct_neg
protected theorem sub_mul (M M' : Matrix m n α) (N : Matrix n o α) :
(M - M') * N = M * N - M' * N := by
rw [sub_eq_add_neg, Matrix.add_mul, Matrix.neg_mul, sub_eq_add_neg]
protected theorem mul_sub (M : Matrix m n α) (N N' : Matrix n o α) :
M * (N - N') = M * N - M * N' := by
rw [sub_eq_add_neg, Matrix.mul_add, Matrix.mul_neg, sub_eq_add_neg]
instance nonUnitalNonAssocRing : NonUnitalNonAssocRing (Matrix n n α) :=
{ Matrix.nonUnitalNonAssocSemiring, Matrix.addCommGroup with }
end NonUnitalNonAssocRing
instance instNonUnitalRing [Fintype n] [NonUnitalRing α] : NonUnitalRing (Matrix n n α) :=
{ Matrix.nonUnitalSemiring, Matrix.addCommGroup with }
instance instNonAssocRing [Fintype n] [DecidableEq n] [NonAssocRing α] :
NonAssocRing (Matrix n n α) :=
{ Matrix.nonAssocSemiring, Matrix.instAddCommGroupWithOne with }
instance instRing [Fintype n] [DecidableEq n] [Ring α] : Ring (Matrix n n α) :=
{ Matrix.semiring, Matrix.instAddCommGroupWithOne with }
section Semiring
variable [Semiring α]
theorem diagonal_pow [Fintype n] [DecidableEq n] (v : n → α) (k : ℕ) :
diagonal v ^ k = diagonal (v ^ k) :=
(map_pow (diagonalRingHom n α) v k).symm
@[simp]
theorem mul_mul_left [Fintype n] (M : Matrix m n α) (N : Matrix n o α) (a : α) :
(of fun i j => a * M i j) * N = a • (M * N) :=
smul_mul a M N
/-- The ring homomorphism `α →+* Matrix n n α`
sending `a` to the diagonal matrix with `a` on the diagonal.
-/
def scalar (n : Type u) [DecidableEq n] [Fintype n] : α →+* Matrix n n α :=
(diagonalRingHom n α).comp <| Pi.constRingHom n α
section Scalar
variable [DecidableEq n] [Fintype n]
@[simp]
theorem scalar_apply (a : α) : scalar n a = diagonal fun _ => a :=
rfl
theorem scalar_inj [Nonempty n] {r s : α} : scalar n r = scalar n s ↔ r = s :=
(diagonal_injective.comp Function.const_injective).eq_iff
theorem scalar_commute_iff {r : α} {M : Matrix n n α} :
Commute (scalar n r) M ↔ r • M = MulOpposite.op r • M := by
simp_rw [Commute, SemiconjBy, scalar_apply, ← smul_eq_diagonal_mul, ← op_smul_eq_mul_diagonal]
theorem scalar_commute (r : α) (hr : ∀ r', Commute r r') (M : Matrix n n α) :
Commute (scalar n r) M := scalar_commute_iff.2 <| ext fun _ _ => hr _
end Scalar
end Semiring
section CommSemiring
variable [CommSemiring α]
theorem smul_eq_mul_diagonal [Fintype n] [DecidableEq n] (M : Matrix m n α) (a : α) :
a • M = M * diagonal fun _ => a := by
ext
simp [mul_comm]
@[simp]
theorem mul_mul_right [Fintype n] (M : Matrix m n α) (N : Matrix n o α) (a : α) :
(M * of fun i j => a * N i j) = a • (M * N) :=
mul_smul M a N
end CommSemiring
section Algebra
variable [Fintype n] [DecidableEq n]
variable [CommSemiring R] [Semiring α] [Semiring β] [Algebra R α] [Algebra R β]
instance instAlgebra : Algebra R (Matrix n n α) where
toRingHom := (Matrix.scalar n).comp (algebraMap R α)
commutes' r x := scalar_commute _ (fun r' => Algebra.commutes _ _) _
smul_def' r x := by ext; simp [Matrix.scalar, Algebra.smul_def r]
theorem algebraMap_matrix_apply {r : R} {i j : n} :
algebraMap R (Matrix n n α) r i j = if i = j then algebraMap R α r else 0 := by
dsimp [algebraMap, Algebra.toRingHom, Matrix.scalar]
split_ifs with h <;> simp [h, Matrix.one_apply_ne]
theorem algebraMap_eq_diagonal (r : R) :
algebraMap R (Matrix n n α) r = diagonal (algebraMap R (n → α) r) := rfl
theorem algebraMap_eq_diagonalRingHom :
algebraMap R (Matrix n n α) = (diagonalRingHom n α).comp (algebraMap R _) := rfl
@[simp]
theorem map_algebraMap (r : R) (f : α → β) (hf : f 0 = 0)
(hf₂ : f (algebraMap R α r) = algebraMap R β r) :
(algebraMap R (Matrix n n α) r).map f = algebraMap R (Matrix n n β) r := by
rw [algebraMap_eq_diagonal, algebraMap_eq_diagonal, diagonal_map hf]
-- Porting note: (congr) the remaining proof was
-- ```
-- congr 1
-- simp only [hf₂, Pi.algebraMap_apply]
-- ```
-- But some `congr 1` doesn't quite work.
simp only [Pi.algebraMap_apply, diagonal_eq_diagonal_iff]
intro
rw [hf₂]
variable (R)
/-- `Matrix.diagonal` as an `AlgHom`. -/
@[simps]
def diagonalAlgHom : (n → α) →ₐ[R] Matrix n n α :=
{ diagonalRingHom n α with
toFun := diagonal
commutes' := fun r => (algebraMap_eq_diagonal r).symm }
end Algebra
end Matrix
/-!
### Bundled versions of `Matrix.map`
-/
namespace Equiv
/-- The `Equiv` between spaces of matrices induced by an `Equiv` between their
coefficients. This is `Matrix.map` as an `Equiv`. -/
@[simps apply]
def mapMatrix (f : α ≃ β) : Matrix m n α ≃ Matrix m n β where
toFun M := M.map f
invFun M := M.map f.symm
left_inv _ := Matrix.ext fun _ _ => f.symm_apply_apply _
right_inv _ := Matrix.ext fun _ _ => f.apply_symm_apply _
@[simp]
theorem mapMatrix_refl : (Equiv.refl α).mapMatrix = Equiv.refl (Matrix m n α) :=
rfl
@[simp]
theorem mapMatrix_symm (f : α ≃ β) : f.mapMatrix.symm = (f.symm.mapMatrix : Matrix m n β ≃ _) :=
rfl
@[simp]
theorem mapMatrix_trans (f : α ≃ β) (g : β ≃ γ) :
f.mapMatrix.trans g.mapMatrix = ((f.trans g).mapMatrix : Matrix m n α ≃ _) :=
rfl
end Equiv
namespace AddMonoidHom
variable [AddZeroClass α] [AddZeroClass β] [AddZeroClass γ]
/-- The `AddMonoidHom` between spaces of matrices induced by an `AddMonoidHom` between their
coefficients. This is `Matrix.map` as an `AddMonoidHom`. -/
@[simps]
def mapMatrix (f : α →+ β) : Matrix m n α →+ Matrix m n β where
toFun M := M.map f
map_zero' := Matrix.map_zero f f.map_zero
map_add' := Matrix.map_add f f.map_add
@[simp]
theorem mapMatrix_id : (AddMonoidHom.id α).mapMatrix = AddMonoidHom.id (Matrix m n α) :=
rfl
@[simp]
theorem mapMatrix_comp (f : β →+ γ) (g : α →+ β) :
f.mapMatrix.comp g.mapMatrix = ((f.comp g).mapMatrix : Matrix m n α →+ _) :=
rfl
end AddMonoidHom
namespace AddEquiv
variable [Add α] [Add β] [Add γ]
/-- The `AddEquiv` between spaces of matrices induced by an `AddEquiv` between their
coefficients. This is `Matrix.map` as an `AddEquiv`. -/
@[simps apply]
def mapMatrix (f : α ≃+ β) : Matrix m n α ≃+ Matrix m n β :=
{ f.toEquiv.mapMatrix with
toFun := fun M => M.map f
invFun := fun M => M.map f.symm
map_add' := Matrix.map_add f f.map_add }
@[simp]
theorem mapMatrix_refl : (AddEquiv.refl α).mapMatrix = AddEquiv.refl (Matrix m n α) :=
rfl
@[simp]
theorem mapMatrix_symm (f : α ≃+ β) : f.mapMatrix.symm = (f.symm.mapMatrix : Matrix m n β ≃+ _) :=
rfl
@[simp]
theorem mapMatrix_trans (f : α ≃+ β) (g : β ≃+ γ) :
f.mapMatrix.trans g.mapMatrix = ((f.trans g).mapMatrix : Matrix m n α ≃+ _) :=
rfl
end AddEquiv
namespace LinearMap
variable [Semiring R] [AddCommMonoid α] [AddCommMonoid β] [AddCommMonoid γ]
variable [Module R α] [Module R β] [Module R γ]
/-- The `LinearMap` between spaces of matrices induced by a `LinearMap` between their
coefficients. This is `Matrix.map` as a `LinearMap`. -/
@[simps]
def mapMatrix (f : α →ₗ[R] β) : Matrix m n α →ₗ[R] Matrix m n β where
toFun M := M.map f
map_add' := Matrix.map_add f f.map_add
map_smul' r := Matrix.map_smul f r (f.map_smul r)
@[simp]
theorem mapMatrix_id : LinearMap.id.mapMatrix = (LinearMap.id : Matrix m n α →ₗ[R] _) :=
rfl
@[simp]
theorem mapMatrix_comp (f : β →ₗ[R] γ) (g : α →ₗ[R] β) :
f.mapMatrix.comp g.mapMatrix = ((f.comp g).mapMatrix : Matrix m n α →ₗ[R] _) :=
rfl
end LinearMap
namespace LinearEquiv
variable [Semiring R] [AddCommMonoid α] [AddCommMonoid β] [AddCommMonoid γ]
variable [Module R α] [Module R β] [Module R γ]
/-- The `LinearEquiv` between spaces of matrices induced by a `LinearEquiv` between their
coefficients. This is `Matrix.map` as a `LinearEquiv`. -/
@[simps apply]
def mapMatrix (f : α ≃ₗ[R] β) : Matrix m n α ≃ₗ[R] Matrix m n β :=
{ f.toEquiv.mapMatrix,
f.toLinearMap.mapMatrix with
toFun := fun M => M.map f
invFun := fun M => M.map f.symm }
@[simp]
theorem mapMatrix_refl : (LinearEquiv.refl R α).mapMatrix = LinearEquiv.refl R (Matrix m n α) :=
rfl
@[simp]
theorem mapMatrix_symm (f : α ≃ₗ[R] β) :
f.mapMatrix.symm = (f.symm.mapMatrix : Matrix m n β ≃ₗ[R] _) :=
rfl
@[simp]
theorem mapMatrix_trans (f : α ≃ₗ[R] β) (g : β ≃ₗ[R] γ) :
f.mapMatrix.trans g.mapMatrix = ((f.trans g).mapMatrix : Matrix m n α ≃ₗ[R] _) :=
rfl
end LinearEquiv
namespace RingHom
variable [Fintype m] [DecidableEq m]
variable [NonAssocSemiring α] [NonAssocSemiring β] [NonAssocSemiring γ]
/-- The `RingHom` between spaces of square matrices induced by a `RingHom` between their
coefficients. This is `Matrix.map` as a `RingHom`. -/
@[simps]
def mapMatrix (f : α →+* β) : Matrix m m α →+* Matrix m m β :=
{ f.toAddMonoidHom.mapMatrix with
toFun := fun M => M.map f
map_one' := by simp
map_mul' := fun L M => Matrix.map_mul }
@[simp]
theorem mapMatrix_id : (RingHom.id α).mapMatrix = RingHom.id (Matrix m m α) :=
rfl
@[simp]
theorem mapMatrix_comp (f : β →+* γ) (g : α →+* β) :
f.mapMatrix.comp g.mapMatrix = ((f.comp g).mapMatrix : Matrix m m α →+* _) :=
rfl
end RingHom
namespace RingEquiv
variable [Fintype m] [DecidableEq m]
variable [NonAssocSemiring α] [NonAssocSemiring β] [NonAssocSemiring γ]
/-- The `RingEquiv` between spaces of square matrices induced by a `RingEquiv` between their
coefficients. This is `Matrix.map` as a `RingEquiv`. -/
@[simps apply]
def mapMatrix (f : α ≃+* β) : Matrix m m α ≃+* Matrix m m β :=
{ f.toRingHom.mapMatrix,
f.toAddEquiv.mapMatrix with
toFun := fun M => M.map f
invFun := fun M => M.map f.symm }
@[simp]
theorem mapMatrix_refl : (RingEquiv.refl α).mapMatrix = RingEquiv.refl (Matrix m m α) :=
rfl
@[simp]
theorem mapMatrix_symm (f : α ≃+* β) : f.mapMatrix.symm = (f.symm.mapMatrix : Matrix m m β ≃+* _) :=
rfl
@[simp]
theorem mapMatrix_trans (f : α ≃+* β) (g : β ≃+* γ) :
f.mapMatrix.trans g.mapMatrix = ((f.trans g).mapMatrix : Matrix m m α ≃+* _) :=
rfl
end RingEquiv
namespace AlgHom
variable [Fintype m] [DecidableEq m]
variable [CommSemiring R] [Semiring α] [Semiring β] [Semiring γ]
variable [Algebra R α] [Algebra R β] [Algebra R γ]
/-- The `AlgHom` between spaces of square matrices induced by an `AlgHom` between their
coefficients. This is `Matrix.map` as an `AlgHom`. -/
@[simps]
def mapMatrix (f : α →ₐ[R] β) : Matrix m m α →ₐ[R] Matrix m m β :=
{ f.toRingHom.mapMatrix with
toFun := fun M => M.map f
commutes' := fun r => Matrix.map_algebraMap r f (map_zero _) (f.commutes r) }
@[simp]
theorem mapMatrix_id : (AlgHom.id R α).mapMatrix = AlgHom.id R (Matrix m m α) :=
rfl
@[simp]
theorem mapMatrix_comp (f : β →ₐ[R] γ) (g : α →ₐ[R] β) :
f.mapMatrix.comp g.mapMatrix = ((f.comp g).mapMatrix : Matrix m m α →ₐ[R] _) :=
rfl
end AlgHom
namespace AlgEquiv
variable [Fintype m] [DecidableEq m]
variable [CommSemiring R] [Semiring α] [Semiring β] [Semiring γ]
variable [Algebra R α] [Algebra R β] [Algebra R γ]
/-- The `AlgEquiv` between spaces of square matrices induced by an `AlgEquiv` between their
coefficients. This is `Matrix.map` as an `AlgEquiv`. -/
@[simps apply]
def mapMatrix (f : α ≃ₐ[R] β) : Matrix m m α ≃ₐ[R] Matrix m m β :=
{ f.toAlgHom.mapMatrix,
f.toRingEquiv.mapMatrix with
toFun := fun M => M.map f
invFun := fun M => M.map f.symm }
@[simp]
theorem mapMatrix_refl : AlgEquiv.refl.mapMatrix = (AlgEquiv.refl : Matrix m m α ≃ₐ[R] _) :=
rfl
@[simp]
theorem mapMatrix_symm (f : α ≃ₐ[R] β) :
f.mapMatrix.symm = (f.symm.mapMatrix : Matrix m m β ≃ₐ[R] _) :=
rfl
@[simp]
theorem mapMatrix_trans (f : α ≃ₐ[R] β) (g : β ≃ₐ[R] γ) :
f.mapMatrix.trans g.mapMatrix = ((f.trans g).mapMatrix : Matrix m m α ≃ₐ[R] _) :=
rfl
end AlgEquiv
open Matrix
namespace Matrix
/-- For two vectors `w` and `v`, `vecMulVec w v i j` is defined to be `w i * v j`.
Put another way, `vecMulVec w v` is exactly `col w * row v`. -/
def vecMulVec [Mul α] (w : m → α) (v : n → α) : Matrix m n α :=
of fun x y => w x * v y
-- TODO: set as an equation lemma for `vecMulVec`, see mathlib4#3024
theorem vecMulVec_apply [Mul α] (w : m → α) (v : n → α) (i j) : vecMulVec w v i j = w i * v j :=
rfl
section NonUnitalNonAssocSemiring
variable [NonUnitalNonAssocSemiring α]
/--
`M *ᵥ v` (notation for `mulVec M v`) is the matrix-vector product of matrix `M` and vector `v`,
where `v` is seen as a column vector.
Put another way, `M *ᵥ v` is the vector whose entries are those of `M * col v` (see `col_mulVec`).
The notation has precedence 73, which comes immediately before ` ⬝ᵥ ` for `Matrix.dotProduct`,
so that `A *ᵥ v ⬝ᵥ B *ᵥ w` is parsed as `(A *ᵥ v) ⬝ᵥ (B *ᵥ w)`.
-/
def mulVec [Fintype n] (M : Matrix m n α) (v : n → α) : m → α
| i => (fun j => M i j) ⬝ᵥ v
@[inherit_doc]
scoped infixr:73 " *ᵥ " => Matrix.mulVec
/--
`v ᵥ* M` (notation for `vecMul v M`) is the vector-matrix product of vector `v` and matrix `M`,
where `v` is seen as a row vector.
Put another way, `v ᵥ* M` is the vector whose entries are those of `row v * M` (see `row_vecMul`).
The notation has precedence 73, which comes immediately before ` ⬝ᵥ ` for `Matrix.dotProduct`,
so that `v ᵥ* A ⬝ᵥ w ᵥ* B` is parsed as `(v ᵥ* A) ⬝ᵥ (w ᵥ* B)`.
-/
def vecMul [Fintype m] (v : m → α) (M : Matrix m n α) : n → α
| j => v ⬝ᵥ fun i => M i j
@[inherit_doc]
scoped infixl:73 " ᵥ* " => Matrix.vecMul
/-- Left multiplication by a matrix, as an `AddMonoidHom` from vectors to vectors. -/
@[simps]
def mulVec.addMonoidHomLeft [Fintype n] (v : n → α) : Matrix m n α →+ m → α where
toFun M := M *ᵥ v
map_zero' := by
ext
simp [mulVec]
map_add' x y := by
ext m
apply add_dotProduct
/-- The `i`th row of the multiplication is the same as the `vecMul` with the `i`th row of `A`. -/
theorem mul_apply_eq_vecMul [Fintype n] (A : Matrix m n α) (B : Matrix n o α) (i : m) :
(A * B) i = A i ᵥ* B :=
rfl
theorem mulVec_diagonal [Fintype m] [DecidableEq m] (v w : m → α) (x : m) :
(diagonal v *ᵥ w) x = v x * w x :=
diagonal_dotProduct v w x
theorem vecMul_diagonal [Fintype m] [DecidableEq m] (v w : m → α) (x : m) :
(v ᵥ* diagonal w) x = v x * w x :=
dotProduct_diagonal' v w x
/-- Associate the dot product of `mulVec` to the left. -/
theorem dotProduct_mulVec [Fintype n] [Fintype m] [NonUnitalSemiring R] (v : m → R)
(A : Matrix m n R) (w : n → R) : v ⬝ᵥ A *ᵥ w = v ᵥ* A ⬝ᵥ w := by
simp only [dotProduct, vecMul, mulVec, Finset.mul_sum, Finset.sum_mul, mul_assoc]
exact Finset.sum_comm
@[simp]
theorem mulVec_zero [Fintype n] (A : Matrix m n α) : A *ᵥ 0 = 0 := by
ext
simp [mulVec]
@[simp]
theorem zero_vecMul [Fintype m] (A : Matrix m n α) : 0 ᵥ* A = 0 := by
ext
simp [vecMul]
@[simp]
theorem zero_mulVec [Fintype n] (v : n → α) : (0 : Matrix m n α) *ᵥ v = 0 := by
ext
simp [mulVec]
@[simp]
theorem vecMul_zero [Fintype m] (v : m → α) : v ᵥ* (0 : Matrix m n α) = 0 := by
ext
simp [vecMul]
theorem smul_mulVec_assoc [Fintype n] [Monoid R] [DistribMulAction R α] [IsScalarTower R α α]
(a : R) (A : Matrix m n α) (b : n → α) : (a • A) *ᵥ b = a • A *ᵥ b := by
ext
apply smul_dotProduct
theorem mulVec_add [Fintype n] (A : Matrix m n α) (x y : n → α) :
A *ᵥ (x + y) = A *ᵥ x + A *ᵥ y := by
ext
apply dotProduct_add
theorem add_mulVec [Fintype n] (A B : Matrix m n α) (x : n → α) :
(A + B) *ᵥ x = A *ᵥ x + B *ᵥ x := by
ext
apply add_dotProduct
theorem vecMul_add [Fintype m] (A B : Matrix m n α) (x : m → α) :
x ᵥ* (A + B) = x ᵥ* A + x ᵥ* B := by
ext
apply dotProduct_add
theorem add_vecMul [Fintype m] (A : Matrix m n α) (x y : m → α) :
(x + y) ᵥ* A = x ᵥ* A + y ᵥ* A := by
ext
apply add_dotProduct
theorem vecMul_smul [Fintype n] [Monoid R] [NonUnitalNonAssocSemiring S] [DistribMulAction R S]
[IsScalarTower R S S] (M : Matrix n m S) (b : R) (v : n → S) :
(b • v) ᵥ* M = b • v ᵥ* M := by
ext i
simp only [vecMul, dotProduct, Finset.smul_sum, Pi.smul_apply, smul_mul_assoc]
theorem mulVec_smul [Fintype n] [Monoid R] [NonUnitalNonAssocSemiring S] [DistribMulAction R S]
[SMulCommClass R S S] (M : Matrix m n S) (b : R) (v : n → S) :
M *ᵥ (b • v) = b • M *ᵥ v := by
ext i
simp only [mulVec, dotProduct, Finset.smul_sum, Pi.smul_apply, mul_smul_comm]
@[simp]
theorem mulVec_single [Fintype n] [DecidableEq n] [NonUnitalNonAssocSemiring R] (M : Matrix m n R)
(j : n) (x : R) : M *ᵥ Pi.single j x = fun i => M i j * x :=
funext fun _ => dotProduct_single _ _ _
@[simp]
theorem single_vecMul [Fintype m] [DecidableEq m] [NonUnitalNonAssocSemiring R] (M : Matrix m n R)
(i : m) (x : R) : Pi.single i x ᵥ* M = fun j => x * M i j :=
funext fun _ => single_dotProduct _ _ _
-- @[simp] -- Porting note: not in simpNF
theorem diagonal_mulVec_single [Fintype n] [DecidableEq n] [NonUnitalNonAssocSemiring R] (v : n → R)
(j : n) (x : R) : diagonal v *ᵥ Pi.single j x = Pi.single j (v j * x) := by
ext i
rw [mulVec_diagonal]
exact Pi.apply_single (fun i x => v i * x) (fun i => mul_zero _) j x i
-- @[simp] -- Porting note: not in simpNF
theorem single_vecMul_diagonal [Fintype n] [DecidableEq n] [NonUnitalNonAssocSemiring R] (v : n → R)
(j : n) (x : R) : (Pi.single j x) ᵥ* (diagonal v) = Pi.single j (x * v j) := by
ext i
rw [vecMul_diagonal]
exact Pi.apply_single (fun i x => x * v i) (fun i => zero_mul _) j x i
end NonUnitalNonAssocSemiring
section NonUnitalSemiring
variable [NonUnitalSemiring α]
@[simp]
theorem vecMul_vecMul [Fintype n] [Fintype m] (v : m → α) (M : Matrix m n α) (N : Matrix n o α) :
v ᵥ* M ᵥ* N = v ᵥ* (M * N) := by
ext
apply dotProduct_assoc
@[simp]
theorem mulVec_mulVec [Fintype n] [Fintype o] (v : o → α) (M : Matrix m n α) (N : Matrix n o α) :
M *ᵥ N *ᵥ v = (M * N) *ᵥ v := by
ext
symm
apply dotProduct_assoc
theorem star_mulVec [Fintype n] [StarRing α] (M : Matrix m n α) (v : n → α) :
star (M *ᵥ v) = star v ᵥ* Mᴴ :=
funext fun _ => (star_dotProduct_star _ _).symm
theorem star_vecMul [Fintype m] [StarRing α] (M : Matrix m n α) (v : m → α) :
star (v ᵥ* M) = Mᴴ *ᵥ star v :=
funext fun _ => (star_dotProduct_star _ _).symm
theorem mulVec_conjTranspose [Fintype m] [StarRing α] (A : Matrix m n α) (x : m → α) :
Aᴴ *ᵥ x = star (star x ᵥ* A) :=
funext fun _ => star_dotProduct _ _
theorem vecMul_conjTranspose [Fintype n] [StarRing α] (A : Matrix m n α) (x : n → α) :
x ᵥ* Aᴴ = star (A *ᵥ star x) :=
funext fun _ => dotProduct_star _ _
theorem mul_mul_apply [Fintype n] (A B C : Matrix n n α) (i j : n) :
(A * B * C) i j = A i ⬝ᵥ B *ᵥ (Cᵀ j) := by
rw [Matrix.mul_assoc]
simp only [mul_apply, dotProduct, mulVec]
rfl
end NonUnitalSemiring
section NonAssocSemiring
variable [NonAssocSemiring α]
theorem mulVec_one [Fintype n] (A : Matrix m n α) : A *ᵥ 1 = fun i => ∑ j, A i j := by
ext; simp [mulVec, dotProduct]
theorem vec_one_mul [Fintype m] (A : Matrix m n α) : 1 ᵥ* A = fun j => ∑ i, A i j := by
ext; simp [vecMul, dotProduct]
variable [Fintype m] [Fintype n] [DecidableEq m]
@[simp]
theorem one_mulVec (v : m → α) : 1 *ᵥ v = v := by
ext
rw [← diagonal_one, mulVec_diagonal, one_mul]
@[simp]
theorem vecMul_one (v : m → α) : v ᵥ* 1 = v := by
ext
rw [← diagonal_one, vecMul_diagonal, mul_one]
@[simp]
theorem diagonal_const_mulVec (x : α) (v : m → α) :
(diagonal fun _ => x) *ᵥ v = x • v := by
ext; simp [mulVec_diagonal]
@[simp]
theorem vecMul_diagonal_const (x : α) (v : m → α) :
v ᵥ* (diagonal fun _ => x) = MulOpposite.op x • v := by
ext; simp [vecMul_diagonal]
@[simp]
theorem natCast_mulVec (x : ℕ) (v : m → α) : x *ᵥ v = (x : α) • v :=
diagonal_const_mulVec _ _
@[simp]
theorem vecMul_natCast (x : ℕ) (v : m → α) : v ᵥ* x = MulOpposite.op (x : α) • v :=
vecMul_diagonal_const _ _
-- See note [no_index around OfNat.ofNat]
@[simp]
theorem ofNat_mulVec (x : ℕ) [x.AtLeastTwo] (v : m → α) :
OfNat.ofNat (no_index x) *ᵥ v = (OfNat.ofNat x : α) • v :=
natCast_mulVec _ _
-- See note [no_index around OfNat.ofNat]
@[simp]
theorem vecMul_ofNat (x : ℕ) [x.AtLeastTwo] (v : m → α) :
v ᵥ* OfNat.ofNat (no_index x) = MulOpposite.op (OfNat.ofNat x : α) • v :=
vecMul_natCast _ _
end NonAssocSemiring
section NonUnitalNonAssocRing
variable [NonUnitalNonAssocRing α]
theorem neg_vecMul [Fintype m] (v : m → α) (A : Matrix m n α) : (-v) ᵥ* A = - (v ᵥ* A) := by
ext
apply neg_dotProduct
theorem vecMul_neg [Fintype m] (v : m → α) (A : Matrix m n α) : v ᵥ* (-A) = - (v ᵥ* A) := by
ext
apply dotProduct_neg
lemma neg_vecMul_neg [Fintype m] (v : m → α) (A : Matrix m n α) : (-v) ᵥ* (-A) = v ᵥ* A := by
rw [vecMul_neg, neg_vecMul, neg_neg]
theorem neg_mulVec [Fintype n] (v : n → α) (A : Matrix m n α) : (-A) *ᵥ v = - (A *ᵥ v) := by
ext
apply neg_dotProduct
theorem mulVec_neg [Fintype n] (v : n → α) (A : Matrix m n α) : A *ᵥ (-v) = - (A *ᵥ v) := by
ext
apply dotProduct_neg
lemma neg_mulVec_neg [Fintype n] (v : n → α) (A : Matrix m n α) : (-A) *ᵥ (-v) = A *ᵥ v := by
rw [mulVec_neg, neg_mulVec, neg_neg]
theorem mulVec_sub [Fintype n] (A : Matrix m n α) (x y : n → α) :
A *ᵥ (x - y) = A *ᵥ x - A *ᵥ y := by
ext
apply dotProduct_sub
theorem sub_mulVec [Fintype n] (A B : Matrix m n α) (x : n → α) :
(A - B) *ᵥ x = A *ᵥ x - B *ᵥ x := by simp [sub_eq_add_neg, add_mulVec, neg_mulVec]
theorem vecMul_sub [Fintype m] (A B : Matrix m n α) (x : m → α) :
x ᵥ* (A - B) = x ᵥ* A - x ᵥ* B := by simp [sub_eq_add_neg, vecMul_add, vecMul_neg]
theorem sub_vecMul [Fintype m] (A : Matrix m n α) (x y : m → α) :
(x - y) ᵥ* A = x ᵥ* A - y ᵥ* A := by
ext
apply sub_dotProduct
end NonUnitalNonAssocRing
section NonUnitalCommSemiring
variable [NonUnitalCommSemiring α]
theorem mulVec_transpose [Fintype m] (A : Matrix m n α) (x : m → α) : Aᵀ *ᵥ x = x ᵥ* A := by
ext
apply dotProduct_comm
theorem vecMul_transpose [Fintype n] (A : Matrix m n α) (x : n → α) : x ᵥ* Aᵀ = A *ᵥ x := by
ext
apply dotProduct_comm
theorem mulVec_vecMul [Fintype n] [Fintype o] (A : Matrix m n α) (B : Matrix o n α) (x : o → α) :
A *ᵥ (x ᵥ* B) = (A * Bᵀ) *ᵥ x := by rw [← mulVec_mulVec, mulVec_transpose]
theorem vecMul_mulVec [Fintype m] [Fintype n] (A : Matrix m n α) (B : Matrix m o α) (x : n → α) :
(A *ᵥ x) ᵥ* B = x ᵥ* (Aᵀ * B) := by rw [← vecMul_vecMul, vecMul_transpose]
end NonUnitalCommSemiring
section CommSemiring
variable [CommSemiring α]
theorem mulVec_smul_assoc [Fintype n] (A : Matrix m n α) (b : n → α) (a : α) :
A *ᵥ (a • b) = a • A *ᵥ b := by
ext
apply dotProduct_smul
end CommSemiring
section NonAssocRing
variable [NonAssocRing α]
variable [Fintype m] [DecidableEq m]
@[simp]
theorem intCast_mulVec (x : ℤ) (v : m → α) : x *ᵥ v = (x : α) • v :=
diagonal_const_mulVec _ _
@[simp]
theorem vecMul_intCast (x : ℤ) (v : m → α) : v ᵥ* x = MulOpposite.op (x : α) • v :=
vecMul_diagonal_const _ _
end NonAssocRing
section Transpose
open Matrix
@[simp]
theorem transpose_transpose (M : Matrix m n α) : Mᵀᵀ = M := by
ext
rfl
theorem transpose_injective : Function.Injective (transpose : Matrix m n α → Matrix n m α) :=
fun _ _ h => ext fun i j => ext_iff.2 h j i
@[simp] theorem transpose_inj {A B : Matrix m n α} : Aᵀ = Bᵀ ↔ A = B := transpose_injective.eq_iff
@[simp]
theorem transpose_eq_diagonal [DecidableEq n] [Zero α] {M : Matrix n n α} {v : n → α} :
Mᵀ = diagonal v ↔ M = diagonal v :=
(Function.Involutive.eq_iff transpose_transpose).trans <|
by rw [diagonal_transpose]
@[simp]
theorem transpose_zero [Zero α] : (0 : Matrix m n α)ᵀ = 0 := rfl
@[simp]
theorem transpose_eq_zero [Zero α] {M : Matrix m n α} : Mᵀ = 0 ↔ M = 0 := transpose_inj
@[simp]
theorem transpose_one [DecidableEq n] [Zero α] [One α] : (1 : Matrix n n α)ᵀ = 1 :=
diagonal_transpose _
@[simp]
theorem transpose_eq_one [DecidableEq n] [Zero α] [One α] {M : Matrix n n α} : Mᵀ = 1 ↔ M = 1 :=
transpose_eq_diagonal
@[simp]
theorem transpose_natCast [DecidableEq n] [AddMonoidWithOne α] (d : ℕ) :
(d : Matrix n n α)ᵀ = d :=
diagonal_transpose _
@[simp]
theorem transpose_eq_natCast [DecidableEq n] [AddMonoidWithOne α] {M : Matrix n n α} {d : ℕ} :
Mᵀ = d ↔ M = d :=
transpose_eq_diagonal
-- See note [no_index around OfNat.ofNat]
@[simp]
theorem transpose_ofNat [DecidableEq n] [AddMonoidWithOne α] (d : ℕ) [d.AtLeastTwo] :
(no_index (OfNat.ofNat d) : Matrix n n α)ᵀ = OfNat.ofNat d :=
transpose_natCast _
-- See note [no_index around OfNat.ofNat]
@[simp]
theorem transpose_eq_ofNat [DecidableEq n] [AddMonoidWithOne α]
{M : Matrix n n α} {d : ℕ} [d.AtLeastTwo] :
Mᵀ = no_index (OfNat.ofNat d) ↔ M = OfNat.ofNat d :=
transpose_eq_diagonal
@[simp]
theorem transpose_intCast [DecidableEq n] [AddGroupWithOne α] (d : ℤ) :
(d : Matrix n n α)ᵀ = d :=
diagonal_transpose _
@[simp]
theorem transpose_eq_intCast [DecidableEq n] [AddGroupWithOne α]
{M : Matrix n n α} {d : ℤ} :
Mᵀ = d ↔ M = d :=
transpose_eq_diagonal
@[simp]
theorem transpose_add [Add α] (M : Matrix m n α) (N : Matrix m n α) : (M + N)ᵀ = Mᵀ + Nᵀ := by
ext
simp
@[simp]
theorem transpose_sub [Sub α] (M : Matrix m n α) (N : Matrix m n α) : (M - N)ᵀ = Mᵀ - Nᵀ := by
ext
simp
@[simp]
theorem transpose_mul [AddCommMonoid α] [CommSemigroup α] [Fintype n] (M : Matrix m n α)
(N : Matrix n l α) : (M * N)ᵀ = Nᵀ * Mᵀ := by
ext
apply dotProduct_comm
@[simp]
theorem transpose_smul {R : Type*} [SMul R α] (c : R) (M : Matrix m n α) : (c • M)ᵀ = c • Mᵀ := by
ext
rfl
@[simp]
theorem transpose_neg [Neg α] (M : Matrix m n α) : (-M)ᵀ = -Mᵀ := by
ext
rfl
theorem transpose_map {f : α → β} {M : Matrix m n α} : Mᵀ.map f = (M.map f)ᵀ := by
ext
rfl
variable (m n α)
/-- `Matrix.transpose` as an `AddEquiv` -/
@[simps apply]
def transposeAddEquiv [Add α] : Matrix m n α ≃+ Matrix n m α where
toFun := transpose
invFun := transpose
left_inv := transpose_transpose
right_inv := transpose_transpose
map_add' := transpose_add
@[simp]
theorem transposeAddEquiv_symm [Add α] : (transposeAddEquiv m n α).symm = transposeAddEquiv n m α :=
rfl
variable {m n α}
theorem transpose_list_sum [AddMonoid α] (l : List (Matrix m n α)) :
l.sumᵀ = (l.map transpose).sum :=
map_list_sum (transposeAddEquiv m n α) l
theorem transpose_multiset_sum [AddCommMonoid α] (s : Multiset (Matrix m n α)) :
s.sumᵀ = (s.map transpose).sum :=
(transposeAddEquiv m n α).toAddMonoidHom.map_multiset_sum s
theorem transpose_sum [AddCommMonoid α] {ι : Type*} (s : Finset ι) (M : ι → Matrix m n α) :
(∑ i ∈ s, M i)ᵀ = ∑ i ∈ s, (M i)ᵀ :=
map_sum (transposeAddEquiv m n α) _ s
variable (m n R α)
/-- `Matrix.transpose` as a `LinearMap` -/
@[simps apply]
def transposeLinearEquiv [Semiring R] [AddCommMonoid α] [Module R α] :
Matrix m n α ≃ₗ[R] Matrix n m α :=
{ transposeAddEquiv m n α with map_smul' := transpose_smul }
@[simp]
theorem transposeLinearEquiv_symm [Semiring R] [AddCommMonoid α] [Module R α] :
(transposeLinearEquiv m n R α).symm = transposeLinearEquiv n m R α :=
rfl
variable {m n R α}
variable (m α)
/-- `Matrix.transpose` as a `RingEquiv` to the opposite ring -/
@[simps]
def transposeRingEquiv [AddCommMonoid α] [CommSemigroup α] [Fintype m] :
Matrix m m α ≃+* (Matrix m m α)ᵐᵒᵖ :=
{ (transposeAddEquiv m m α).trans MulOpposite.opAddEquiv with
toFun := fun M => MulOpposite.op Mᵀ
invFun := fun M => M.unopᵀ
map_mul' := fun M N =>
(congr_arg MulOpposite.op (transpose_mul M N)).trans (MulOpposite.op_mul _ _)
left_inv := fun M => transpose_transpose M
right_inv := fun M => MulOpposite.unop_injective <| transpose_transpose M.unop }
variable {m α}
@[simp]
theorem transpose_pow [CommSemiring α] [Fintype m] [DecidableEq m] (M : Matrix m m α) (k : ℕ) :
(M ^ k)ᵀ = Mᵀ ^ k :=
MulOpposite.op_injective <| map_pow (transposeRingEquiv m α) M k
theorem transpose_list_prod [CommSemiring α] [Fintype m] [DecidableEq m] (l : List (Matrix m m α)) :
l.prodᵀ = (l.map transpose).reverse.prod :=
(transposeRingEquiv m α).unop_map_list_prod l
variable (R m α)
/-- `Matrix.transpose` as an `AlgEquiv` to the opposite ring -/
@[simps]
def transposeAlgEquiv [CommSemiring R] [CommSemiring α] [Fintype m] [DecidableEq m] [Algebra R α] :
Matrix m m α ≃ₐ[R] (Matrix m m α)ᵐᵒᵖ :=
{ (transposeAddEquiv m m α).trans MulOpposite.opAddEquiv,
transposeRingEquiv m α with
toFun := fun M => MulOpposite.op Mᵀ
commutes' := fun r => by
simp only [algebraMap_eq_diagonal, diagonal_transpose, MulOpposite.algebraMap_apply] }
variable {R m α}
end Transpose
section ConjTranspose
open Matrix
/-- Tell `simp` what the entries are in a conjugate transposed matrix.
Compare with `mul_apply`, `diagonal_apply_eq`, etc.
-/
@[simp]
theorem conjTranspose_apply [Star α] (M : Matrix m n α) (i j) :
M.conjTranspose j i = star (M i j) :=
rfl
@[simp]
theorem conjTranspose_conjTranspose [InvolutiveStar α] (M : Matrix m n α) : Mᴴᴴ = M :=
Matrix.ext <| by simp
theorem conjTranspose_injective [InvolutiveStar α] :
Function.Injective (conjTranspose : Matrix m n α → Matrix n m α) :=
(map_injective star_injective).comp transpose_injective
@[simp] theorem conjTranspose_inj [InvolutiveStar α] {A B : Matrix m n α} : Aᴴ = Bᴴ ↔ A = B :=
conjTranspose_injective.eq_iff
@[simp]
theorem conjTranspose_eq_diagonal [DecidableEq n] [AddMonoid α] [StarAddMonoid α]
{M : Matrix n n α} {v : n → α} :
Mᴴ = diagonal v ↔ M = diagonal (star v) :=
(Function.Involutive.eq_iff conjTranspose_conjTranspose).trans <|
by rw [diagonal_conjTranspose]
@[simp]
theorem conjTranspose_zero [AddMonoid α] [StarAddMonoid α] : (0 : Matrix m n α)ᴴ = 0 :=
Matrix.ext <| by simp
@[simp]
theorem conjTranspose_eq_zero [AddMonoid α] [StarAddMonoid α] {M : Matrix m n α} :
Mᴴ = 0 ↔ M = 0 := by
rw [← conjTranspose_inj (A := M), conjTranspose_zero]
@[simp]
theorem conjTranspose_one [DecidableEq n] [Semiring α] [StarRing α] : (1 : Matrix n n α)ᴴ = 1 := by
simp [conjTranspose]
@[simp]
theorem conjTranspose_eq_one [DecidableEq n] [Semiring α] [StarRing α] {M : Matrix n n α} :
Mᴴ = 1 ↔ M = 1 :=
(Function.Involutive.eq_iff conjTranspose_conjTranspose).trans <|
by rw [conjTranspose_one]
@[simp]
theorem conjTranspose_natCast [DecidableEq n] [Semiring α] [StarRing α] (d : ℕ) :
(d : Matrix n n α)ᴴ = d := by
simp [conjTranspose, Matrix.map_natCast, diagonal_natCast]
@[simp]
theorem conjTranspose_eq_natCast [DecidableEq n] [Semiring α] [StarRing α]
{M : Matrix n n α} {d : ℕ} :
Mᴴ = d ↔ M = d :=
(Function.Involutive.eq_iff conjTranspose_conjTranspose).trans <|
by rw [conjTranspose_natCast]
-- See note [no_index around OfNat.ofNat]
@[simp]
theorem conjTranspose_ofNat [DecidableEq n] [Semiring α] [StarRing α] (d : ℕ) [d.AtLeastTwo] :
(no_index (OfNat.ofNat d) : Matrix n n α)ᴴ = OfNat.ofNat d :=
conjTranspose_natCast _
-- See note [no_index around OfNat.ofNat]
@[simp]
theorem conjTranspose_eq_ofNat [DecidableEq n] [Semiring α] [StarRing α]
{M : Matrix n n α} {d : ℕ} [d.AtLeastTwo] :
Mᴴ = no_index (OfNat.ofNat d) ↔ M = OfNat.ofNat d :=
conjTranspose_eq_natCast
@[simp]
theorem conjTranspose_intCast [DecidableEq n] [Ring α] [StarRing α] (d : ℤ) :
(d : Matrix n n α)ᴴ = d := by
simp [conjTranspose, Matrix.map_intCast, diagonal_intCast]
@[simp]
theorem conjTranspose_eq_intCast [DecidableEq n] [Ring α] [StarRing α]
{M : Matrix n n α} {d : ℤ} :
Mᴴ = d ↔ M = d :=
(Function.Involutive.eq_iff conjTranspose_conjTranspose).trans <|
by rw [conjTranspose_intCast]
@[simp]
theorem conjTranspose_add [AddMonoid α] [StarAddMonoid α] (M N : Matrix m n α) :
(M + N)ᴴ = Mᴴ + Nᴴ :=
Matrix.ext <| by simp
@[simp]
theorem conjTranspose_sub [AddGroup α] [StarAddMonoid α] (M N : Matrix m n α) :
(M - N)ᴴ = Mᴴ - Nᴴ :=
Matrix.ext <| by simp
/-- Note that `StarModule` is quite a strong requirement; as such we also provide the following
variants which this lemma would not apply to:
* `Matrix.conjTranspose_smul_non_comm`
* `Matrix.conjTranspose_nsmul`
* `Matrix.conjTranspose_zsmul`
* `Matrix.conjTranspose_natCast_smul`
* `Matrix.conjTranspose_intCast_smul`
* `Matrix.conjTranspose_inv_natCast_smul`
* `Matrix.conjTranspose_inv_intCast_smul`
* `Matrix.conjTranspose_rat_smul`
* `Matrix.conjTranspose_ratCast_smul`
-/
@[simp]
theorem conjTranspose_smul [Star R] [Star α] [SMul R α] [StarModule R α] (c : R)
(M : Matrix m n α) : (c • M)ᴴ = star c • Mᴴ :=
Matrix.ext fun _ _ => star_smul _ _
@[simp]
theorem conjTranspose_smul_non_comm [Star R] [Star α] [SMul R α] [SMul Rᵐᵒᵖ α] (c : R)
(M : Matrix m n α) (h : ∀ (r : R) (a : α), star (r • a) = MulOpposite.op (star r) • star a) :
(c • M)ᴴ = MulOpposite.op (star c) • Mᴴ :=
Matrix.ext <| by simp [h]
-- @[simp] -- Porting note (#10618): simp can prove this
theorem conjTranspose_smul_self [Mul α] [StarMul α] (c : α) (M : Matrix m n α) :
(c • M)ᴴ = MulOpposite.op (star c) • Mᴴ :=
conjTranspose_smul_non_comm c M star_mul
@[simp]
theorem conjTranspose_nsmul [AddMonoid α] [StarAddMonoid α] (c : ℕ) (M : Matrix m n α) :
(c • M)ᴴ = c • Mᴴ :=
Matrix.ext <| by simp
@[simp]
theorem conjTranspose_zsmul [AddGroup α] [StarAddMonoid α] (c : ℤ) (M : Matrix m n α) :
(c • M)ᴴ = c • Mᴴ :=
Matrix.ext <| by simp
@[simp]
theorem conjTranspose_natCast_smul [Semiring R] [AddCommMonoid α] [StarAddMonoid α] [Module R α]
(c : ℕ) (M : Matrix m n α) : ((c : R) • M)ᴴ = (c : R) • Mᴴ :=
Matrix.ext <| by simp
-- See note [no_index around OfNat.ofNat]
@[simp]
theorem conjTranspose_ofNat_smul [Semiring R] [AddCommMonoid α] [StarAddMonoid α] [Module R α]
(c : ℕ) [c.AtLeastTwo] (M : Matrix m n α) :
((no_index (OfNat.ofNat c : R)) • M)ᴴ = (OfNat.ofNat c : R) • Mᴴ :=
conjTranspose_natCast_smul c M
@[simp]
theorem conjTranspose_intCast_smul [Ring R] [AddCommGroup α] [StarAddMonoid α] [Module R α] (c : ℤ)
(M : Matrix m n α) : ((c : R) • M)ᴴ = (c : R) • Mᴴ :=
Matrix.ext <| by simp
@[simp]
theorem conjTranspose_inv_natCast_smul [DivisionSemiring R] [AddCommMonoid α] [StarAddMonoid α]
[Module R α] (c : ℕ) (M : Matrix m n α) : ((c : R)⁻¹ • M)ᴴ = (c : R)⁻¹ • Mᴴ :=
Matrix.ext <| by simp
-- See note [no_index around OfNat.ofNat]
@[simp]
theorem conjTranspose_inv_ofNat_smul [DivisionSemiring R] [AddCommMonoid α] [StarAddMonoid α]
[Module R α] (c : ℕ) [c.AtLeastTwo] (M : Matrix m n α) :
((no_index (OfNat.ofNat c : R))⁻¹ • M)ᴴ = (OfNat.ofNat c : R)⁻¹ • Mᴴ :=
conjTranspose_inv_natCast_smul c M
@[simp]
theorem conjTranspose_inv_intCast_smul [DivisionRing R] [AddCommGroup α] [StarAddMonoid α]
[Module R α] (c : ℤ) (M : Matrix m n α) : ((c : R)⁻¹ • M)ᴴ = (c : R)⁻¹ • Mᴴ :=
Matrix.ext <| by simp
@[simp]
theorem conjTranspose_ratCast_smul [DivisionRing R] [AddCommGroup α] [StarAddMonoid α] [Module R α]
(c : ℚ) (M : Matrix m n α) : ((c : R) • M)ᴴ = (c : R) • Mᴴ :=
Matrix.ext <| by simp
@[simp]
theorem conjTranspose_rat_smul [AddCommGroup α] [StarAddMonoid α] [Module ℚ α] (c : ℚ)
(M : Matrix m n α) : (c • M)ᴴ = c • Mᴴ :=
Matrix.ext <| by simp
@[simp]
theorem conjTranspose_mul [Fintype n] [NonUnitalSemiring α] [StarRing α] (M : Matrix m n α)
(N : Matrix n l α) : (M * N)ᴴ = Nᴴ * Mᴴ :=
Matrix.ext <| by simp [mul_apply]
@[simp]
theorem conjTranspose_neg [AddGroup α] [StarAddMonoid α] (M : Matrix m n α) : (-M)ᴴ = -Mᴴ :=
Matrix.ext <| by simp
theorem conjTranspose_map [Star α] [Star β] {A : Matrix m n α} (f : α → β)
(hf : Function.Semiconj f star star) : Aᴴ.map f = (A.map f)ᴴ :=
Matrix.ext fun _ _ => hf _
/-- When `star x = x` on the coefficients (such as the real numbers) `conjTranspose` and `transpose`
are the same operation. -/
@[simp]
theorem conjTranspose_eq_transpose_of_trivial [Star α] [TrivialStar α] (A : Matrix m n α) :
Aᴴ = Aᵀ := Matrix.ext fun _ _ => star_trivial _
variable (m n α)
/-- `Matrix.conjTranspose` as an `AddEquiv` -/
@[simps apply]
def conjTransposeAddEquiv [AddMonoid α] [StarAddMonoid α] : Matrix m n α ≃+ Matrix n m α where
toFun := conjTranspose
invFun := conjTranspose
left_inv := conjTranspose_conjTranspose
right_inv := conjTranspose_conjTranspose
map_add' := conjTranspose_add
@[simp]
theorem conjTransposeAddEquiv_symm [AddMonoid α] [StarAddMonoid α] :
(conjTransposeAddEquiv m n α).symm = conjTransposeAddEquiv n m α :=
rfl
variable {m n α}
theorem conjTranspose_list_sum [AddMonoid α] [StarAddMonoid α] (l : List (Matrix m n α)) :
l.sumᴴ = (l.map conjTranspose).sum :=
map_list_sum (conjTransposeAddEquiv m n α) l
theorem conjTranspose_multiset_sum [AddCommMonoid α] [StarAddMonoid α]
(s : Multiset (Matrix m n α)) : s.sumᴴ = (s.map conjTranspose).sum :=
(conjTransposeAddEquiv m n α).toAddMonoidHom.map_multiset_sum s
theorem conjTranspose_sum [AddCommMonoid α] [StarAddMonoid α] {ι : Type*} (s : Finset ι)
(M : ι → Matrix m n α) : (∑ i ∈ s, M i)ᴴ = ∑ i ∈ s, (M i)ᴴ :=
map_sum (conjTransposeAddEquiv m n α) _ s
variable (m n R α)
/-- `Matrix.conjTranspose` as a `LinearMap` -/
@[simps apply]
def conjTransposeLinearEquiv [CommSemiring R] [StarRing R] [AddCommMonoid α] [StarAddMonoid α]
[Module R α] [StarModule R α] : Matrix m n α ≃ₗ⋆[R] Matrix n m α :=
{ conjTransposeAddEquiv m n α with map_smul' := conjTranspose_smul }
@[simp]
theorem conjTransposeLinearEquiv_symm [CommSemiring R] [StarRing R] [AddCommMonoid α]
[StarAddMonoid α] [Module R α] [StarModule R α] :
(conjTransposeLinearEquiv m n R α).symm = conjTransposeLinearEquiv n m R α :=
rfl
variable {m n R α}
variable (m α)
/-- `Matrix.conjTranspose` as a `RingEquiv` to the opposite ring -/
@[simps]
def conjTransposeRingEquiv [Semiring α] [StarRing α] [Fintype m] :
Matrix m m α ≃+* (Matrix m m α)ᵐᵒᵖ :=
{ (conjTransposeAddEquiv m m α).trans MulOpposite.opAddEquiv with
toFun := fun M => MulOpposite.op Mᴴ
invFun := fun M => M.unopᴴ
map_mul' := fun M N =>
(congr_arg MulOpposite.op (conjTranspose_mul M N)).trans (MulOpposite.op_mul _ _) }
variable {m α}
@[simp]
theorem conjTranspose_pow [Semiring α] [StarRing α] [Fintype m] [DecidableEq m] (M : Matrix m m α)
(k : ℕ) : (M ^ k)ᴴ = Mᴴ ^ k :=
MulOpposite.op_injective <| map_pow (conjTransposeRingEquiv m α) M k
theorem conjTranspose_list_prod [Semiring α] [StarRing α] [Fintype m] [DecidableEq m]
(l : List (Matrix m m α)) : l.prodᴴ = (l.map conjTranspose).reverse.prod :=
(conjTransposeRingEquiv m α).unop_map_list_prod l
end ConjTranspose
section Star
/-- When `α` has a star operation, square matrices `Matrix n n α` have a star
operation equal to `Matrix.conjTranspose`. -/
instance [Star α] : Star (Matrix n n α) where star := conjTranspose
theorem star_eq_conjTranspose [Star α] (M : Matrix m m α) : star M = Mᴴ :=
rfl
@[simp]
theorem star_apply [Star α] (M : Matrix n n α) (i j) : (star M) i j = star (M j i) :=
rfl
instance [InvolutiveStar α] : InvolutiveStar (Matrix n n α) where
star_involutive := conjTranspose_conjTranspose
/-- When `α` is a `*`-additive monoid, `Matrix.star` is also a `*`-additive monoid. -/
instance [AddMonoid α] [StarAddMonoid α] : StarAddMonoid (Matrix n n α) where
star_add := conjTranspose_add
instance [Star α] [Star β] [SMul α β] [StarModule α β] : StarModule α (Matrix n n β) where
star_smul := conjTranspose_smul
/-- When `α` is a `*`-(semi)ring, `Matrix.star` is also a `*`-(semi)ring. -/
instance [Fintype n] [NonUnitalSemiring α] [StarRing α] : StarRing (Matrix n n α) where
star_add := conjTranspose_add
star_mul := conjTranspose_mul
/-- A version of `star_mul` for `*` instead of `*`. -/
theorem star_mul [Fintype n] [NonUnitalSemiring α] [StarRing α] (M N : Matrix n n α) :
star (M * N) = star N * star M :=
conjTranspose_mul _ _
end Star
/-- Given maps `(r_reindex : l → m)` and `(c_reindex : o → n)` reindexing the rows and columns of
a matrix `M : Matrix m n α`, the matrix `M.submatrix r_reindex c_reindex : Matrix l o α` is defined
by `(M.submatrix r_reindex c_reindex) i j = M (r_reindex i) (c_reindex j)` for `(i,j) : l × o`.
Note that the total number of row and columns does not have to be preserved. -/
def submatrix (A : Matrix m n α) (r_reindex : l → m) (c_reindex : o → n) : Matrix l o α :=
of fun i j => A (r_reindex i) (c_reindex j)
@[simp]
theorem submatrix_apply (A : Matrix m n α) (r_reindex : l → m) (c_reindex : o → n) (i j) :
A.submatrix r_reindex c_reindex i j = A (r_reindex i) (c_reindex j) :=
rfl
@[simp]
theorem submatrix_id_id (A : Matrix m n α) : A.submatrix id id = A :=
ext fun _ _ => rfl
@[simp]
theorem submatrix_submatrix {l₂ o₂ : Type*} (A : Matrix m n α) (r₁ : l → m) (c₁ : o → n)
(r₂ : l₂ → l) (c₂ : o₂ → o) :
(A.submatrix r₁ c₁).submatrix r₂ c₂ = A.submatrix (r₁ ∘ r₂) (c₁ ∘ c₂) :=
ext fun _ _ => rfl
@[simp]
theorem transpose_submatrix (A : Matrix m n α) (r_reindex : l → m) (c_reindex : o → n) :
(A.submatrix r_reindex c_reindex)ᵀ = Aᵀ.submatrix c_reindex r_reindex :=
ext fun _ _ => rfl
@[simp]
theorem conjTranspose_submatrix [Star α] (A : Matrix m n α) (r_reindex : l → m)
(c_reindex : o → n) : (A.submatrix r_reindex c_reindex)ᴴ = Aᴴ.submatrix c_reindex r_reindex :=
ext fun _ _ => rfl
theorem submatrix_add [Add α] (A B : Matrix m n α) :
((A + B).submatrix : (l → m) → (o → n) → Matrix l o α) = A.submatrix + B.submatrix :=
rfl
theorem submatrix_neg [Neg α] (A : Matrix m n α) :
((-A).submatrix : (l → m) → (o → n) → Matrix l o α) = -A.submatrix :=
rfl
theorem submatrix_sub [Sub α] (A B : Matrix m n α) :
((A - B).submatrix : (l → m) → (o → n) → Matrix l o α) = A.submatrix - B.submatrix :=
rfl
@[simp]
theorem submatrix_zero [Zero α] :
((0 : Matrix m n α).submatrix : (l → m) → (o → n) → Matrix l o α) = 0 :=
rfl
theorem submatrix_smul {R : Type*} [SMul R α] (r : R) (A : Matrix m n α) :
((r • A : Matrix m n α).submatrix : (l → m) → (o → n) → Matrix l o α) = r • A.submatrix :=
rfl
theorem submatrix_map (f : α → β) (e₁ : l → m) (e₂ : o → n) (A : Matrix m n α) :
(A.map f).submatrix e₁ e₂ = (A.submatrix e₁ e₂).map f :=
rfl
/-- Given a `(m × m)` diagonal matrix defined by a map `d : m → α`, if the reindexing map `e` is
injective, then the resulting matrix is again diagonal. -/
theorem submatrix_diagonal [Zero α] [DecidableEq m] [DecidableEq l] (d : m → α) (e : l → m)
(he : Function.Injective e) : (diagonal d).submatrix e e = diagonal (d ∘ e) :=
ext fun i j => by
rw [submatrix_apply]
by_cases h : i = j
· rw [h, diagonal_apply_eq, diagonal_apply_eq]
simp only [Function.comp_apply] -- Porting note: (simp) added this
· rw [diagonal_apply_ne _ h, diagonal_apply_ne _ (he.ne h)]
theorem submatrix_one [Zero α] [One α] [DecidableEq m] [DecidableEq l] (e : l → m)
(he : Function.Injective e) : (1 : Matrix m m α).submatrix e e = 1 :=
submatrix_diagonal _ e he
theorem submatrix_mul [Fintype n] [Fintype o] [Mul α] [AddCommMonoid α] {p q : Type*}
(M : Matrix m n α) (N : Matrix n p α) (e₁ : l → m) (e₂ : o → n) (e₃ : q → p)
(he₂ : Function.Bijective e₂) :
(M * N).submatrix e₁ e₃ = M.submatrix e₁ e₂ * N.submatrix e₂ e₃ :=
ext fun _ _ => (he₂.sum_comp _).symm
theorem diag_submatrix (A : Matrix m m α) (e : l → m) : diag (A.submatrix e e) = A.diag ∘ e :=
rfl
/-! `simp` lemmas for `Matrix.submatrix`s interaction with `Matrix.diagonal`, `1`, and `Matrix.mul`
for when the mappings are bundled. -/
@[simp]
theorem submatrix_diagonal_embedding [Zero α] [DecidableEq m] [DecidableEq l] (d : m → α)
(e : l ↪ m) : (diagonal d).submatrix e e = diagonal (d ∘ e) :=
submatrix_diagonal d e e.injective
@[simp]
theorem submatrix_diagonal_equiv [Zero α] [DecidableEq m] [DecidableEq l] (d : m → α) (e : l ≃ m) :
(diagonal d).submatrix e e = diagonal (d ∘ e) :=
submatrix_diagonal d e e.injective
@[simp]
theorem submatrix_one_embedding [Zero α] [One α] [DecidableEq m] [DecidableEq l] (e : l ↪ m) :
(1 : Matrix m m α).submatrix e e = 1 :=
submatrix_one e e.injective
@[simp]
theorem submatrix_one_equiv [Zero α] [One α] [DecidableEq m] [DecidableEq l] (e : l ≃ m) :
(1 : Matrix m m α).submatrix e e = 1 :=
submatrix_one e e.injective
@[simp]
theorem submatrix_mul_equiv [Fintype n] [Fintype o] [AddCommMonoid α] [Mul α] {p q : Type*}
(M : Matrix m n α) (N : Matrix n p α) (e₁ : l → m) (e₂ : o ≃ n) (e₃ : q → p) :
M.submatrix e₁ e₂ * N.submatrix e₂ e₃ = (M * N).submatrix e₁ e₃ :=
(submatrix_mul M N e₁ e₂ e₃ e₂.bijective).symm
theorem submatrix_mulVec_equiv [Fintype n] [Fintype o] [NonUnitalNonAssocSemiring α]
(M : Matrix m n α) (v : o → α) (e₁ : l → m) (e₂ : o ≃ n) :
M.submatrix e₁ e₂ *ᵥ v = (M *ᵥ (v ∘ e₂.symm)) ∘ e₁ :=
funext fun _ => Eq.symm (dotProduct_comp_equiv_symm _ _ _)
theorem submatrix_vecMul_equiv [Fintype l] [Fintype m] [NonUnitalNonAssocSemiring α]
(M : Matrix m n α) (v : l → α) (e₁ : l ≃ m) (e₂ : o → n) :
v ᵥ* M.submatrix e₁ e₂ = ((v ∘ e₁.symm) ᵥ* M) ∘ e₂ :=
funext fun _ => Eq.symm (comp_equiv_symm_dotProduct _ _ _)
theorem mul_submatrix_one [Fintype n] [Finite o] [NonAssocSemiring α] [DecidableEq o] (e₁ : n ≃ o)
(e₂ : l → o) (M : Matrix m n α) :
M * (1 : Matrix o o α).submatrix e₁ e₂ = submatrix M id (e₁.symm ∘ e₂) := by
cases nonempty_fintype o
let A := M.submatrix id e₁.symm
have : M = A.submatrix id e₁ := by
simp only [A, submatrix_submatrix, Function.comp_id, submatrix_id_id, Equiv.symm_comp_self]
rw [this, submatrix_mul_equiv]
simp only [A, Matrix.mul_one, submatrix_submatrix, Function.comp_id, submatrix_id_id,
Equiv.symm_comp_self]
theorem one_submatrix_mul [Fintype m] [Finite o] [NonAssocSemiring α] [DecidableEq o] (e₁ : l → o)
(e₂ : m ≃ o) (M : Matrix m n α) :
((1 : Matrix o o α).submatrix e₁ e₂) * M = submatrix M (e₂.symm ∘ e₁) id := by
cases nonempty_fintype o
let A := M.submatrix e₂.symm id
have : M = A.submatrix e₂ id := by
simp only [A, submatrix_submatrix, Function.comp_id, submatrix_id_id, Equiv.symm_comp_self]
rw [this, submatrix_mul_equiv]
simp only [A, Matrix.one_mul, submatrix_submatrix, Function.comp_id, submatrix_id_id,
Equiv.symm_comp_self]
/-- The natural map that reindexes a matrix's rows and columns with equivalent types is an
equivalence. -/
def reindex (eₘ : m ≃ l) (eₙ : n ≃ o) : Matrix m n α ≃ Matrix l o α where
toFun M := M.submatrix eₘ.symm eₙ.symm
invFun M := M.submatrix eₘ eₙ
left_inv M := by simp
right_inv M := by simp
@[simp]
theorem reindex_apply (eₘ : m ≃ l) (eₙ : n ≃ o) (M : Matrix m n α) :
reindex eₘ eₙ M = M.submatrix eₘ.symm eₙ.symm :=
rfl
-- @[simp] -- Porting note (#10618): simp can prove this
theorem reindex_refl_refl (A : Matrix m n α) : reindex (Equiv.refl _) (Equiv.refl _) A = A :=
A.submatrix_id_id
@[simp]
theorem reindex_symm (eₘ : m ≃ l) (eₙ : n ≃ o) :
(reindex eₘ eₙ).symm = (reindex eₘ.symm eₙ.symm : Matrix l o α ≃ _) :=
rfl
@[simp]
theorem reindex_trans {l₂ o₂ : Type*} (eₘ : m ≃ l) (eₙ : n ≃ o) (eₘ₂ : l ≃ l₂) (eₙ₂ : o ≃ o₂) :
(reindex eₘ eₙ).trans (reindex eₘ₂ eₙ₂) =
(reindex (eₘ.trans eₘ₂) (eₙ.trans eₙ₂) : Matrix m n α ≃ _) :=
Equiv.ext fun A => (A.submatrix_submatrix eₘ.symm eₙ.symm eₘ₂.symm eₙ₂.symm : _)
theorem transpose_reindex (eₘ : m ≃ l) (eₙ : n ≃ o) (M : Matrix m n α) :
(reindex eₘ eₙ M)ᵀ = reindex eₙ eₘ Mᵀ :=
rfl
theorem conjTranspose_reindex [Star α] (eₘ : m ≃ l) (eₙ : n ≃ o) (M : Matrix m n α) :
(reindex eₘ eₙ M)ᴴ = reindex eₙ eₘ Mᴴ :=
rfl
-- @[simp] -- Porting note (#10618): simp can prove this
theorem submatrix_mul_transpose_submatrix [Fintype m] [Fintype n] [AddCommMonoid α] [Mul α]
(e : m ≃ n) (M : Matrix m n α) : M.submatrix id e * Mᵀ.submatrix e id = M * Mᵀ := by
rw [submatrix_mul_equiv, submatrix_id_id]
/-- The left `n × l` part of an `n × (l+r)` matrix. -/
abbrev subLeft {m l r : Nat} (A : Matrix (Fin m) (Fin (l + r)) α) : Matrix (Fin m) (Fin l) α :=
submatrix A id (Fin.castAdd r)
/-- The right `n × r` part of an `n × (l+r)` matrix. -/
abbrev subRight {m l r : Nat} (A : Matrix (Fin m) (Fin (l + r)) α) : Matrix (Fin m) (Fin r) α :=
submatrix A id (Fin.natAdd l)
/-- The top `u × n` part of a `(u+d) × n` matrix. -/
abbrev subUp {d u n : Nat} (A : Matrix (Fin (u + d)) (Fin n) α) : Matrix (Fin u) (Fin n) α :=
submatrix A (Fin.castAdd d) id
/-- The bottom `d × n` part of a `(u+d) × n` matrix. -/
abbrev subDown {d u n : Nat} (A : Matrix (Fin (u + d)) (Fin n) α) : Matrix (Fin d) (Fin n) α :=
submatrix A (Fin.natAdd u) id
/-- The top-right `u × r` part of a `(u+d) × (l+r)` matrix. -/
abbrev subUpRight {d u l r : Nat} (A : Matrix (Fin (u + d)) (Fin (l + r)) α) :
Matrix (Fin u) (Fin r) α :=
subUp (subRight A)
/-- The bottom-right `d × r` part of a `(u+d) × (l+r)` matrix. -/
abbrev subDownRight {d u l r : Nat} (A : Matrix (Fin (u + d)) (Fin (l + r)) α) :
Matrix (Fin d) (Fin r) α :=
subDown (subRight A)
/-- The top-left `u × l` part of a `(u+d) × (l+r)` matrix. -/
abbrev subUpLeft {d u l r : Nat} (A : Matrix (Fin (u + d)) (Fin (l + r)) α) :
Matrix (Fin u) (Fin l) α :=
subUp (subLeft A)
/-- The bottom-left `d × l` part of a `(u+d) × (l+r)` matrix. -/
abbrev subDownLeft {d u l r : Nat} (A : Matrix (Fin (u + d)) (Fin (l + r)) α) :
Matrix (Fin d) (Fin l) α :=
subDown (subLeft A)
end Matrix
namespace RingHom
variable [Fintype n] [NonAssocSemiring α] [NonAssocSemiring β]
theorem map_matrix_mul (M : Matrix m n α) (N : Matrix n o α) (i : m) (j : o) (f : α →+* β) :
f ((M * N) i j) = (M.map f * N.map f) i j := by
simp [Matrix.mul_apply, map_sum]
theorem map_dotProduct [NonAssocSemiring R] [NonAssocSemiring S] (f : R →+* S) (v w : n → R) :
f (v ⬝ᵥ w) = f ∘ v ⬝ᵥ f ∘ w := by
simp only [Matrix.dotProduct, map_sum f, f.map_mul, Function.comp]
theorem map_vecMul [NonAssocSemiring R] [NonAssocSemiring S] (f : R →+* S) (M : Matrix n m R)
(v : n → R) (i : m) : f ((v ᵥ* M) i) = ((f ∘ v) ᵥ* M.map f) i := by
simp only [Matrix.vecMul, Matrix.map_apply, RingHom.map_dotProduct, Function.comp]
theorem map_mulVec [NonAssocSemiring R] [NonAssocSemiring S] (f : R →+* S) (M : Matrix m n R)
(v : n → R) (i : m) : f ((M *ᵥ v) i) = (M.map f *ᵥ (f ∘ v)) i := by
simp only [Matrix.mulVec, Matrix.map_apply, RingHom.map_dotProduct, Function.comp]
end RingHom
|
Data\Matrix\Basis.lean | /-
Copyright (c) 2020 Jalex Stark. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jalex Stark, Scott Morrison, Eric Wieser, Oliver Nash, Wen Yang
-/
import Mathlib.Data.Matrix.Basic
import Mathlib.LinearAlgebra.Matrix.Trace
/-!
# Matrices with a single non-zero element.
This file provides `Matrix.stdBasisMatrix`. The matrix `Matrix.stdBasisMatrix i j c` has `c`
at position `(i, j)`, and zeroes elsewhere.
-/
variable {l m n : Type*}
variable {R α : Type*}
namespace Matrix
open Matrix
variable [DecidableEq l] [DecidableEq m] [DecidableEq n]
variable [Semiring α]
/-- `stdBasisMatrix i j a` is the matrix with `a` in the `i`-th row, `j`-th column,
and zeroes elsewhere.
-/
def stdBasisMatrix (i : m) (j : n) (a : α) : Matrix m n α := fun i' j' =>
if i = i' ∧ j = j' then a else 0
@[simp]
theorem smul_stdBasisMatrix [SMulZeroClass R α] (r : R) (i : m) (j : n) (a : α) :
r • stdBasisMatrix i j a = stdBasisMatrix i j (r • a) := by
unfold stdBasisMatrix
ext
simp [smul_ite]
@[simp]
theorem stdBasisMatrix_zero (i : m) (j : n) : stdBasisMatrix i j (0 : α) = 0 := by
unfold stdBasisMatrix
ext
simp
theorem stdBasisMatrix_add (i : m) (j : n) (a b : α) :
stdBasisMatrix i j (a + b) = stdBasisMatrix i j a + stdBasisMatrix i j b := by
unfold stdBasisMatrix; ext
split_ifs with h <;> simp [h]
theorem mulVec_stdBasisMatrix [Fintype m] (i : n) (j : m) (c : α) (x : m → α) :
mulVec (stdBasisMatrix i j c) x = Function.update (0 : n → α) i (c * x j) := by
ext i'
simp [stdBasisMatrix, mulVec, dotProduct]
rcases eq_or_ne i i' with rfl|h
· simp
simp [h, h.symm]
theorem matrix_eq_sum_std_basis [Fintype m] [Fintype n] (x : Matrix m n α) :
x = ∑ i : m, ∑ j : n, stdBasisMatrix i j (x i j) := by
ext i j; symm
iterate 2 rw [Finset.sum_apply]
convert (Fintype.sum_eq_single i ?_).trans ?_; swap
· -- Porting note(#12717): `simp` seems unwilling to apply `Fintype.sum_apply`
simp (config := { unfoldPartialApp := true }) [stdBasisMatrix, (Fintype.sum_apply)]
· intro j' hj'
-- Porting note(#12717): `simp` seems unwilling to apply `Fintype.sum_apply`
simp (config := { unfoldPartialApp := true }) [stdBasisMatrix, (Fintype.sum_apply), hj']
-- TODO: tie this up with the `Basis` machinery of linear algebra
-- this is not completely trivial because we are indexing by two types, instead of one
-- TODO: add `std_basis_vec`
theorem std_basis_eq_basis_mul_basis (i : m) (j : n) :
stdBasisMatrix i j (1 : α) =
vecMulVec (fun i' => ite (i = i') 1 0) fun j' => ite (j = j') 1 0 := by
ext i' j'
-- Porting note: lean3 didn't apply `mul_ite`.
simp [-mul_ite, stdBasisMatrix, vecMulVec, ite_and]
-- todo: the old proof used fintypes, I don't know `Finsupp` but this feels generalizable
@[elab_as_elim]
protected theorem induction_on' [Finite m] [Finite n] {P : Matrix m n α → Prop} (M : Matrix m n α)
(h_zero : P 0) (h_add : ∀ p q, P p → P q → P (p + q))
(h_std_basis : ∀ (i : m) (j : n) (x : α), P (stdBasisMatrix i j x)) : P M := by
cases nonempty_fintype m; cases nonempty_fintype n
rw [matrix_eq_sum_std_basis M, ← Finset.sum_product']
apply Finset.sum_induction _ _ h_add h_zero
· intros
apply h_std_basis
@[elab_as_elim]
protected theorem induction_on [Finite m] [Finite n] [Nonempty m] [Nonempty n]
{P : Matrix m n α → Prop} (M : Matrix m n α) (h_add : ∀ p q, P p → P q → P (p + q))
(h_std_basis : ∀ i j x, P (stdBasisMatrix i j x)) : P M :=
Matrix.induction_on' M
(by
inhabit m
inhabit n
simpa using h_std_basis default default 0)
h_add h_std_basis
namespace StdBasisMatrix
section
variable (i : m) (j : n) (c : α) (i' : m) (j' : n)
@[simp]
theorem apply_same : stdBasisMatrix i j c i j = c :=
if_pos (And.intro rfl rfl)
@[simp]
theorem apply_of_ne (h : ¬(i = i' ∧ j = j')) : stdBasisMatrix i j c i' j' = 0 := by
simp only [stdBasisMatrix, and_imp, ite_eq_right_iff]
tauto
@[simp]
theorem apply_of_row_ne {i i' : m} (hi : i ≠ i') (j j' : n) (a : α) :
stdBasisMatrix i j a i' j' = 0 := by simp [hi]
@[simp]
theorem apply_of_col_ne (i i' : m) {j j' : n} (hj : j ≠ j') (a : α) :
stdBasisMatrix i j a i' j' = 0 := by simp [hj]
end
section
variable (i j : n) (c : α) (i' j' : n)
@[simp]
theorem diag_zero (h : j ≠ i) : diag (stdBasisMatrix i j c) = 0 :=
funext fun _ => if_neg fun ⟨e₁, e₂⟩ => h (e₂.trans e₁.symm)
@[simp]
theorem diag_same : diag (stdBasisMatrix i i c) = Pi.single i c := by
ext j
by_cases hij : i = j <;> (try rw [hij]) <;> simp [hij]
variable [Fintype n]
@[simp]
theorem trace_zero (h : j ≠ i) : trace (stdBasisMatrix i j c) = 0 := by
-- Porting note: added `-diag_apply`
simp [trace, -diag_apply, h]
@[simp]
theorem trace_eq : trace (stdBasisMatrix i i c) = c := by
-- Porting note: added `-diag_apply`
simp [trace, -diag_apply]
@[simp]
theorem mul_left_apply_same (b : n) (M : Matrix n n α) :
(stdBasisMatrix i j c * M) i b = c * M j b := by simp [mul_apply, stdBasisMatrix]
@[simp]
theorem mul_right_apply_same (a : n) (M : Matrix n n α) :
(M * stdBasisMatrix i j c) a j = M a i * c := by simp [mul_apply, stdBasisMatrix, mul_comm]
@[simp]
theorem mul_left_apply_of_ne (a b : n) (h : a ≠ i) (M : Matrix n n α) :
(stdBasisMatrix i j c * M) a b = 0 := by simp [mul_apply, h.symm]
@[simp]
theorem mul_right_apply_of_ne (a b : n) (hbj : b ≠ j) (M : Matrix n n α) :
(M * stdBasisMatrix i j c) a b = 0 := by simp [mul_apply, hbj.symm]
@[simp]
theorem mul_same (k : n) (d : α) :
stdBasisMatrix i j c * stdBasisMatrix j k d = stdBasisMatrix i k (c * d) := by
ext a b
simp only [mul_apply, stdBasisMatrix, boole_mul]
by_cases h₁ : i = a <;> by_cases h₂ : k = b <;> simp [h₁, h₂]
@[simp]
theorem mul_of_ne {k l : n} (h : j ≠ k) (d : α) :
stdBasisMatrix i j c * stdBasisMatrix k l d = 0 := by
ext a b
simp only [mul_apply, boole_mul, stdBasisMatrix]
by_cases h₁ : i = a
-- porting note (#10745): was `simp [h₁, h, h.symm]`
· simp only [h₁, true_and, mul_ite, ite_mul, zero_mul, mul_zero, ← ite_and, zero_apply]
refine Finset.sum_eq_zero (fun x _ => ?_)
apply if_neg
rintro ⟨⟨rfl, rfl⟩, h⟩
contradiction
· simp only [h₁, false_and, ite_false, mul_ite, zero_mul, mul_zero, ite_self,
Finset.sum_const_zero, zero_apply]
end
end StdBasisMatrix
section Commute
variable [Fintype n]
theorem row_eq_zero_of_commute_stdBasisMatrix {i j k : n} {M : Matrix n n α}
(hM : Commute (stdBasisMatrix i j 1) M) (hkj : k ≠ j) : M j k = 0 := by
have := ext_iff.mpr hM i k
aesop
theorem col_eq_zero_of_commute_stdBasisMatrix {i j k : n} {M : Matrix n n α}
(hM : Commute (stdBasisMatrix i j 1) M) (hki : k ≠ i) : M k i = 0 := by
have := ext_iff.mpr hM k j
aesop
theorem diag_eq_of_commute_stdBasisMatrix {i j : n} {M : Matrix n n α}
(hM : Commute (stdBasisMatrix i j 1) M) : M i i = M j j := by
have := ext_iff.mpr hM i j
aesop
/-- `M` is a scalar matrix if it commutes with every non-diagonal `stdBasisMatrix`. -/
theorem mem_range_scalar_of_commute_stdBasisMatrix {M : Matrix n n α}
(hM : Pairwise fun i j => Commute (stdBasisMatrix i j 1) M) :
M ∈ Set.range (Matrix.scalar n) := by
cases isEmpty_or_nonempty n
· exact ⟨0, Subsingleton.elim _ _⟩
obtain ⟨i⟩ := ‹Nonempty n›
refine ⟨M i i, Matrix.ext fun j k => ?_⟩
simp only [scalar_apply]
obtain rfl | hkl := Decidable.eq_or_ne j k
· rw [diagonal_apply_eq]
obtain rfl | hij := Decidable.eq_or_ne i j
· rfl
· exact diag_eq_of_commute_stdBasisMatrix (hM hij)
· rw [diagonal_apply_ne _ hkl]
obtain rfl | hij := Decidable.eq_or_ne i j
· rw [col_eq_zero_of_commute_stdBasisMatrix (hM hkl.symm) hkl]
· rw [row_eq_zero_of_commute_stdBasisMatrix (hM hij) hkl.symm]
theorem mem_range_scalar_iff_commute_stdBasisMatrix {M : Matrix n n α} :
M ∈ Set.range (Matrix.scalar n) ↔ ∀ (i j : n), i ≠ j → Commute (stdBasisMatrix i j 1) M := by
refine ⟨fun ⟨r, hr⟩ i j _ => hr ▸ Commute.symm ?_, mem_range_scalar_of_commute_stdBasisMatrix⟩
rw [scalar_commute_iff]
simp
/-- `M` is a scalar matrix if and only if it commutes with every `stdBasisMatrix`. -/
theorem mem_range_scalar_iff_commute_stdBasisMatrix' {M : Matrix n n α} :
M ∈ Set.range (Matrix.scalar n) ↔ ∀ (i j : n), Commute (stdBasisMatrix i j 1) M := by
refine ⟨fun ⟨r, hr⟩ i j => hr ▸ Commute.symm ?_,
fun hM => mem_range_scalar_iff_commute_stdBasisMatrix.mpr <| fun i j _ => hM i j⟩
rw [scalar_commute_iff]
simp
end Commute
end Matrix
|
Data\Matrix\Block.lean | /-
Copyright (c) 2018 Ellen Arlt. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin
-/
import Mathlib.Data.Matrix.Basic
/-!
# Block Matrices
## Main definitions
* `Matrix.fromBlocks`: build a block matrix out of 4 blocks
* `Matrix.toBlocks₁₁`, `Matrix.toBlocks₁₂`, `Matrix.toBlocks₂₁`, `Matrix.toBlocks₂₂`:
extract each of the four blocks from `Matrix.fromBlocks`.
* `Matrix.blockDiagonal`: block diagonal of equally sized blocks. On square blocks, this is a
ring homomorphisms, `Matrix.blockDiagonalRingHom`.
* `Matrix.blockDiag`: extract the blocks from the diagonal of a block diagonal matrix.
* `Matrix.blockDiagonal'`: block diagonal of unequally sized blocks. On square blocks, this is a
ring homomorphisms, `Matrix.blockDiagonal'RingHom`.
* `Matrix.blockDiag'`: extract the blocks from the diagonal of a block diagonal matrix.
-/
variable {l m n o p q : Type*} {m' n' p' : o → Type*}
variable {R : Type*} {S : Type*} {α : Type*} {β : Type*}
open Matrix
namespace Matrix
theorem dotProduct_block [Fintype m] [Fintype n] [Mul α] [AddCommMonoid α] (v w : m ⊕ n → α) :
v ⬝ᵥ w = v ∘ Sum.inl ⬝ᵥ w ∘ Sum.inl + v ∘ Sum.inr ⬝ᵥ w ∘ Sum.inr :=
Fintype.sum_sum_type _
section BlockMatrices
/-- We can form a single large matrix by flattening smaller 'block' matrices of compatible
dimensions. -/
@[pp_nodot]
def fromBlocks (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α) (D : Matrix o m α) :
Matrix (n ⊕ o) (l ⊕ m) α :=
of <| Sum.elim (fun i => Sum.elim (A i) (B i)) fun i => Sum.elim (C i) (D i)
@[simp]
theorem fromBlocks_apply₁₁ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) (i : n) (j : l) : fromBlocks A B C D (Sum.inl i) (Sum.inl j) = A i j :=
rfl
@[simp]
theorem fromBlocks_apply₁₂ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) (i : n) (j : m) : fromBlocks A B C D (Sum.inl i) (Sum.inr j) = B i j :=
rfl
@[simp]
theorem fromBlocks_apply₂₁ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) (i : o) (j : l) : fromBlocks A B C D (Sum.inr i) (Sum.inl j) = C i j :=
rfl
@[simp]
theorem fromBlocks_apply₂₂ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) (i : o) (j : m) : fromBlocks A B C D (Sum.inr i) (Sum.inr j) = D i j :=
rfl
/-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding
"top left" submatrix. -/
def toBlocks₁₁ (M : Matrix (n ⊕ o) (l ⊕ m) α) : Matrix n l α :=
of fun i j => M (Sum.inl i) (Sum.inl j)
/-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding
"top right" submatrix. -/
def toBlocks₁₂ (M : Matrix (n ⊕ o) (l ⊕ m) α) : Matrix n m α :=
of fun i j => M (Sum.inl i) (Sum.inr j)
/-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding
"bottom left" submatrix. -/
def toBlocks₂₁ (M : Matrix (n ⊕ o) (l ⊕ m) α) : Matrix o l α :=
of fun i j => M (Sum.inr i) (Sum.inl j)
/-- Given a matrix whose row and column indexes are sum types, we can extract the corresponding
"bottom right" submatrix. -/
def toBlocks₂₂ (M : Matrix (n ⊕ o) (l ⊕ m) α) : Matrix o m α :=
of fun i j => M (Sum.inr i) (Sum.inr j)
theorem fromBlocks_toBlocks (M : Matrix (n ⊕ o) (l ⊕ m) α) :
fromBlocks M.toBlocks₁₁ M.toBlocks₁₂ M.toBlocks₂₁ M.toBlocks₂₂ = M := by
ext i j
rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> rfl
@[simp]
theorem toBlocks_fromBlocks₁₁ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) : (fromBlocks A B C D).toBlocks₁₁ = A :=
rfl
@[simp]
theorem toBlocks_fromBlocks₁₂ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) : (fromBlocks A B C D).toBlocks₁₂ = B :=
rfl
@[simp]
theorem toBlocks_fromBlocks₂₁ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) : (fromBlocks A B C D).toBlocks₂₁ = C :=
rfl
@[simp]
theorem toBlocks_fromBlocks₂₂ (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) : (fromBlocks A B C D).toBlocks₂₂ = D :=
rfl
/-- Two block matrices are equal if their blocks are equal. -/
theorem ext_iff_blocks {A B : Matrix (n ⊕ o) (l ⊕ m) α} :
A = B ↔
A.toBlocks₁₁ = B.toBlocks₁₁ ∧
A.toBlocks₁₂ = B.toBlocks₁₂ ∧ A.toBlocks₂₁ = B.toBlocks₂₁ ∧ A.toBlocks₂₂ = B.toBlocks₂₂ :=
⟨fun h => h ▸ ⟨rfl, rfl, rfl, rfl⟩, fun ⟨h₁₁, h₁₂, h₂₁, h₂₂⟩ => by
rw [← fromBlocks_toBlocks A, ← fromBlocks_toBlocks B, h₁₁, h₁₂, h₂₁, h₂₂]⟩
@[simp]
theorem fromBlocks_inj {A : Matrix n l α} {B : Matrix n m α} {C : Matrix o l α} {D : Matrix o m α}
{A' : Matrix n l α} {B' : Matrix n m α} {C' : Matrix o l α} {D' : Matrix o m α} :
fromBlocks A B C D = fromBlocks A' B' C' D' ↔ A = A' ∧ B = B' ∧ C = C' ∧ D = D' :=
ext_iff_blocks
theorem fromBlocks_map (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α) (D : Matrix o m α)
(f : α → β) : (fromBlocks A B C D).map f =
fromBlocks (A.map f) (B.map f) (C.map f) (D.map f) := by
ext i j; rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> simp [fromBlocks]
theorem fromBlocks_transpose (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) : (fromBlocks A B C D)ᵀ = fromBlocks Aᵀ Cᵀ Bᵀ Dᵀ := by
ext i j
rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> simp [fromBlocks]
theorem fromBlocks_conjTranspose [Star α] (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) : (fromBlocks A B C D)ᴴ = fromBlocks Aᴴ Cᴴ Bᴴ Dᴴ := by
simp only [conjTranspose, fromBlocks_transpose, fromBlocks_map]
@[simp]
theorem fromBlocks_submatrix_sum_swap_left (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) (f : p → l ⊕ m) :
(fromBlocks A B C D).submatrix Sum.swap f = (fromBlocks C D A B).submatrix id f := by
ext i j
cases i <;> dsimp <;> cases f j <;> rfl
@[simp]
theorem fromBlocks_submatrix_sum_swap_right (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) (f : p → n ⊕ o) :
(fromBlocks A B C D).submatrix f Sum.swap = (fromBlocks B A D C).submatrix f id := by
ext i j
cases j <;> dsimp <;> cases f i <;> rfl
theorem fromBlocks_submatrix_sum_swap_sum_swap {l m n o α : Type*} (A : Matrix n l α)
(B : Matrix n m α) (C : Matrix o l α) (D : Matrix o m α) :
(fromBlocks A B C D).submatrix Sum.swap Sum.swap = fromBlocks D C B A := by simp
/-- A 2x2 block matrix is block diagonal if the blocks outside of the diagonal vanish -/
def IsTwoBlockDiagonal [Zero α] (A : Matrix (n ⊕ o) (l ⊕ m) α) : Prop :=
toBlocks₁₂ A = 0 ∧ toBlocks₂₁ A = 0
/-- Let `p` pick out certain rows and `q` pick out certain columns of a matrix `M`. Then
`toBlock M p q` is the corresponding block matrix. -/
def toBlock (M : Matrix m n α) (p : m → Prop) (q : n → Prop) : Matrix { a // p a } { a // q a } α :=
M.submatrix (↑) (↑)
@[simp]
theorem toBlock_apply (M : Matrix m n α) (p : m → Prop) (q : n → Prop) (i : { a // p a })
(j : { a // q a }) : toBlock M p q i j = M ↑i ↑j :=
rfl
/-- Let `p` pick out certain rows and columns of a square matrix `M`. Then
`toSquareBlockProp M p` is the corresponding block matrix. -/
def toSquareBlockProp (M : Matrix m m α) (p : m → Prop) : Matrix { a // p a } { a // p a } α :=
toBlock M _ _
theorem toSquareBlockProp_def (M : Matrix m m α) (p : m → Prop) :
-- Porting note: added missing `of`
toSquareBlockProp M p = of (fun i j : { a // p a } => M ↑i ↑j) :=
rfl
/-- Let `b` map rows and columns of a square matrix `M` to blocks. Then
`toSquareBlock M b k` is the block `k` matrix. -/
def toSquareBlock (M : Matrix m m α) (b : m → β) (k : β) :
Matrix { a // b a = k } { a // b a = k } α :=
toSquareBlockProp M _
theorem toSquareBlock_def (M : Matrix m m α) (b : m → β) (k : β) :
-- Porting note: added missing `of`
toSquareBlock M b k = of (fun i j : { a // b a = k } => M ↑i ↑j) :=
rfl
theorem fromBlocks_smul [SMul R α] (x : R) (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) : x • fromBlocks A B C D = fromBlocks (x • A) (x • B) (x • C) (x • D) := by
ext i j; rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> simp [fromBlocks]
theorem fromBlocks_neg [Neg R] (A : Matrix n l R) (B : Matrix n m R) (C : Matrix o l R)
(D : Matrix o m R) : -fromBlocks A B C D = fromBlocks (-A) (-B) (-C) (-D) := by
ext i j
cases i <;> cases j <;> simp [fromBlocks]
@[simp]
theorem fromBlocks_zero [Zero α] : fromBlocks (0 : Matrix n l α) 0 0 (0 : Matrix o m α) = 0 := by
ext i j
rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> rfl
theorem fromBlocks_add [Add α] (A : Matrix n l α) (B : Matrix n m α) (C : Matrix o l α)
(D : Matrix o m α) (A' : Matrix n l α) (B' : Matrix n m α) (C' : Matrix o l α)
(D' : Matrix o m α) : fromBlocks A B C D + fromBlocks A' B' C' D' =
fromBlocks (A + A') (B + B') (C + C') (D + D') := by
ext i j; rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> rfl
theorem fromBlocks_multiply [Fintype l] [Fintype m] [NonUnitalNonAssocSemiring α] (A : Matrix n l α)
(B : Matrix n m α) (C : Matrix o l α) (D : Matrix o m α) (A' : Matrix l p α) (B' : Matrix l q α)
(C' : Matrix m p α) (D' : Matrix m q α) :
fromBlocks A B C D * fromBlocks A' B' C' D' =
fromBlocks (A * A' + B * C') (A * B' + B * D') (C * A' + D * C') (C * B' + D * D') := by
ext i j
rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> simp only [fromBlocks, mul_apply, of_apply,
Sum.elim_inr, Fintype.sum_sum_type, Sum.elim_inl, add_apply]
theorem fromBlocks_mulVec [Fintype l] [Fintype m] [NonUnitalNonAssocSemiring α] (A : Matrix n l α)
(B : Matrix n m α) (C : Matrix o l α) (D : Matrix o m α) (x : l ⊕ m → α) :
(fromBlocks A B C D) *ᵥ x =
Sum.elim (A *ᵥ (x ∘ Sum.inl) + B *ᵥ (x ∘ Sum.inr))
(C *ᵥ (x ∘ Sum.inl) + D *ᵥ (x ∘ Sum.inr)) := by
ext i
cases i <;> simp [mulVec, dotProduct]
theorem vecMul_fromBlocks [Fintype n] [Fintype o] [NonUnitalNonAssocSemiring α] (A : Matrix n l α)
(B : Matrix n m α) (C : Matrix o l α) (D : Matrix o m α) (x : n ⊕ o → α) :
x ᵥ* fromBlocks A B C D =
Sum.elim ((x ∘ Sum.inl) ᵥ* A + (x ∘ Sum.inr) ᵥ* C)
((x ∘ Sum.inl) ᵥ* B + (x ∘ Sum.inr) ᵥ* D) := by
ext i
cases i <;> simp [vecMul, dotProduct]
variable [DecidableEq l] [DecidableEq m]
section Zero
variable [Zero α]
theorem toBlock_diagonal_self (d : m → α) (p : m → Prop) :
Matrix.toBlock (diagonal d) p p = diagonal fun i : Subtype p => d ↑i := by
ext i j
by_cases h : i = j
· simp [h]
· simp [One.one, h, Subtype.val_injective.ne h]
theorem toBlock_diagonal_disjoint (d : m → α) {p q : m → Prop} (hpq : Disjoint p q) :
Matrix.toBlock (diagonal d) p q = 0 := by
ext ⟨i, hi⟩ ⟨j, hj⟩
have : i ≠ j := fun heq => hpq.le_bot i ⟨hi, heq.symm ▸ hj⟩
simp [diagonal_apply_ne d this]
@[simp]
theorem fromBlocks_diagonal (d₁ : l → α) (d₂ : m → α) :
fromBlocks (diagonal d₁) 0 0 (diagonal d₂) = diagonal (Sum.elim d₁ d₂) := by
ext i j
rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> simp [diagonal]
@[simp]
lemma toBlocks₁₁_diagonal (v : l ⊕ m → α) :
toBlocks₁₁ (diagonal v) = diagonal (fun i => v (Sum.inl i)) := by
unfold toBlocks₁₁
funext i j
simp only [ne_eq, Sum.inl.injEq, of_apply, diagonal_apply]
@[simp]
lemma toBlocks₂₂_diagonal (v : l ⊕ m → α) :
toBlocks₂₂ (diagonal v) = diagonal (fun i => v (Sum.inr i)) := by
unfold toBlocks₂₂
funext i j
simp only [ne_eq, Sum.inr.injEq, of_apply, diagonal_apply]
@[simp]
lemma toBlocks₁₂_diagonal (v : l ⊕ m → α) : toBlocks₁₂ (diagonal v) = 0 := rfl
@[simp]
lemma toBlocks₂₁_diagonal (v : l ⊕ m → α) : toBlocks₂₁ (diagonal v) = 0 := rfl
end Zero
section HasZeroHasOne
variable [Zero α] [One α]
@[simp]
theorem fromBlocks_one : fromBlocks (1 : Matrix l l α) 0 0 (1 : Matrix m m α) = 1 := by
ext i j
rcases i with ⟨⟩ <;> rcases j with ⟨⟩ <;> simp [one_apply]
@[simp]
theorem toBlock_one_self (p : m → Prop) : Matrix.toBlock (1 : Matrix m m α) p p = 1 :=
toBlock_diagonal_self _ p
theorem toBlock_one_disjoint {p q : m → Prop} (hpq : Disjoint p q) :
Matrix.toBlock (1 : Matrix m m α) p q = 0 :=
toBlock_diagonal_disjoint _ hpq
end HasZeroHasOne
end BlockMatrices
section BlockDiagonal
variable [DecidableEq o]
section Zero
variable [Zero α] [Zero β]
/-- `Matrix.blockDiagonal M` turns a homogenously-indexed collection of matrices
`M : o → Matrix m n α'` into an `m × o`-by-`n × o` block matrix which has the entries of `M` along
the diagonal and zero elsewhere.
See also `Matrix.blockDiagonal'` if the matrices may not have the same size everywhere.
-/
def blockDiagonal (M : o → Matrix m n α) : Matrix (m × o) (n × o) α :=
of <| (fun ⟨i, k⟩ ⟨j, k'⟩ => if k = k' then M k i j else 0 : m × o → n × o → α)
-- TODO: set as an equation lemma for `blockDiagonal`, see mathlib4#3024
theorem blockDiagonal_apply' (M : o → Matrix m n α) (i k j k') :
blockDiagonal M ⟨i, k⟩ ⟨j, k'⟩ = if k = k' then M k i j else 0 :=
rfl
theorem blockDiagonal_apply (M : o → Matrix m n α) (ik jk) :
blockDiagonal M ik jk = if ik.2 = jk.2 then M ik.2 ik.1 jk.1 else 0 := by
cases ik
cases jk
rfl
@[simp]
theorem blockDiagonal_apply_eq (M : o → Matrix m n α) (i j k) :
blockDiagonal M (i, k) (j, k) = M k i j :=
if_pos rfl
theorem blockDiagonal_apply_ne (M : o → Matrix m n α) (i j) {k k'} (h : k ≠ k') :
blockDiagonal M (i, k) (j, k') = 0 :=
if_neg h
theorem blockDiagonal_map (M : o → Matrix m n α) (f : α → β) (hf : f 0 = 0) :
(blockDiagonal M).map f = blockDiagonal fun k => (M k).map f := by
ext
simp only [map_apply, blockDiagonal_apply, eq_comm]
rw [apply_ite f, hf]
@[simp]
theorem blockDiagonal_transpose (M : o → Matrix m n α) :
(blockDiagonal M)ᵀ = blockDiagonal fun k => (M k)ᵀ := by
ext
simp only [transpose_apply, blockDiagonal_apply, eq_comm]
split_ifs with h
· rw [h]
· rfl
@[simp]
theorem blockDiagonal_conjTranspose {α : Type*} [AddMonoid α] [StarAddMonoid α]
(M : o → Matrix m n α) : (blockDiagonal M)ᴴ = blockDiagonal fun k => (M k)ᴴ := by
simp only [conjTranspose, blockDiagonal_transpose]
rw [blockDiagonal_map _ star (star_zero α)]
@[simp]
theorem blockDiagonal_zero : blockDiagonal (0 : o → Matrix m n α) = 0 := by
ext
simp [blockDiagonal_apply]
@[simp]
theorem blockDiagonal_diagonal [DecidableEq m] (d : o → m → α) :
(blockDiagonal fun k => diagonal (d k)) = diagonal fun ik => d ik.2 ik.1 := by
ext ⟨i, k⟩ ⟨j, k'⟩
simp only [blockDiagonal_apply, diagonal_apply, Prod.mk.inj_iff, ← ite_and]
congr 1
rw [and_comm]
@[simp]
theorem blockDiagonal_one [DecidableEq m] [One α] : blockDiagonal (1 : o → Matrix m m α) = 1 :=
show (blockDiagonal fun _ : o => diagonal fun _ : m => (1 : α)) = diagonal fun _ => 1 by
rw [blockDiagonal_diagonal]
end Zero
@[simp]
theorem blockDiagonal_add [AddZeroClass α] (M N : o → Matrix m n α) :
blockDiagonal (M + N) = blockDiagonal M + blockDiagonal N := by
ext
simp only [blockDiagonal_apply, Pi.add_apply, add_apply]
split_ifs <;> simp
section
variable (o m n α)
/-- `Matrix.blockDiagonal` as an `AddMonoidHom`. -/
@[simps]
def blockDiagonalAddMonoidHom [AddZeroClass α] :
(o → Matrix m n α) →+ Matrix (m × o) (n × o) α where
toFun := blockDiagonal
map_zero' := blockDiagonal_zero
map_add' := blockDiagonal_add
end
@[simp]
theorem blockDiagonal_neg [AddGroup α] (M : o → Matrix m n α) :
blockDiagonal (-M) = -blockDiagonal M :=
map_neg (blockDiagonalAddMonoidHom m n o α) M
@[simp]
theorem blockDiagonal_sub [AddGroup α] (M N : o → Matrix m n α) :
blockDiagonal (M - N) = blockDiagonal M - blockDiagonal N :=
map_sub (blockDiagonalAddMonoidHom m n o α) M N
@[simp]
theorem blockDiagonal_mul [Fintype n] [Fintype o] [NonUnitalNonAssocSemiring α]
(M : o → Matrix m n α) (N : o → Matrix n p α) :
(blockDiagonal fun k => M k * N k) = blockDiagonal M * blockDiagonal N := by
ext ⟨i, k⟩ ⟨j, k'⟩
simp only [blockDiagonal_apply, mul_apply, ← Finset.univ_product_univ, Finset.sum_product]
split_ifs with h <;> simp [h]
section
variable (α m o)
/-- `Matrix.blockDiagonal` as a `RingHom`. -/
@[simps]
def blockDiagonalRingHom [DecidableEq m] [Fintype o] [Fintype m] [NonAssocSemiring α] :
(o → Matrix m m α) →+* Matrix (m × o) (m × o) α :=
{ blockDiagonalAddMonoidHom m m o α with
toFun := blockDiagonal
map_one' := blockDiagonal_one
map_mul' := blockDiagonal_mul }
end
@[simp]
theorem blockDiagonal_pow [DecidableEq m] [Fintype o] [Fintype m] [Semiring α]
(M : o → Matrix m m α) (n : ℕ) : blockDiagonal (M ^ n) = blockDiagonal M ^ n :=
map_pow (blockDiagonalRingHom m o α) M n
@[simp]
theorem blockDiagonal_smul {R : Type*} [Monoid R] [AddMonoid α] [DistribMulAction R α] (x : R)
(M : o → Matrix m n α) : blockDiagonal (x • M) = x • blockDiagonal M := by
ext
simp only [blockDiagonal_apply, Pi.smul_apply, smul_apply]
split_ifs <;> simp
end BlockDiagonal
section BlockDiag
/-- Extract a block from the diagonal of a block diagonal matrix.
This is the block form of `Matrix.diag`, and the left-inverse of `Matrix.blockDiagonal`. -/
def blockDiag (M : Matrix (m × o) (n × o) α) (k : o) : Matrix m n α :=
of fun i j => M (i, k) (j, k)
-- TODO: set as an equation lemma for `blockDiag`, see mathlib4#3024
theorem blockDiag_apply (M : Matrix (m × o) (n × o) α) (k : o) (i j) :
blockDiag M k i j = M (i, k) (j, k) :=
rfl
theorem blockDiag_map (M : Matrix (m × o) (n × o) α) (f : α → β) :
blockDiag (M.map f) = fun k => (blockDiag M k).map f :=
rfl
@[simp]
theorem blockDiag_transpose (M : Matrix (m × o) (n × o) α) (k : o) :
blockDiag Mᵀ k = (blockDiag M k)ᵀ :=
ext fun _ _ => rfl
@[simp]
theorem blockDiag_conjTranspose {α : Type*} [AddMonoid α] [StarAddMonoid α]
(M : Matrix (m × o) (n × o) α) (k : o) : blockDiag Mᴴ k = (blockDiag M k)ᴴ :=
ext fun _ _ => rfl
section Zero
variable [Zero α] [Zero β]
@[simp]
theorem blockDiag_zero : blockDiag (0 : Matrix (m × o) (n × o) α) = 0 :=
rfl
@[simp]
theorem blockDiag_diagonal [DecidableEq o] [DecidableEq m] (d : m × o → α) (k : o) :
blockDiag (diagonal d) k = diagonal fun i => d (i, k) :=
ext fun i j => by
obtain rfl | hij := Decidable.eq_or_ne i j
· rw [blockDiag_apply, diagonal_apply_eq, diagonal_apply_eq]
· rw [blockDiag_apply, diagonal_apply_ne _ hij, diagonal_apply_ne _ (mt _ hij)]
exact Prod.fst_eq_iff.mpr
@[simp]
theorem blockDiag_blockDiagonal [DecidableEq o] (M : o → Matrix m n α) :
blockDiag (blockDiagonal M) = M :=
funext fun _ => ext fun i j => blockDiagonal_apply_eq M i j _
theorem blockDiagonal_injective [DecidableEq o] :
Function.Injective (blockDiagonal : (o → Matrix m n α) → Matrix _ _ α) :=
Function.LeftInverse.injective blockDiag_blockDiagonal
@[simp]
theorem blockDiagonal_inj [DecidableEq o] {M N : o → Matrix m n α} :
blockDiagonal M = blockDiagonal N ↔ M = N :=
blockDiagonal_injective.eq_iff
@[simp]
theorem blockDiag_one [DecidableEq o] [DecidableEq m] [One α] :
blockDiag (1 : Matrix (m × o) (m × o) α) = 1 :=
funext <| blockDiag_diagonal _
end Zero
@[simp]
theorem blockDiag_add [AddZeroClass α] (M N : Matrix (m × o) (n × o) α) :
blockDiag (M + N) = blockDiag M + blockDiag N :=
rfl
section
variable (o m n α)
/-- `Matrix.blockDiag` as an `AddMonoidHom`. -/
@[simps]
def blockDiagAddMonoidHom [AddZeroClass α] : Matrix (m × o) (n × o) α →+ o → Matrix m n α where
toFun := blockDiag
map_zero' := blockDiag_zero
map_add' := blockDiag_add
end
@[simp]
theorem blockDiag_neg [AddGroup α] (M : Matrix (m × o) (n × o) α) : blockDiag (-M) = -blockDiag M :=
map_neg (blockDiagAddMonoidHom m n o α) M
@[simp]
theorem blockDiag_sub [AddGroup α] (M N : Matrix (m × o) (n × o) α) :
blockDiag (M - N) = blockDiag M - blockDiag N :=
map_sub (blockDiagAddMonoidHom m n o α) M N
@[simp]
theorem blockDiag_smul {R : Type*} [Monoid R] [AddMonoid α] [DistribMulAction R α] (x : R)
(M : Matrix (m × o) (n × o) α) : blockDiag (x • M) = x • blockDiag M :=
rfl
end BlockDiag
section BlockDiagonal'
variable [DecidableEq o]
section Zero
variable [Zero α] [Zero β]
/-- `Matrix.blockDiagonal' M` turns `M : Π i, Matrix (m i) (n i) α` into a
`Σ i, m i`-by-`Σ i, n i` block matrix which has the entries of `M` along the diagonal
and zero elsewhere.
This is the dependently-typed version of `Matrix.blockDiagonal`. -/
def blockDiagonal' (M : ∀ i, Matrix (m' i) (n' i) α) : Matrix (Σi, m' i) (Σi, n' i) α :=
of <|
(fun ⟨k, i⟩ ⟨k', j⟩ => if h : k = k' then M k i (cast (congr_arg n' h.symm) j) else 0 :
(Σi, m' i) → (Σi, n' i) → α)
-- TODO: set as an equation lemma for `blockDiagonal'`, see mathlib4#3024
theorem blockDiagonal'_apply' (M : ∀ i, Matrix (m' i) (n' i) α) (k i k' j) :
blockDiagonal' M ⟨k, i⟩ ⟨k', j⟩ =
if h : k = k' then M k i (cast (congr_arg n' h.symm) j) else 0 :=
rfl
theorem blockDiagonal'_eq_blockDiagonal (M : o → Matrix m n α) {k k'} (i j) :
blockDiagonal M (i, k) (j, k') = blockDiagonal' M ⟨k, i⟩ ⟨k', j⟩ :=
rfl
theorem blockDiagonal'_submatrix_eq_blockDiagonal (M : o → Matrix m n α) :
(blockDiagonal' M).submatrix (Prod.toSigma ∘ Prod.swap) (Prod.toSigma ∘ Prod.swap) =
blockDiagonal M :=
Matrix.ext fun ⟨_, _⟩ ⟨_, _⟩ => rfl
theorem blockDiagonal'_apply (M : ∀ i, Matrix (m' i) (n' i) α) (ik jk) :
blockDiagonal' M ik jk =
if h : ik.1 = jk.1 then M ik.1 ik.2 (cast (congr_arg n' h.symm) jk.2) else 0 := by
cases ik
cases jk
rfl
@[simp]
theorem blockDiagonal'_apply_eq (M : ∀ i, Matrix (m' i) (n' i) α) (k i j) :
blockDiagonal' M ⟨k, i⟩ ⟨k, j⟩ = M k i j :=
dif_pos rfl
theorem blockDiagonal'_apply_ne (M : ∀ i, Matrix (m' i) (n' i) α) {k k'} (i j) (h : k ≠ k') :
blockDiagonal' M ⟨k, i⟩ ⟨k', j⟩ = 0 :=
dif_neg h
theorem blockDiagonal'_map (M : ∀ i, Matrix (m' i) (n' i) α) (f : α → β) (hf : f 0 = 0) :
(blockDiagonal' M).map f = blockDiagonal' fun k => (M k).map f := by
ext
simp only [map_apply, blockDiagonal'_apply, eq_comm]
rw [apply_dite f, hf]
@[simp]
theorem blockDiagonal'_transpose (M : ∀ i, Matrix (m' i) (n' i) α) :
(blockDiagonal' M)ᵀ = blockDiagonal' fun k => (M k)ᵀ := by
ext ⟨ii, ix⟩ ⟨ji, jx⟩
simp only [transpose_apply, blockDiagonal'_apply]
split_ifs <;> cc
@[simp]
theorem blockDiagonal'_conjTranspose {α} [AddMonoid α] [StarAddMonoid α]
(M : ∀ i, Matrix (m' i) (n' i) α) : (blockDiagonal' M)ᴴ = blockDiagonal' fun k => (M k)ᴴ := by
simp only [conjTranspose, blockDiagonal'_transpose]
exact blockDiagonal'_map _ star (star_zero α)
@[simp]
theorem blockDiagonal'_zero : blockDiagonal' (0 : ∀ i, Matrix (m' i) (n' i) α) = 0 := by
ext
simp [blockDiagonal'_apply]
@[simp]
theorem blockDiagonal'_diagonal [∀ i, DecidableEq (m' i)] (d : ∀ i, m' i → α) :
(blockDiagonal' fun k => diagonal (d k)) = diagonal fun ik => d ik.1 ik.2 := by
ext ⟨i, k⟩ ⟨j, k'⟩
simp only [blockDiagonal'_apply, diagonal]
obtain rfl | hij := Decidable.eq_or_ne i j
· simp
· simp [hij]
@[simp]
theorem blockDiagonal'_one [∀ i, DecidableEq (m' i)] [One α] :
blockDiagonal' (1 : ∀ i, Matrix (m' i) (m' i) α) = 1 :=
show (blockDiagonal' fun i : o => diagonal fun _ : m' i => (1 : α)) = diagonal fun _ => 1 by
rw [blockDiagonal'_diagonal]
end Zero
@[simp]
theorem blockDiagonal'_add [AddZeroClass α] (M N : ∀ i, Matrix (m' i) (n' i) α) :
blockDiagonal' (M + N) = blockDiagonal' M + blockDiagonal' N := by
ext
simp only [blockDiagonal'_apply, Pi.add_apply, add_apply]
split_ifs <;> simp
section
variable (m' n' α)
/-- `Matrix.blockDiagonal'` as an `AddMonoidHom`. -/
@[simps]
def blockDiagonal'AddMonoidHom [AddZeroClass α] :
(∀ i, Matrix (m' i) (n' i) α) →+ Matrix (Σi, m' i) (Σi, n' i) α where
toFun := blockDiagonal'
map_zero' := blockDiagonal'_zero
map_add' := blockDiagonal'_add
end
@[simp]
theorem blockDiagonal'_neg [AddGroup α] (M : ∀ i, Matrix (m' i) (n' i) α) :
blockDiagonal' (-M) = -blockDiagonal' M :=
map_neg (blockDiagonal'AddMonoidHom m' n' α) M
@[simp]
theorem blockDiagonal'_sub [AddGroup α] (M N : ∀ i, Matrix (m' i) (n' i) α) :
blockDiagonal' (M - N) = blockDiagonal' M - blockDiagonal' N :=
map_sub (blockDiagonal'AddMonoidHom m' n' α) M N
@[simp]
theorem blockDiagonal'_mul [NonUnitalNonAssocSemiring α] [∀ i, Fintype (n' i)] [Fintype o]
(M : ∀ i, Matrix (m' i) (n' i) α) (N : ∀ i, Matrix (n' i) (p' i) α) :
(blockDiagonal' fun k => M k * N k) = blockDiagonal' M * blockDiagonal' N := by
ext ⟨k, i⟩ ⟨k', j⟩
simp only [blockDiagonal'_apply, mul_apply, ← Finset.univ_sigma_univ, Finset.sum_sigma]
rw [Fintype.sum_eq_single k]
· simp only [if_pos, dif_pos] -- Porting note: added
split_ifs <;> simp
· intro j' hj'
exact Finset.sum_eq_zero fun _ _ => by rw [dif_neg hj'.symm, zero_mul]
section
variable (α m')
/-- `Matrix.blockDiagonal'` as a `RingHom`. -/
@[simps]
def blockDiagonal'RingHom [∀ i, DecidableEq (m' i)] [Fintype o] [∀ i, Fintype (m' i)]
[NonAssocSemiring α] : (∀ i, Matrix (m' i) (m' i) α) →+* Matrix (Σi, m' i) (Σi, m' i) α :=
{ blockDiagonal'AddMonoidHom m' m' α with
toFun := blockDiagonal'
map_one' := blockDiagonal'_one
map_mul' := blockDiagonal'_mul }
end
@[simp]
theorem blockDiagonal'_pow [∀ i, DecidableEq (m' i)] [Fintype o] [∀ i, Fintype (m' i)] [Semiring α]
(M : ∀ i, Matrix (m' i) (m' i) α) (n : ℕ) : blockDiagonal' (M ^ n) = blockDiagonal' M ^ n :=
map_pow (blockDiagonal'RingHom m' α) M n
@[simp]
theorem blockDiagonal'_smul {R : Type*} [Semiring R] [AddCommMonoid α] [Module R α] (x : R)
(M : ∀ i, Matrix (m' i) (n' i) α) : blockDiagonal' (x • M) = x • blockDiagonal' M := by
ext
simp only [blockDiagonal'_apply, Pi.smul_apply, smul_apply]
split_ifs <;> simp
end BlockDiagonal'
section BlockDiag'
/-- Extract a block from the diagonal of a block diagonal matrix.
This is the block form of `Matrix.diag`, and the left-inverse of `Matrix.blockDiagonal'`. -/
def blockDiag' (M : Matrix (Σi, m' i) (Σi, n' i) α) (k : o) : Matrix (m' k) (n' k) α :=
of fun i j => M ⟨k, i⟩ ⟨k, j⟩
-- TODO: set as an equation lemma for `blockDiag'`, see mathlib4#3024
theorem blockDiag'_apply (M : Matrix (Σi, m' i) (Σi, n' i) α) (k : o) (i j) :
blockDiag' M k i j = M ⟨k, i⟩ ⟨k, j⟩ :=
rfl
theorem blockDiag'_map (M : Matrix (Σi, m' i) (Σi, n' i) α) (f : α → β) :
blockDiag' (M.map f) = fun k => (blockDiag' M k).map f :=
rfl
@[simp]
theorem blockDiag'_transpose (M : Matrix (Σi, m' i) (Σi, n' i) α) (k : o) :
blockDiag' Mᵀ k = (blockDiag' M k)ᵀ :=
ext fun _ _ => rfl
@[simp]
theorem blockDiag'_conjTranspose {α : Type*} [AddMonoid α] [StarAddMonoid α]
(M : Matrix (Σi, m' i) (Σi, n' i) α) (k : o) : blockDiag' Mᴴ k = (blockDiag' M k)ᴴ :=
ext fun _ _ => rfl
section Zero
variable [Zero α] [Zero β]
@[simp]
theorem blockDiag'_zero : blockDiag' (0 : Matrix (Σi, m' i) (Σi, n' i) α) = 0 :=
rfl
@[simp]
theorem blockDiag'_diagonal [DecidableEq o] [∀ i, DecidableEq (m' i)] (d : (Σi, m' i) → α) (k : o) :
blockDiag' (diagonal d) k = diagonal fun i => d ⟨k, i⟩ :=
ext fun i j => by
obtain rfl | hij := Decidable.eq_or_ne i j
· rw [blockDiag'_apply, diagonal_apply_eq, diagonal_apply_eq]
· rw [blockDiag'_apply, diagonal_apply_ne _ hij, diagonal_apply_ne _ (mt (fun h => ?_) hij)]
cases h
rfl
@[simp]
theorem blockDiag'_blockDiagonal' [DecidableEq o] (M : ∀ i, Matrix (m' i) (n' i) α) :
blockDiag' (blockDiagonal' M) = M :=
funext fun _ => ext fun _ _ => blockDiagonal'_apply_eq M _ _ _
theorem blockDiagonal'_injective [DecidableEq o] :
Function.Injective (blockDiagonal' : (∀ i, Matrix (m' i) (n' i) α) → Matrix _ _ α) :=
Function.LeftInverse.injective blockDiag'_blockDiagonal'
@[simp]
theorem blockDiagonal'_inj [DecidableEq o] {M N : ∀ i, Matrix (m' i) (n' i) α} :
blockDiagonal' M = blockDiagonal' N ↔ M = N :=
blockDiagonal'_injective.eq_iff
@[simp]
theorem blockDiag'_one [DecidableEq o] [∀ i, DecidableEq (m' i)] [One α] :
blockDiag' (1 : Matrix (Σi, m' i) (Σi, m' i) α) = 1 :=
funext <| blockDiag'_diagonal _
end Zero
@[simp]
theorem blockDiag'_add [AddZeroClass α] (M N : Matrix (Σi, m' i) (Σi, n' i) α) :
blockDiag' (M + N) = blockDiag' M + blockDiag' N :=
rfl
section
variable (m' n' α)
/-- `Matrix.blockDiag'` as an `AddMonoidHom`. -/
@[simps]
def blockDiag'AddMonoidHom [AddZeroClass α] :
Matrix (Σi, m' i) (Σi, n' i) α →+ ∀ i, Matrix (m' i) (n' i) α where
toFun := blockDiag'
map_zero' := blockDiag'_zero
map_add' := blockDiag'_add
end
@[simp]
theorem blockDiag'_neg [AddGroup α] (M : Matrix (Σi, m' i) (Σi, n' i) α) :
blockDiag' (-M) = -blockDiag' M :=
map_neg (blockDiag'AddMonoidHom m' n' α) M
@[simp]
theorem blockDiag'_sub [AddGroup α] (M N : Matrix (Σi, m' i) (Σi, n' i) α) :
blockDiag' (M - N) = blockDiag' M - blockDiag' N :=
map_sub (blockDiag'AddMonoidHom m' n' α) M N
@[simp]
theorem blockDiag'_smul {R : Type*} [Monoid R] [AddMonoid α] [DistribMulAction R α] (x : R)
(M : Matrix (Σi, m' i) (Σi, n' i) α) : blockDiag' (x • M) = x • blockDiag' M :=
rfl
end BlockDiag'
section
variable [CommRing R]
theorem toBlock_mul_eq_mul {m n k : Type*} [Fintype n] (p : m → Prop) (q : k → Prop)
(A : Matrix m n R) (B : Matrix n k R) :
(A * B).toBlock p q = A.toBlock p ⊤ * B.toBlock ⊤ q := by
ext i k
simp only [toBlock_apply, mul_apply]
rw [Finset.sum_subtype]
simp [Pi.top_apply, Prop.top_eq_true]
theorem toBlock_mul_eq_add {m n k : Type*} [Fintype n] (p : m → Prop) (q : n → Prop)
[DecidablePred q] (r : k → Prop) (A : Matrix m n R) (B : Matrix n k R) : (A * B).toBlock p r =
A.toBlock p q * B.toBlock q r + (A.toBlock p fun i => ¬q i) * B.toBlock (fun i => ¬q i) r := by
classical
ext i k
simp only [toBlock_apply, mul_apply, Pi.add_apply]
exact (Fintype.sum_subtype_add_sum_subtype q fun x => A (↑i) x * B x ↑k).symm
end
end Matrix
|
Data\Matrix\CharP.lean | /-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import Mathlib.Algebra.CharP.Defs
import Mathlib.Data.Matrix.Basic
/-!
# Matrices in prime characteristic
In this file we prove that matrices over a ring of characteristic `p`
with nonempty index type have the same characteristic.
-/
open Matrix
variable {n : Type*} {R : Type*} [AddMonoidWithOne R]
instance Matrix.charP [DecidableEq n] [Nonempty n] (p : ℕ) [CharP R p] :
CharP (Matrix n n R) p where
cast_eq_zero_iff' k := by simp_rw [← diagonal_natCast, ← diagonal_zero, diagonal_eq_diagonal_iff,
CharP.cast_eq_zero_iff R p k, forall_const]
|
Data\Matrix\ColumnRowPartitioned.lean | /-
Copyright (c) 2023 Mohanad ahmed. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mohanad Ahmed
-/
import Mathlib.Data.Matrix.Basic
import Mathlib.Data.Matrix.Block
import Mathlib.LinearAlgebra.Matrix.NonsingularInverse
/-! # Block Matrices from Rows and Columns
This file provides the basic definitions of matrices composed from columns and rows.
The concatenation of two matrices with the same row indices can be expressed as
`A = fromColumns A₁ A₂` the concatenation of two matrices with the same column indices
can be expressed as `B = fromRows B₁ B₂`.
We then provide a few lemmas that deal with the products of these with each other and
with block matrices
## Tags
column matrices, row matrices, column row block matrices
-/
namespace Matrix
variable {R : Type*}
variable {m m₁ m₂ n n₁ n₂ : Type*}
/-- Concatenate together two matrices A₁[m₁ × N] and A₂[m₂ × N] with the same columns (N) to get a
bigger matrix indexed by [(m₁ ⊕ m₂) × N] -/
def fromRows (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) : Matrix (m₁ ⊕ m₂) n R :=
of (Sum.elim A₁ A₂)
/-- Concatenate together two matrices B₁[m × n₁] and B₂[m × n₂] with the same rows (M) to get a
bigger matrix indexed by [m × (n₁ ⊕ n₂)] -/
def fromColumns (B₁ : Matrix m n₁ R) (B₂ : Matrix m n₂ R) : Matrix m (n₁ ⊕ n₂) R :=
of fun i => Sum.elim (B₁ i) (B₂ i)
/-- Given a column partitioned matrix extract the first column -/
def toColumns₁ (A : Matrix m (n₁ ⊕ n₂) R) : Matrix m n₁ R := of fun i j => (A i (Sum.inl j))
/-- Given a column partitioned matrix extract the second column -/
def toColumns₂ (A : Matrix m (n₁ ⊕ n₂) R) : Matrix m n₂ R := of fun i j => (A i (Sum.inr j))
/-- Given a row partitioned matrix extract the first row -/
def toRows₁ (A : Matrix (m₁ ⊕ m₂) n R) : Matrix m₁ n R := of fun i j => (A (Sum.inl i) j)
/-- Given a row partitioned matrix extract the second row -/
def toRows₂ (A : Matrix (m₁ ⊕ m₂) n R) : Matrix m₂ n R := of fun i j => (A (Sum.inr i) j)
@[simp]
lemma fromRows_apply_inl (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) (i : m₁) (j : n) :
(fromRows A₁ A₂) (Sum.inl i) j = A₁ i j := rfl
@[simp]
lemma fromRows_apply_inr (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) (i : m₂) (j : n) :
(fromRows A₁ A₂) (Sum.inr i) j = A₂ i j := rfl
@[simp]
lemma fromColumns_apply_inl (A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) (i : m) (j : n₁) :
(fromColumns A₁ A₂) i (Sum.inl j) = A₁ i j := rfl
@[simp]
lemma fromColumns_apply_inr (A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) (i : m) (j : n₂) :
(fromColumns A₁ A₂) i (Sum.inr j) = A₂ i j := rfl
@[simp]
lemma toRows₁_apply (A : Matrix (m₁ ⊕ m₂) n R) (i : m₁) (j : n) :
(toRows₁ A) i j = A (Sum.inl i) j := rfl
@[simp]
lemma toRows₂_apply (A : Matrix (m₁ ⊕ m₂) n R) (i : m₂) (j : n) :
(toRows₂ A) i j = A (Sum.inr i) j := rfl
@[simp]
lemma toRows₁_fromRows (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) :
toRows₁ (fromRows A₁ A₂) = A₁ := rfl
@[simp]
lemma toRows₂_fromRows (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) :
toRows₂ (fromRows A₁ A₂) = A₂ := rfl
@[simp]
lemma toColumns₁_apply (A : Matrix m (n₁ ⊕ n₂) R) (i : m) (j : n₁) :
(toColumns₁ A) i j = A i (Sum.inl j) := rfl
@[simp]
lemma toColumns₂_apply (A : Matrix m (n₁ ⊕ n₂) R) (i : m) (j : n₂) :
(toColumns₂ A) i j = A i (Sum.inr j) := rfl
@[simp]
lemma toColumns₁_fromColumns (A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) :
toColumns₁ (fromColumns A₁ A₂) = A₁ := rfl
@[simp]
lemma toColumns₂_fromColumns (A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) :
toColumns₂ (fromColumns A₁ A₂) = A₂ := rfl
@[simp]
lemma fromColumns_toColumns (A : Matrix m (n₁ ⊕ n₂) R) :
fromColumns A.toColumns₁ A.toColumns₂ = A := by
ext i (j | j) <;> simp
@[simp]
lemma fromRows_toRows (A : Matrix (m₁ ⊕ m₂) n R) : fromRows A.toRows₁ A.toRows₂ = A := by
ext (i | i) j <;> simp
lemma fromRows_inj : Function.Injective2 (@fromRows R m₁ m₂ n) := by
intros x1 x2 y1 y2
simp only [Function.funext_iff, ← Matrix.ext_iff]
aesop
lemma fromColumns_inj : Function.Injective2 (@fromColumns R m n₁ n₂) := by
intros x1 x2 y1 y2
simp only [Function.funext_iff, ← Matrix.ext_iff]
aesop
lemma fromColumns_ext_iff (A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) (B₁ : Matrix m n₁ R)
(B₂ : Matrix m n₂ R) :
fromColumns A₁ A₂ = fromColumns B₁ B₂ ↔ A₁ = B₁ ∧ A₂ = B₂ := fromColumns_inj.eq_iff
lemma fromRows_ext_iff (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) (B₁ : Matrix m₁ n R)
(B₂ : Matrix m₂ n R) :
fromRows A₁ A₂ = fromRows B₁ B₂ ↔ A₁ = B₁ ∧ A₂ = B₂ := fromRows_inj.eq_iff
/-- A column partioned matrix when transposed gives a row partioned matrix with columns of the
initial matrix tranposed to become rows. -/
lemma transpose_fromColumns (A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) :
transpose (fromColumns A₁ A₂) = fromRows (transpose A₁) (transpose A₂) := by
ext (i | i) j <;> simp
/-- A row partioned matrix when transposed gives a column partioned matrix with rows of the initial
matrix tranposed to become columns. -/
lemma transpose_fromRows (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) :
transpose (fromRows A₁ A₂) = fromColumns (transpose A₁) (transpose A₂) := by
ext i (j | j) <;> simp
section Neg
variable [Neg R]
/-- Negating a matrix partitioned by rows is equivalent to negating each of the rows. -/
@[simp]
lemma fromRows_neg (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) :
-fromRows A₁ A₂ = fromRows (-A₁) (-A₂) := by
ext (i | i) j <;> simp
/-- Negating a matrix partitioned by columns is equivalent to negating each of the columns. -/
@[simp]
lemma fromColumns_neg (A₁ : Matrix n m₁ R) (A₂ : Matrix n m₂ R) :
-fromColumns A₁ A₂ = fromColumns (-A₁) (-A₂) := by
ext i (j | j) <;> simp
end Neg
@[simp]
lemma fromColumns_fromRows_eq_fromBlocks (B₁₁ : Matrix m₁ n₁ R) (B₁₂ : Matrix m₁ n₂ R)
(B₂₁ : Matrix m₂ n₁ R) (B₂₂ : Matrix m₂ n₂ R) :
fromColumns (fromRows B₁₁ B₂₁) (fromRows B₁₂ B₂₂) = fromBlocks B₁₁ B₁₂ B₂₁ B₂₂ := by
ext (_ | _) (_ | _) <;> simp
@[simp]
lemma fromRows_fromColumn_eq_fromBlocks (B₁₁ : Matrix m₁ n₁ R) (B₁₂ : Matrix m₁ n₂ R)
(B₂₁ : Matrix m₂ n₁ R) (B₂₂ : Matrix m₂ n₂ R) :
fromRows (fromColumns B₁₁ B₁₂) (fromColumns B₂₁ B₂₂) = fromBlocks B₁₁ B₁₂ B₂₁ B₂₂ := by
ext (_ | _) (_ | _) <;> simp
section Semiring
variable [Semiring R]
@[simp]
lemma fromRows_mulVec [Fintype n] (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) (v : n → R) :
fromRows A₁ A₂ *ᵥ v = Sum.elim (A₁ *ᵥ v) (A₂ *ᵥ v) := by
ext (_ | _) <;> rfl
@[simp]
lemma vecMul_fromColumns [Fintype m] (B₁ : Matrix m n₁ R) (B₂ : Matrix m n₂ R) (v : m → R) :
v ᵥ* fromColumns B₁ B₂ = Sum.elim (v ᵥ* B₁) (v ᵥ* B₂) := by
ext (_ | _) <;> rfl
@[simp]
lemma sum_elim_vecMul_fromRows [Fintype m₁] [Fintype m₂] (B₁ : Matrix m₁ n R) (B₂ : Matrix m₂ n R)
(v₁ : m₁ → R) (v₂ : m₂ → R) :
Sum.elim v₁ v₂ ᵥ* fromRows B₁ B₂ = v₁ ᵥ* B₁ + v₂ ᵥ* B₂ := by
ext
simp [Matrix.vecMul, fromRows, dotProduct]
@[simp]
lemma fromColumns_mulVec_sum_elim [Fintype n₁] [Fintype n₂]
(A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R) (v₁ : n₁ → R) (v₂ : n₂ → R) :
fromColumns A₁ A₂ *ᵥ Sum.elim v₁ v₂ = A₁ *ᵥ v₁ + A₂ *ᵥ v₂ := by
ext
simp [Matrix.mulVec, fromColumns]
@[simp]
lemma fromRows_mul [Fintype n] (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R) (B : Matrix n m R) :
fromRows A₁ A₂ * B = fromRows (A₁ * B) (A₂ * B) := by
ext (_ | _) _ <;> simp [mul_apply]
@[simp]
lemma mul_fromColumns [Fintype n] (A : Matrix m n R) (B₁ : Matrix n n₁ R) (B₂ : Matrix n n₂ R) :
A * fromColumns B₁ B₂ = fromColumns (A * B₁) (A * B₂) := by
ext _ (_ | _) <;> simp [mul_apply]
@[simp]
lemma fromRows_zero : fromRows (0 : Matrix m₁ n R) (0 : Matrix m₂ n R) = 0 := by
ext (_ | _) _ <;> simp
@[simp]
lemma fromColumns_zero : fromColumns (0 : Matrix m n₁ R) (0 : Matrix m n₂ R) = 0 := by
ext _ (_ | _) <;> simp
/-- A row partitioned matrix multiplied by a column partioned matrix gives a 2 by 2 block matrix -/
lemma fromRows_mul_fromColumns [Fintype n] (A₁ : Matrix m₁ n R) (A₂ : Matrix m₂ n R)
(B₁ : Matrix n n₁ R) (B₂ : Matrix n n₂ R) :
(fromRows A₁ A₂) * (fromColumns B₁ B₂) =
fromBlocks (A₁ * B₁) (A₁ * B₂) (A₂ * B₁) (A₂ * B₂) := by
ext (_ | _) (_ | _) <;> simp
/-- A column partitioned matrix mulitplied by a row partitioned matrix gives the sum of the "outer"
products of the block matrices -/
lemma fromColumns_mul_fromRows [Fintype n₁] [Fintype n₂] (A₁ : Matrix m n₁ R) (A₂ : Matrix m n₂ R)
(B₁ : Matrix n₁ n R) (B₂ : Matrix n₂ n R) :
fromColumns A₁ A₂ * fromRows B₁ B₂ = (A₁ * B₁ + A₂ * B₂) := by
ext
simp [mul_apply]
/-- A column partitioned matrix multipiled by a block matrix results in a column partioned matrix -/
lemma fromColumns_mul_fromBlocks [Fintype m₁] [Fintype m₂] (A₁ : Matrix m m₁ R) (A₂ : Matrix m m₂ R)
(B₁₁ : Matrix m₁ n₁ R) (B₁₂ : Matrix m₁ n₂ R) (B₂₁ : Matrix m₂ n₁ R) (B₂₂ : Matrix m₂ n₂ R) :
(fromColumns A₁ A₂) * fromBlocks B₁₁ B₁₂ B₂₁ B₂₂ =
fromColumns (A₁ * B₁₁ + A₂ * B₂₁) (A₁ * B₁₂ + A₂ * B₂₂) := by
ext _ (_ | _) <;> simp [mul_apply]
/-- A block matrix mulitplied by a row partitioned matrix gives a row partitioned matrix -/
lemma fromBlocks_mul_fromRows [Fintype n₁] [Fintype n₂] (A₁ : Matrix n₁ n R) (A₂ : Matrix n₂ n R)
(B₁₁ : Matrix m₁ n₁ R) (B₁₂ : Matrix m₁ n₂ R) (B₂₁ : Matrix m₂ n₁ R) (B₂₂ : Matrix m₂ n₂ R) :
fromBlocks B₁₁ B₁₂ B₂₁ B₂₂ * (fromRows A₁ A₂) =
fromRows (B₁₁ * A₁ + B₁₂ * A₂) (B₂₁ * A₁ + B₂₂ * A₂) := by
ext (_ | _) _ <;> simp [mul_apply]
end Semiring
section CommRing
variable [CommRing R]
/-- Multiplication of a matrix by its inverse is commutative.
This is the column and row partitioned matrix form of `Matrix.mul_eq_one_comm`.
The condition `e : n ≃ n₁ ⊕ n₂` states that `fromColumns A₁ A₂` and `fromRows B₁ B₂` are "square".
-/
lemma fromColumns_mul_fromRows_eq_one_comm
[Fintype n₁] [Fintype n₂] [Fintype n] [DecidableEq n] [DecidableEq n₁] [DecidableEq n₂]
(e : n ≃ n₁ ⊕ n₂)
(A₁ : Matrix n n₁ R) (A₂ : Matrix n n₂ R) (B₁ : Matrix n₁ n R) (B₂ : Matrix n₂ n R) :
fromColumns A₁ A₂ * fromRows B₁ B₂ = 1 ↔ fromRows B₁ B₂ * fromColumns A₁ A₂ = 1 := by
calc fromColumns A₁ A₂ * fromRows B₁ B₂ = 1
_ ↔ submatrix (fromColumns A₁ A₂) id e * submatrix (fromRows B₁ B₂) e id = 1 := by
simp
_ ↔ submatrix (fromRows B₁ B₂) e id * submatrix (fromColumns A₁ A₂) id e = 1 :=
mul_eq_one_comm
_ ↔ reindex e.symm e.symm (fromRows B₁ B₂ * fromColumns A₁ A₂) = reindex e.symm e.symm 1 := by
simp only [reindex_apply, Equiv.symm_symm, submatrix_one_equiv,
submatrix_mul (he₂ := Function.bijective_id)]
_ ↔ fromRows B₁ B₂ * fromColumns A₁ A₂ = 1 :=
(reindex _ _).injective.eq_iff
/-- The lemma `fromColumns_mul_fromRows_eq_one_comm` specialized to the case where the index sets n₁
and n₂, are the result of subtyping by a predicate and its complement. -/
lemma equiv_compl_fromColumns_mul_fromRows_eq_one_comm
[Fintype n] [DecidableEq n] (p : n → Prop) [DecidablePred p]
(A₁ : Matrix n {i // p i} R) (A₂ : Matrix n {i // ¬p i} R)
(B₁ : Matrix {i // p i} n R) (B₂ : Matrix {i // ¬p i} n R) :
fromColumns A₁ A₂ * fromRows B₁ B₂ = 1 ↔ fromRows B₁ B₂ * fromColumns A₁ A₂ = 1 :=
fromColumns_mul_fromRows_eq_one_comm (id (Equiv.sumCompl p).symm) A₁ A₂ B₁ B₂
end CommRing
section Star
variable [Star R]
/-- A column partioned matrix in a Star ring when conjugate transposed gives a row partitioned
matrix with the columns of the initial matrix conjugate transposed to become rows. -/
lemma conjTranspose_fromColumns_eq_fromRows_conjTranspose (A₁ : Matrix m n₁ R)
(A₂ : Matrix m n₂ R) :
conjTranspose (fromColumns A₁ A₂) = fromRows (conjTranspose A₁) (conjTranspose A₂) := by
ext (_ | _) _ <;> simp
/-- A row partioned matrix in a Star ring when conjugate transposed gives a column partitioned
matrix with the rows of the initial matrix conjugate transposed to become columns. -/
lemma conjTranspose_fromRows_eq_fromColumns_conjTranspose (A₁ : Matrix m₁ n R)
(A₂ : Matrix m₂ n R) : conjTranspose (fromRows A₁ A₂) =
fromColumns (conjTranspose A₁) (conjTranspose A₂) := by
ext _ (_ | _) <;> simp
end Star
end Matrix
|
Data\Matrix\Composition.lean | /-
Copyright (c) 2024 Yunzhou Xie. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Yunzhou Xie
-/
import Mathlib.Data.Matrix.Basic
/-!
# Composition of matrices
This file shows that Mₙ(Mₘ(R)) ≃ Mₙₘ(R), Mₙ(Rᵒᵖ) ≃ₐ[K] Mₙ(R)ᵒᵖ
and also different levels of equivalence when R is an AddCommMonoid,
Semiring, and Algebra over a CommSemiring K.
## Main results
* `Matrix.comp` is an equivalence between `Matrix I J (Matrix K L R)` and
`I × K` by `J × L` matrices.
* `Matrix.swap` is an equivalence between `(I × J)` by `(K × L)` matrices and
`J × I` by `L × K` matrices.
-/
namespace Matrix
variable (I J K L R : Type*)
/-- I by J matrix where each entry is a K by L matrix is equivalent to
I × K by J × L matrix -/
@[simps]
def comp : Matrix I J (Matrix K L R) ≃ Matrix (I × K) (J × L) R where
toFun m ik jl := m ik.1 jl.1 ik.2 jl.2
invFun n i j k l := n (i, k) (j, l)
left_inv _ := rfl
right_inv _ := rfl
section AddCommMonoid
variable [AddCommMonoid R]
/-- `Matrix.comp` as `AddEquiv` -/
@[simps!]
def compAddEquiv : Matrix I J (Matrix K L R) ≃+ Matrix (I × K) (J × L) R where
__ := Matrix.comp I J K L R
map_add' _ _ := rfl
end AddCommMonoid
section Semiring
variable [Semiring R] [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J]
/-- `Matrix.comp` as `RingEquiv` -/
@[simps!]
def compRingEquiv : Matrix I I (Matrix J J R) ≃+* Matrix (I × J) (I × J) R where
__ := Matrix.compAddEquiv I I J J R
map_mul' _ _ := by
ext _ _
exact (Matrix.sum_apply _ _ _ _).trans $ Eq.symm Fintype.sum_prod_type
end Semiring
section LinearMap
variable (K : Type*) [CommSemiring K] [AddCommMonoid R] [Module K R]
/-- `Matrix.comp` as `LinearEquiv` -/
@[simps!]
def compLinearEquiv : Matrix I J (Matrix K L R) ≃ₗ[K] Matrix (I × K) (J × L) R where
__ := Matrix.compAddEquiv I J K L R
map_smul' _ _ := rfl
end LinearMap
section Algebra
variable (K : Type*) [CommSemiring K] [Semiring R] [Fintype I] [Fintype J] [Algebra K R]
variable [DecidableEq I] [DecidableEq J]
/-- `Matrix.comp` as `AlgEquiv` -/
@[simps!]
def compAlgEquiv : Matrix I I (Matrix J J R) ≃ₐ[K] Matrix (I × J) (I × J) R where
__ := Matrix.compRingEquiv I J R
commutes' c := by
ext _ _
simp only [compRingEquiv, compAddEquiv, comp, AddEquiv.toEquiv_eq_coe, RingEquiv.toEquiv_eq_coe,
Equiv.toFun_as_coe, EquivLike.coe_coe, RingEquiv.coe_mk, AddEquiv.coe_mk, Equiv.coe_fn_mk,
algebraMap_eq_diagonal]
rw [Pi.algebraMap_def, Pi.algebraMap_def, Algebra.algebraMap_eq_smul_one',
Algebra.algebraMap_eq_smul_one', ← diagonal_one, diagonal_apply, diagonal_apply]
aesop
end Algebra
end Matrix
|
Data\Matrix\DMatrix.lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Mathlib.Algebra.Group.Hom.Defs
/-!
# Dependent-typed matrices
-/
universe u u' v w z
/-- `DMatrix m n` is the type of dependently typed matrices
whose rows are indexed by the type `m` and
whose columns are indexed by the type `n`.
In most applications `m` and `n` are finite types. -/
def DMatrix (m : Type u) (n : Type u') (α : m → n → Type v) : Type max u u' v :=
∀ i j, α i j
variable {l m n o : Type*}
variable {α : m → n → Type v}
namespace DMatrix
section Ext
variable {M N : DMatrix m n α}
theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N :=
⟨fun h => funext fun i => funext <| h i, fun h => by simp [h]⟩
@[ext]
theorem ext : (∀ i j, M i j = N i j) → M = N :=
ext_iff.mp
end Ext
/-- `M.map f` is the DMatrix obtained by applying `f` to each entry of the matrix `M`. -/
def map (M : DMatrix m n α) {β : m → n → Type w} (f : ∀ ⦃i j⦄, α i j → β i j) : DMatrix m n β :=
fun i j => f (M i j)
@[simp]
theorem map_apply {M : DMatrix m n α} {β : m → n → Type w} {f : ∀ ⦃i j⦄, α i j → β i j} {i : m}
{j : n} : M.map f i j = f (M i j) := rfl
@[simp]
theorem map_map {M : DMatrix m n α} {β : m → n → Type w} {γ : m → n → Type z}
{f : ∀ ⦃i j⦄, α i j → β i j} {g : ∀ ⦃i j⦄, β i j → γ i j} :
(M.map f).map g = M.map fun i j x => g (f x) := by ext; simp
/-- The transpose of a dmatrix. -/
def transpose (M : DMatrix m n α) : DMatrix n m fun j i => α i j
| x, y => M y x
@[inherit_doc]
scoped postfix:1024 "ᵀ" => DMatrix.transpose
/-- `DMatrix.col u` is the column matrix whose entries are given by `u`. -/
def col {α : m → Type v} (w : ∀ i, α i) : DMatrix m Unit fun i _j => α i
| x, _y => w x
/-- `DMatrix.row u` is the row matrix whose entries are given by `u`. -/
def row {α : n → Type v} (v : ∀ j, α j) : DMatrix Unit n fun _i j => α j
| _x, y => v y
instance [∀ i j, Inhabited (α i j)] : Inhabited (DMatrix m n α) :=
inferInstanceAs <| Inhabited <| ∀ i j, α i j
instance [∀ i j, Add (α i j)] : Add (DMatrix m n α) :=
inferInstanceAs <| Add <| ∀ i j, α i j
instance [∀ i j, AddSemigroup (α i j)] : AddSemigroup (DMatrix m n α) :=
inferInstanceAs <| AddSemigroup <| ∀ i j, α i j
instance [∀ i j, AddCommSemigroup (α i j)] : AddCommSemigroup (DMatrix m n α) :=
inferInstanceAs <| AddCommSemigroup <| ∀ i j, α i j
instance [∀ i j, Zero (α i j)] : Zero (DMatrix m n α) :=
inferInstanceAs <| Zero <| ∀ i j, α i j
instance [∀ i j, AddMonoid (α i j)] : AddMonoid (DMatrix m n α) :=
inferInstanceAs <| AddMonoid <| ∀ i j, α i j
instance [∀ i j, AddCommMonoid (α i j)] : AddCommMonoid (DMatrix m n α) :=
inferInstanceAs <| AddCommMonoid <| ∀ i j, α i j
instance [∀ i j, Neg (α i j)] : Neg (DMatrix m n α) :=
inferInstanceAs <| Neg <| ∀ i j, α i j
instance [∀ i j, Sub (α i j)] : Sub (DMatrix m n α) :=
inferInstanceAs <| Sub <| ∀ i j, α i j
instance [∀ i j, AddGroup (α i j)] : AddGroup (DMatrix m n α) :=
inferInstanceAs <| AddGroup <| ∀ i j, α i j
instance [∀ i j, AddCommGroup (α i j)] : AddCommGroup (DMatrix m n α) :=
inferInstanceAs <| AddCommGroup <| ∀ i j, α i j
instance [∀ i j, Unique (α i j)] : Unique (DMatrix m n α) :=
inferInstanceAs <| Unique <| ∀ i j, α i j
instance [∀ i j, Subsingleton (α i j)] : Subsingleton (DMatrix m n α) :=
inferInstanceAs <| Subsingleton <| ∀ i j, α i j
#adaptation_note
/--
After https://github.com/leanprover/lean4/pull/4481
the `simpNF` linter incorrectly claims this lemma can't be applied by `simp`.
-/
@[simp, nolint simpNF]
theorem zero_apply [∀ i j, Zero (α i j)] (i j) : (0 : DMatrix m n α) i j = 0 := rfl
@[simp]
theorem neg_apply [∀ i j, Neg (α i j)] (M : DMatrix m n α) (i j) : (-M) i j = -M i j := rfl
@[simp]
theorem add_apply [∀ i j, Add (α i j)] (M N : DMatrix m n α) (i j) : (M + N) i j = M i j + N i j :=
rfl
@[simp]
theorem sub_apply [∀ i j, Sub (α i j)] (M N : DMatrix m n α) (i j) : (M - N) i j = M i j - N i j :=
rfl
@[simp]
theorem map_zero [∀ i j, Zero (α i j)] {β : m → n → Type w} [∀ i j, Zero (β i j)]
{f : ∀ ⦃i j⦄, α i j → β i j} (h : ∀ i j, f (0 : α i j) = 0) :
(0 : DMatrix m n α).map f = 0 := by ext; simp [h]
theorem map_add [∀ i j, AddMonoid (α i j)] {β : m → n → Type w} [∀ i j, AddMonoid (β i j)]
(f : ∀ ⦃i j⦄, α i j →+ β i j) (M N : DMatrix m n α) :
((M + N).map fun i j => @f i j) = (M.map fun i j => @f i j) + N.map fun i j => @f i j := by
ext; simp
theorem map_sub [∀ i j, AddGroup (α i j)] {β : m → n → Type w} [∀ i j, AddGroup (β i j)]
(f : ∀ ⦃i j⦄, α i j →+ β i j) (M N : DMatrix m n α) :
((M - N).map fun i j => @f i j) = (M.map fun i j => @f i j) - N.map fun i j => @f i j := by
ext; simp
instance subsingleton_of_empty_left [IsEmpty m] : Subsingleton (DMatrix m n α) :=
⟨fun M N => by
ext i
exact isEmptyElim i⟩
instance subsingleton_of_empty_right [IsEmpty n] : Subsingleton (DMatrix m n α) :=
⟨fun M N => by ext i j; exact isEmptyElim j⟩
end DMatrix
/-- The `AddMonoidHom` between spaces of dependently typed matrices
induced by an `AddMonoidHom` between their coefficients. -/
def AddMonoidHom.mapDMatrix [∀ i j, AddMonoid (α i j)] {β : m → n → Type w}
[∀ i j, AddMonoid (β i j)] (f : ∀ ⦃i j⦄, α i j →+ β i j) : DMatrix m n α →+ DMatrix m n β where
toFun M := M.map fun i j => @f i j
map_zero' := by simp
map_add' := DMatrix.map_add f
@[simp]
theorem AddMonoidHom.mapDMatrix_apply [∀ i j, AddMonoid (α i j)] {β : m → n → Type w}
[∀ i j, AddMonoid (β i j)] (f : ∀ ⦃i j⦄, α i j →+ β i j) (M : DMatrix m n α) :
AddMonoidHom.mapDMatrix f M = M.map fun i j => @f i j := rfl
|
Data\Matrix\DualNumber.lean | /-
Copyright (c) 2023 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import Mathlib.Algebra.DualNumber
import Mathlib.Data.Matrix.Basic
/-!
# Matrices of dual numbers are isomorphic to dual numbers over matrices
Showing this for the more general case of `TrivSqZeroExt R M` would require an action between
`Matrix n n R` and `Matrix n n M`, which would risk causing diamonds.
-/
variable {R n : Type} [CommSemiring R] [Fintype n] [DecidableEq n]
open Matrix TrivSqZeroExt
/-- Matrices over dual numbers and dual numbers over matrices are isomorphic. -/
@[simps]
def Matrix.dualNumberEquiv : Matrix n n (DualNumber R) ≃ₐ[R] DualNumber (Matrix n n R) where
toFun A := ⟨of fun i j => (A i j).fst, of fun i j => (A i j).snd⟩
invFun d := of fun i j => (d.fst i j, d.snd i j)
left_inv A := Matrix.ext fun i j => TrivSqZeroExt.ext rfl rfl
right_inv d := TrivSqZeroExt.ext (Matrix.ext fun i j => rfl) (Matrix.ext fun i j => rfl)
map_mul' A B := by
ext
· dsimp [mul_apply]
simp_rw [fst_sum]
rfl
· simp_rw [snd_mul, smul_eq_mul, op_smul_eq_mul]
simp only [mul_apply, snd_sum, DualNumber.snd_mul, snd_mk, of_apply, fst_mk, add_apply]
rw [← Finset.sum_add_distrib]
map_add' A B := TrivSqZeroExt.ext rfl rfl
commutes' r := by
simp_rw [algebraMap_eq_inl', algebraMap_eq_diagonal, Pi.algebraMap_def,
Algebra.id.map_eq_self, algebraMap_eq_inl, ← diagonal_map (inl_zero R), map_apply, fst_inl,
snd_inl]
rfl
|
Data\Matrix\Hadamard.lean | /-
Copyright (c) 2021 Lu-Ming Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Lu-Ming Zhang
-/
import Mathlib.LinearAlgebra.Matrix.Trace
/-!
# Hadamard product of matrices
This file defines the Hadamard product `Matrix.hadamard`
and contains basic properties about them.
## Main definition
- `Matrix.hadamard`: defines the Hadamard product,
which is the pointwise product of two matrices of the same size.
## Notation
* `⊙`: the Hadamard product `Matrix.hadamard`;
## References
* <https://en.wikipedia.org/wiki/hadamard_product_(matrices)>
## Tags
hadamard product, hadamard
-/
variable {α β γ m n : Type*}
variable {R : Type*}
namespace Matrix
open Matrix
/-- `Matrix.hadamard` defines the Hadamard product,
which is the pointwise product of two matrices of the same size. -/
def hadamard [Mul α] (A : Matrix m n α) (B : Matrix m n α) : Matrix m n α :=
of fun i j => A i j * B i j
-- TODO: set as an equation lemma for `hadamard`, see mathlib4#3024
@[simp]
theorem hadamard_apply [Mul α] (A : Matrix m n α) (B : Matrix m n α) (i j) :
hadamard A B i j = A i j * B i j :=
rfl
scoped infixl:100 " ⊙ " => Matrix.hadamard
section BasicProperties
variable (A : Matrix m n α) (B : Matrix m n α) (C : Matrix m n α)
-- commutativity
theorem hadamard_comm [CommSemigroup α] : A ⊙ B = B ⊙ A :=
ext fun _ _ => mul_comm _ _
-- associativity
theorem hadamard_assoc [Semigroup α] : A ⊙ B ⊙ C = A ⊙ (B ⊙ C) :=
ext fun _ _ => mul_assoc _ _ _
-- distributivity
theorem hadamard_add [Distrib α] : A ⊙ (B + C) = A ⊙ B + A ⊙ C :=
ext fun _ _ => left_distrib _ _ _
theorem add_hadamard [Distrib α] : (B + C) ⊙ A = B ⊙ A + C ⊙ A :=
ext fun _ _ => right_distrib _ _ _
-- scalar multiplication
section Scalar
@[simp]
theorem smul_hadamard [Mul α] [SMul R α] [IsScalarTower R α α] (k : R) : (k • A) ⊙ B = k • A ⊙ B :=
ext fun _ _ => smul_mul_assoc _ _ _
@[simp]
theorem hadamard_smul [Mul α] [SMul R α] [SMulCommClass R α α] (k : R) : A ⊙ (k • B) = k • A ⊙ B :=
ext fun _ _ => mul_smul_comm _ _ _
end Scalar
section Zero
variable [MulZeroClass α]
@[simp]
theorem hadamard_zero : A ⊙ (0 : Matrix m n α) = 0 :=
ext fun _ _ => mul_zero _
@[simp]
theorem zero_hadamard : (0 : Matrix m n α) ⊙ A = 0 :=
ext fun _ _ => zero_mul _
end Zero
section One
variable [DecidableEq n] [MulZeroOneClass α]
variable (M : Matrix n n α)
theorem hadamard_one : M ⊙ (1 : Matrix n n α) = diagonal fun i => M i i := by
ext i j
by_cases h : i = j <;> simp [h]
theorem one_hadamard : (1 : Matrix n n α) ⊙ M = diagonal fun i => M i i := by
ext i j
by_cases h : i = j <;> simp [h]
end One
section Diagonal
variable [DecidableEq n] [MulZeroClass α]
theorem diagonal_hadamard_diagonal (v : n → α) (w : n → α) :
diagonal v ⊙ diagonal w = diagonal (v * w) :=
ext fun _ _ => (apply_ite₂ _ _ _ _ _ _).trans (congr_arg _ <| zero_mul 0)
end Diagonal
section trace
variable [Fintype m] [Fintype n]
variable (R) [Semiring α] [Semiring R] [Module R α]
theorem sum_hadamard_eq : (∑ i : m, ∑ j : n, (A ⊙ B) i j) = trace (A * Bᵀ) :=
rfl
theorem dotProduct_vecMul_hadamard [DecidableEq m] [DecidableEq n] (v : m → α) (w : n → α) :
dotProduct (v ᵥ* (A ⊙ B)) w = trace (diagonal v * A * (B * diagonal w)ᵀ) := by
rw [← sum_hadamard_eq, Finset.sum_comm]
simp [dotProduct, vecMul, Finset.sum_mul, mul_assoc]
end trace
end BasicProperties
end Matrix
|
Data\Matrix\Invertible.lean | /-
Copyright (c) 2023 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import Mathlib.Data.Matrix.Basic
/-! # Extra lemmas about invertible matrices
A few of the `Invertible` lemmas generalize to multiplication of rectangular matrices.
For lemmas about the matrix inverse in terms of the determinant and adjugate, see `Matrix.inv`
in `LinearAlgebra/Matrix/NonsingularInverse.lean`.
## Main results
* `Matrix.invertibleConjTranspose`
* `Matrix.invertibleTranspose`
* `Matrix.isUnit_conjTranpose`
* `Matrix.isUnit_tranpose`
-/
open scoped Matrix
variable {m n : Type*} {α : Type*}
variable [Fintype n] [DecidableEq n]
namespace Matrix
section Semiring
variable [Semiring α]
/-- A copy of `invOf_mul_self_assoc` for rectangular matrices. -/
protected theorem invOf_mul_self_assoc (A : Matrix n n α) (B : Matrix n m α) [Invertible A] :
⅟ A * (A * B) = B := by rw [← Matrix.mul_assoc, invOf_mul_self, Matrix.one_mul]
/-- A copy of `mul_invOf_self_assoc` for rectangular matrices. -/
protected theorem mul_invOf_self_assoc (A : Matrix n n α) (B : Matrix n m α) [Invertible A] :
A * (⅟ A * B) = B := by rw [← Matrix.mul_assoc, mul_invOf_self, Matrix.one_mul]
/-- A copy of `mul_invOf_mul_self_cancel` for rectangular matrices. -/
protected theorem mul_invOf_mul_self_cancel (A : Matrix m n α) (B : Matrix n n α) [Invertible B] :
A * ⅟ B * B = A := by rw [Matrix.mul_assoc, invOf_mul_self, Matrix.mul_one]
/-- A copy of `mul_mul_invOf_self_cancel` for rectangular matrices. -/
protected theorem mul_mul_invOf_self_cancel (A : Matrix m n α) (B : Matrix n n α) [Invertible B] :
A * B * ⅟ B = A := by rw [Matrix.mul_assoc, mul_invOf_self, Matrix.mul_one]
section ConjTranspose
variable [StarRing α] (A : Matrix n n α)
/-- The conjugate transpose of an invertible matrix is invertible. -/
instance invertibleConjTranspose [Invertible A] : Invertible Aᴴ := Invertible.star _
lemma conjTranspose_invOf [Invertible A] [Invertible Aᴴ] : (⅟A)ᴴ = ⅟(Aᴴ) := star_invOf _
/-- A matrix is invertible if the conjugate transpose is invertible. -/
def invertibleOfInvertibleConjTranspose [Invertible Aᴴ] : Invertible A := by
rw [← conjTranspose_conjTranspose A, ← star_eq_conjTranspose]
infer_instance
@[simp] lemma isUnit_conjTranspose : IsUnit Aᴴ ↔ IsUnit A := isUnit_star
end ConjTranspose
end Semiring
section CommSemiring
variable [CommSemiring α] (A : Matrix n n α)
/-- The transpose of an invertible matrix is invertible. -/
instance invertibleTranspose [Invertible A] : Invertible Aᵀ where
invOf := (⅟A)ᵀ
invOf_mul_self := by rw [← transpose_mul, mul_invOf_self, transpose_one]
mul_invOf_self := by rw [← transpose_mul, invOf_mul_self, transpose_one]
lemma transpose_invOf [Invertible A] [Invertible Aᵀ] : (⅟A)ᵀ = ⅟(Aᵀ) := by
letI := invertibleTranspose A
convert (rfl : _ = ⅟(Aᵀ))
/-- `Aᵀ` is invertible when `A` is. -/
def invertibleOfInvertibleTranspose [Invertible Aᵀ] : Invertible A where
invOf := (⅟(Aᵀ))ᵀ
invOf_mul_self := by rw [← transpose_one, ← mul_invOf_self Aᵀ, transpose_mul, transpose_transpose]
mul_invOf_self := by rw [← transpose_one, ← invOf_mul_self Aᵀ, transpose_mul, transpose_transpose]
/-- Together `Matrix.invertibleTranspose` and `Matrix.invertibleOfInvertibleTranspose` form an
equivalence, although both sides of the equiv are subsingleton anyway. -/
@[simps]
def transposeInvertibleEquivInvertible : Invertible Aᵀ ≃ Invertible A where
toFun := @invertibleOfInvertibleTranspose _ _ _ _ _ _
invFun := @invertibleTranspose _ _ _ _ _ _
left_inv _ := Subsingleton.elim _ _
right_inv _ := Subsingleton.elim _ _
@[simp] lemma isUnit_transpose : IsUnit Aᵀ ↔ IsUnit A := by
simp only [← nonempty_invertible_iff_isUnit,
(transposeInvertibleEquivInvertible A).nonempty_congr]
end CommSemiring
end Matrix
|
Data\Matrix\Kronecker.lean | /-
Copyright (c) 2021 Filippo A. E. Nuccio. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Filippo A. E. Nuccio, Eric Wieser
-/
import Mathlib.Data.Matrix.Basic
import Mathlib.Data.Matrix.Block
import Mathlib.LinearAlgebra.Matrix.Determinant.Basic
import Mathlib.LinearAlgebra.Matrix.NonsingularInverse
import Mathlib.LinearAlgebra.TensorProduct.Basic
import Mathlib.RingTheory.TensorProduct.Basic
/-!
# Kronecker product of matrices
This defines the [Kronecker product](https://en.wikipedia.org/wiki/Kronecker_product).
## Main definitions
* `Matrix.kroneckerMap`: A generalization of the Kronecker product: given a map `f : α → β → γ`
and matrices `A` and `B` with coefficients in `α` and `β`, respectively, it is defined as the
matrix with coefficients in `γ` such that
`kroneckerMap f A B (i₁, i₂) (j₁, j₂) = f (A i₁ j₁) (B i₁ j₂)`.
* `Matrix.kroneckerMapBilinear`: when `f` is bilinear, so is `kroneckerMap f`.
## Specializations
* `Matrix.kronecker`: An alias of `kroneckerMap (*)`. Prefer using the notation.
* `Matrix.kroneckerBilinear`: `Matrix.kronecker` is bilinear
* `Matrix.kroneckerTMul`: An alias of `kroneckerMap (⊗ₜ)`. Prefer using the notation.
* `Matrix.kroneckerTMulBilinear`: `Matrix.kroneckerTMul` is bilinear
## Notations
These require `open Kronecker`:
* `A ⊗ₖ B` for `kroneckerMap (*) A B`. Lemmas about this notation use the token `kronecker`.
* `A ⊗ₖₜ B` and `A ⊗ₖₜ[R] B` for `kroneckerMap (⊗ₜ) A B`. Lemmas about this notation use the token
`kroneckerTMul`.
-/
namespace Matrix
open Matrix
open scoped RightActions
variable {R α α' β β' γ γ' : Type*}
variable {l m n p : Type*} {q r : Type*} {l' m' n' p' : Type*}
section KroneckerMap
/-- Produce a matrix with `f` applied to every pair of elements from `A` and `B`. -/
def kroneckerMap (f : α → β → γ) (A : Matrix l m α) (B : Matrix n p β) : Matrix (l × n) (m × p) γ :=
of fun (i : l × n) (j : m × p) => f (A i.1 j.1) (B i.2 j.2)
-- TODO: set as an equation lemma for `kroneckerMap`, see mathlib4#3024
@[simp]
theorem kroneckerMap_apply (f : α → β → γ) (A : Matrix l m α) (B : Matrix n p β) (i j) :
kroneckerMap f A B i j = f (A i.1 j.1) (B i.2 j.2) :=
rfl
theorem kroneckerMap_transpose (f : α → β → γ) (A : Matrix l m α) (B : Matrix n p β) :
kroneckerMap f Aᵀ Bᵀ = (kroneckerMap f A B)ᵀ :=
ext fun _ _ => rfl
theorem kroneckerMap_map_left (f : α' → β → γ) (g : α → α') (A : Matrix l m α) (B : Matrix n p β) :
kroneckerMap f (A.map g) B = kroneckerMap (fun a b => f (g a) b) A B :=
ext fun _ _ => rfl
theorem kroneckerMap_map_right (f : α → β' → γ) (g : β → β') (A : Matrix l m α) (B : Matrix n p β) :
kroneckerMap f A (B.map g) = kroneckerMap (fun a b => f a (g b)) A B :=
ext fun _ _ => rfl
theorem kroneckerMap_map (f : α → β → γ) (g : γ → γ') (A : Matrix l m α) (B : Matrix n p β) :
(kroneckerMap f A B).map g = kroneckerMap (fun a b => g (f a b)) A B :=
ext fun _ _ => rfl
@[simp]
theorem kroneckerMap_zero_left [Zero α] [Zero γ] (f : α → β → γ) (hf : ∀ b, f 0 b = 0)
(B : Matrix n p β) : kroneckerMap f (0 : Matrix l m α) B = 0 :=
ext fun _ _ => hf _
@[simp]
theorem kroneckerMap_zero_right [Zero β] [Zero γ] (f : α → β → γ) (hf : ∀ a, f a 0 = 0)
(A : Matrix l m α) : kroneckerMap f A (0 : Matrix n p β) = 0 :=
ext fun _ _ => hf _
theorem kroneckerMap_add_left [Add α] [Add γ] (f : α → β → γ)
(hf : ∀ a₁ a₂ b, f (a₁ + a₂) b = f a₁ b + f a₂ b) (A₁ A₂ : Matrix l m α) (B : Matrix n p β) :
kroneckerMap f (A₁ + A₂) B = kroneckerMap f A₁ B + kroneckerMap f A₂ B :=
ext fun _ _ => hf _ _ _
theorem kroneckerMap_add_right [Add β] [Add γ] (f : α → β → γ)
(hf : ∀ a b₁ b₂, f a (b₁ + b₂) = f a b₁ + f a b₂) (A : Matrix l m α) (B₁ B₂ : Matrix n p β) :
kroneckerMap f A (B₁ + B₂) = kroneckerMap f A B₁ + kroneckerMap f A B₂ :=
ext fun _ _ => hf _ _ _
theorem kroneckerMap_smul_left [SMul R α] [SMul R γ] (f : α → β → γ) (r : R)
(hf : ∀ a b, f (r • a) b = r • f a b) (A : Matrix l m α) (B : Matrix n p β) :
kroneckerMap f (r • A) B = r • kroneckerMap f A B :=
ext fun _ _ => hf _ _
theorem kroneckerMap_smul_right [SMul R β] [SMul R γ] (f : α → β → γ) (r : R)
(hf : ∀ a b, f a (r • b) = r • f a b) (A : Matrix l m α) (B : Matrix n p β) :
kroneckerMap f A (r • B) = r • kroneckerMap f A B :=
ext fun _ _ => hf _ _
theorem kroneckerMap_diagonal_diagonal [Zero α] [Zero β] [Zero γ] [DecidableEq m] [DecidableEq n]
(f : α → β → γ) (hf₁ : ∀ b, f 0 b = 0) (hf₂ : ∀ a, f a 0 = 0) (a : m → α) (b : n → β) :
kroneckerMap f (diagonal a) (diagonal b) = diagonal fun mn => f (a mn.1) (b mn.2) := by
ext ⟨i₁, i₂⟩ ⟨j₁, j₂⟩
simp [diagonal, apply_ite f, ite_and, ite_apply, apply_ite (f (a i₁)), hf₁, hf₂]
theorem kroneckerMap_diagonal_right [Zero β] [Zero γ] [DecidableEq n] (f : α → β → γ)
(hf : ∀ a, f a 0 = 0) (A : Matrix l m α) (b : n → β) :
kroneckerMap f A (diagonal b) = blockDiagonal fun i => A.map fun a => f a (b i) := by
ext ⟨i₁, i₂⟩ ⟨j₁, j₂⟩
simp [diagonal, blockDiagonal, apply_ite (f (A i₁ j₁)), hf]
theorem kroneckerMap_diagonal_left [Zero α] [Zero γ] [DecidableEq l] (f : α → β → γ)
(hf : ∀ b, f 0 b = 0) (a : l → α) (B : Matrix m n β) :
kroneckerMap f (diagonal a) B =
Matrix.reindex (Equiv.prodComm _ _) (Equiv.prodComm _ _)
(blockDiagonal fun i => B.map fun b => f (a i) b) := by
ext ⟨i₁, i₂⟩ ⟨j₁, j₂⟩
simp [diagonal, blockDiagonal, apply_ite f, ite_apply, hf]
@[simp]
theorem kroneckerMap_one_one [Zero α] [Zero β] [Zero γ] [One α] [One β] [One γ] [DecidableEq m]
[DecidableEq n] (f : α → β → γ) (hf₁ : ∀ b, f 0 b = 0) (hf₂ : ∀ a, f a 0 = 0)
(hf₃ : f 1 1 = 1) : kroneckerMap f (1 : Matrix m m α) (1 : Matrix n n β) = 1 :=
(kroneckerMap_diagonal_diagonal _ hf₁ hf₂ _ _).trans <| by simp only [hf₃, diagonal_one]
theorem kroneckerMap_reindex (f : α → β → γ) (el : l ≃ l') (em : m ≃ m') (en : n ≃ n') (ep : p ≃ p')
(M : Matrix l m α) (N : Matrix n p β) :
kroneckerMap f (reindex el em M) (reindex en ep N) =
reindex (el.prodCongr en) (em.prodCongr ep) (kroneckerMap f M N) := by
ext ⟨i, i'⟩ ⟨j, j'⟩
rfl
theorem kroneckerMap_reindex_left (f : α → β → γ) (el : l ≃ l') (em : m ≃ m') (M : Matrix l m α)
(N : Matrix n n' β) :
kroneckerMap f (Matrix.reindex el em M) N =
reindex (el.prodCongr (Equiv.refl _)) (em.prodCongr (Equiv.refl _)) (kroneckerMap f M N) :=
kroneckerMap_reindex _ _ _ (Equiv.refl _) (Equiv.refl _) _ _
theorem kroneckerMap_reindex_right (f : α → β → γ) (em : m ≃ m') (en : n ≃ n') (M : Matrix l l' α)
(N : Matrix m n β) :
kroneckerMap f M (reindex em en N) =
reindex ((Equiv.refl _).prodCongr em) ((Equiv.refl _).prodCongr en) (kroneckerMap f M N) :=
kroneckerMap_reindex _ (Equiv.refl _) (Equiv.refl _) _ _ _ _
theorem kroneckerMap_assoc {δ ξ ω ω' : Type*} (f : α → β → γ) (g : γ → δ → ω) (f' : α → ξ → ω')
(g' : β → δ → ξ) (A : Matrix l m α) (B : Matrix n p β) (D : Matrix q r δ) (φ : ω ≃ ω')
(hφ : ∀ a b d, φ (g (f a b) d) = f' a (g' b d)) :
(reindex (Equiv.prodAssoc l n q) (Equiv.prodAssoc m p r)).trans (Equiv.mapMatrix φ)
(kroneckerMap g (kroneckerMap f A B) D) =
kroneckerMap f' A (kroneckerMap g' B D) :=
ext fun _ _ => hφ _ _ _
theorem kroneckerMap_assoc₁ {δ ξ ω : Type*} (f : α → β → γ) (g : γ → δ → ω) (f' : α → ξ → ω)
(g' : β → δ → ξ) (A : Matrix l m α) (B : Matrix n p β) (D : Matrix q r δ)
(h : ∀ a b d, g (f a b) d = f' a (g' b d)) :
reindex (Equiv.prodAssoc l n q) (Equiv.prodAssoc m p r)
(kroneckerMap g (kroneckerMap f A B) D) =
kroneckerMap f' A (kroneckerMap g' B D) :=
ext fun _ _ => h _ _ _
/-- When `f` is bilinear then `Matrix.kroneckerMap f` is also bilinear. -/
@[simps!]
def kroneckerMapBilinear [CommSemiring R] [AddCommMonoid α] [AddCommMonoid β] [AddCommMonoid γ]
[Module R α] [Module R β] [Module R γ] (f : α →ₗ[R] β →ₗ[R] γ) :
Matrix l m α →ₗ[R] Matrix n p β →ₗ[R] Matrix (l × n) (m × p) γ :=
LinearMap.mk₂ R (kroneckerMap fun r s => f r s) (kroneckerMap_add_left _ <| f.map_add₂)
(fun _ => kroneckerMap_smul_left _ _ <| f.map_smul₂ _)
(kroneckerMap_add_right _ fun a => (f a).map_add) fun r =>
kroneckerMap_smul_right _ _ fun a => (f a).map_smul r
/-- `Matrix.kroneckerMapBilinear` commutes with `*` if `f` does.
This is primarily used with `R = ℕ` to prove `Matrix.mul_kronecker_mul`. -/
theorem kroneckerMapBilinear_mul_mul [CommSemiring R] [Fintype m] [Fintype m']
[NonUnitalNonAssocSemiring α] [NonUnitalNonAssocSemiring β] [NonUnitalNonAssocSemiring γ]
[Module R α] [Module R β] [Module R γ] (f : α →ₗ[R] β →ₗ[R] γ)
(h_comm : ∀ a b a' b', f (a * b) (a' * b') = f a a' * f b b') (A : Matrix l m α)
(B : Matrix m n α) (A' : Matrix l' m' β) (B' : Matrix m' n' β) :
kroneckerMapBilinear f (A * B) (A' * B') =
kroneckerMapBilinear f A A' * kroneckerMapBilinear f B B' := by
ext ⟨i, i'⟩ ⟨j, j'⟩
simp only [kroneckerMapBilinear_apply_apply, mul_apply, ← Finset.univ_product_univ,
Finset.sum_product, kroneckerMap_apply]
simp_rw [map_sum f, LinearMap.sum_apply, map_sum, h_comm]
/-- `trace` distributes over `Matrix.kroneckerMapBilinear`.
This is primarily used with `R = ℕ` to prove `Matrix.trace_kronecker`. -/
theorem trace_kroneckerMapBilinear [CommSemiring R] [Fintype m] [Fintype n] [AddCommMonoid α]
[AddCommMonoid β] [AddCommMonoid γ] [Module R α] [Module R β] [Module R γ]
(f : α →ₗ[R] β →ₗ[R] γ) (A : Matrix m m α) (B : Matrix n n β) :
trace (kroneckerMapBilinear f A B) = f (trace A) (trace B) := by
simp_rw [Matrix.trace, Matrix.diag, kroneckerMapBilinear_apply_apply, LinearMap.map_sum₂,
map_sum, ← Finset.univ_product_univ, Finset.sum_product, kroneckerMap_apply]
/-- `determinant` of `Matrix.kroneckerMapBilinear`.
This is primarily used with `R = ℕ` to prove `Matrix.det_kronecker`. -/
theorem det_kroneckerMapBilinear [CommSemiring R] [Fintype m] [Fintype n] [DecidableEq m]
[DecidableEq n] [CommRing α] [CommRing β] [CommRing γ] [Module R α] [Module R β] [Module R γ]
(f : α →ₗ[R] β →ₗ[R] γ) (h_comm : ∀ a b a' b', f (a * b) (a' * b') = f a a' * f b b')
(A : Matrix m m α) (B : Matrix n n β) :
det (kroneckerMapBilinear f A B) =
det (A.map fun a => f a 1) ^ Fintype.card n * det (B.map fun b => f 1 b) ^ Fintype.card m :=
calc
det (kroneckerMapBilinear f A B) =
det (kroneckerMapBilinear f A 1 * kroneckerMapBilinear f 1 B) := by
rw [← kroneckerMapBilinear_mul_mul f h_comm, Matrix.mul_one, Matrix.one_mul]
_ = det (blockDiagonal fun _ => A.map fun a => f a 1) *
det (blockDiagonal fun _ => B.map fun b => f 1 b) := by
rw [det_mul, ← diagonal_one, ← diagonal_one, kroneckerMapBilinear_apply_apply,
kroneckerMap_diagonal_right _ fun _ => _, kroneckerMapBilinear_apply_apply,
kroneckerMap_diagonal_left _ fun _ => _, det_reindex_self]
· intro; exact LinearMap.map_zero₂ _ _
· intro; exact map_zero _
_ = _ := by simp_rw [det_blockDiagonal, Finset.prod_const, Finset.card_univ]
end KroneckerMap
/-! ### Specialization to `Matrix.kroneckerMap (*)` -/
section Kronecker
open Matrix
/-- The Kronecker product. This is just a shorthand for `kroneckerMap (*)`. Prefer the notation
`⊗ₖ` rather than this definition. -/
@[simp]
def kronecker [Mul α] : Matrix l m α → Matrix n p α → Matrix (l × n) (m × p) α :=
kroneckerMap (· * ·)
scoped[Kronecker] infixl:100 " ⊗ₖ " => Matrix.kroneckerMap (· * ·)
open Kronecker
@[simp]
theorem kronecker_apply [Mul α] (A : Matrix l m α) (B : Matrix n p α) (i₁ i₂ j₁ j₂) :
(A ⊗ₖ B) (i₁, i₂) (j₁, j₂) = A i₁ j₁ * B i₂ j₂ :=
rfl
/-- `Matrix.kronecker` as a bilinear map. -/
def kroneckerBilinear [CommSemiring R] [Semiring α] [Algebra R α] :
Matrix l m α →ₗ[R] Matrix n p α →ₗ[R] Matrix (l × n) (m × p) α :=
kroneckerMapBilinear (Algebra.lmul R α)
/-! What follows is a copy, in order, of every `Matrix.kroneckerMap` lemma above that has
hypotheses which can be filled by properties of `*`. -/
-- @[simp] -- Porting note (#10618): simp can prove this
theorem zero_kronecker [MulZeroClass α] (B : Matrix n p α) : (0 : Matrix l m α) ⊗ₖ B = 0 :=
kroneckerMap_zero_left _ zero_mul B
-- @[simp] -- Porting note (#10618): simp can prove this
theorem kronecker_zero [MulZeroClass α] (A : Matrix l m α) : A ⊗ₖ (0 : Matrix n p α) = 0 :=
kroneckerMap_zero_right _ mul_zero A
theorem add_kronecker [Distrib α] (A₁ A₂ : Matrix l m α) (B : Matrix n p α) :
(A₁ + A₂) ⊗ₖ B = A₁ ⊗ₖ B + A₂ ⊗ₖ B :=
kroneckerMap_add_left _ add_mul _ _ _
theorem kronecker_add [Distrib α] (A : Matrix l m α) (B₁ B₂ : Matrix n p α) :
A ⊗ₖ (B₁ + B₂) = A ⊗ₖ B₁ + A ⊗ₖ B₂ :=
kroneckerMap_add_right _ mul_add _ _ _
theorem smul_kronecker [Monoid R] [Monoid α] [MulAction R α] [IsScalarTower R α α] (r : R)
(A : Matrix l m α) (B : Matrix n p α) : (r • A) ⊗ₖ B = r • A ⊗ₖ B :=
kroneckerMap_smul_left _ _ (fun _ _ => smul_mul_assoc _ _ _) _ _
theorem kronecker_smul [Monoid R] [Monoid α] [MulAction R α] [SMulCommClass R α α] (r : R)
(A : Matrix l m α) (B : Matrix n p α) : A ⊗ₖ (r • B) = r • A ⊗ₖ B :=
kroneckerMap_smul_right _ _ (fun _ _ => mul_smul_comm _ _ _) _ _
theorem diagonal_kronecker_diagonal [MulZeroClass α] [DecidableEq m] [DecidableEq n] (a : m → α)
(b : n → α) : diagonal a ⊗ₖ diagonal b = diagonal fun mn => a mn.1 * b mn.2 :=
kroneckerMap_diagonal_diagonal _ zero_mul mul_zero _ _
theorem kronecker_diagonal [MulZeroClass α] [DecidableEq n] (A : Matrix l m α) (b : n → α) :
A ⊗ₖ diagonal b = blockDiagonal fun i => A <• b i :=
kroneckerMap_diagonal_right _ mul_zero _ _
theorem diagonal_kronecker [MulZeroClass α] [DecidableEq l] (a : l → α) (B : Matrix m n α) :
diagonal a ⊗ₖ B =
Matrix.reindex (Equiv.prodComm _ _) (Equiv.prodComm _ _) (blockDiagonal fun i => a i • B) :=
kroneckerMap_diagonal_left _ zero_mul _ _
@[simp]
theorem natCast_kronecker_natCast [NonAssocSemiring α] [DecidableEq m] [DecidableEq n] (a b : ℕ) :
(a : Matrix m m α) ⊗ₖ (b : Matrix n n α) = ↑(a * b) :=
(diagonal_kronecker_diagonal _ _).trans <| by simp_rw [← Nat.cast_mul]; rfl
theorem kronecker_natCast [NonAssocSemiring α] [DecidableEq n] (A : Matrix l m α) (b : ℕ) :
A ⊗ₖ (b : Matrix n n α) = blockDiagonal fun _ => b • A :=
kronecker_diagonal _ _ |>.trans <| by
congr! 2
ext
simp [(Nat.cast_commute b _).eq]
theorem natCast_kronecker [NonAssocSemiring α] [DecidableEq l] (a : ℕ) (B : Matrix m n α) :
(a : Matrix l l α) ⊗ₖ B =
Matrix.reindex (Equiv.prodComm _ _) (Equiv.prodComm _ _) (blockDiagonal fun _ => a • B) :=
diagonal_kronecker _ _ |>.trans <| by
congr! 2
ext
simp [(Nat.cast_commute a _).eq]
theorem kronecker_ofNat [Semiring α] [DecidableEq n] (A : Matrix l m α) (b : ℕ) [b.AtLeastTwo] :
A ⊗ₖ (no_index (OfNat.ofNat b) : Matrix n n α) =
blockDiagonal fun _ => A <• (OfNat.ofNat b : α) :=
kronecker_diagonal _ _
theorem ofNat_kronecker [Semiring α] [DecidableEq l] (a : ℕ) [a.AtLeastTwo] (B : Matrix m n α) :
(no_index (OfNat.ofNat a) : Matrix l l α) ⊗ₖ B =
Matrix.reindex (.prodComm _ _) (.prodComm _ _)
(blockDiagonal fun _ => (OfNat.ofNat a : α) • B) :=
diagonal_kronecker _ _
-- @[simp] -- Porting note (#10618): simp can prove this
theorem one_kronecker_one [MulZeroOneClass α] [DecidableEq m] [DecidableEq n] :
(1 : Matrix m m α) ⊗ₖ (1 : Matrix n n α) = 1 :=
kroneckerMap_one_one _ zero_mul mul_zero (one_mul _)
theorem kronecker_one [MulZeroOneClass α] [DecidableEq n] (A : Matrix l m α) :
A ⊗ₖ (1 : Matrix n n α) = blockDiagonal fun _ => A :=
(kronecker_diagonal _ _).trans <| congr_arg _ <| funext fun _ => Matrix.ext fun _ _ => mul_one _
theorem one_kronecker [MulZeroOneClass α] [DecidableEq l] (B : Matrix m n α) :
(1 : Matrix l l α) ⊗ₖ B =
Matrix.reindex (Equiv.prodComm _ _) (Equiv.prodComm _ _) (blockDiagonal fun _ => B) :=
(diagonal_kronecker _ _).trans <|
congr_arg _ <| congr_arg _ <| funext fun _ => Matrix.ext fun _ _ => one_mul _
theorem mul_kronecker_mul [Fintype m] [Fintype m'] [CommSemiring α] (A : Matrix l m α)
(B : Matrix m n α) (A' : Matrix l' m' α) (B' : Matrix m' n' α) :
(A * B) ⊗ₖ (A' * B') = A ⊗ₖ A' * B ⊗ₖ B' :=
kroneckerMapBilinear_mul_mul (Algebra.lmul ℕ α).toLinearMap mul_mul_mul_comm A B A' B'
-- @[simp] -- Porting note: simp-normal form is `kronecker_assoc'`
theorem kronecker_assoc [Semigroup α] (A : Matrix l m α) (B : Matrix n p α) (C : Matrix q r α) :
reindex (Equiv.prodAssoc l n q) (Equiv.prodAssoc m p r) (A ⊗ₖ B ⊗ₖ C) = A ⊗ₖ (B ⊗ₖ C) :=
kroneckerMap_assoc₁ _ _ _ _ A B C mul_assoc
@[simp]
theorem kronecker_assoc' [Semigroup α] (A : Matrix l m α) (B : Matrix n p α) (C : Matrix q r α) :
submatrix (A ⊗ₖ B ⊗ₖ C) (Equiv.prodAssoc l n q).symm (Equiv.prodAssoc m p r).symm =
A ⊗ₖ (B ⊗ₖ C) :=
kroneckerMap_assoc₁ _ _ _ _ A B C mul_assoc
theorem trace_kronecker [Fintype m] [Fintype n] [Semiring α] (A : Matrix m m α) (B : Matrix n n α) :
trace (A ⊗ₖ B) = trace A * trace B :=
trace_kroneckerMapBilinear (Algebra.lmul ℕ α).toLinearMap _ _
theorem det_kronecker [Fintype m] [Fintype n] [DecidableEq m] [DecidableEq n] [CommRing R]
(A : Matrix m m R) (B : Matrix n n R) :
det (A ⊗ₖ B) = det A ^ Fintype.card n * det B ^ Fintype.card m := by
refine (det_kroneckerMapBilinear (Algebra.lmul ℕ R).toLinearMap mul_mul_mul_comm _ _).trans ?_
congr 3
· ext i j
exact mul_one _
· ext i j
exact one_mul _
theorem inv_kronecker [Fintype m] [Fintype n] [DecidableEq m] [DecidableEq n] [CommRing R]
(A : Matrix m m R) (B : Matrix n n R) : (A ⊗ₖ B)⁻¹ = A⁻¹ ⊗ₖ B⁻¹ := by
-- handle the special cases where either matrix is not invertible
by_cases hA : IsUnit A.det
swap
· cases isEmpty_or_nonempty n
· subsingleton
have hAB : ¬IsUnit (A ⊗ₖ B).det := by
refine mt (fun hAB => ?_) hA
rw [det_kronecker] at hAB
exact (isUnit_pow_iff Fintype.card_ne_zero).mp (isUnit_of_mul_isUnit_left hAB)
rw [nonsing_inv_apply_not_isUnit _ hA, zero_kronecker, nonsing_inv_apply_not_isUnit _ hAB]
by_cases hB : IsUnit B.det; swap
· cases isEmpty_or_nonempty m
· subsingleton
have hAB : ¬IsUnit (A ⊗ₖ B).det := by
refine mt (fun hAB => ?_) hB
rw [det_kronecker] at hAB
exact (isUnit_pow_iff Fintype.card_ne_zero).mp (isUnit_of_mul_isUnit_right hAB)
rw [nonsing_inv_apply_not_isUnit _ hB, kronecker_zero, nonsing_inv_apply_not_isUnit _ hAB]
-- otherwise follows trivially from `mul_kronecker_mul`
· apply inv_eq_right_inv
rw [← mul_kronecker_mul, ← one_kronecker_one, mul_nonsing_inv _ hA, mul_nonsing_inv _ hB]
end Kronecker
/-! ### Specialization to `Matrix.kroneckerMap (⊗ₜ)` -/
section KroneckerTmul
variable (R)
open TensorProduct
open Matrix TensorProduct
section Module
suppress_compilation
variable [CommSemiring R] [AddCommMonoid α] [AddCommMonoid β] [AddCommMonoid γ]
variable [Module R α] [Module R β] [Module R γ]
/-- The Kronecker tensor product. This is just a shorthand for `kroneckerMap (⊗ₜ)`.
Prefer the notation `⊗ₖₜ` rather than this definition. -/
@[simp]
def kroneckerTMul : Matrix l m α → Matrix n p β → Matrix (l × n) (m × p) (α ⊗[R] β) :=
kroneckerMap (· ⊗ₜ ·)
scoped[Kronecker] infixl:100 " ⊗ₖₜ " => Matrix.kroneckerMap (· ⊗ₜ ·)
scoped[Kronecker]
notation:100 x " ⊗ₖₜ[" R "] " y:100 => Matrix.kroneckerMap (TensorProduct.tmul R) x y
open Kronecker
@[simp]
theorem kroneckerTMul_apply (A : Matrix l m α) (B : Matrix n p β) (i₁ i₂ j₁ j₂) :
(A ⊗ₖₜ B) (i₁, i₂) (j₁, j₂) = A i₁ j₁ ⊗ₜ[R] B i₂ j₂ :=
rfl
/-- `Matrix.kronecker` as a bilinear map. -/
def kroneckerTMulBilinear :
Matrix l m α →ₗ[R] Matrix n p β →ₗ[R] Matrix (l × n) (m × p) (α ⊗[R] β) :=
kroneckerMapBilinear (TensorProduct.mk R α β)
/-! What follows is a copy, in order, of every `Matrix.kroneckerMap` lemma above that has
hypotheses which can be filled by properties of `⊗ₜ`. -/
-- @[simp] -- Porting note (#10618): simp can prove this
theorem zero_kroneckerTMul (B : Matrix n p β) : (0 : Matrix l m α) ⊗ₖₜ[R] B = 0 :=
kroneckerMap_zero_left _ (zero_tmul α) B
-- @[simp] -- Porting note (#10618): simp can prove this
theorem kroneckerTMul_zero (A : Matrix l m α) : A ⊗ₖₜ[R] (0 : Matrix n p β) = 0 :=
kroneckerMap_zero_right _ (tmul_zero β) A
theorem add_kroneckerTMul (A₁ A₂ : Matrix l m α) (B : Matrix n p α) :
(A₁ + A₂) ⊗ₖₜ[R] B = A₁ ⊗ₖₜ B + A₂ ⊗ₖₜ B :=
kroneckerMap_add_left _ add_tmul _ _ _
theorem kroneckerTMul_add (A : Matrix l m α) (B₁ B₂ : Matrix n p α) :
A ⊗ₖₜ[R] (B₁ + B₂) = A ⊗ₖₜ B₁ + A ⊗ₖₜ B₂ :=
kroneckerMap_add_right _ tmul_add _ _ _
theorem smul_kroneckerTMul (r : R) (A : Matrix l m α) (B : Matrix n p α) :
(r • A) ⊗ₖₜ[R] B = r • A ⊗ₖₜ B :=
kroneckerMap_smul_left _ _ (fun _ _ => smul_tmul' _ _ _) _ _
theorem kroneckerTMul_smul (r : R) (A : Matrix l m α) (B : Matrix n p α) :
A ⊗ₖₜ[R] (r • B) = r • A ⊗ₖₜ B :=
kroneckerMap_smul_right _ _ (fun _ _ => tmul_smul _ _ _) _ _
theorem diagonal_kroneckerTMul_diagonal [DecidableEq m] [DecidableEq n] (a : m → α) (b : n → α) :
diagonal a ⊗ₖₜ[R] diagonal b = diagonal fun mn => a mn.1 ⊗ₜ b mn.2 :=
kroneckerMap_diagonal_diagonal _ (zero_tmul _) (tmul_zero _) _ _
theorem kroneckerTMul_diagonal [DecidableEq n] (A : Matrix l m α) (b : n → α) :
A ⊗ₖₜ[R] diagonal b = blockDiagonal fun i => A.map fun a => a ⊗ₜ[R] b i :=
kroneckerMap_diagonal_right _ (tmul_zero _) _ _
theorem diagonal_kroneckerTMul [DecidableEq l] (a : l → α) (B : Matrix m n α) :
diagonal a ⊗ₖₜ[R] B =
Matrix.reindex (Equiv.prodComm _ _) (Equiv.prodComm _ _)
(blockDiagonal fun i => B.map fun b => a i ⊗ₜ[R] b) :=
kroneckerMap_diagonal_left _ (zero_tmul _) _ _
-- @[simp] -- Porting note: simp-normal form is `kroneckerTMul_assoc'`
theorem kroneckerTMul_assoc (A : Matrix l m α) (B : Matrix n p β) (C : Matrix q r γ) :
reindex (Equiv.prodAssoc l n q) (Equiv.prodAssoc m p r)
(((A ⊗ₖₜ[R] B) ⊗ₖₜ[R] C).map (TensorProduct.assoc R α β γ)) =
A ⊗ₖₜ[R] B ⊗ₖₜ[R] C :=
ext fun _ _ => assoc_tmul _ _ _
@[simp]
theorem kroneckerTMul_assoc' (A : Matrix l m α) (B : Matrix n p β) (C : Matrix q r γ) :
submatrix (((A ⊗ₖₜ[R] B) ⊗ₖₜ[R] C).map (TensorProduct.assoc R α β γ))
(Equiv.prodAssoc l n q).symm (Equiv.prodAssoc m p r).symm = A ⊗ₖₜ[R] B ⊗ₖₜ[R] C :=
ext fun _ _ => assoc_tmul _ _ _
theorem trace_kroneckerTMul [Fintype m] [Fintype n] (A : Matrix m m α) (B : Matrix n n β) :
trace (A ⊗ₖₜ[R] B) = trace A ⊗ₜ[R] trace B :=
trace_kroneckerMapBilinear (TensorProduct.mk R α β) _ _
end Module
section Algebra
open Kronecker
open Algebra.TensorProduct
section Semiring
variable [CommSemiring R] [Semiring α] [Semiring β] [Algebra R α] [Algebra R β]
@[simp]
theorem one_kroneckerTMul_one [DecidableEq m] [DecidableEq n] :
(1 : Matrix m m α) ⊗ₖₜ[R] (1 : Matrix n n α) = 1 :=
kroneckerMap_one_one _ (zero_tmul _) (tmul_zero _) rfl
unseal mul in
theorem mul_kroneckerTMul_mul [Fintype m] [Fintype m'] (A : Matrix l m α) (B : Matrix m n α)
(A' : Matrix l' m' β) (B' : Matrix m' n' β) :
(A * B) ⊗ₖₜ[R] (A' * B') = A ⊗ₖₜ[R] A' * B ⊗ₖₜ[R] B' :=
kroneckerMapBilinear_mul_mul (TensorProduct.mk R α β) tmul_mul_tmul A B A' B'
end Semiring
section CommRing
variable [CommRing R] [CommRing α] [CommRing β] [Algebra R α] [Algebra R β]
unseal mul in
theorem det_kroneckerTMul [Fintype m] [Fintype n] [DecidableEq m] [DecidableEq n]
(A : Matrix m m α) (B : Matrix n n β) :
det (A ⊗ₖₜ[R] B) = (det A ^ Fintype.card n) ⊗ₜ[R] (det B ^ Fintype.card m) := by
refine (det_kroneckerMapBilinear (TensorProduct.mk R α β) tmul_mul_tmul _ _).trans ?_
simp (config := { eta := false }) only [mk_apply, ← includeLeft_apply (S := R),
← includeRight_apply]
simp only [← AlgHom.mapMatrix_apply, ← AlgHom.map_det]
simp only [includeLeft_apply, includeRight_apply, tmul_pow, tmul_mul_tmul, one_pow,
_root_.mul_one, _root_.one_mul]
end CommRing
end Algebra
-- insert lemmas specific to `kroneckerTMul` below this line
end KroneckerTmul
end Matrix
|
Data\Matrix\Notation.lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen, Eric Wieser
-/
import Mathlib.Algebra.Group.Fin.Tuple
import Mathlib.Data.Matrix.Basic
import Mathlib.Data.Matrix.RowCol
import Mathlib.Data.Fin.VecNotation
import Mathlib.Tactic.FinCases
/-!
# Matrix and vector notation
This file includes `simp` lemmas for applying operations in `Data.Matrix.Basic` to values built out
of the matrix notation `![a, b] = vecCons a (vecCons b vecEmpty)` defined in
`Data.Fin.VecNotation`.
This also provides the new notation `!![a, b; c, d] = Matrix.of ![![a, b], ![c, d]]`.
This notation also works for empty matrices; `!![,,,] : Matrix (Fin 0) (Fin 3)` and
`!![;;;] : Matrix (Fin 3) (Fin 0)`.
## Implementation notes
The `simp` lemmas require that one of the arguments is of the form `vecCons _ _`.
This ensures `simp` works with entries only when (some) entries are already given.
In other words, this notation will only appear in the output of `simp` if it
already appears in the input.
## Notations
This file provide notation `!![a, b; c, d]` for matrices, which corresponds to
`Matrix.of ![![a, b], ![c, d]]`.
## Examples
Examples of usage can be found in the `test/matrix.lean` file.
-/
namespace Matrix
universe u uₘ uₙ uₒ
variable {α : Type u} {o n m : ℕ} {m' : Type uₘ} {n' : Type uₙ} {o' : Type uₒ}
open Matrix
section toExpr
open Lean
open Qq
/-- Matrices can be reflected whenever their entries can. We insert a `Matrix.of` to
prevent immediate decay to a function. -/
protected instance toExpr [ToLevel.{u}] [ToLevel.{uₘ}] [ToLevel.{uₙ}]
[Lean.ToExpr α] [Lean.ToExpr m'] [Lean.ToExpr n'] [Lean.ToExpr (m' → n' → α)] :
Lean.ToExpr (Matrix m' n' α) :=
have eα : Q(Type $(toLevel.{u})) := toTypeExpr α
have em' : Q(Type $(toLevel.{uₘ})) := toTypeExpr m'
have en' : Q(Type $(toLevel.{uₙ})) := toTypeExpr n'
{ toTypeExpr :=
q(Matrix $eα $em' $en')
toExpr := fun M =>
have eM : Q($em' → $en' → $eα) := toExpr (show m' → n' → α from M)
q(Matrix.of $eM) }
end toExpr
section Parser
open Lean Meta Elab Term Macro TSyntax PrettyPrinter.Delaborator SubExpr
/-- Notation for m×n matrices, aka `Matrix (Fin m) (Fin n) α`.
For instance:
* `!![a, b, c; d, e, f]` is the matrix with two rows and three columns, of type
`Matrix (Fin 2) (Fin 3) α`
* `!![a, b, c]` is a row vector of type `Matrix (Fin 1) (Fin 3) α` (see also `Matrix.row`).
* `!![a; b; c]` is a column vector of type `Matrix (Fin 3) (Fin 1) α` (see also `Matrix.col`).
This notation implements some special cases:
* `![,,]`, with `n` `,`s, is a term of type `Matrix (Fin 0) (Fin n) α`
* `![;;]`, with `m` `;`s, is a term of type `Matrix (Fin m) (Fin 0) α`
* `![]` is the 0×0 matrix
Note that vector notation is provided elsewhere (by `Matrix.vecNotation`) as `![a, b, c]`.
Under the hood, `!![a, b, c; d, e, f]` is syntax for `Matrix.of ![![a, b, c], ![d, e, f]]`.
-/
syntax (name := matrixNotation)
"!![" ppRealGroup(sepBy1(ppGroup(term,+,?), ";", "; ", allowTrailingSep)) "]" : term
@[inherit_doc matrixNotation]
syntax (name := matrixNotationRx0) "!![" ";"+ "]" : term
@[inherit_doc matrixNotation]
syntax (name := matrixNotation0xC) "!![" ","* "]" : term
macro_rules
| `(!![$[$[$rows],*];*]) => do
let m := rows.size
let n := if h : 0 < m then rows[0].size else 0
let rowVecs ← rows.mapM fun row : Array Term => do
unless row.size = n do
Macro.throwErrorAt (mkNullNode row) s!"\
Rows must be of equal length; this row has {row.size} items, \
the previous rows have {n}"
`(![$row,*])
`(@Matrix.of (Fin $(quote m)) (Fin $(quote n)) _ ![$rowVecs,*])
| `(!![$[;%$semicolons]*]) => do
let emptyVec ← `(![])
let emptyVecs := semicolons.map (fun _ => emptyVec)
`(@Matrix.of (Fin $(quote semicolons.size)) (Fin 0) _ ![$emptyVecs,*])
| `(!![$[,%$commas]*]) => `(@Matrix.of (Fin 0) (Fin $(quote commas.size)) _ ![])
/-- Delaborator for the `!![]` notation. -/
@[delab app.DFunLike.coe]
def delabMatrixNotation : Delab := whenNotPPOption getPPExplicit <| whenPPOption getPPNotation <|
withOverApp 6 do
let mkApp3 (.const ``Matrix.of _) (.app (.const ``Fin _) em) (.app (.const ``Fin _) en) _ :=
(← getExpr).appFn!.appArg! | failure
let some m ← withNatValue em (pure ∘ some) | failure
let some n ← withNatValue en (pure ∘ some) | failure
withAppArg do
if m = 0 then
guard <| (← getExpr).isAppOfArity ``vecEmpty 1
let commas := mkArray n (mkAtom ",")
`(!![$[,%$commas]*])
else
if n = 0 then
let `(![$[![]%$evecs],*]) ← delab | failure
`(!![$[;%$evecs]*])
else
let `(![$[![$[$melems],*]],*]) ← delab | failure
`(!![$[$[$melems],*];*])
end Parser
variable (a b : ℕ)
/-- Use `![...]` notation for displaying a `Fin`-indexed matrix, for example:
```
#eval !![1, 2; 3, 4] + !![3, 4; 5, 6] -- !![4, 6; 8, 10]
```
-/
instance repr [Repr α] : Repr (Matrix (Fin m) (Fin n) α) where
reprPrec f _p :=
(Std.Format.bracket "!![" · "]") <|
(Std.Format.joinSep · (";" ++ Std.Format.line)) <|
(List.finRange m).map fun i =>
Std.Format.fill <| -- wrap line in a single place rather than all at once
(Std.Format.joinSep · ("," ++ Std.Format.line)) <|
(List.finRange n).map fun j => _root_.repr (f i j)
@[simp]
theorem cons_val' (v : n' → α) (B : Fin m → n' → α) (i j) :
vecCons v B i j = vecCons (v j) (fun i => B i j) i := by refine Fin.cases ?_ ?_ i <;> simp
@[simp]
theorem head_val' (B : Fin m.succ → n' → α) (j : n') : (vecHead fun i => B i j) = vecHead B j :=
rfl
@[simp]
theorem tail_val' (B : Fin m.succ → n' → α) (j : n') :
(vecTail fun i => B i j) = fun i => vecTail B i j := rfl
section DotProduct
variable [AddCommMonoid α] [Mul α]
@[simp]
theorem dotProduct_empty (v w : Fin 0 → α) : dotProduct v w = 0 :=
Finset.sum_empty
@[simp]
theorem cons_dotProduct (x : α) (v : Fin n → α) (w : Fin n.succ → α) :
dotProduct (vecCons x v) w = x * vecHead w + dotProduct v (vecTail w) := by
simp [dotProduct, Fin.sum_univ_succ, vecHead, vecTail]
@[simp]
theorem dotProduct_cons (v : Fin n.succ → α) (x : α) (w : Fin n → α) :
dotProduct v (vecCons x w) = vecHead v * x + dotProduct (vecTail v) w := by
simp [dotProduct, Fin.sum_univ_succ, vecHead, vecTail]
-- @[simp] -- Porting note (#10618): simp can prove this
theorem cons_dotProduct_cons (x : α) (v : Fin n → α) (y : α) (w : Fin n → α) :
dotProduct (vecCons x v) (vecCons y w) = x * y + dotProduct v w := by simp
end DotProduct
section ColRow
variable {ι : Type*}
@[simp]
theorem col_empty (v : Fin 0 → α) : col ι v = vecEmpty :=
empty_eq _
@[simp]
theorem col_cons (x : α) (u : Fin m → α) :
col ι (vecCons x u) = of (vecCons (fun _ => x) (col ι u)) := by
ext i j
refine Fin.cases ?_ ?_ i <;> simp [vecHead, vecTail]
@[simp]
theorem row_empty : row ι (vecEmpty : Fin 0 → α) = of fun _ => vecEmpty := rfl
@[simp]
theorem row_cons (x : α) (u : Fin m → α) : row ι (vecCons x u) = of fun _ => vecCons x u :=
rfl
end ColRow
section Transpose
@[simp]
theorem transpose_empty_rows (A : Matrix m' (Fin 0) α) : Aᵀ = of ![] :=
empty_eq _
@[simp]
theorem transpose_empty_cols (A : Matrix (Fin 0) m' α) : Aᵀ = of fun _ => ![] :=
funext fun _ => empty_eq _
@[simp]
theorem cons_transpose (v : n' → α) (A : Matrix (Fin m) n' α) :
(of (vecCons v A))ᵀ = of fun i => vecCons (v i) (Aᵀ i) := by
ext i j
refine Fin.cases ?_ ?_ j <;> simp
@[simp]
theorem head_transpose (A : Matrix m' (Fin n.succ) α) :
vecHead (of.symm Aᵀ) = vecHead ∘ of.symm A :=
rfl
@[simp]
theorem tail_transpose (A : Matrix m' (Fin n.succ) α) : vecTail (of.symm Aᵀ) = (vecTail ∘ A)ᵀ := by
ext i j
rfl
end Transpose
section Mul
variable [NonUnitalNonAssocSemiring α]
@[simp]
theorem empty_mul [Fintype n'] (A : Matrix (Fin 0) n' α) (B : Matrix n' o' α) : A * B = of ![] :=
empty_eq _
@[simp]
theorem empty_mul_empty (A : Matrix m' (Fin 0) α) (B : Matrix (Fin 0) o' α) : A * B = 0 :=
rfl
@[simp]
theorem mul_empty [Fintype n'] (A : Matrix m' n' α) (B : Matrix n' (Fin 0) α) :
A * B = of fun _ => ![] :=
funext fun _ => empty_eq _
theorem mul_val_succ [Fintype n'] (A : Matrix (Fin m.succ) n' α) (B : Matrix n' o' α) (i : Fin m)
(j : o') : (A * B) i.succ j = (of (vecTail (of.symm A)) * B) i j :=
rfl
@[simp]
theorem cons_mul [Fintype n'] (v : n' → α) (A : Fin m → n' → α) (B : Matrix n' o' α) :
of (vecCons v A) * B = of (vecCons (v ᵥ* B) (of.symm (of A * B))) := by
ext i j
refine Fin.cases ?_ ?_ i
· rfl
simp [mul_val_succ]
end Mul
section VecMul
variable [NonUnitalNonAssocSemiring α]
@[simp]
theorem empty_vecMul (v : Fin 0 → α) (B : Matrix (Fin 0) o' α) : v ᵥ* B = 0 :=
rfl
@[simp]
theorem vecMul_empty [Fintype n'] (v : n' → α) (B : Matrix n' (Fin 0) α) : v ᵥ* B = ![] :=
empty_eq _
@[simp]
theorem cons_vecMul (x : α) (v : Fin n → α) (B : Fin n.succ → o' → α) :
vecCons x v ᵥ* of B = x • vecHead B + v ᵥ* of (vecTail B) := by
ext i
simp [vecMul]
@[simp]
theorem vecMul_cons (v : Fin n.succ → α) (w : o' → α) (B : Fin n → o' → α) :
v ᵥ* of (vecCons w B) = vecHead v • w + vecTail v ᵥ* of B := by
ext i
simp [vecMul]
-- @[simp] -- Porting note (#10618): simp can prove this
theorem cons_vecMul_cons (x : α) (v : Fin n → α) (w : o' → α) (B : Fin n → o' → α) :
vecCons x v ᵥ* of (vecCons w B) = x • w + v ᵥ* of B := by simp
end VecMul
section MulVec
variable [NonUnitalNonAssocSemiring α]
@[simp]
theorem empty_mulVec [Fintype n'] (A : Matrix (Fin 0) n' α) (v : n' → α) : A *ᵥ v = ![] :=
empty_eq _
@[simp]
theorem mulVec_empty (A : Matrix m' (Fin 0) α) (v : Fin 0 → α) : A *ᵥ v = 0 :=
rfl
@[simp]
theorem cons_mulVec [Fintype n'] (v : n' → α) (A : Fin m → n' → α) (w : n' → α) :
(of <| vecCons v A) *ᵥ w = vecCons (dotProduct v w) (of A *ᵥ w) := by
ext i
refine Fin.cases ?_ ?_ i <;> simp [mulVec]
@[simp]
theorem mulVec_cons {α} [CommSemiring α] (A : m' → Fin n.succ → α) (x : α) (v : Fin n → α) :
(of A) *ᵥ (vecCons x v) = x • vecHead ∘ A + (of (vecTail ∘ A)) *ᵥ v := by
ext i
simp [mulVec, mul_comm]
end MulVec
section VecMulVec
variable [NonUnitalNonAssocSemiring α]
@[simp]
theorem empty_vecMulVec (v : Fin 0 → α) (w : n' → α) : vecMulVec v w = ![] :=
empty_eq _
@[simp]
theorem vecMulVec_empty (v : m' → α) (w : Fin 0 → α) : vecMulVec v w = of fun _ => ![] :=
funext fun _ => empty_eq _
@[simp]
theorem cons_vecMulVec (x : α) (v : Fin m → α) (w : n' → α) :
vecMulVec (vecCons x v) w = vecCons (x • w) (vecMulVec v w) := by
ext i
refine Fin.cases ?_ ?_ i <;> simp [vecMulVec]
@[simp]
theorem vecMulVec_cons (v : m' → α) (x : α) (w : Fin n → α) :
vecMulVec v (vecCons x w) = of fun i => v i • vecCons x w := rfl
end VecMulVec
section SMul
variable [NonUnitalNonAssocSemiring α]
-- @[simp] -- Porting note (#10618): simp can prove this
theorem smul_mat_empty {m' : Type*} (x : α) (A : Fin 0 → m' → α) : x • A = ![] :=
empty_eq _
-- @[simp] -- Porting note (#10618): simp can prove this
theorem smul_mat_cons (x : α) (v : n' → α) (A : Fin m → n' → α) :
x • vecCons v A = vecCons (x • v) (x • A) := by
ext i
refine Fin.cases ?_ ?_ i <;> simp
end SMul
section Submatrix
@[simp]
theorem submatrix_empty (A : Matrix m' n' α) (row : Fin 0 → m') (col : o' → n') :
submatrix A row col = ![] :=
empty_eq _
@[simp]
theorem submatrix_cons_row (A : Matrix m' n' α) (i : m') (row : Fin m → m') (col : o' → n') :
submatrix A (vecCons i row) col = vecCons (fun j => A i (col j)) (submatrix A row col) := by
ext i j
refine Fin.cases ?_ ?_ i <;> simp [submatrix]
/-- Updating a row then removing it is the same as removing it. -/
@[simp]
theorem submatrix_updateRow_succAbove (A : Matrix (Fin m.succ) n' α) (v : n' → α) (f : o' → n')
(i : Fin m.succ) : (A.updateRow i v).submatrix i.succAbove f = A.submatrix i.succAbove f :=
ext fun r s => (congr_fun (updateRow_ne (Fin.succAbove_ne i r) : _ = A _) (f s) : _)
/-- Updating a column then removing it is the same as removing it. -/
@[simp]
theorem submatrix_updateColumn_succAbove (A : Matrix m' (Fin n.succ) α) (v : m' → α) (f : o' → m')
(i : Fin n.succ) : (A.updateColumn i v).submatrix f i.succAbove = A.submatrix f i.succAbove :=
ext fun _r s => updateColumn_ne (Fin.succAbove_ne i s)
end Submatrix
section Vec2AndVec3
section One
variable [Zero α] [One α]
theorem one_fin_two : (1 : Matrix (Fin 2) (Fin 2) α) = !![1, 0; 0, 1] := by
ext i j
fin_cases i <;> fin_cases j <;> rfl
theorem one_fin_three : (1 : Matrix (Fin 3) (Fin 3) α) = !![1, 0, 0; 0, 1, 0; 0, 0, 1] := by
ext i j
fin_cases i <;> fin_cases j <;> rfl
end One
section AddMonoidWithOne
variable [AddMonoidWithOne α]
theorem natCast_fin_two (n : ℕ) : (n : Matrix (Fin 2) (Fin 2) α) = !![↑n, 0; 0, ↑n] := by
ext i j
fin_cases i <;> fin_cases j <;> rfl
theorem natCast_fin_three (n : ℕ) :
(n : Matrix (Fin 3) (Fin 3) α) = !![↑n, 0, 0; 0, ↑n, 0; 0, 0, ↑n] := by
ext i j
fin_cases i <;> fin_cases j <;> rfl
-- See note [no_index around OfNat.ofNat]
theorem ofNat_fin_two (n : ℕ) [n.AtLeastTwo] :
(no_index (OfNat.ofNat n) : Matrix (Fin 2) (Fin 2) α) =
!![OfNat.ofNat n, 0; 0, OfNat.ofNat n] :=
natCast_fin_two _
-- See note [no_index around OfNat.ofNat]
theorem ofNat_fin_three (n : ℕ) [n.AtLeastTwo] :
(no_index (OfNat.ofNat n) : Matrix (Fin 3) (Fin 3) α) =
!![OfNat.ofNat n, 0, 0; 0, OfNat.ofNat n, 0; 0, 0, OfNat.ofNat n] :=
natCast_fin_three _
end AddMonoidWithOne
theorem eta_fin_two (A : Matrix (Fin 2) (Fin 2) α) : A = !![A 0 0, A 0 1; A 1 0, A 1 1] := by
ext i j
fin_cases i <;> fin_cases j <;> rfl
theorem eta_fin_three (A : Matrix (Fin 3) (Fin 3) α) :
A = !![A 0 0, A 0 1, A 0 2;
A 1 0, A 1 1, A 1 2;
A 2 0, A 2 1, A 2 2] := by
ext i j
fin_cases i <;> fin_cases j <;> rfl
theorem mul_fin_two [AddCommMonoid α] [Mul α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁₁ b₁₂ b₂₁ b₂₂ : α) :
!![a₁₁, a₁₂;
a₂₁, a₂₂] * !![b₁₁, b₁₂;
b₂₁, b₂₂] = !![a₁₁ * b₁₁ + a₁₂ * b₂₁, a₁₁ * b₁₂ + a₁₂ * b₂₂;
a₂₁ * b₁₁ + a₂₂ * b₂₁, a₂₁ * b₁₂ + a₂₂ * b₂₂] := by
ext i j
fin_cases i <;> fin_cases j <;> simp [Matrix.mul_apply, dotProduct, Fin.sum_univ_succ]
theorem mul_fin_three [AddCommMonoid α] [Mul α]
(a₁₁ a₁₂ a₁₃ a₂₁ a₂₂ a₂₃ a₃₁ a₃₂ a₃₃ b₁₁ b₁₂ b₁₃ b₂₁ b₂₂ b₂₃ b₃₁ b₃₂ b₃₃ : α) :
!![a₁₁, a₁₂, a₁₃;
a₂₁, a₂₂, a₂₃;
a₃₁, a₃₂, a₃₃] * !![b₁₁, b₁₂, b₁₃;
b₂₁, b₂₂, b₂₃;
b₃₁, b₃₂, b₃₃] =
!![a₁₁*b₁₁ + a₁₂*b₂₁ + a₁₃*b₃₁, a₁₁*b₁₂ + a₁₂*b₂₂ + a₁₃*b₃₂, a₁₁*b₁₃ + a₁₂*b₂₃ + a₁₃*b₃₃;
a₂₁*b₁₁ + a₂₂*b₂₁ + a₂₃*b₃₁, a₂₁*b₁₂ + a₂₂*b₂₂ + a₂₃*b₃₂, a₂₁*b₁₃ + a₂₂*b₂₃ + a₂₃*b₃₃;
a₃₁*b₁₁ + a₃₂*b₂₁ + a₃₃*b₃₁, a₃₁*b₁₂ + a₃₂*b₂₂ + a₃₃*b₃₂, a₃₁*b₁₃ + a₃₂*b₂₃ + a₃₃*b₃₃] := by
ext i j
fin_cases i <;> fin_cases j
<;> simp [Matrix.mul_apply, dotProduct, Fin.sum_univ_succ, ← add_assoc]
theorem vec2_eq {a₀ a₁ b₀ b₁ : α} (h₀ : a₀ = b₀) (h₁ : a₁ = b₁) : ![a₀, a₁] = ![b₀, b₁] := by
subst_vars
rfl
theorem vec3_eq {a₀ a₁ a₂ b₀ b₁ b₂ : α} (h₀ : a₀ = b₀) (h₁ : a₁ = b₁) (h₂ : a₂ = b₂) :
![a₀, a₁, a₂] = ![b₀, b₁, b₂] := by
subst_vars
rfl
theorem vec2_add [Add α] (a₀ a₁ b₀ b₁ : α) : ![a₀, a₁] + ![b₀, b₁] = ![a₀ + b₀, a₁ + b₁] := by
rw [cons_add_cons, cons_add_cons, empty_add_empty]
theorem vec3_add [Add α] (a₀ a₁ a₂ b₀ b₁ b₂ : α) :
![a₀, a₁, a₂] + ![b₀, b₁, b₂] = ![a₀ + b₀, a₁ + b₁, a₂ + b₂] := by
rw [cons_add_cons, cons_add_cons, cons_add_cons, empty_add_empty]
theorem smul_vec2 {R : Type*} [SMul R α] (x : R) (a₀ a₁ : α) :
x • ![a₀, a₁] = ![x • a₀, x • a₁] := by rw [smul_cons, smul_cons, smul_empty]
theorem smul_vec3 {R : Type*} [SMul R α] (x : R) (a₀ a₁ a₂ : α) :
x • ![a₀, a₁, a₂] = ![x • a₀, x • a₁, x • a₂] := by
rw [smul_cons, smul_cons, smul_cons, smul_empty]
variable [AddCommMonoid α] [Mul α]
theorem vec2_dotProduct' {a₀ a₁ b₀ b₁ : α} : ![a₀, a₁] ⬝ᵥ ![b₀, b₁] = a₀ * b₀ + a₁ * b₁ := by
rw [cons_dotProduct_cons, cons_dotProduct_cons, dotProduct_empty, add_zero]
@[simp]
theorem vec2_dotProduct (v w : Fin 2 → α) : v ⬝ᵥ w = v 0 * w 0 + v 1 * w 1 :=
vec2_dotProduct'
theorem vec3_dotProduct' {a₀ a₁ a₂ b₀ b₁ b₂ : α} :
![a₀, a₁, a₂] ⬝ᵥ ![b₀, b₁, b₂] = a₀ * b₀ + a₁ * b₁ + a₂ * b₂ := by
rw [cons_dotProduct_cons, cons_dotProduct_cons, cons_dotProduct_cons, dotProduct_empty,
add_zero, add_assoc]
@[simp]
theorem vec3_dotProduct (v w : Fin 3 → α) : v ⬝ᵥ w = v 0 * w 0 + v 1 * w 1 + v 2 * w 2 :=
vec3_dotProduct'
end Vec2AndVec3
end Matrix
|
Data\Matrix\PEquiv.lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import Mathlib.Data.Matrix.Basic
import Mathlib.Data.PEquiv
/-!
# partial equivalences for matrices
Using partial equivalences to represent matrices.
This file introduces the function `PEquiv.toMatrix`, which returns a matrix containing ones and
zeros. For any partial equivalence `f`, `f.toMatrix i j = 1 ↔ f i = some j`.
The following important properties of this function are proved
`toMatrix_trans : (f.trans g).toMatrix = f.toMatrix * g.toMatrix`
`toMatrix_symm : f.symm.toMatrix = f.toMatrixᵀ`
`toMatrix_refl : (PEquiv.refl n).toMatrix = 1`
`toMatrix_bot : ⊥.toMatrix = 0`
This theory gives the matrix representation of projection linear maps, and their right inverses.
For example, the matrix `(single (0 : Fin 1) (i : Fin n)).toMatrix` corresponds to the ith
projection map from R^n to R.
Any injective function `Fin m → Fin n` gives rise to a `PEquiv`, whose matrix is the projection
map from R^m → R^n represented by the same function. The transpose of this matrix is the right
inverse of this map, sending anything not in the image to zero.
## notations
This file uses `ᵀ` for `Matrix.transpose`.
-/
namespace PEquiv
open Matrix
universe u v
variable {k l m n : Type*}
variable {α : Type v}
open Matrix
/-- `toMatrix` returns a matrix containing ones and zeros. `f.toMatrix i j` is `1` if
`f i = some j` and `0` otherwise -/
def toMatrix [DecidableEq n] [Zero α] [One α] (f : m ≃. n) : Matrix m n α :=
of fun i j => if j ∈ f i then (1 : α) else 0
-- TODO: set as an equation lemma for `toMatrix`, see mathlib4#3024
@[simp]
theorem toMatrix_apply [DecidableEq n] [Zero α] [One α] (f : m ≃. n) (i j) :
toMatrix f i j = if j ∈ f i then (1 : α) else 0 :=
rfl
theorem mul_matrix_apply [Fintype m] [DecidableEq m] [Semiring α] (f : l ≃. m) (M : Matrix m n α)
(i j) : (f.toMatrix * M :) i j = Option.casesOn (f i) 0 fun fi => M fi j := by
dsimp [toMatrix, Matrix.mul_apply]
cases' h : f i with fi
· simp [h]
· rw [Finset.sum_eq_single fi] <;> simp (config := { contextual := true }) [h, eq_comm]
theorem toMatrix_symm [DecidableEq m] [DecidableEq n] [Zero α] [One α] (f : m ≃. n) :
(f.symm.toMatrix : Matrix n m α) = f.toMatrixᵀ := by
ext
simp only [transpose, mem_iff_mem f, toMatrix_apply]
congr
@[simp]
theorem toMatrix_refl [DecidableEq n] [Zero α] [One α] :
((PEquiv.refl n).toMatrix : Matrix n n α) = 1 := by
ext
simp [toMatrix_apply, one_apply]
theorem matrix_mul_apply [Fintype m] [Semiring α] [DecidableEq n] (M : Matrix l m α) (f : m ≃. n)
(i j) : (M * f.toMatrix :) i j = Option.casesOn (f.symm j) 0 fun fj => M i fj := by
dsimp [toMatrix, Matrix.mul_apply]
cases' h : f.symm j with fj
· simp [h, ← f.eq_some_iff]
· rw [Finset.sum_eq_single fj]
· simp [h, ← f.eq_some_iff]
· rintro b - n
simp [h, ← f.eq_some_iff, n.symm]
· simp
theorem toPEquiv_mul_matrix [Fintype m] [DecidableEq m] [Semiring α] (f : m ≃ m)
(M : Matrix m n α) : f.toPEquiv.toMatrix * M = M.submatrix f id := by
ext i j
rw [mul_matrix_apply, Equiv.toPEquiv_apply, submatrix_apply, id]
theorem mul_toPEquiv_toMatrix {m n α : Type*} [Fintype n] [DecidableEq n] [Semiring α] (f : n ≃ n)
(M : Matrix m n α) : M * f.toPEquiv.toMatrix = M.submatrix id f.symm :=
Matrix.ext fun i j => by
rw [PEquiv.matrix_mul_apply, ← Equiv.toPEquiv_symm, Equiv.toPEquiv_apply,
Matrix.submatrix_apply, id]
theorem toMatrix_trans [Fintype m] [DecidableEq m] [DecidableEq n] [Semiring α] (f : l ≃. m)
(g : m ≃. n) : ((f.trans g).toMatrix : Matrix l n α) = f.toMatrix * g.toMatrix := by
ext i j
rw [mul_matrix_apply]
dsimp [toMatrix, PEquiv.trans]
cases f i <;> simp
@[simp]
theorem toMatrix_bot [DecidableEq n] [Zero α] [One α] :
((⊥ : PEquiv m n).toMatrix : Matrix m n α) = 0 :=
rfl
theorem toMatrix_injective [DecidableEq n] [MonoidWithZero α] [Nontrivial α] :
Function.Injective (@toMatrix m n α _ _ _) := by
classical
intro f g
refine not_imp_not.1 ?_
simp only [Matrix.ext_iff.symm, toMatrix_apply, PEquiv.ext_iff, not_forall, exists_imp]
intro i hi
use i
cases' hf : f i with fi
· cases' hg : g i with gi
· rw [hf, hg] at hi; exact (hi rfl).elim
· use gi
simp
· use fi
simp [hf.symm, Ne.symm hi]
theorem toMatrix_swap [DecidableEq n] [Ring α] (i j : n) :
(Equiv.swap i j).toPEquiv.toMatrix =
(1 : Matrix n n α) - (single i i).toMatrix - (single j j).toMatrix + (single i j).toMatrix +
(single j i).toMatrix := by
ext
dsimp [toMatrix, single, Equiv.swap_apply_def, Equiv.toPEquiv, one_apply]
split_ifs <;> simp_all
@[simp]
theorem single_mul_single [Fintype n] [DecidableEq k] [DecidableEq m] [DecidableEq n] [Semiring α]
(a : m) (b : n) (c : k) :
((single a b).toMatrix : Matrix _ _ α) * (single b c).toMatrix = (single a c).toMatrix := by
rw [← toMatrix_trans, single_trans_single]
theorem single_mul_single_of_ne [Fintype n] [DecidableEq n] [DecidableEq k] [DecidableEq m]
[Semiring α] {b₁ b₂ : n} (hb : b₁ ≠ b₂) (a : m) (c : k) :
(single a b₁).toMatrix * (single b₂ c).toMatrix = (0 : Matrix _ _ α) := by
rw [← toMatrix_trans, single_trans_single_of_ne hb, toMatrix_bot]
/-- Restatement of `single_mul_single`, which will simplify expressions in `simp` normal form,
when associativity may otherwise need to be carefully applied. -/
@[simp]
theorem single_mul_single_right [Fintype n] [Fintype k] [DecidableEq n] [DecidableEq k]
[DecidableEq m] [Semiring α] (a : m) (b : n) (c : k) (M : Matrix k l α) :
(single a b).toMatrix * ((single b c).toMatrix * M) = (single a c).toMatrix * M := by
rw [← Matrix.mul_assoc, single_mul_single]
/-- We can also define permutation matrices by permuting the rows of the identity matrix. -/
theorem equiv_toPEquiv_toMatrix [DecidableEq n] [Zero α] [One α] (σ : Equiv n n) (i j : n) :
σ.toPEquiv.toMatrix i j = (1 : Matrix n n α) (σ i) j :=
if_congr Option.some_inj rfl rfl
end PEquiv
|
Data\Matrix\Rank.lean | /-
Copyright (c) 2021 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Eric Wieser
-/
import Mathlib.LinearAlgebra.Determinant
import Mathlib.LinearAlgebra.FiniteDimensional
import Mathlib.LinearAlgebra.Matrix.Diagonal
import Mathlib.LinearAlgebra.Matrix.DotProduct
import Mathlib.LinearAlgebra.Matrix.Dual
/-!
# Rank of matrices
The rank of a matrix `A` is defined to be the rank of range of the linear map corresponding to `A`.
This definition does not depend on the choice of basis, see `Matrix.rank_eq_finrank_range_toLin`.
## Main declarations
* `Matrix.rank`: the rank of a matrix
-/
open Matrix
namespace Matrix
open FiniteDimensional
variable {l m n o R : Type*} [Fintype n] [Fintype o]
section CommRing
variable [CommRing R]
/-- The rank of a matrix is the rank of its image. -/
noncomputable def rank (A : Matrix m n R) : ℕ :=
finrank R <| LinearMap.range A.mulVecLin
@[simp]
theorem rank_one [StrongRankCondition R] [DecidableEq n] :
rank (1 : Matrix n n R) = Fintype.card n := by
rw [rank, mulVecLin_one, LinearMap.range_id, finrank_top, finrank_pi]
@[simp]
theorem rank_zero [Nontrivial R] : rank (0 : Matrix m n R) = 0 := by
rw [rank, mulVecLin_zero, LinearMap.range_zero, finrank_bot]
theorem rank_le_card_width [StrongRankCondition R] (A : Matrix m n R) :
A.rank ≤ Fintype.card n := by
haveI : Module.Finite R (n → R) := Module.Finite.pi
haveI : Module.Free R (n → R) := Module.Free.pi _ _
exact A.mulVecLin.finrank_range_le.trans_eq (finrank_pi _)
theorem rank_le_width [StrongRankCondition R] {m n : ℕ} (A : Matrix (Fin m) (Fin n) R) :
A.rank ≤ n :=
A.rank_le_card_width.trans <| (Fintype.card_fin n).le
theorem rank_mul_le_left [StrongRankCondition R] (A : Matrix m n R) (B : Matrix n o R) :
(A * B).rank ≤ A.rank := by
rw [rank, rank, mulVecLin_mul]
exact Cardinal.toNat_le_toNat (LinearMap.rank_comp_le_left _ _) (rank_lt_aleph0 _ _)
theorem rank_mul_le_right [StrongRankCondition R] (A : Matrix m n R) (B : Matrix n o R) :
(A * B).rank ≤ B.rank := by
rw [rank, rank, mulVecLin_mul]
exact finrank_le_finrank_of_rank_le_rank (LinearMap.lift_rank_comp_le_right _ _)
(rank_lt_aleph0 _ _)
theorem rank_mul_le [StrongRankCondition R] (A : Matrix m n R) (B : Matrix n o R) :
(A * B).rank ≤ min A.rank B.rank :=
le_min (rank_mul_le_left _ _) (rank_mul_le_right _ _)
theorem rank_unit [StrongRankCondition R] [DecidableEq n] (A : (Matrix n n R)ˣ) :
(A : Matrix n n R).rank = Fintype.card n := by
apply le_antisymm (rank_le_card_width (A : Matrix n n R)) _
have := rank_mul_le_left (A : Matrix n n R) (↑A⁻¹ : Matrix n n R)
rwa [← Units.val_mul, mul_inv_self, Units.val_one, rank_one] at this
theorem rank_of_isUnit [StrongRankCondition R] [DecidableEq n] (A : Matrix n n R) (h : IsUnit A) :
A.rank = Fintype.card n := by
obtain ⟨A, rfl⟩ := h
exact rank_unit A
/-- Right multiplying by an invertible matrix does not change the rank -/
@[simp]
lemma rank_mul_eq_left_of_isUnit_det [DecidableEq n]
(A : Matrix n n R) (B : Matrix m n R) (hA : IsUnit A.det) :
(B * A).rank = B.rank := by
suffices Function.Surjective A.mulVecLin by
rw [rank, mulVecLin_mul, LinearMap.range_comp_of_range_eq_top _
(LinearMap.range_eq_top.mpr this), ← rank]
intro v
exact ⟨(A⁻¹).mulVecLin v, by simp [mul_nonsing_inv _ hA]⟩
/-- Left multiplying by an invertible matrix does not change the rank -/
@[simp]
lemma rank_mul_eq_right_of_isUnit_det [Fintype m] [DecidableEq m]
(A : Matrix m m R) (B : Matrix m n R) (hA : IsUnit A.det) :
(A * B).rank = B.rank := by
let b : Basis m R (m → R) := Pi.basisFun R m
replace hA : IsUnit (LinearMap.toMatrix b b A.mulVecLin).det := by
convert hA; rw [← LinearEquiv.eq_symm_apply]; rfl
have hAB : mulVecLin (A * B) = (LinearEquiv.ofIsUnitDet hA).comp (mulVecLin B) := by ext; simp
rw [rank, rank, hAB, LinearMap.range_comp, LinearEquiv.finrank_map_eq]
/-- Taking a subset of the rows and permuting the columns reduces the rank. -/
theorem rank_submatrix_le [StrongRankCondition R] [Fintype m] (f : n → m) (e : n ≃ m)
(A : Matrix m m R) : rank (A.submatrix f e) ≤ rank A := by
rw [rank, rank, mulVecLin_submatrix, LinearMap.range_comp, LinearMap.range_comp,
show LinearMap.funLeft R R e.symm = LinearEquiv.funCongrLeft R R e.symm from rfl,
LinearEquiv.range, Submodule.map_top]
exact Submodule.finrank_map_le _ _
theorem rank_reindex [Fintype m] (e₁ e₂ : m ≃ n) (A : Matrix m m R) :
rank (reindex e₁ e₂ A) = rank A := by
rw [rank, rank, mulVecLin_reindex, LinearMap.range_comp, LinearMap.range_comp,
LinearEquiv.range, Submodule.map_top, LinearEquiv.finrank_map_eq]
@[simp]
theorem rank_submatrix [Fintype m] (A : Matrix m m R) (e₁ e₂ : n ≃ m) :
rank (A.submatrix e₁ e₂) = rank A := by
simpa only [reindex_apply] using rank_reindex e₁.symm e₂.symm A
theorem rank_eq_finrank_range_toLin [Finite m] [DecidableEq n] {M₁ M₂ : Type*} [AddCommGroup M₁]
[AddCommGroup M₂] [Module R M₁] [Module R M₂] (A : Matrix m n R) (v₁ : Basis m R M₁)
(v₂ : Basis n R M₂) : A.rank = finrank R (LinearMap.range (toLin v₂ v₁ A)) := by
cases nonempty_fintype m
let e₁ := (Pi.basisFun R m).equiv v₁ (Equiv.refl _)
let e₂ := (Pi.basisFun R n).equiv v₂ (Equiv.refl _)
have range_e₂ : LinearMap.range e₂ = ⊤ := by
rw [LinearMap.range_eq_top]
exact e₂.surjective
refine LinearEquiv.finrank_eq (e₁.ofSubmodules _ _ ?_)
rw [← LinearMap.range_comp, ← LinearMap.range_comp_of_range_eq_top (toLin v₂ v₁ A) range_e₂]
congr 1
apply LinearMap.pi_ext'
rintro i
apply LinearMap.ext_ring
have aux₁ := toLin_self (Pi.basisFun R n) (Pi.basisFun R m) A i
have aux₂ := Basis.equiv_apply (Pi.basisFun R n) i v₂
rw [toLin_eq_toLin', toLin'_apply'] at aux₁
rw [Pi.basisFun_apply, LinearMap.coe_stdBasis] at aux₁ aux₂
simp only [e₁, e₁, LinearMap.comp_apply, LinearEquiv.coe_coe, Equiv.refl_apply, aux₁, aux₂,
LinearMap.coe_single, toLin_self, map_sum, LinearEquiv.map_smul, Basis.equiv_apply]
theorem rank_le_card_height [Fintype m] [StrongRankCondition R] (A : Matrix m n R) :
A.rank ≤ Fintype.card m := by
haveI : Module.Finite R (m → R) := Module.Finite.pi
haveI : Module.Free R (m → R) := Module.Free.pi _ _
exact (Submodule.finrank_le _).trans (finrank_pi R).le
theorem rank_le_height [StrongRankCondition R] {m n : ℕ} (A : Matrix (Fin m) (Fin n) R) :
A.rank ≤ m :=
A.rank_le_card_height.trans <| (Fintype.card_fin m).le
/-- The rank of a matrix is the rank of the space spanned by its columns. -/
theorem rank_eq_finrank_span_cols (A : Matrix m n R) :
A.rank = finrank R (Submodule.span R (Set.range Aᵀ)) := by rw [rank, Matrix.range_mulVecLin]
end CommRing
section Field
variable [Field R]
/-- The rank of a diagnonal matrix is the count of non-zero elements on its main diagonal -/
theorem rank_diagonal [Fintype m] [DecidableEq m] [DecidableEq R] (w : m → R) :
(diagonal w).rank = Fintype.card {i // (w i) ≠ 0} := by
rw [Matrix.rank, ← Matrix.toLin'_apply', FiniteDimensional.finrank, ← LinearMap.rank,
LinearMap.rank_diagonal, Cardinal.toNat_natCast]
end Field
/-! ### Lemmas about transpose and conjugate transpose
This section contains lemmas about the rank of `Matrix.transpose` and `Matrix.conjTranspose`.
Unfortunately the proofs are essentially duplicated between the two; `ℚ` is a linearly-ordered ring
but can't be a star-ordered ring, while `ℂ` is star-ordered (with `open ComplexOrder`) but
not linearly ordered. For now we don't prove the transpose case for `ℂ`.
TODO: the lemmas `Matrix.rank_transpose` and `Matrix.rank_conjTranspose` current follow a short
proof that is a simple consequence of `Matrix.rank_transpose_mul_self` and
`Matrix.rank_conjTranspose_mul_self`. This proof pulls in unnecessary assumptions on `R`, and should
be replaced with a proof that uses Gaussian reduction or argues via linear combinations.
-/
section StarOrderedField
variable [Fintype m] [Field R] [PartialOrder R] [StarRing R] [StarOrderedRing R]
theorem ker_mulVecLin_conjTranspose_mul_self (A : Matrix m n R) :
LinearMap.ker (Aᴴ * A).mulVecLin = LinearMap.ker (mulVecLin A) := by
ext x
simp only [LinearMap.mem_ker, mulVecLin_apply, conjTranspose_mul_self_mulVec_eq_zero]
theorem rank_conjTranspose_mul_self (A : Matrix m n R) : (Aᴴ * A).rank = A.rank := by
dsimp only [rank]
refine add_left_injective (finrank R (LinearMap.ker (mulVecLin A))) ?_
dsimp only
trans finrank R { x // x ∈ LinearMap.range (mulVecLin (Aᴴ * A)) } +
finrank R { x // x ∈ LinearMap.ker (mulVecLin (Aᴴ * A)) }
· rw [ker_mulVecLin_conjTranspose_mul_self]
· simp only [LinearMap.finrank_range_add_finrank_ker]
-- this follows the proof here https://math.stackexchange.com/a/81903/1896
/-- TODO: prove this in greater generality. -/
@[simp]
theorem rank_conjTranspose (A : Matrix m n R) : Aᴴ.rank = A.rank :=
le_antisymm
(((rank_conjTranspose_mul_self _).symm.trans_le <| rank_mul_le_left _ _).trans_eq <|
congr_arg _ <| conjTranspose_conjTranspose _)
((rank_conjTranspose_mul_self _).symm.trans_le <| rank_mul_le_left _ _)
@[simp]
theorem rank_self_mul_conjTranspose (A : Matrix m n R) : (A * Aᴴ).rank = A.rank := by
simpa only [rank_conjTranspose, conjTranspose_conjTranspose] using
rank_conjTranspose_mul_self Aᴴ
end StarOrderedField
section LinearOrderedField
variable [Fintype m] [LinearOrderedField R]
theorem ker_mulVecLin_transpose_mul_self (A : Matrix m n R) :
LinearMap.ker (Aᵀ * A).mulVecLin = LinearMap.ker (mulVecLin A) := by
ext x
simp only [LinearMap.mem_ker, mulVecLin_apply, ← mulVec_mulVec]
constructor
· intro h
replace h := congr_arg (dotProduct x) h
rwa [dotProduct_mulVec, dotProduct_zero, vecMul_transpose, dotProduct_self_eq_zero] at h
· intro h
rw [h, mulVec_zero]
theorem rank_transpose_mul_self (A : Matrix m n R) : (Aᵀ * A).rank = A.rank := by
dsimp only [rank]
refine add_left_injective (finrank R <| LinearMap.ker A.mulVecLin) ?_
dsimp only
trans finrank R { x // x ∈ LinearMap.range (mulVecLin (Aᵀ * A)) } +
finrank R { x // x ∈ LinearMap.ker (mulVecLin (Aᵀ * A)) }
· rw [ker_mulVecLin_transpose_mul_self]
· simp only [LinearMap.finrank_range_add_finrank_ker]
end LinearOrderedField
@[simp]
theorem rank_transpose [Field R] [Fintype m] (A : Matrix m n R) : Aᵀ.rank = A.rank := by
classical
rw [Aᵀ.rank_eq_finrank_range_toLin (Pi.basisFun R n).dualBasis (Pi.basisFun R m).dualBasis,
toLin_transpose, ← LinearMap.dualMap_def, LinearMap.finrank_range_dualMap_eq_finrank_range,
toLin_eq_toLin', toLin'_apply', rank]
@[simp]
theorem rank_self_mul_transpose [LinearOrderedField R] [Fintype m] (A : Matrix m n R) :
(A * Aᵀ).rank = A.rank := by
simpa only [rank_transpose, transpose_transpose] using rank_transpose_mul_self Aᵀ
/-- The rank of a matrix is the rank of the space spanned by its rows. -/
theorem rank_eq_finrank_span_row [Field R] [Finite m] (A : Matrix m n R) :
A.rank = finrank R (Submodule.span R (Set.range A)) := by
cases nonempty_fintype m
rw [← rank_transpose, rank_eq_finrank_span_cols, transpose_transpose]
end Matrix
|
Data\Matrix\Reflection.lean | /-
Copyright (c) 2022 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import Mathlib.Data.Matrix.Notation
import Mathlib.Data.Matrix.Basic
import Mathlib.Data.Fin.Tuple.Reflection
/-!
# Lemmas for concrete matrices `Matrix (Fin m) (Fin n) α`
This file contains alternative definitions of common operators on matrices that expand
definitionally to the expected expression when evaluated on `!![]` notation.
This allows "proof by reflection", where we prove `A = !![A 0 0, A 0 1; A 1 0, A 1 1]` by defining
`Matrix.etaExpand A` to be equal to the RHS definitionally, and then prove that
`A = eta_expand A`.
The definitions in this file should normally not be used directly; the intent is for the
corresponding `*_eq` lemmas to be used in a place where they are definitionally unfolded.
## Main definitions
* `Matrix.transposeᵣ`
* `Matrix.dotProductᵣ`
* `Matrix.mulᵣ`
* `Matrix.mulVecᵣ`
* `Matrix.vecMulᵣ`
* `Matrix.etaExpand`
-/
open Matrix
namespace Matrix
variable {l m n : ℕ} {α β : Type*}
/-- `∀` with better defeq for `∀ x : Matrix (Fin m) (Fin n) α, P x`. -/
def Forall : ∀ {m n} (_ : Matrix (Fin m) (Fin n) α → Prop), Prop
| 0, _, P => P (of ![])
| _ + 1, _, P => FinVec.Forall fun r => Forall fun A => P (of (Matrix.vecCons r A))
/-- This can be use to prove
```lean
example (P : Matrix (Fin 2) (Fin 3) α → Prop) :
(∀ x, P x) ↔ ∀ a b c d e f, P !![a, b, c; d, e, f] :=
(forall_iff _).symm
```
-/
theorem forall_iff : ∀ {m n} (P : Matrix (Fin m) (Fin n) α → Prop), Forall P ↔ ∀ x, P x
| 0, n, P => Iff.symm Fin.forall_fin_zero_pi
| m + 1, n, P => by
simp only [Forall, FinVec.forall_iff, forall_iff]
exact Iff.symm Fin.forall_fin_succ_pi
example (P : Matrix (Fin 2) (Fin 3) α → Prop) :
(∀ x, P x) ↔ ∀ a b c d e f, P !![a, b, c; d, e, f] :=
(forall_iff _).symm
/-- `∃` with better defeq for `∃ x : Matrix (Fin m) (Fin n) α, P x`. -/
def Exists : ∀ {m n} (_ : Matrix (Fin m) (Fin n) α → Prop), Prop
| 0, _, P => P (of ![])
| _ + 1, _, P => FinVec.Exists fun r => Exists fun A => P (of (Matrix.vecCons r A))
/-- This can be use to prove
```lean
example (P : Matrix (Fin 2) (Fin 3) α → Prop) :
(∃ x, P x) ↔ ∃ a b c d e f, P !![a, b, c; d, e, f] :=
(exists_iff _).symm
```
-/
theorem exists_iff : ∀ {m n} (P : Matrix (Fin m) (Fin n) α → Prop), Exists P ↔ ∃ x, P x
| 0, n, P => Iff.symm Fin.exists_fin_zero_pi
| m + 1, n, P => by
simp only [Exists, FinVec.exists_iff, exists_iff]
exact Iff.symm Fin.exists_fin_succ_pi
example (P : Matrix (Fin 2) (Fin 3) α → Prop) :
(∃ x, P x) ↔ ∃ a b c d e f, P !![a, b, c; d, e, f] :=
(exists_iff _).symm
/-- `Matrix.transpose` with better defeq for `Fin` -/
def transposeᵣ : ∀ {m n}, Matrix (Fin m) (Fin n) α → Matrix (Fin n) (Fin m) α
| _, 0, _ => of ![]
| _, _ + 1, A =>
of <| vecCons (FinVec.map (fun v : Fin _ → α => v 0) A) (transposeᵣ (A.submatrix id Fin.succ))
/-- This can be used to prove
```lean
example (a b c d : α) : transpose !![a, b; c, d] = !![a, c; b, d] := (transposeᵣ_eq _).symm
```
-/
@[simp]
theorem transposeᵣ_eq : ∀ {m n} (A : Matrix (Fin m) (Fin n) α), transposeᵣ A = transpose A
| _, 0, A => Subsingleton.elim _ _
| m, n + 1, A =>
Matrix.ext fun i j => by
simp_rw [transposeᵣ, transposeᵣ_eq]
refine i.cases ?_ fun i => ?_
· dsimp
rw [FinVec.map_eq, Function.comp_apply]
· simp only [of_apply, Matrix.cons_val_succ]
rfl
example (a b c d : α) : transpose !![a, b; c, d] = !![a, c; b, d] :=
(transposeᵣ_eq _).symm
/-- `Matrix.dotProduct` with better defeq for `Fin` -/
def dotProductᵣ [Mul α] [Add α] [Zero α] {m} (a b : Fin m → α) : α :=
FinVec.sum <| FinVec.seq (FinVec.map (· * ·) a) b
/-- This can be used to prove
```lean
example (a b c d : α) [Mul α] [AddCommMonoid α] :
dot_product ![a, b] ![c, d] = a * c + b * d :=
(dot_productᵣ_eq _ _).symm
```
-/
@[simp]
theorem dotProductᵣ_eq [Mul α] [AddCommMonoid α] {m} (a b : Fin m → α) :
dotProductᵣ a b = dotProduct a b := by
simp_rw [dotProductᵣ, dotProduct, FinVec.sum_eq, FinVec.seq_eq, FinVec.map_eq,
Function.comp_apply]
example (a b c d : α) [Mul α] [AddCommMonoid α] : dotProduct ![a, b] ![c, d] = a * c + b * d :=
(dotProductᵣ_eq _ _).symm
/-- `Matrix.mul` with better defeq for `Fin` -/
def mulᵣ [Mul α] [Add α] [Zero α] (A : Matrix (Fin l) (Fin m) α) (B : Matrix (Fin m) (Fin n) α) :
Matrix (Fin l) (Fin n) α :=
of <| FinVec.map (fun v₁ => FinVec.map (fun v₂ => dotProductᵣ v₁ v₂) Bᵀ) A
/-- This can be used to prove
```lean
example [AddCommMonoid α] [Mul α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁₁ b₁₂ b₂₁ b₂₂ : α) :
!![a₁₁, a₁₂;
a₂₁, a₂₂] * !![b₁₁, b₁₂;
b₂₁, b₂₂] =
!![a₁₁*b₁₁ + a₁₂*b₂₁, a₁₁*b₁₂ + a₁₂*b₂₂;
a₂₁*b₁₁ + a₂₂*b₂₁, a₂₁*b₁₂ + a₂₂*b₂₂] :=
(mulᵣ_eq _ _).symm
```
-/
@[simp]
theorem mulᵣ_eq [Mul α] [AddCommMonoid α] (A : Matrix (Fin l) (Fin m) α)
(B : Matrix (Fin m) (Fin n) α) : mulᵣ A B = A * B := by
simp [mulᵣ, Function.comp, Matrix.transpose]
rfl
example [AddCommMonoid α] [Mul α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁₁ b₁₂ b₂₁ b₂₂ : α) :
!![a₁₁, a₁₂; a₂₁, a₂₂] * !![b₁₁, b₁₂; b₂₁, b₂₂] =
!![a₁₁ * b₁₁ + a₁₂ * b₂₁, a₁₁ * b₁₂ + a₁₂ * b₂₂;
a₂₁ * b₁₁ + a₂₂ * b₂₁, a₂₁ * b₁₂ + a₂₂ * b₂₂] :=
(mulᵣ_eq _ _).symm
/-- `Matrix.mulVec` with better defeq for `Fin` -/
def mulVecᵣ [Mul α] [Add α] [Zero α] (A : Matrix (Fin l) (Fin m) α) (v : Fin m → α) : Fin l → α :=
FinVec.map (fun a => dotProductᵣ a v) A
/-- This can be used to prove
```lean
example [NonUnitalNonAssocSemiring α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁ b₂ : α) :
!![a₁₁, a₁₂;
a₂₁, a₂₂] *ᵥ ![b₁, b₂] = ![a₁₁*b₁ + a₁₂*b₂, a₂₁*b₁ + a₂₂*b₂] :=
(mulVecᵣ_eq _ _).symm
```
-/
@[simp]
theorem mulVecᵣ_eq [NonUnitalNonAssocSemiring α] (A : Matrix (Fin l) (Fin m) α) (v : Fin m → α) :
mulVecᵣ A v = A *ᵥ v := by
simp [mulVecᵣ, Function.comp]
rfl
example [NonUnitalNonAssocSemiring α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁ b₂ : α) :
!![a₁₁, a₁₂; a₂₁, a₂₂] *ᵥ ![b₁, b₂] = ![a₁₁ * b₁ + a₁₂ * b₂, a₂₁ * b₁ + a₂₂ * b₂] :=
(mulVecᵣ_eq _ _).symm
/-- `Matrix.vecMul` with better defeq for `Fin` -/
def vecMulᵣ [Mul α] [Add α] [Zero α] (v : Fin l → α) (A : Matrix (Fin l) (Fin m) α) : Fin m → α :=
FinVec.map (fun a => dotProductᵣ v a) Aᵀ
/-- This can be used to prove
```lean
example [NonUnitalNonAssocSemiring α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁ b₂ : α) :
![b₁, b₂] ᵥ* !![a₁₁, a₁₂;
a₂₁, a₂₂] = ![b₁*a₁₁ + b₂*a₂₁, b₁*a₁₂ + b₂*a₂₂] :=
(vecMulᵣ_eq _ _).symm
```
-/
@[simp]
theorem vecMulᵣ_eq [NonUnitalNonAssocSemiring α] (v : Fin l → α) (A : Matrix (Fin l) (Fin m) α) :
vecMulᵣ v A = v ᵥ* A := by
simp [vecMulᵣ, Function.comp]
rfl
example [NonUnitalNonAssocSemiring α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁ b₂ : α) :
![b₁, b₂] ᵥ* !![a₁₁, a₁₂; a₂₁, a₂₂] = ![b₁ * a₁₁ + b₂ * a₂₁, b₁ * a₁₂ + b₂ * a₂₂] :=
(vecMulᵣ_eq _ _).symm
/-- Expand `A` to `!![A 0 0, ...; ..., A m n]` -/
def etaExpand {m n} (A : Matrix (Fin m) (Fin n) α) : Matrix (Fin m) (Fin n) α :=
Matrix.of (FinVec.etaExpand fun i => FinVec.etaExpand fun j => A i j)
/-- This can be used to prove
```lean
example (A : Matrix (Fin 2) (Fin 2) α) :
A = !![A 0 0, A 0 1;
A 1 0, A 1 1] :=
(etaExpand_eq _).symm
```
-/
theorem etaExpand_eq {m n} (A : Matrix (Fin m) (Fin n) α) : etaExpand A = A := by
simp_rw [etaExpand, FinVec.etaExpand_eq, Matrix.of]
-- This to be in the above `simp_rw` before leanprover/lean4#2644
erw [Equiv.refl_apply]
example (A : Matrix (Fin 2) (Fin 2) α) : A = !![A 0 0, A 0 1; A 1 0, A 1 1] :=
(etaExpand_eq _).symm
end Matrix
|
Data\Matrix\RowCol.lean | /-
Copyright (c) 2019 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen, Eric Wieser
-/
import Mathlib.Data.Matrix.Basic
/-!
# Row and column matrices
This file provides results about row and column matrices
## Main definitions
* `Matrix.row r : Matrix Unit n α`: a matrix with a single row
* `Matrix.col c : Matrix m Unit α`: a matrix with a single column
* `Matrix.updateRow M i r`: update the `i`th row of `M` to `r`
* `Matrix.updateCol M j c`: update the `j`th column of `M` to `c`
-/
variable {l m n o : Type*}
universe u v w
variable {R : Type*} {α : Type v} {β : Type w}
namespace Matrix
/--
`Matrix.col ι u` the matrix with all columns equal to the vector `u`.
To get a column matrix with exactly one column, `Matrix.col (Fin 1) u` is the canonical choice.
-/
def col (ι : Type*) (w : m → α) : Matrix m ι α :=
of fun x _ => w x
-- TODO: set as an equation lemma for `col`, see mathlib4#3024
@[simp]
theorem col_apply {ι : Type*} (w : m → α) (i) (j : ι) : col ι w i j = w i :=
rfl
/--
`Matrix.row ι u` the matrix with all rows equal to the vector `u`.
To get a row matrix with exactly one row, `Matrix.row (Fin 1) u` is the canonical choice.
-/
def row (ι : Type*) (v : n → α) : Matrix ι n α :=
of fun _ y => v y
variable {ι : Type*}
-- TODO: set as an equation lemma for `row`, see mathlib4#3024
@[simp]
theorem row_apply (v : n → α) (i : ι) (j) : row ι v i j = v j :=
rfl
theorem col_injective [Nonempty ι] : Function.Injective (col ι : (m → α) → Matrix m ι α) := by
inhabit ι
exact fun _x _y h => funext fun i => congr_fun₂ h i default
@[simp] theorem col_inj [Nonempty ι] {v w : m → α} : col ι v = col ι w ↔ v = w :=
col_injective.eq_iff
@[simp] theorem col_zero [Zero α] : col ι (0 : m → α) = 0 := rfl
@[simp] theorem col_eq_zero [Zero α] [Nonempty ι] (v : m → α) : col ι v = 0 ↔ v = 0 := col_inj
@[simp]
theorem col_add [Add α] (v w : m → α) : col ι (v + w) = col ι v + col ι w := by
ext
rfl
@[simp]
theorem col_smul [SMul R α] (x : R) (v : m → α) : col ι (x • v) = x • col ι v := by
ext
rfl
theorem row_injective [Nonempty ι] : Function.Injective (row ι : (n → α) → Matrix ι n α) := by
inhabit ι
exact fun _x _y h => funext fun j => congr_fun₂ h default j
@[simp] theorem row_inj [Nonempty ι] {v w : n → α} : row ι v = row ι w ↔ v = w :=
row_injective.eq_iff
@[simp] theorem row_zero [Zero α] : row ι (0 : n → α) = 0 := rfl
@[simp] theorem row_eq_zero [Zero α] [Nonempty ι] (v : n → α) : row ι v = 0 ↔ v = 0 := row_inj
@[simp]
theorem row_add [Add α] (v w : m → α) : row ι (v + w) = row ι v + row ι w := by
ext
rfl
@[simp]
theorem row_smul [SMul R α] (x : R) (v : m → α) : row ι (x • v) = x • row ι v := by
ext
rfl
@[simp]
theorem transpose_col (v : m → α) : (Matrix.col ι v)ᵀ = Matrix.row ι v := by
ext
rfl
@[simp]
theorem transpose_row (v : m → α) : (Matrix.row ι v)ᵀ = Matrix.col ι v := by
ext
rfl
@[simp]
theorem conjTranspose_col [Star α] (v : m → α) : (col ι v)ᴴ = row ι (star v) := by
ext
rfl
@[simp]
theorem conjTranspose_row [Star α] (v : m → α) : (row ι v)ᴴ = col ι (star v) := by
ext
rfl
theorem row_vecMul [Fintype m] [NonUnitalNonAssocSemiring α] (M : Matrix m n α) (v : m → α) :
Matrix.row ι (v ᵥ* M) = Matrix.row ι v * M := by
ext
rfl
theorem col_vecMul [Fintype m] [NonUnitalNonAssocSemiring α] (M : Matrix m n α) (v : m → α) :
Matrix.col ι (v ᵥ* M) = (Matrix.row ι v * M)ᵀ := by
ext
rfl
theorem col_mulVec [Fintype n] [NonUnitalNonAssocSemiring α] (M : Matrix m n α) (v : n → α) :
Matrix.col ι (M *ᵥ v) = M * Matrix.col ι v := by
ext
rfl
theorem row_mulVec [Fintype n] [NonUnitalNonAssocSemiring α] (M : Matrix m n α) (v : n → α) :
Matrix.row ι (M *ᵥ v) = (M * Matrix.col ι v)ᵀ := by
ext
rfl
@[simp]
theorem row_mul_col_apply [Fintype m] [Mul α] [AddCommMonoid α] (v w : m → α) (i j) :
(row ι v * col ι w) i j = v ⬝ᵥ w :=
rfl
@[simp]
theorem diag_col_mul_row [Mul α] [AddCommMonoid α] [Unique ι] (a b : n → α) :
diag (col ι a * row ι b) = a * b := by
ext
simp [Matrix.mul_apply, col, row]
variable (ι)
theorem vecMulVec_eq [Mul α] [AddCommMonoid α] [Unique ι] (w : m → α) (v : n → α) :
vecMulVec w v = col ι w * row ι v := by
ext
simp [vecMulVec, mul_apply]
/-! ### Updating rows and columns -/
/-- Update, i.e. replace the `i`th row of matrix `A` with the values in `b`. -/
def updateRow [DecidableEq m] (M : Matrix m n α) (i : m) (b : n → α) : Matrix m n α :=
of <| Function.update M i b
/-- Update, i.e. replace the `j`th column of matrix `A` with the values in `b`. -/
def updateColumn [DecidableEq n] (M : Matrix m n α) (j : n) (b : m → α) : Matrix m n α :=
of fun i => Function.update (M i) j (b i)
variable {M : Matrix m n α} {i : m} {j : n} {b : n → α} {c : m → α}
@[simp]
theorem updateRow_self [DecidableEq m] : updateRow M i b i = b :=
-- Porting note: (implicit arg) added `(β := _)`
Function.update_same (β := fun _ => (n → α)) i b M
@[simp]
theorem updateColumn_self [DecidableEq n] : updateColumn M j c i j = c i :=
-- Porting note: (implicit arg) added `(β := _)`
Function.update_same (β := fun _ => α) j (c i) (M i)
@[simp]
theorem updateRow_ne [DecidableEq m] {i' : m} (i_ne : i' ≠ i) : updateRow M i b i' = M i' :=
-- Porting note: (implicit arg) added `(β := _)`
Function.update_noteq (β := fun _ => (n → α)) i_ne b M
@[simp]
theorem updateColumn_ne [DecidableEq n] {j' : n} (j_ne : j' ≠ j) :
updateColumn M j c i j' = M i j' :=
-- Porting note: (implicit arg) added `(β := _)`
Function.update_noteq (β := fun _ => α) j_ne (c i) (M i)
theorem updateRow_apply [DecidableEq m] {i' : m} :
updateRow M i b i' j = if i' = i then b j else M i' j := by
by_cases h : i' = i
· rw [h, updateRow_self, if_pos rfl]
· rw [updateRow_ne h, if_neg h]
theorem updateColumn_apply [DecidableEq n] {j' : n} :
updateColumn M j c i j' = if j' = j then c i else M i j' := by
by_cases h : j' = j
· rw [h, updateColumn_self, if_pos rfl]
· rw [updateColumn_ne h, if_neg h]
@[simp]
theorem updateColumn_subsingleton [Subsingleton n] (A : Matrix m n R) (i : n) (b : m → R) :
A.updateColumn i b = (col (Fin 1) b).submatrix id (Function.const n 0) := by
ext x y
simp [updateColumn_apply, Subsingleton.elim i y]
@[simp]
theorem updateRow_subsingleton [Subsingleton m] (A : Matrix m n R) (i : m) (b : n → R) :
A.updateRow i b = (row (Fin 1) b).submatrix (Function.const m 0) id := by
ext x y
simp [updateColumn_apply, Subsingleton.elim i x]
theorem map_updateRow [DecidableEq m] (f : α → β) :
map (updateRow M i b) f = updateRow (M.map f) i (f ∘ b) := by
ext
rw [updateRow_apply, map_apply, map_apply, updateRow_apply]
exact apply_ite f _ _ _
theorem map_updateColumn [DecidableEq n] (f : α → β) :
map (updateColumn M j c) f = updateColumn (M.map f) j (f ∘ c) := by
ext
rw [updateColumn_apply, map_apply, map_apply, updateColumn_apply]
exact apply_ite f _ _ _
theorem updateRow_transpose [DecidableEq n] : updateRow Mᵀ j c = (updateColumn M j c)ᵀ := by
ext
rw [transpose_apply, updateRow_apply, updateColumn_apply]
rfl
theorem updateColumn_transpose [DecidableEq m] : updateColumn Mᵀ i b = (updateRow M i b)ᵀ := by
ext
rw [transpose_apply, updateRow_apply, updateColumn_apply]
rfl
theorem updateRow_conjTranspose [DecidableEq n] [Star α] :
updateRow Mᴴ j (star c) = (updateColumn M j c)ᴴ := by
rw [conjTranspose, conjTranspose, transpose_map, transpose_map, updateRow_transpose,
map_updateColumn]
rfl
theorem updateColumn_conjTranspose [DecidableEq m] [Star α] :
updateColumn Mᴴ i (star b) = (updateRow M i b)ᴴ := by
rw [conjTranspose, conjTranspose, transpose_map, transpose_map, updateColumn_transpose,
map_updateRow]
rfl
@[simp]
theorem updateRow_eq_self [DecidableEq m] (A : Matrix m n α) (i : m) : A.updateRow i (A i) = A :=
Function.update_eq_self i A
@[simp]
theorem updateColumn_eq_self [DecidableEq n] (A : Matrix m n α) (i : n) :
(A.updateColumn i fun j => A j i) = A :=
funext fun j => Function.update_eq_self i (A j)
theorem diagonal_updateColumn_single [DecidableEq n] [Zero α] (v : n → α) (i : n) (x : α) :
(diagonal v).updateColumn i (Pi.single i x) = diagonal (Function.update v i x) := by
ext j k
obtain rfl | hjk := eq_or_ne j k
· rw [diagonal_apply_eq]
obtain rfl | hji := eq_or_ne j i
· rw [updateColumn_self, Pi.single_eq_same, Function.update_same]
· rw [updateColumn_ne hji, diagonal_apply_eq, Function.update_noteq hji]
· rw [diagonal_apply_ne _ hjk]
obtain rfl | hki := eq_or_ne k i
· rw [updateColumn_self, Pi.single_eq_of_ne hjk]
· rw [updateColumn_ne hki, diagonal_apply_ne _ hjk]
theorem diagonal_updateRow_single [DecidableEq n] [Zero α] (v : n → α) (i : n) (x : α) :
(diagonal v).updateRow i (Pi.single i x) = diagonal (Function.update v i x) := by
rw [← diagonal_transpose, updateRow_transpose, diagonal_updateColumn_single, diagonal_transpose]
/-! Updating rows and columns commutes in the obvious way with reindexing the matrix. -/
theorem updateRow_submatrix_equiv [DecidableEq l] [DecidableEq m] (A : Matrix m n α) (i : l)
(r : o → α) (e : l ≃ m) (f : o ≃ n) :
updateRow (A.submatrix e f) i r = (A.updateRow (e i) fun j => r (f.symm j)).submatrix e f := by
ext i' j
simp only [submatrix_apply, updateRow_apply, Equiv.apply_eq_iff_eq, Equiv.symm_apply_apply]
theorem submatrix_updateRow_equiv [DecidableEq l] [DecidableEq m] (A : Matrix m n α) (i : m)
(r : n → α) (e : l ≃ m) (f : o ≃ n) :
(A.updateRow i r).submatrix e f = updateRow (A.submatrix e f) (e.symm i) fun i => r (f i) :=
Eq.trans (by simp_rw [Equiv.apply_symm_apply]) (updateRow_submatrix_equiv A _ _ e f).symm
theorem updateColumn_submatrix_equiv [DecidableEq o] [DecidableEq n] (A : Matrix m n α) (j : o)
(c : l → α) (e : l ≃ m) (f : o ≃ n) : updateColumn (A.submatrix e f) j c =
(A.updateColumn (f j) fun i => c (e.symm i)).submatrix e f := by
simpa only [← transpose_submatrix, updateRow_transpose] using
congr_arg transpose (updateRow_submatrix_equiv Aᵀ j c f e)
theorem submatrix_updateColumn_equiv [DecidableEq o] [DecidableEq n] (A : Matrix m n α) (j : n)
(c : m → α) (e : l ≃ m) (f : o ≃ n) : (A.updateColumn j c).submatrix e f =
updateColumn (A.submatrix e f) (f.symm j) fun i => c (e i) :=
Eq.trans (by simp_rw [Equiv.apply_symm_apply]) (updateColumn_submatrix_equiv A _ _ e f).symm
/-! `reindex` versions of the above `submatrix` lemmas for convenience. -/
theorem updateRow_reindex [DecidableEq l] [DecidableEq m] (A : Matrix m n α) (i : l) (r : o → α)
(e : m ≃ l) (f : n ≃ o) :
updateRow (reindex e f A) i r = reindex e f (A.updateRow (e.symm i) fun j => r (f j)) :=
updateRow_submatrix_equiv _ _ _ _ _
theorem reindex_updateRow [DecidableEq l] [DecidableEq m] (A : Matrix m n α) (i : m) (r : n → α)
(e : m ≃ l) (f : n ≃ o) :
reindex e f (A.updateRow i r) = updateRow (reindex e f A) (e i) fun i => r (f.symm i) :=
submatrix_updateRow_equiv _ _ _ _ _
theorem updateColumn_reindex [DecidableEq o] [DecidableEq n] (A : Matrix m n α) (j : o) (c : l → α)
(e : m ≃ l) (f : n ≃ o) :
updateColumn (reindex e f A) j c = reindex e f (A.updateColumn (f.symm j) fun i => c (e i)) :=
updateColumn_submatrix_equiv _ _ _ _ _
theorem reindex_updateColumn [DecidableEq o] [DecidableEq n] (A : Matrix m n α) (j : n) (c : m → α)
(e : m ≃ l) (f : n ≃ o) :
reindex e f (A.updateColumn j c) = updateColumn (reindex e f A) (f j) fun i => c (e.symm i) :=
submatrix_updateColumn_equiv _ _ _ _ _
end Matrix
|
Data\Matroid\Basic.lean | /-
Copyright (c) 2023 Peter Nelson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Peter Nelson
-/
import Mathlib.Data.Set.Card
import Mathlib.Order.Minimal
import Mathlib.Data.Matroid.Init
/-!
# Matroids
A `Matroid` is a structure that combinatorially abstracts
the notion of linear independence and dependence;
matroids have connections with graph theory, discrete optimization,
additive combinatorics and algebraic geometry.
Mathematically, a matroid `M` is a structure on a set `E` comprising a
collection of subsets of `E` called the bases of `M`,
where the bases are required to obey certain axioms.
This file gives a definition of a matroid `M` in terms of its bases,
and some API relating independent sets (subsets of bases) and the notion of a
basis of a set `X` (a maximal independent subset of `X`).
## Main definitions
* a `Matroid α` on a type `α` is a structure comprising a 'ground set'
and a suitably behaved 'base' predicate.
Given `M : Matroid α` ...
* `M.E` denotes the ground set of `M`, which has type `Set α`
* For `B : Set α`, `M.Base B` means that `B` is a base of `M`.
* For `I : Set α`, `M.Indep I` means that `I` is independent in `M`
(that is, `I` is contained in a base of `M`).
* For `D : Set α`, `M.Dep D` means that `D` is contained in the ground set of `M`
but isn't independent.
* For `I : Set α` and `X : Set α`, `M.Basis I X` means that `I` is a maximal independent
subset of `X`.
* `M.Finite` means that `M` has finite ground set.
* `M.Nonempty` means that the ground set of `M` is nonempty.
* `FiniteRk M` means that the bases of `M` are finite.
* `InfiniteRk M` means that the bases of `M` are infinite.
* `RkPos M` means that the bases of `M` are nonempty.
* `Finitary M` means that a set is independent if and only if all its finite subsets are
independent.
* `aesop_mat` : a tactic designed to prove `X ⊆ M.E` for some set `X` and matroid `M`.
## Implementation details
There are a few design decisions worth discussing.
### Finiteness
The first is that our matroids are allowed to be infinite.
Unlike with many mathematical structures, this isn't such an obvious choice.
Finite matroids have been studied since the 1930's,
and there was never controversy as to what is and isn't an example of a finite matroid -
in fact, surprisingly many apparently different definitions of a matroid
give rise to the same class of objects.
However, generalizing different definitions of a finite matroid
to the infinite in the obvious way (i.e. by simply allowing the ground set to be infinite)
gives a number of different notions of 'infinite matroid' that disagree with each other,
and that all lack nice properties.
Many different competing notions of infinite matroid were studied through the years;
in fact, the problem of which definition is the best was only really solved in 2013,
when Bruhn et al. [2] showed that there is a unique 'reasonable' notion of an infinite matroid
(these objects had previously defined by Higgs under the name 'B-matroid').
These are defined by adding one carefully chosen axiom to the standard set,
and adapting existing axioms to not mention set cardinalities;
they enjoy nearly all the nice properties of standard finite matroids.
Even though at least 90% of the literature is on finite matroids,
B-matroids are the definition we use, because they allow for additional generality,
nearly all theorems are still true and just as easy to state,
and (hopefully) the more general definition will prevent the need for a costly future refactor.
The disadvantage is that developing API for the finite case is harder work
(for instance, it is harder to prove that something is a matroid in the first place,
and one must deal with `ℕ∞` rather than `ℕ`).
For serious work on finite matroids, we provide the typeclasses
`[M.Finite]` and `[FiniteRk M]` and associated API.
### Cardinality
Just as with bases of a vector space,
all bases of a finite matroid `M` are finite and have the same cardinality;
this cardinality is an important invariant known as the 'rank' of `M`.
For infinite matroids, bases are not in general equicardinal;
in fact the equicardinality of bases of infinite matroids is independent of ZFC [3].
What is still true is that either all bases are finite and equicardinal,
or all bases are infinite. This means that the natural notion of 'size'
for a set in matroid theory is given by the function `Set.encard`, which
is the cardinality as a term in `ℕ∞`. We use this function extensively
in building the API; it is preferable to both `Set.ncard` and `Finset.card`
because it allows infinite sets to be handled without splitting into cases.
### The ground `Set`
A last place where we make a consequential choice is making the ground set of a matroid
a structure field of type `Set α` (where `α` is the type of 'possible matroid elements')
rather than just having a type `α` of all the matroid elements.
This is because of how common it is to simultaneously consider
a number of matroids on different but related ground sets.
For example, a matroid `M` on ground set `E` can have its structure
'restricted' to some subset `R ⊆ E` to give a smaller matroid `M ↾ R` with ground set `R`.
A statement like `(M ↾ R₁) ↾ R₂ = M ↾ R₂` is mathematically obvious.
But if the ground set of a matroid is a type, this doesn't typecheck,
and is only true up to canonical isomorphism.
Restriction is just the tip of the iceberg here;
one can also 'contract' and 'delete' elements and sets of elements
in a matroid to give a smaller matroid,
and in practice it is common to make statements like `M₁.E = M₂.E ∩ M₃.E` and
`((M ⟋ e) ↾ R) ⟋ C = M ⟋ (C ∪ {e}) ↾ R`.
Such things are a nightmare to work with unless `=` is actually propositional equality
(especially because the relevant coercions are usually between sets and not just elements).
So the solution is that the ground set `M.E` has type `Set α`,
and there are elements of type `α` that aren't in the matroid.
The tradeoff is that for many statements, one now has to add
hypotheses of the form `X ⊆ M.E` to make sure than `X` is actually 'in the matroid',
rather than letting a 'type of matroid elements' take care of this invisibly.
It still seems that this is worth it.
The tactic `aesop_mat` exists specifically to discharge such goals
with minimal fuss (using default values).
The tactic works fairly well, but has room for improvement.
Even though the carrier set is written `M.E`,
A related decision is to not have matroids themselves be a typeclass.
This would make things be notationally simpler
(having `Base` in the presence of `[Matroid α]` rather than `M.Base` for a term `M : Matroid α`)
but is again just too awkward when one has multiple matroids on the same type.
In fact, in regular written mathematics,
it is normal to explicitly indicate which matroid something is happening in,
so our notation mirrors common practice.
### Notation
We use a couple of nonstandard conventions in theorem names that are related to the above.
First, we mirror common informal practice by referring explicitly to the `ground` set rather
than the notation `E`. (Writing `ground` everywhere in a proof term would be unwieldy, and
writing `E` in theorem names would be unnatural to read.)
Second, because we are typically interested in subsets of the ground set `M.E`,
using `Set.compl` is inconvenient, since `Xᶜ ⊆ M.E` is typically false for `X ⊆ M.E`.
On the other hand (especially when duals arise), it is common to complement
a set `X ⊆ M.E` *within* the ground set, giving `M.E \ X`.
For this reason, we use the term `compl` in theorem names to refer to taking a set difference
with respect to the ground set, rather than a complement within a type. The lemma
`compl_base_dual` is one of the many examples of this.
## References
[1] The standard text on matroid theory
[J. G. Oxley, Matroid Theory, Oxford University Press, New York, 2011.]
[2] The robust axiomatic definition of infinite matroids
[H. Bruhn, R. Diestel, M. Kriesell, R. Pendavingh, P. Wollan, Axioms for infinite matroids,
Adv. Math 239 (2013), 18-46]
[3] Equicardinality of matroid bases is independent of ZFC.
[N. Bowler, S. Geschke, Self-dual uniform matroids on infinite sets,
Proc. Amer. Math. Soc. 144 (2016), 459-471]
-/
open Set
/-- A predicate `P` on sets satisfies the **exchange property** if,
for all `X` and `Y` satisfying `P` and all `a ∈ X \ Y`, there exists `b ∈ Y \ X` so that
swapping `a` for `b` in `X` maintains `P`. -/
def Matroid.ExchangeProperty {α : Type _} (P : Set α → Prop) : Prop :=
∀ X Y, P X → P Y → ∀ a ∈ X \ Y, ∃ b ∈ Y \ X, P (insert b (X \ {a}))
/-- A set `X` has the maximal subset property for a predicate `P` if every subset of `X` satisfying
`P` is contained in a maximal subset of `X` satisfying `P`. -/
def Matroid.ExistsMaximalSubsetProperty {α : Type _} (P : Set α → Prop) (X : Set α) : Prop :=
∀ I, P I → I ⊆ X → ∃ J, I ⊆ J ∧ Maximal (fun K ↦ P K ∧ K ⊆ X) J
/-- A `Matroid α` is a ground set `E` of type `Set α`, and a nonempty collection of its subsets
satisfying the exchange property and the maximal subset property. Each such set is called a
`Base` of `M`. An `Indep`endent set is just a set contained in a base, but we include this
predicate as a structure field for better definitional properties.
In most cases, using this definition directly is not the best way to construct a matroid,
since it requires specifying both the bases and independent sets. If the bases are known,
use `Matroid.ofBase` or a variant. If just the independent sets are known,
define an `IndepMatroid`, and then use `IndepMatroid.matroid`.
-/
@[ext] structure Matroid (α : Type _) where
/-- `M` has a ground set `E`. -/
(E : Set α)
/-- `M` has a predicate `Base` definining its bases. -/
(Base : Set α → Prop)
/-- `M` has a predicate `Indep` defining its independent sets. -/
(Indep : Set α → Prop)
/-- The `Indep`endent sets are those contained in `Base`s. -/
(indep_iff' : ∀ ⦃I⦄, Indep I ↔ ∃ B, Base B ∧ I ⊆ B)
/-- There is at least one `Base`. -/
(exists_base : ∃ B, Base B)
/-- For any bases `B`, `B'` and `e ∈ B \ B'`, there is some `f ∈ B' \ B` for which `B-e+f`
is a base. -/
(base_exchange : Matroid.ExchangeProperty Base)
/-- Every independent subset `I` of a set `X` for is contained in a maximal independent
subset of `X`. -/
(maximality : ∀ X, X ⊆ E → Matroid.ExistsMaximalSubsetProperty Indep X)
/-- Every base is contained in the ground set. -/
(subset_ground : ∀ B, Base B → B ⊆ E)
namespace Matroid
variable {α : Type*} {M : Matroid α}
/-- Typeclass for a matroid having finite ground set. Just a wrapper for `M.E.Finite`-/
protected class Finite (M : Matroid α) : Prop where
/-- The ground set is finite -/
(ground_finite : M.E.Finite)
/-- Typeclass for a matroid having nonempty ground set. Just a wrapper for `M.E.Nonempty`-/
protected class Nonempty (M : Matroid α) : Prop where
/-- The ground set is nonempty -/
(ground_nonempty : M.E.Nonempty)
theorem ground_nonempty (M : Matroid α) [M.Nonempty] : M.E.Nonempty :=
Nonempty.ground_nonempty
theorem ground_nonempty_iff (M : Matroid α) : M.E.Nonempty ↔ M.Nonempty :=
⟨fun h ↦ ⟨h⟩, fun ⟨h⟩ ↦ h⟩
theorem ground_finite (M : Matroid α) [M.Finite] : M.E.Finite :=
Finite.ground_finite
theorem set_finite (M : Matroid α) [M.Finite] (X : Set α) (hX : X ⊆ M.E := by aesop) : X.Finite :=
M.ground_finite.subset hX
instance finite_of_finite [Finite α] {M : Matroid α} : M.Finite :=
⟨Set.toFinite _⟩
/-- A `FiniteRk` matroid is one whose bases are finite -/
class FiniteRk (M : Matroid α) : Prop where
/-- There is a finite base -/
exists_finite_base : ∃ B, M.Base B ∧ B.Finite
instance finiteRk_of_finite (M : Matroid α) [M.Finite] : FiniteRk M :=
⟨M.exists_base.imp (fun B hB ↦ ⟨hB, M.set_finite B (M.subset_ground _ hB)⟩)⟩
/-- An `InfiniteRk` matroid is one whose bases are infinite. -/
class InfiniteRk (M : Matroid α) : Prop where
/-- There is an infinite base -/
exists_infinite_base : ∃ B, M.Base B ∧ B.Infinite
/-- A `RkPos` matroid is one whose bases are nonempty. -/
class RkPos (M : Matroid α) : Prop where
/-- The empty set isn't a base -/
empty_not_base : ¬M.Base ∅
theorem rkPos_iff_empty_not_base : M.RkPos ↔ ¬M.Base ∅ :=
⟨fun ⟨h⟩ ↦ h, fun h ↦ ⟨h⟩⟩
section exchange
namespace ExchangeProperty
variable {Base : Set α → Prop} {B B' : Set α}
/-- A family of sets with the exchange property is an antichain. -/
theorem antichain (exch : ExchangeProperty Base) (hB : Base B) (hB' : Base B') (h : B ⊆ B') :
B = B' :=
h.antisymm (fun x hx ↦ by_contra
(fun hxB ↦ let ⟨_, hy, _⟩ := exch B' B hB' hB x ⟨hx, hxB⟩; hy.2 <| h hy.1))
theorem encard_diff_le_aux {B₁ B₂ : Set α}
(exch : ExchangeProperty Base) (hB₁ : Base B₁) (hB₂ : Base B₂) :
(B₁ \ B₂).encard ≤ (B₂ \ B₁).encard := by
obtain (he | hinf | ⟨e, he, hcard⟩) :=
(B₂ \ B₁).eq_empty_or_encard_eq_top_or_encard_diff_singleton_lt
· rw [exch.antichain hB₂ hB₁ (diff_eq_empty.mp he)]
· exact le_top.trans_eq hinf.symm
obtain ⟨f, hf, hB'⟩ := exch B₂ B₁ hB₂ hB₁ e he
have : encard (insert f (B₂ \ {e}) \ B₁) < encard (B₂ \ B₁) := by
rw [insert_diff_of_mem _ hf.1, diff_diff_comm]; exact hcard
have hencard := encard_diff_le_aux exch hB₁ hB'
rw [insert_diff_of_mem _ hf.1, diff_diff_comm, ← union_singleton, ← diff_diff, diff_diff_right,
inter_singleton_eq_empty.mpr he.2, union_empty] at hencard
rw [← encard_diff_singleton_add_one he, ← encard_diff_singleton_add_one hf]
exact add_le_add_right hencard 1
termination_by (B₂ \ B₁).encard
variable {B₁ B₂ : Set α}
/-- For any two sets `B₁`, `B₂` in a family with the exchange property, the differences `B₁ \ B₂`
and `B₂ \ B₁` have the same `ℕ∞`-cardinality. -/
theorem encard_diff_eq (exch : ExchangeProperty Base) (hB₁ : Base B₁) (hB₂ : Base B₂) :
(B₁ \ B₂).encard = (B₂ \ B₁).encard :=
(encard_diff_le_aux exch hB₁ hB₂).antisymm (encard_diff_le_aux exch hB₂ hB₁)
/-- Any two sets `B₁`, `B₂` in a family with the exchange property have the same
`ℕ∞`-cardinality. -/
theorem encard_base_eq (exch : ExchangeProperty Base) (hB₁ : Base B₁) (hB₂ : Base B₂) :
B₁.encard = B₂.encard := by
rw [← encard_diff_add_encard_inter B₁ B₂, exch.encard_diff_eq hB₁ hB₂, inter_comm,
encard_diff_add_encard_inter]
end ExchangeProperty
end exchange
section aesop
/-- The `aesop_mat` tactic attempts to prove a set is contained in the ground set of a matroid.
It uses a `[Matroid]` ruleset, and is allowed to fail. -/
macro (name := aesop_mat) "aesop_mat" c:Aesop.tactic_clause* : tactic =>
`(tactic|
aesop $c* (config := { terminal := true })
(rule_sets := [$(Lean.mkIdent `Matroid):ident]))
/- We add a number of trivial lemmas (deliberately specialized to statements in terms of the
ground set of a matroid) to the ruleset `Matroid` for `aesop`. -/
variable {X Y : Set α} {e : α}
@[aesop unsafe 5% (rule_sets := [Matroid])]
private theorem inter_right_subset_ground (hX : X ⊆ M.E) :
X ∩ Y ⊆ M.E := inter_subset_left.trans hX
@[aesop unsafe 5% (rule_sets := [Matroid])]
private theorem inter_left_subset_ground (hX : X ⊆ M.E) :
Y ∩ X ⊆ M.E := inter_subset_right.trans hX
@[aesop unsafe 5% (rule_sets := [Matroid])]
private theorem diff_subset_ground (hX : X ⊆ M.E) : X \ Y ⊆ M.E :=
diff_subset.trans hX
@[aesop unsafe 10% (rule_sets := [Matroid])]
private theorem ground_diff_subset_ground : M.E \ X ⊆ M.E :=
diff_subset_ground rfl.subset
@[aesop unsafe 10% (rule_sets := [Matroid])]
private theorem singleton_subset_ground (he : e ∈ M.E) : {e} ⊆ M.E :=
singleton_subset_iff.mpr he
@[aesop unsafe 5% (rule_sets := [Matroid])]
private theorem subset_ground_of_subset (hXY : X ⊆ Y) (hY : Y ⊆ M.E) : X ⊆ M.E :=
hXY.trans hY
@[aesop unsafe 5% (rule_sets := [Matroid])]
private theorem mem_ground_of_mem_of_subset (hX : X ⊆ M.E) (heX : e ∈ X) : e ∈ M.E :=
hX heX
@[aesop safe (rule_sets := [Matroid])]
private theorem insert_subset_ground {e : α} {X : Set α} {M : Matroid α}
(he : e ∈ M.E) (hX : X ⊆ M.E) : insert e X ⊆ M.E :=
insert_subset he hX
@[aesop safe (rule_sets := [Matroid])]
private theorem ground_subset_ground {M : Matroid α} : M.E ⊆ M.E :=
rfl.subset
attribute [aesop safe (rule_sets := [Matroid])] empty_subset union_subset iUnion_subset
end aesop
section Base
variable {B B₁ B₂ : Set α}
@[aesop unsafe 10% (rule_sets := [Matroid])]
theorem Base.subset_ground (hB : M.Base B) : B ⊆ M.E :=
M.subset_ground B hB
theorem Base.exchange {e : α} (hB₁ : M.Base B₁) (hB₂ : M.Base B₂) (hx : e ∈ B₁ \ B₂) :
∃ y ∈ B₂ \ B₁, M.Base (insert y (B₁ \ {e})) :=
M.base_exchange B₁ B₂ hB₁ hB₂ _ hx
theorem Base.exchange_mem {e : α}
(hB₁ : M.Base B₁) (hB₂ : M.Base B₂) (hxB₁ : e ∈ B₁) (hxB₂ : e ∉ B₂) :
∃ y, (y ∈ B₂ ∧ y ∉ B₁) ∧ M.Base (insert y (B₁ \ {e})) := by
simpa using hB₁.exchange hB₂ ⟨hxB₁, hxB₂⟩
theorem Base.eq_of_subset_base (hB₁ : M.Base B₁) (hB₂ : M.Base B₂) (hB₁B₂ : B₁ ⊆ B₂) :
B₁ = B₂ :=
M.base_exchange.antichain hB₁ hB₂ hB₁B₂
theorem Base.not_base_of_ssubset {X : Set α} (hB : M.Base B) (hX : X ⊂ B) : ¬ M.Base X :=
fun h ↦ hX.ne (h.eq_of_subset_base hB hX.subset)
theorem Base.insert_not_base {e : α} (hB : M.Base B) (heB : e ∉ B) : ¬ M.Base (insert e B) :=
fun h ↦ h.not_base_of_ssubset (ssubset_insert heB) hB
theorem Base.encard_diff_comm (hB₁ : M.Base B₁) (hB₂ : M.Base B₂) :
(B₁ \ B₂).encard = (B₂ \ B₁).encard :=
M.base_exchange.encard_diff_eq hB₁ hB₂
theorem Base.ncard_diff_comm (hB₁ : M.Base B₁) (hB₂ : M.Base B₂) :
(B₁ \ B₂).ncard = (B₂ \ B₁).ncard := by
rw [ncard_def, hB₁.encard_diff_comm hB₂, ← ncard_def]
theorem Base.card_eq_card_of_base (hB₁ : M.Base B₁) (hB₂ : M.Base B₂) :
B₁.encard = B₂.encard := by
rw [M.base_exchange.encard_base_eq hB₁ hB₂]
theorem Base.ncard_eq_ncard_of_base (hB₁ : M.Base B₁) (hB₂ : M.Base B₂) : B₁.ncard = B₂.ncard := by
rw [ncard_def B₁, hB₁.card_eq_card_of_base hB₂, ← ncard_def]
theorem Base.finite_of_finite {B' : Set α}
(hB : M.Base B) (h : B.Finite) (hB' : M.Base B') : B'.Finite :=
(finite_iff_finite_of_encard_eq_encard (hB.card_eq_card_of_base hB')).mp h
theorem Base.infinite_of_infinite (hB : M.Base B) (h : B.Infinite) (hB₁ : M.Base B₁) :
B₁.Infinite :=
by_contra (fun hB_inf ↦ (hB₁.finite_of_finite (not_infinite.mp hB_inf) hB).not_infinite h)
theorem Base.finite [FiniteRk M] (hB : M.Base B) : B.Finite :=
let ⟨B₀,hB₀⟩ := ‹FiniteRk M›.exists_finite_base
hB₀.1.finite_of_finite hB₀.2 hB
theorem Base.infinite [InfiniteRk M] (hB : M.Base B) : B.Infinite :=
let ⟨B₀,hB₀⟩ := ‹InfiniteRk M›.exists_infinite_base
hB₀.1.infinite_of_infinite hB₀.2 hB
theorem empty_not_base [h : RkPos M] : ¬M.Base ∅ :=
h.empty_not_base
theorem Base.nonempty [RkPos M] (hB : M.Base B) : B.Nonempty := by
rw [nonempty_iff_ne_empty]; rintro rfl; exact M.empty_not_base hB
theorem Base.rkPos_of_nonempty (hB : M.Base B) (h : B.Nonempty) : M.RkPos := by
rw [rkPos_iff_empty_not_base]
intro he
obtain rfl := he.eq_of_subset_base hB (empty_subset B)
simp at h
theorem Base.finiteRk_of_finite (hB : M.Base B) (hfin : B.Finite) : FiniteRk M :=
⟨⟨B, hB, hfin⟩⟩
theorem Base.infiniteRk_of_infinite (hB : M.Base B) (h : B.Infinite) : InfiniteRk M :=
⟨⟨B, hB, h⟩⟩
theorem not_finiteRk (M : Matroid α) [InfiniteRk M] : ¬ FiniteRk M := by
intro h; obtain ⟨B,hB⟩ := M.exists_base; exact hB.infinite hB.finite
theorem not_infiniteRk (M : Matroid α) [FiniteRk M] : ¬ InfiniteRk M := by
intro h; obtain ⟨B,hB⟩ := M.exists_base; exact hB.infinite hB.finite
theorem finite_or_infiniteRk (M : Matroid α) : FiniteRk M ∨ InfiniteRk M :=
let ⟨B, hB⟩ := M.exists_base
B.finite_or_infinite.elim
(Or.inl ∘ hB.finiteRk_of_finite) (Or.inr ∘ hB.infiniteRk_of_infinite)
theorem Base.diff_finite_comm (hB₁ : M.Base B₁) (hB₂ : M.Base B₂) :
(B₁ \ B₂).Finite ↔ (B₂ \ B₁).Finite :=
finite_iff_finite_of_encard_eq_encard (hB₁.encard_diff_comm hB₂)
theorem Base.diff_infinite_comm (hB₁ : M.Base B₁) (hB₂ : M.Base B₂) :
(B₁ \ B₂).Infinite ↔ (B₂ \ B₁).Infinite :=
infinite_iff_infinite_of_encard_eq_encard (hB₁.encard_diff_comm hB₂)
theorem eq_of_base_iff_base_forall {M₁ M₂ : Matroid α} (hE : M₁.E = M₂.E)
(h : ∀ ⦃B⦄, B ⊆ M₁.E → (M₁.Base B ↔ M₂.Base B)) : M₁ = M₂ := by
have h' : ∀ B, M₁.Base B ↔ M₂.Base B :=
fun B ↦ ⟨fun hB ↦ (h hB.subset_ground).1 hB,
fun hB ↦ (h <| hB.subset_ground.trans_eq hE.symm).2 hB⟩
ext <;> simp [hE, M₁.indep_iff', M₂.indep_iff', h']
theorem base_compl_iff_maximal_disjoint_base (hB : B ⊆ M.E := by aesop_mat) :
M.Base (M.E \ B) ↔ Maximal (fun I ↦ I ⊆ M.E ∧ ∃ B, M.Base B ∧ Disjoint I B) B := by
simp_rw [maximal_iff, and_iff_right hB, and_imp, forall_exists_index]
refine ⟨fun h ↦ ⟨⟨_, h, disjoint_sdiff_right⟩,
fun I hI B' ⟨hB', hIB'⟩ hBI ↦ hBI.antisymm ?_⟩, fun ⟨⟨B', hB', hBB'⟩,h⟩ ↦ ?_⟩
· rw [hB'.eq_of_subset_base h, ← subset_compl_iff_disjoint_right, diff_eq, compl_inter,
compl_compl] at hIB'
· exact fun e he ↦ (hIB' he).elim (fun h' ↦ (h' (hI he)).elim) id
rw [subset_diff, and_iff_right hB'.subset_ground, disjoint_comm]
exact disjoint_of_subset_left hBI hIB'
rw [h diff_subset B' ⟨hB', disjoint_sdiff_left⟩]
· simpa [hB'.subset_ground]
simp [subset_diff, hB, hBB']
end Base
section dep_indep
/-- A subset of `M.E` is `Dep`endent if it is not `Indep`endent . -/
def Dep (M : Matroid α) (D : Set α) : Prop := ¬M.Indep D ∧ D ⊆ M.E
variable {B B' I J D X : Set α} {e f : α}
theorem indep_iff : M.Indep I ↔ ∃ B, M.Base B ∧ I ⊆ B :=
M.indep_iff' (I := I)
theorem setOf_indep_eq (M : Matroid α) : {I | M.Indep I} = lowerClosure ({B | M.Base B}) := by
simp_rw [indep_iff]
rfl
theorem Indep.exists_base_superset (hI : M.Indep I) : ∃ B, M.Base B ∧ I ⊆ B :=
indep_iff.1 hI
theorem dep_iff : M.Dep D ↔ ¬M.Indep D ∧ D ⊆ M.E := Iff.rfl
theorem setOf_dep_eq (M : Matroid α) : {D | M.Dep D} = {I | M.Indep I}ᶜ ∩ Iic M.E := rfl
@[aesop unsafe 30% (rule_sets := [Matroid])]
theorem Indep.subset_ground (hI : M.Indep I) : I ⊆ M.E := by
obtain ⟨B, hB, hIB⟩ := hI.exists_base_superset
exact hIB.trans hB.subset_ground
@[aesop unsafe 20% (rule_sets := [Matroid])]
theorem Dep.subset_ground (hD : M.Dep D) : D ⊆ M.E :=
hD.2
theorem indep_or_dep (hX : X ⊆ M.E := by aesop_mat) : M.Indep X ∨ M.Dep X := by
rw [Dep, and_iff_left hX]
apply em
theorem Indep.not_dep (hI : M.Indep I) : ¬ M.Dep I :=
fun h ↦ h.1 hI
theorem Dep.not_indep (hD : M.Dep D) : ¬ M.Indep D :=
hD.1
theorem dep_of_not_indep (hD : ¬ M.Indep D) (hDE : D ⊆ M.E := by aesop_mat) : M.Dep D :=
⟨hD, hDE⟩
theorem indep_of_not_dep (hI : ¬ M.Dep I) (hIE : I ⊆ M.E := by aesop_mat) : M.Indep I :=
by_contra (fun h ↦ hI ⟨h, hIE⟩)
@[simp] theorem not_dep_iff (hX : X ⊆ M.E := by aesop_mat) : ¬ M.Dep X ↔ M.Indep X := by
rw [Dep, and_iff_left hX, not_not]
@[simp] theorem not_indep_iff (hX : X ⊆ M.E := by aesop_mat) : ¬ M.Indep X ↔ M.Dep X := by
rw [Dep, and_iff_left hX]
theorem indep_iff_not_dep : M.Indep I ↔ ¬M.Dep I ∧ I ⊆ M.E := by
rw [dep_iff, not_and, not_imp_not]
exact ⟨fun h ↦ ⟨fun _ ↦ h, h.subset_ground⟩, fun h ↦ h.1 h.2⟩
theorem Indep.subset (hJ : M.Indep J) (hIJ : I ⊆ J) : M.Indep I := by
obtain ⟨B, hB, hJB⟩ := hJ.exists_base_superset
exact indep_iff.2 ⟨B, hB, hIJ.trans hJB⟩
theorem Dep.superset (hD : M.Dep D) (hDX : D ⊆ X) (hXE : X ⊆ M.E := by aesop_mat) : M.Dep X :=
dep_of_not_indep (fun hI ↦ (hI.subset hDX).not_dep hD)
theorem Base.indep (hB : M.Base B) : M.Indep B :=
indep_iff.2 ⟨B, hB, subset_rfl⟩
@[simp] theorem empty_indep (M : Matroid α) : M.Indep ∅ :=
Exists.elim M.exists_base (fun _ hB ↦ hB.indep.subset (empty_subset _))
theorem Dep.nonempty (hD : M.Dep D) : D.Nonempty := by
rw [nonempty_iff_ne_empty]; rintro rfl; exact hD.not_indep M.empty_indep
theorem Indep.finite [FiniteRk M] (hI : M.Indep I) : I.Finite :=
let ⟨_, hB, hIB⟩ := hI.exists_base_superset
hB.finite.subset hIB
theorem Indep.rkPos_of_nonempty (hI : M.Indep I) (hne : I.Nonempty) : M.RkPos := by
obtain ⟨B, hB, hIB⟩ := hI.exists_base_superset
exact hB.rkPos_of_nonempty (hne.mono hIB)
theorem Indep.inter_right (hI : M.Indep I) (X : Set α) : M.Indep (I ∩ X) :=
hI.subset inter_subset_left
theorem Indep.inter_left (hI : M.Indep I) (X : Set α) : M.Indep (X ∩ I) :=
hI.subset inter_subset_right
theorem Indep.diff (hI : M.Indep I) (X : Set α) : M.Indep (I \ X) :=
hI.subset diff_subset
theorem Base.eq_of_subset_indep (hB : M.Base B) (hI : M.Indep I) (hBI : B ⊆ I) : B = I :=
let ⟨B', hB', hB'I⟩ := hI.exists_base_superset
hBI.antisymm (by rwa [hB.eq_of_subset_base hB' (hBI.trans hB'I)])
theorem base_iff_maximal_indep : M.Base B ↔ Maximal M.Indep B := by
rw [maximal_subset_iff]
refine ⟨fun h ↦ ⟨h.indep, fun _ ↦ h.eq_of_subset_indep⟩, fun ⟨h, h'⟩ ↦ ?_⟩
obtain ⟨B', hB', hBB'⟩ := h.exists_base_superset
rwa [h' hB'.indep hBB']
theorem Indep.base_of_maximal (hI : M.Indep I) (h : ∀ ⦃J⦄, M.Indep J → I ⊆ J → I = J) :
M.Base I := by
rwa [base_iff_maximal_indep, maximal_subset_iff, and_iff_right hI]
theorem Base.dep_of_ssubset (hB : M.Base B) (h : B ⊂ X) (hX : X ⊆ M.E := by aesop_mat) : M.Dep X :=
⟨fun hX ↦ h.ne (hB.eq_of_subset_indep hX h.subset), hX⟩
theorem Base.dep_of_insert (hB : M.Base B) (heB : e ∉ B) (he : e ∈ M.E := by aesop_mat) :
M.Dep (insert e B) := hB.dep_of_ssubset (ssubset_insert heB) (insert_subset he hB.subset_ground)
theorem Base.mem_of_insert_indep (hB : M.Base B) (heB : M.Indep (insert e B)) : e ∈ B :=
by_contra fun he ↦ (hB.dep_of_insert he (heB.subset_ground (mem_insert _ _))).not_indep heB
/-- If the difference of two Bases is a singleton, then they differ by an insertion/removal -/
theorem Base.eq_exchange_of_diff_eq_singleton (hB : M.Base B) (hB' : M.Base B') (h : B \ B' = {e}) :
∃ f ∈ B' \ B, B' = (insert f B) \ {e} := by
obtain ⟨f, hf, hb⟩ := hB.exchange hB' (h.symm.subset (mem_singleton e))
have hne : f ≠ e := by rintro rfl; exact hf.2 (h.symm.subset (mem_singleton f)).1
rw [insert_diff_singleton_comm hne] at hb
refine ⟨f, hf, (hb.eq_of_subset_base hB' ?_).symm⟩
rw [diff_subset_iff, insert_subset_iff, union_comm, ← diff_subset_iff, h, and_iff_left rfl.subset]
exact Or.inl hf.1
theorem Base.exchange_base_of_indep (hB : M.Base B) (hf : f ∉ B)
(hI : M.Indep (insert f (B \ {e}))) : M.Base (insert f (B \ {e})) := by
obtain ⟨B', hB', hIB'⟩ := hI.exists_base_superset
have hcard := hB'.encard_diff_comm hB
rw [insert_subset_iff, ← diff_eq_empty, diff_diff_comm, diff_eq_empty, subset_singleton_iff_eq]
at hIB'
obtain ⟨hfB, (h | h)⟩ := hIB'
· rw [h, encard_empty, encard_eq_zero, eq_empty_iff_forall_not_mem] at hcard
exact (hcard f ⟨hfB, hf⟩).elim
rw [h, encard_singleton, encard_eq_one] at hcard
obtain ⟨x, hx⟩ := hcard
obtain (rfl : f = x) := hx.subset ⟨hfB, hf⟩
simp_rw [← h, ← singleton_union, ← hx, sdiff_sdiff_right_self, inf_eq_inter, inter_comm B,
diff_union_inter]
exact hB'
theorem Base.exchange_base_of_indep' (hB : M.Base B) (he : e ∈ B) (hf : f ∉ B)
(hI : M.Indep (insert f B \ {e})) : M.Base (insert f B \ {e}) := by
have hfe : f ≠ e := by rintro rfl; exact hf he
rw [← insert_diff_singleton_comm hfe] at *
exact hB.exchange_base_of_indep hf hI
theorem Base.insert_dep (hB : M.Base B) (h : e ∈ M.E \ B) : M.Dep (insert e B) := by
rw [← not_indep_iff (insert_subset h.1 hB.subset_ground)]
exact h.2 ∘ (fun hi ↦ insert_eq_self.mp (hB.eq_of_subset_indep hi (subset_insert e B)).symm)
theorem Indep.exists_insert_of_not_base (hI : M.Indep I) (hI' : ¬M.Base I) (hB : M.Base B) :
∃ e ∈ B \ I, M.Indep (insert e I) := by
obtain ⟨B', hB', hIB'⟩ := hI.exists_base_superset
obtain ⟨x, hxB', hx⟩ := exists_of_ssubset (hIB'.ssubset_of_ne (by (rintro rfl; exact hI' hB')))
by_cases hxB : x ∈ B
· exact ⟨x, ⟨hxB, hx⟩, hB'.indep.subset (insert_subset hxB' hIB')⟩
obtain ⟨e,he, hBase⟩ := hB'.exchange hB ⟨hxB',hxB⟩
exact ⟨e, ⟨he.1, not_mem_subset hIB' he.2⟩,
indep_iff.2 ⟨_, hBase, insert_subset_insert (subset_diff_singleton hIB' hx)⟩⟩
/-- This is the same as `Indep.exists_insert_of_not_base`, but phrased so that
it is defeq to the augmentation axiom for independent sets. -/
theorem Indep.exists_insert_of_not_maximal (M : Matroid α) ⦃I B : Set α⦄ (hI : M.Indep I)
(hInotmax : ¬ Maximal M.Indep I) (hB : Maximal M.Indep B) :
∃ x ∈ B \ I, M.Indep (insert x I) := by
simp only [maximal_subset_iff, hI, not_and, not_forall, exists_prop, true_imp_iff] at hB hInotmax
refine hI.exists_insert_of_not_base (fun hIb ↦ ?_) ?_
· obtain ⟨I', hII', hI', hne⟩ := hInotmax
exact hne <| hIb.eq_of_subset_indep hII' hI'
exact hB.1.base_of_maximal fun J hJ hBJ ↦ hB.2 hJ hBJ
theorem Indep.base_of_forall_insert (hB : M.Indep B)
(hBmax : ∀ e ∈ M.E \ B, ¬ M.Indep (insert e B)) : M.Base B := by
refine by_contra fun hnb ↦ ?_
obtain ⟨B', hB'⟩ := M.exists_base
obtain ⟨e, he, h⟩ := hB.exists_insert_of_not_base hnb hB'
exact hBmax e ⟨hB'.subset_ground he.1, he.2⟩ h
theorem ground_indep_iff_base : M.Indep M.E ↔ M.Base M.E :=
⟨fun h ↦ h.base_of_maximal (fun _ hJ hEJ ↦ hEJ.antisymm hJ.subset_ground), Base.indep⟩
theorem Base.exists_insert_of_ssubset (hB : M.Base B) (hIB : I ⊂ B) (hB' : M.Base B') :
∃ e ∈ B' \ I, M.Indep (insert e I) :=
(hB.indep.subset hIB.subset).exists_insert_of_not_base
(fun hI ↦ hIB.ne (hI.eq_of_subset_base hB hIB.subset)) hB'
theorem eq_of_indep_iff_indep_forall {M₁ M₂ : Matroid α} (hE : M₁.E = M₂.E)
(h : ∀ I, I ⊆ M₁.E → (M₁.Indep I ↔ M₂.Indep I)) : M₁ = M₂ :=
have h' : M₁.Indep = M₂.Indep := by
ext I
by_cases hI : I ⊆ M₁.E
· rwa [h]
exact iff_of_false (fun hi ↦ hI hi.subset_ground)
(fun hi ↦ hI (hi.subset_ground.trans_eq hE.symm))
eq_of_base_iff_base_forall hE (fun B _ ↦ by simp_rw [base_iff_maximal_indep, h'])
theorem eq_iff_indep_iff_indep_forall {M₁ M₂ : Matroid α} :
M₁ = M₂ ↔ (M₁.E = M₂.E) ∧ ∀ I, I ⊆ M₁.E → (M₁.Indep I ↔ M₂.Indep I) :=
⟨fun h ↦ by (subst h; simp), fun h ↦ eq_of_indep_iff_indep_forall h.1 h.2⟩
/-- A `Finitary` matroid is one where a set is independent if and only if it all
its finite subsets are independent, or equivalently a matroid whose circuits are finite. -/
class Finitary (M : Matroid α) : Prop where
/-- `I` is independent if all its finite subsets are independent. -/
indep_of_forall_finite : ∀ I, (∀ J, J ⊆ I → J.Finite → M.Indep J) → M.Indep I
theorem indep_of_forall_finite_subset_indep {M : Matroid α} [Finitary M] (I : Set α)
(h : ∀ J, J ⊆ I → J.Finite → M.Indep J) : M.Indep I :=
Finitary.indep_of_forall_finite I h
theorem indep_iff_forall_finite_subset_indep {M : Matroid α} [Finitary M] :
M.Indep I ↔ ∀ J, J ⊆ I → J.Finite → M.Indep J :=
⟨fun h _ hJI _ ↦ h.subset hJI, Finitary.indep_of_forall_finite I⟩
instance finitary_of_finiteRk {M : Matroid α} [FiniteRk M] : Finitary M :=
⟨ by
refine fun I hI ↦ I.finite_or_infinite.elim (hI _ Subset.rfl) (fun h ↦ False.elim ?_)
obtain ⟨B, hB⟩ := M.exists_base
obtain ⟨I₀, hI₀I, hI₀fin, hI₀card⟩ := h.exists_subset_ncard_eq (B.ncard + 1)
obtain ⟨B', hB', hI₀B'⟩ := (hI _ hI₀I hI₀fin).exists_base_superset
have hle := ncard_le_ncard hI₀B' hB'.finite
rw [hI₀card, hB'.ncard_eq_ncard_of_base hB, Nat.add_one_le_iff] at hle
exact hle.ne rfl ⟩
/-- Matroids obey the maximality axiom -/
theorem existsMaximalSubsetProperty_indep (M : Matroid α) :
∀ X, X ⊆ M.E → ExistsMaximalSubsetProperty M.Indep X :=
M.maximality
end dep_indep
section Basis
/-- A Basis for a set `X ⊆ M.E` is a maximal independent subset of `X`
(Often in the literature, the word 'Basis' is used to refer to what we call a 'Base'). -/
def Basis (M : Matroid α) (I X : Set α) : Prop :=
Maximal (fun A ↦ M.Indep A ∧ A ⊆ X) I ∧ X ⊆ M.E
/-- A `Basis'` is a basis without the requirement that `X ⊆ M.E`. This is convenient for some
API building, especially when working with rank and closure. -/
def Basis' (M : Matroid α) (I X : Set α) : Prop :=
Maximal (fun A ↦ M.Indep A ∧ A ⊆ X) I
variable {B I J X Y : Set α} {e : α}
theorem Basis'.indep (hI : M.Basis' I X) : M.Indep I :=
hI.1.1
theorem Basis.indep (hI : M.Basis I X) : M.Indep I :=
hI.1.1.1
theorem Basis.subset (hI : M.Basis I X) : I ⊆ X :=
hI.1.1.2
theorem Basis.basis' (hI : M.Basis I X) : M.Basis' I X :=
hI.1
theorem Basis'.basis (hI : M.Basis' I X) (hX : X ⊆ M.E := by aesop_mat) : M.Basis I X :=
⟨hI, hX⟩
theorem Basis'.subset (hI : M.Basis' I X) : I ⊆ X :=
hI.1.2
@[aesop unsafe 15% (rule_sets := [Matroid])]
theorem Basis.subset_ground (hI : M.Basis I X) : X ⊆ M.E :=
hI.2
theorem Basis.basis_inter_ground (hI : M.Basis I X) : M.Basis I (X ∩ M.E) := by
convert hI
rw [inter_eq_self_of_subset_left hI.subset_ground]
@[aesop unsafe 15% (rule_sets := [Matroid])]
theorem Basis.left_subset_ground (hI : M.Basis I X) : I ⊆ M.E :=
hI.indep.subset_ground
theorem Basis.eq_of_subset_indep (hI : M.Basis I X) (hJ : M.Indep J) (hIJ : I ⊆ J) (hJX : J ⊆ X) :
I = J :=
hIJ.antisymm (hI.1.2 ⟨hJ, hJX⟩ hIJ)
theorem Basis.Finite (hI : M.Basis I X) [FiniteRk M] : I.Finite := hI.indep.finite
theorem basis_iff' :
M.Basis I X ↔ (M.Indep I ∧ I ⊆ X ∧ ∀ ⦃J⦄, M.Indep J → I ⊆ J → J ⊆ X → I = J) ∧ X ⊆ M.E := by
rw [Basis, maximal_subset_iff]
tauto
theorem basis_iff (hX : X ⊆ M.E := by aesop_mat) :
M.Basis I X ↔ (M.Indep I ∧ I ⊆ X ∧ ∀ J, M.Indep J → I ⊆ J → J ⊆ X → I = J) := by
rw [basis_iff', and_iff_left hX]
theorem basis'_iff_basis_inter_ground : M.Basis' I X ↔ M.Basis I (X ∩ M.E) := by
rw [Basis', Basis, and_iff_left inter_subset_right, maximal_iff_maximal_of_imp_of_forall]
· exact fun I hI ↦ ⟨hI.1, hI.2.trans inter_subset_left⟩
exact fun I hI ↦ ⟨I, rfl.le, hI.1, subset_inter hI.2 hI.1.subset_ground⟩
theorem basis'_iff_basis (hX : X ⊆ M.E := by aesop_mat) : M.Basis' I X ↔ M.Basis I X := by
rw [basis'_iff_basis_inter_ground, inter_eq_self_of_subset_left hX]
theorem basis_iff_basis'_subset_ground : M.Basis I X ↔ M.Basis' I X ∧ X ⊆ M.E :=
⟨fun h ↦ ⟨h.basis', h.subset_ground⟩, fun h ↦ (basis'_iff_basis h.2).mp h.1⟩
theorem Basis'.basis_inter_ground (hIX : M.Basis' I X) : M.Basis I (X ∩ M.E) :=
basis'_iff_basis_inter_ground.mp hIX
theorem Basis'.eq_of_subset_indep (hI : M.Basis' I X) (hJ : M.Indep J) (hIJ : I ⊆ J)
(hJX : J ⊆ X) : I = J :=
hIJ.antisymm (hI.2 ⟨hJ, hJX⟩ hIJ)
theorem Basis'.insert_not_indep (hI : M.Basis' I X) (he : e ∈ X \ I) : ¬ M.Indep (insert e I) :=
fun hi ↦ he.2 <| insert_eq_self.1 <| Eq.symm <|
hI.eq_of_subset_indep hi (subset_insert _ _) (insert_subset he.1 hI.subset)
theorem basis_iff_maximal (hX : X ⊆ M.E := by aesop_mat) :
M.Basis I X ↔ Maximal (fun I ↦ M.Indep I ∧ I ⊆ X) I := by
rw [Basis, and_iff_left hX]
theorem Indep.basis_of_maximal_subset (hI : M.Indep I) (hIX : I ⊆ X)
(hmax : ∀ ⦃J⦄, M.Indep J → I ⊆ J → J ⊆ X → J ⊆ I) (hX : X ⊆ M.E := by aesop_mat) :
M.Basis I X := by
rw [basis_iff (by aesop_mat : X ⊆ M.E), and_iff_right hI, and_iff_right hIX]
exact fun J hJ hIJ hJX ↦ hIJ.antisymm (hmax hJ hIJ hJX)
theorem Basis.basis_subset (hI : M.Basis I X) (hIY : I ⊆ Y) (hYX : Y ⊆ X) : M.Basis I Y := by
rw [basis_iff (hYX.trans hI.subset_ground), and_iff_right hI.indep, and_iff_right hIY]
exact fun J hJ hIJ hJY ↦ hI.eq_of_subset_indep hJ hIJ (hJY.trans hYX)
@[simp] theorem basis_self_iff_indep : M.Basis I I ↔ M.Indep I := by
rw [basis_iff', and_iff_right rfl.subset, and_assoc, and_iff_left_iff_imp]
exact fun hi ↦ ⟨fun _ _ ↦ subset_antisymm, hi.subset_ground⟩
theorem Indep.basis_self (h : M.Indep I) : M.Basis I I :=
basis_self_iff_indep.mpr h
@[simp] theorem basis_empty_iff (M : Matroid α) : M.Basis I ∅ ↔ I = ∅ :=
⟨fun h ↦ subset_empty_iff.mp h.subset, fun h ↦ by (rw [h]; exact M.empty_indep.basis_self)⟩
theorem Basis.dep_of_ssubset (hI : M.Basis I X) (hIY : I ⊂ Y) (hYX : Y ⊆ X) : M.Dep Y := by
have : X ⊆ M.E := hI.subset_ground
rw [← not_indep_iff]
exact fun hY ↦ hIY.ne (hI.eq_of_subset_indep hY hIY.subset hYX)
theorem Basis.insert_dep (hI : M.Basis I X) (he : e ∈ X \ I) : M.Dep (insert e I) :=
hI.dep_of_ssubset (ssubset_insert he.2) (insert_subset he.1 hI.subset)
theorem Basis.mem_of_insert_indep (hI : M.Basis I X) (he : e ∈ X) (hIe : M.Indep (insert e I)) :
e ∈ I :=
by_contra (fun heI ↦ (hI.insert_dep ⟨he, heI⟩).not_indep hIe)
theorem Basis'.mem_of_insert_indep (hI : M.Basis' I X) (he : e ∈ X) (hIe : M.Indep (insert e I)) :
e ∈ I :=
hI.basis_inter_ground.mem_of_insert_indep ⟨he, hIe.subset_ground (mem_insert _ _)⟩ hIe
theorem Basis.not_basis_of_ssubset (hI : M.Basis I X) (hJI : J ⊂ I) : ¬ M.Basis J X :=
fun h ↦ hJI.ne (h.eq_of_subset_indep hI.indep hJI.subset hI.subset)
theorem Indep.subset_basis_of_subset (hI : M.Indep I) (hIX : I ⊆ X) (hX : X ⊆ M.E := by aesop_mat) :
∃ J, M.Basis J X ∧ I ⊆ J := by
obtain ⟨J, hJ, hJmax⟩ := M.maximality X hX I hI hIX
exact ⟨J, ⟨hJmax, hX⟩, hJ⟩
theorem Indep.subset_basis'_of_subset (hI : M.Indep I) (hIX : I ⊆ X) :
∃ J, M.Basis' J X ∧ I ⊆ J := by
simp_rw [basis'_iff_basis_inter_ground]
exact hI.subset_basis_of_subset (subset_inter hIX hI.subset_ground)
theorem exists_basis (M : Matroid α) (X : Set α) (hX : X ⊆ M.E := by aesop_mat) :
∃ I, M.Basis I X :=
let ⟨_, hI, _⟩ := M.empty_indep.subset_basis_of_subset (empty_subset X)
⟨_,hI⟩
theorem exists_basis' (M : Matroid α) (X : Set α) : ∃ I, M.Basis' I X :=
let ⟨_, hI, _⟩ := M.empty_indep.subset_basis'_of_subset (empty_subset X)
⟨_,hI⟩
theorem exists_basis_subset_basis (M : Matroid α) (hXY : X ⊆ Y) (hY : Y ⊆ M.E := by aesop_mat) :
∃ I J, M.Basis I X ∧ M.Basis J Y ∧ I ⊆ J := by
obtain ⟨I, hI⟩ := M.exists_basis X (hXY.trans hY)
obtain ⟨J, hJ, hIJ⟩ := hI.indep.subset_basis_of_subset (hI.subset.trans hXY)
exact ⟨_, _, hI, hJ, hIJ⟩
theorem Basis.exists_basis_inter_eq_of_superset (hI : M.Basis I X) (hXY : X ⊆ Y)
(hY : Y ⊆ M.E := by aesop_mat) : ∃ J, M.Basis J Y ∧ J ∩ X = I := by
obtain ⟨J, hJ, hIJ⟩ := hI.indep.subset_basis_of_subset (hI.subset.trans hXY)
refine ⟨J, hJ, subset_antisymm ?_ (subset_inter hIJ hI.subset)⟩
exact fun e he ↦ hI.mem_of_insert_indep he.2 (hJ.indep.subset (insert_subset he.1 hIJ))
theorem exists_basis_union_inter_basis (M : Matroid α) (X Y : Set α) (hX : X ⊆ M.E := by aesop_mat)
(hY : Y ⊆ M.E := by aesop_mat) : ∃ I, M.Basis I (X ∪ Y) ∧ M.Basis (I ∩ Y) Y :=
let ⟨J, hJ⟩ := M.exists_basis Y
(hJ.exists_basis_inter_eq_of_superset subset_union_right).imp
(fun I hI ↦ ⟨hI.1, by rwa [hI.2]⟩)
theorem Indep.eq_of_basis (hI : M.Indep I) (hJ : M.Basis J I) : J = I :=
hJ.eq_of_subset_indep hI hJ.subset rfl.subset
theorem Basis.exists_base (hI : M.Basis I X) : ∃ B, M.Base B ∧ I = B ∩ X :=
let ⟨B,hB, hIB⟩ := hI.indep.exists_base_superset
⟨B, hB, subset_antisymm (subset_inter hIB hI.subset)
(by rw [hI.eq_of_subset_indep (hB.indep.inter_right X) (subset_inter hIB hI.subset)
inter_subset_right])⟩
@[simp] theorem basis_ground_iff : M.Basis B M.E ↔ M.Base B := by
rw [Basis, and_iff_left rfl.subset, base_iff_maximal_indep,
maximal_and_iff_right_of_imp (fun _ h ↦ h.subset_ground),
and_iff_left_of_imp (fun h ↦ h.1.subset_ground)]
theorem Base.basis_ground (hB : M.Base B) : M.Basis B M.E :=
basis_ground_iff.mpr hB
theorem Indep.basis_iff_forall_insert_dep (hI : M.Indep I) (hIX : I ⊆ X) :
M.Basis I X ↔ ∀ e ∈ X \ I, M.Dep (insert e I) := by
rw [Basis, maximal_iff_forall_insert (fun I J hI hIJ ↦ ⟨hI.1.subset hIJ, hIJ.trans hI.2⟩)]
simp only [hI, hIX, and_self, insert_subset_iff, and_true, not_and, true_and, mem_diff, and_imp,
Dep, hI.subset_ground]
exact ⟨fun h e heX heI ↦ ⟨fun hi ↦ h.1 e heI hi heX, h.2 heX⟩,
fun h ↦ ⟨fun e heI hi heX ↦ (h e heX heI).1 hi,
fun e heX ↦ (em (e ∈ I)).elim (fun h ↦ hI.subset_ground h) fun heI ↦ (h _ heX heI).2 ⟩⟩
theorem Indep.basis_of_forall_insert (hI : M.Indep I) (hIX : I ⊆ X)
(he : ∀ e ∈ X \ I, M.Dep (insert e I)) : M.Basis I X :=
(hI.basis_iff_forall_insert_dep hIX).mpr he
theorem Indep.basis_insert_iff (hI : M.Indep I) :
M.Basis I (insert e I) ↔ M.Dep (insert e I) ∨ e ∈ I := by
simp_rw [hI.basis_iff_forall_insert_dep (subset_insert _ _), dep_iff, insert_subset_iff,
and_iff_left hI.subset_ground, mem_diff, mem_insert_iff, or_and_right, and_not_self,
or_false, and_imp, forall_eq]
tauto
theorem Basis.iUnion_basis_iUnion {ι : Type _} (X I : ι → Set α) (hI : ∀ i, M.Basis (I i) (X i))
(h_ind : M.Indep (⋃ i, I i)) : M.Basis (⋃ i, I i) (⋃ i, X i) := by
refine h_ind.basis_of_forall_insert
(iUnion_subset (fun i ↦ (hI i).subset.trans (subset_iUnion _ _))) ?_
rintro e ⟨⟨_, ⟨⟨i, hi, rfl⟩, (hes : e ∈ X i)⟩⟩, he'⟩
rw [mem_iUnion, not_exists] at he'
refine ((hI i).insert_dep ⟨hes, he' _⟩).superset (insert_subset_insert (subset_iUnion _ _)) ?_
rw [insert_subset_iff, iUnion_subset_iff, and_iff_left (fun i ↦ (hI i).indep.subset_ground)]
exact (hI i).subset_ground hes
theorem Basis.basis_iUnion {ι : Type _} [Nonempty ι] (X : ι → Set α)
(hI : ∀ i, M.Basis I (X i)) : M.Basis I (⋃ i, X i) := by
convert Basis.iUnion_basis_iUnion X (fun _ ↦ I) (fun i ↦ hI i) _ <;> rw [iUnion_const]
exact (hI (Classical.arbitrary ι)).indep
theorem Basis.basis_sUnion {Xs : Set (Set α)} (hne : Xs.Nonempty) (h : ∀ X ∈ Xs, M.Basis I X) :
M.Basis I (⋃₀ Xs) := by
rw [sUnion_eq_iUnion]
have := Iff.mpr nonempty_coe_sort hne
exact Basis.basis_iUnion _ fun X ↦ (h X X.prop)
theorem Indep.basis_setOf_insert_basis (hI : M.Indep I) :
M.Basis I {x | M.Basis I (insert x I)} := by
refine hI.basis_of_forall_insert (fun e he ↦ (?_ : M.Basis _ _))
(fun e he ↦ ⟨fun hu ↦ he.2 ?_, he.1.subset_ground⟩)
· rw [insert_eq_of_mem he]; exact hI.basis_self
simpa using (hu.eq_of_basis he.1).symm
theorem Basis.union_basis_union (hIX : M.Basis I X) (hJY : M.Basis J Y) (h : M.Indep (I ∪ J)) :
M.Basis (I ∪ J) (X ∪ Y) := by
rw [union_eq_iUnion, union_eq_iUnion]
refine Basis.iUnion_basis_iUnion _ _ ?_ ?_
· simp only [Bool.forall_bool, cond_false, cond_true]; exact ⟨hJY, hIX⟩
rwa [← union_eq_iUnion]
theorem Basis.basis_union (hIX : M.Basis I X) (hIY : M.Basis I Y) : M.Basis I (X ∪ Y) := by
convert hIX.union_basis_union hIY _ <;> rw [union_self]; exact hIX.indep
theorem Basis.basis_union_of_subset (hI : M.Basis I X) (hJ : M.Indep J) (hIJ : I ⊆ J) :
M.Basis J (J ∪ X) := by
convert hJ.basis_self.union_basis_union hI _ <;>
rw [union_eq_self_of_subset_right hIJ]
assumption
theorem Basis.insert_basis_insert (hI : M.Basis I X) (h : M.Indep (insert e I)) :
M.Basis (insert e I) (insert e X) := by
simp_rw [← union_singleton] at *
exact hI.union_basis_union (h.subset subset_union_right).basis_self h
theorem Base.base_of_basis_superset (hB : M.Base B) (hBX : B ⊆ X) (hIX : M.Basis I X) :
M.Base I := by
by_contra h
obtain ⟨e,heBI,he⟩ := hIX.indep.exists_insert_of_not_base h hB
exact heBI.2 (hIX.mem_of_insert_indep (hBX heBI.1) he)
theorem Indep.exists_base_subset_union_base (hI : M.Indep I) (hB : M.Base B) :
∃ B', M.Base B' ∧ I ⊆ B' ∧ B' ⊆ I ∪ B := by
obtain ⟨B', hB', hIB'⟩ := hI.subset_basis_of_subset <| subset_union_left (t := B)
exact ⟨B', hB.base_of_basis_superset subset_union_right hB', hIB', hB'.subset⟩
theorem Basis.inter_eq_of_subset_indep (hIX : M.Basis I X) (hIJ : I ⊆ J) (hJ : M.Indep J) :
J ∩ X = I :=
(subset_inter hIJ hIX.subset).antisymm'
(fun _ he ↦ hIX.mem_of_insert_indep he.2 (hJ.subset (insert_subset he.1 hIJ)))
theorem Basis'.inter_eq_of_subset_indep (hI : M.Basis' I X) (hIJ : I ⊆ J) (hJ : M.Indep J) :
J ∩ X = I := by
rw [← hI.basis_inter_ground.inter_eq_of_subset_indep hIJ hJ, inter_comm X, ← inter_assoc,
inter_eq_self_of_subset_left hJ.subset_ground]
theorem Base.basis_of_subset (hX : X ⊆ M.E := by aesop_mat) (hB : M.Base B) (hBX : B ⊆ X) :
M.Basis B X := by
rw [basis_iff, and_iff_right hB.indep, and_iff_right hBX]
exact fun J hJ hBJ _ ↦ hB.eq_of_subset_indep hJ hBJ
theorem exists_basis_disjoint_basis_of_subset (M : Matroid α) {X Y : Set α} (hXY : X ⊆ Y)
(hY : Y ⊆ M.E := by aesop_mat) : ∃ I J, M.Basis I X ∧ M.Basis (I ∪ J) Y ∧ Disjoint X J := by
obtain ⟨I, I', hI, hI', hII'⟩ := M.exists_basis_subset_basis hXY
refine ⟨I, I' \ I, hI, by rwa [union_diff_self, union_eq_self_of_subset_left hII'], ?_⟩
rw [disjoint_iff_forall_ne]
rintro e heX _ ⟨heI', heI⟩ rfl
exact heI <| hI.mem_of_insert_indep heX (hI'.indep.subset (insert_subset heI' hII'))
end Basis
section Finite
/-- For finite `E`, finitely many matroids have ground set contained in `E`. -/
theorem finite_setOf_matroid {E : Set α} (hE : E.Finite) : {M : Matroid α | M.E ⊆ E}.Finite := by
set f : Matroid α → Set α × (Set (Set α)) := fun M ↦ ⟨M.E, {B | M.Base B}⟩
have hf : f.Injective := by
refine fun M M' hMM' ↦ ?_
rw [Prod.mk.injEq, and_comm, Set.ext_iff, and_comm] at hMM'
exact eq_of_base_iff_base_forall hMM'.1 (fun B _ ↦ hMM'.2 B)
rw [← Set.finite_image_iff hf.injOn]
refine (hE.finite_subsets.prod hE.finite_subsets.finite_subsets).subset ?_
rintro _ ⟨M, hE : M.E ⊆ E, rfl⟩
simp only [Set.mem_prod, Set.mem_setOf_eq, Set.setOf_subset_setOf]
exact ⟨hE, fun B hB ↦ hB.subset_ground.trans hE⟩
/-- For finite `E`, finitely many matroids have ground set `E`. -/
theorem finite_setOf_matroid' {E : Set α} (hE : E.Finite) : {M : Matroid α | M.E = E}.Finite :=
(finite_setOf_matroid hE).subset (fun M ↦ by rintro rfl; exact rfl.subset)
end Finite
end Matroid
|
Data\Matroid\Closure.lean | /-
Copyright (c) 2024 Peter Nelson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Peter Nelson
-/
import Mathlib.Data.Matroid.Restrict
import Mathlib.Order.Closure
/-!
# Matroid Closure
A `Flat` of a matroid `M` is a combinatorial analogue of a subspace of a vector space,
and is defined to be a subset `F` of the ground set of `M` such that for each basis
`I` for `M`, every set having `I` as a basis is contained in `F`.
The *closure* of a set `X` in a matroid `M` is the intersection of all flats of `M` containing `X`.
This is a combinatorial analogue of the linear span of a set of vectors.
For `M : Matroid α`, this file defines a predicate `M.Flat : Set α → Prop` and a function
`M.closure : Set α → Set α` corresponding to these notions, and develops API for the latter.
API for `Matroid.Flat` will appear in another file; we include the definition here since
it is used in the definition of `Matroid.closure`.
## Main definitions
* For `M : Matroid α` and `F : Set α`, `M.Flat F` means that `F` is a flat of `M`.
* For `M : Matroid α` and `X : Set α`, `M.closure X` is the closure of `X` in `M`.
* For `M : Matroid α` and `X : ↑(Iic M.E)` (i.e. a bundled subset of `M.E`),
`M.subtypeClosure X` is the closure of `X`, viewed as a term in `↑(Iic M.E)`.
This is a `ClosureOperator` on `↑(Iic M.E)`.
## Implementation details
If `X : Set α` satisfies `X ⊆ M.E`, then it is clear how `M.closure X` should be defined.
But `M.closure X` also needs to be defined for all `X : Set α`,
so a convention is needed for how it handles sets containing junk elements outside `M.E`.
All such choices come with tradeoffs. Provided that `M.closure X` has already been defined
for `X ⊆ M.E`, the two best candidates for extending it to all `X` seem to be:
(1) The function for which `M.closure X = M.closure (X ∩ M.E)` for all `X : Set α`
(2) The function for which `M.closure X = M.closure (X ∩ M.E) ∪ X` for all `X : Set α`
For both options, the function `closure` is monotone and idempotent with no assumptions on `X`.
Choice (1) has the advantage that `M.closure X ⊆ M.E` holds for all `X` without the assumption
that `X ⊆ M.E`, which is very nice for `aesop_mat`. It is also fairly convenient to rewrite
`M.closure X` to `M.closure (X ∩ M.E)` when one needs to work with a subset of the ground set.
Its disadvantage is that the statement `X ⊆ M.closure X` is only true provided that `X ⊆ M.E`.
Choice (2) has the reverse property: we would have `X ⊆ M.closure X` for all `X`,
but the condition `M.closure X ⊆ M.E` requires `X ⊆ M.E` to hold.
It has a couple of other advantages too: is is actually the closure function of a matroid on `α`
with ground set `univ` (specifically, the direct sum of `M` and a free matroid on `M.Eᶜ`),
and because of this, it is an example of a `ClosureOperator` on `α`, which in turn gives access
to nice existing API for both `ClosureOperator` and `GaloisInsertion`.
This also relates to flats; `F ⊆ M.E ∧ ClosureOperator.IsClosed F` is equivalent to `M.Flat F`.
(All of this fails for choice (1), since `X ⊆ M.closure X` is required for
a `ClosureOperator`, but isn't true for non-subsets of `M.E`)
The API that choice (2) would offer is very beguiling, but after extensive experimentation in
an external repo, it seems that (1) is far less rough around the edges in practice,
so we go with (1). It may be helpful at some point to define a primed version
`Matroid.closure' : ClosureOperator (Set α)` corresponding to choice (2).
Failing that, the `ClosureOperator`/`GaloisInsertion` API is still available on
the subtype `↑(Iic M.E)` via `Matroid.SubtypeClosure`, albeit less elegantly.
-/
open Set
namespace Matroid
variable {ι α : Type*} {M : Matroid α} {F X Y : Set α} {e : α}
section Flat
/-- A flat is a maximal set having a given basis -/
@[mk_iff]
structure Flat (M : Matroid α) (F : Set α) : Prop where
subset_of_basis_of_basis : ∀ ⦃I X⦄, M.Basis I F → M.Basis I X → X ⊆ F
subset_ground : F ⊆ M.E
attribute [aesop unsafe 20% (rule_sets := [Matroid])] Flat.subset_ground
@[simp] lemma ground_flat (M : Matroid α) : M.Flat M.E :=
⟨fun _ _ _ ↦ Basis.subset_ground, Subset.rfl⟩
lemma Flat.iInter {ι : Type*} [Nonempty ι] {Fs : ι → Set α}
(hFs : ∀ i, M.Flat (Fs i)) : M.Flat (⋂ i, Fs i) := by
refine ⟨fun I X hI hIX ↦ subset_iInter fun i ↦ ?_,
(iInter_subset _ (Classical.arbitrary _)).trans (hFs _).subset_ground⟩
obtain ⟨J, hIJ, hJ⟩ := hI.indep.subset_basis_of_subset (hI.subset.trans (iInter_subset _ i))
refine subset_union_right.trans ((hFs i).1 (X := Fs i ∪ X) hIJ ?_)
convert hIJ.basis_union (hIX.basis_union_of_subset hIJ.indep hJ) using 1
rw [← union_assoc, union_eq_self_of_subset_right hIJ.subset]
/-- The property of being a flat gives rise to a `ClosureOperator` on the subsets of `M.E`,
in which the `IsClosed` sets correspond to `Flat`s.
(We can't define such an operator on all of `Set α`,
since this would incorrectly force `univ` to always be a flat.) -/
def subtypeClosure (M : Matroid α) : ClosureOperator (Iic M.E) :=
ClosureOperator.ofCompletePred (fun F ↦ M.Flat F.1) fun s hs ↦ by
obtain (rfl | hne) := s.eq_empty_or_nonempty
· simp
have _ := hne.coe_sort
convert Flat.iInter (M := M) (Fs := fun (F : s) ↦ F.1.1) (fun F ↦ hs F.1 F.2)
ext
aesop
lemma flat_iff_isClosed : M.Flat F ↔ ∃ h : F ⊆ M.E, M.subtypeClosure.IsClosed ⟨F, h⟩ := by
simpa [subtypeClosure] using Flat.subset_ground
lemma isClosed_iff_flat {F : Iic M.E} : M.subtypeClosure.IsClosed F ↔ M.Flat F := by
simp [subtypeClosure]
end Flat
/-- The closure of `X ⊆ M.E` is the intersection of all the flats of `M` containing `X`.
A set `X` that doesn't satisfy `X ⊆ M.E` has the junk value `M.closure X := M.closure (X ∩ M.E)`. -/
def closure (M : Matroid α) (X : Set α) : Set α := ⋂₀ {F | M.Flat F ∧ X ∩ M.E ⊆ F}
lemma closure_def (M : Matroid α) (X : Set α) : M.closure X = ⋂₀ {F | M.Flat F ∧ X ∩ M.E ⊆ F} := rfl
lemma closure_def' (M : Matroid α) (X : Set α) (hX : X ⊆ M.E := by aesop_mat) :
M.closure X = ⋂₀ {F | M.Flat F ∧ X ⊆ F} := by
rw [closure, inter_eq_self_of_subset_left hX]
lemma closure_eq_subtypeClosure (M : Matroid α) (X : Set α) :
M.closure X = M.subtypeClosure ⟨X ∩ M.E, inter_subset_right⟩ := by
suffices ∀ (x : α), (∀ (t : Set α), M.Flat t → X ∩ M.E ⊆ t → x ∈ t) ↔
(x ∈ M.E ∧ ∀ a ⊆ M.E, X ∩ M.E ⊆ a → M.Flat a → x ∈ a) by
simpa [closure, subtypeClosure, Set.ext_iff]
exact fun x ↦ ⟨fun h ↦ ⟨h _ M.ground_flat inter_subset_right, fun F _ hXF hF ↦ h F hF hXF⟩,
fun ⟨_, h⟩ F hF hXF ↦ h F hF.subset_ground hXF hF⟩
@[aesop unsafe 10% (rule_sets := [Matroid])]
lemma closure_subset_ground (M : Matroid α) (X : Set α) : M.closure X ⊆ M.E :=
sInter_subset_of_mem ⟨M.ground_flat, inter_subset_right⟩
@[simp] lemma ground_subset_closure_iff : M.E ⊆ M.closure X ↔ M.closure X = M.E := by
simp [M.closure_subset_ground X, subset_antisymm_iff]
@[simp] lemma closure_inter_ground (M : Matroid α) (X : Set α) :
M.closure (X ∩ M.E) = M.closure X := by
simp_rw [closure_def, inter_assoc, inter_self]
lemma inter_ground_subset_closure (M : Matroid α) (X : Set α) : X ∩ M.E ⊆ M.closure X := by
simp_rw [closure_def, subset_sInter_iff]; aesop
lemma mem_closure_iff_forall_mem_flat (X : Set α) (hX : X ⊆ M.E := by aesop_mat) :
e ∈ M.closure X ↔ ∀ F, M.Flat F → X ⊆ F → e ∈ F := by
simp_rw [M.closure_def' X, mem_sInter, mem_setOf, and_imp]
lemma subset_closure_iff_forall_subset_flat (X : Set α) (hX : X ⊆ M.E := by aesop_mat) :
Y ⊆ M.closure X ↔ ∀ F, M.Flat F → X ⊆ F → Y ⊆ F := by
simp_rw [M.closure_def' X, subset_sInter_iff, mem_setOf, and_imp]
lemma subset_closure (M : Matroid α) (X : Set α) (hX : X ⊆ M.E := by aesop_mat) :
X ⊆ M.closure X := by
simp [M.closure_def' X, subset_sInter_iff]
lemma Flat.closure (hF : M.Flat F) : M.closure F = F :=
(sInter_subset_of_mem (by simpa)).antisymm (M.subset_closure F)
@[simp] lemma closure_ground (M : Matroid α) : M.closure M.E = M.E :=
(M.closure_subset_ground M.E).antisymm (M.subset_closure M.E)
@[simp] lemma closure_univ (M : Matroid α) : M.closure univ = M.E := by
rw [← closure_inter_ground, univ_inter, closure_ground]
lemma closure_subset_closure (M : Matroid α) (h : X ⊆ Y) : M.closure X ⊆ M.closure Y :=
subset_sInter (fun _ h' ↦ sInter_subset_of_mem
⟨h'.1, subset_trans (inter_subset_inter_left _ h) h'.2⟩)
lemma closure_mono (M : Matroid α) : Monotone M.closure :=
fun _ _ ↦ M.closure_subset_closure
@[simp] lemma closure_closure (M : Matroid α) (X : Set α) : M.closure (M.closure X) = M.closure X :=
(M.subset_closure _).antisymm' (subset_sInter
(fun F hF ↦ (closure_subset_closure _ (sInter_subset_of_mem hF)).trans hF.1.closure.subset))
lemma closure_subset_closure_of_subset_closure (hXY : X ⊆ M.closure Y) :
M.closure X ⊆ M.closure Y :=
(M.closure_subset_closure hXY).trans_eq (M.closure_closure Y)
lemma closure_subset_closure_iff_subset_closure (hX : X ⊆ M.E := by aesop_mat) :
M.closure X ⊆ M.closure Y ↔ X ⊆ M.closure Y :=
⟨(M.subset_closure X).trans, closure_subset_closure_of_subset_closure⟩
lemma subset_closure_of_subset (M : Matroid α) (hXY : X ⊆ Y) (hY : Y ⊆ M.E := by aesop_mat) :
X ⊆ M.closure Y :=
hXY.trans (M.subset_closure Y)
lemma subset_closure_of_subset' (M : Matroid α) (hXY : X ⊆ Y) (hX : X ⊆ M.E := by aesop_mat) :
X ⊆ M.closure Y := by
rw [← closure_inter_ground]; exact M.subset_closure_of_subset (subset_inter hXY hX)
lemma exists_of_closure_ssubset (hXY : M.closure X ⊂ M.closure Y) : ∃ e ∈ Y, e ∉ M.closure X := by
by_contra! hcon
exact hXY.not_subset (M.closure_subset_closure_of_subset_closure hcon)
lemma mem_closure_of_mem (M : Matroid α) (h : e ∈ X) (hX : X ⊆ M.E := by aesop_mat) :
e ∈ M.closure X :=
(M.subset_closure X) h
lemma mem_closure_of_mem' (M : Matroid α) (heX : e ∈ X) (h : e ∈ M.E := by aesop_mat) :
e ∈ M.closure X := by
rw [← closure_inter_ground]
exact M.mem_closure_of_mem ⟨heX, h⟩
lemma not_mem_of_mem_diff_closure (he : e ∈ M.E \ M.closure X) : e ∉ X :=
fun heX ↦ he.2 <| M.mem_closure_of_mem' heX he.1
@[aesop unsafe 10% (rule_sets := [Matroid])]
lemma mem_ground_of_mem_closure (he : e ∈ M.closure X) : e ∈ M.E :=
(M.closure_subset_ground _) he
lemma closure_iUnion_closure_eq_closure_iUnion (M : Matroid α) (Xs : ι → Set α) :
M.closure (⋃ i, M.closure (Xs i)) = M.closure (⋃ i, Xs i) := by
simp_rw [closure_eq_subtypeClosure, iUnion_inter, Subtype.coe_inj]
convert M.subtypeClosure.closure_iSup_closure (fun i ↦ ⟨Xs i ∩ M.E, inter_subset_right⟩) <;>
simp [← iUnion_inter, subtypeClosure]
lemma closure_iUnion_congr (Xs Ys : ι → Set α) (h : ∀ i, M.closure (Xs i) = M.closure (Ys i)) :
M.closure (⋃ i, Xs i) = M.closure (⋃ i, Ys i) := by
simp [h, ← M.closure_iUnion_closure_eq_closure_iUnion]
lemma closure_biUnion_closure_eq_closure_sUnion (M : Matroid α) (Xs : Set (Set α)) :
M.closure (⋃ X ∈ Xs, M.closure X) = M.closure (⋃₀ Xs) := by
rw [sUnion_eq_iUnion, biUnion_eq_iUnion, closure_iUnion_closure_eq_closure_iUnion]
lemma closure_biUnion_closure_eq_closure_biUnion (M : Matroid α) (Xs : ι → Set α) (A : Set ι) :
M.closure (⋃ i ∈ A, M.closure (Xs i)) = M.closure (⋃ i ∈ A, Xs i) := by
rw [biUnion_eq_iUnion, M.closure_iUnion_closure_eq_closure_iUnion, biUnion_eq_iUnion]
lemma closure_biUnion_congr (M : Matroid α) (Xs Ys : ι → Set α) (A : Set ι)
(h : ∀ i ∈ A, M.closure (Xs i) = M.closure (Ys i)) :
M.closure (⋃ i ∈ A, Xs i) = M.closure (⋃ i ∈ A, Ys i) := by
rw [← closure_biUnion_closure_eq_closure_biUnion, iUnion₂_congr h,
closure_biUnion_closure_eq_closure_biUnion]
lemma closure_closure_union_closure_eq_closure_union (M : Matroid α) (X Y : Set α) :
M.closure (M.closure X ∪ M.closure Y) = M.closure (X ∪ Y) := by
rw [eq_comm, union_eq_iUnion, ← closure_iUnion_closure_eq_closure_iUnion, union_eq_iUnion]
simp_rw [Bool.cond_eq_ite, apply_ite]
@[simp] lemma closure_union_closure_right_eq (M : Matroid α) (X Y : Set α) :
M.closure (X ∪ M.closure Y) = M.closure (X ∪ Y) := by
rw [← closure_closure_union_closure_eq_closure_union, closure_closure,
closure_closure_union_closure_eq_closure_union]
@[simp] lemma closure_union_closure_left_eq (M : Matroid α) (X Y : Set α) :
M.closure (M.closure X ∪ Y) = M.closure (X ∪ Y) := by
rw [← closure_closure_union_closure_eq_closure_union, closure_closure,
closure_closure_union_closure_eq_closure_union]
@[simp] lemma closure_insert_closure_eq_closure_insert (M : Matroid α) (e : α) (X : Set α) :
M.closure (insert e (M.closure X)) = M.closure (insert e X) := by
simp_rw [← singleton_union, closure_union_closure_right_eq]
@[simp] lemma closure_union_closure_empty_eq (M : Matroid α) (X : Set α) :
M.closure X ∪ M.closure ∅ = M.closure X :=
union_eq_self_of_subset_right (M.closure_subset_closure (empty_subset _))
@[simp] lemma closure_empty_union_closure_eq (M : Matroid α) (X : Set α) :
M.closure ∅ ∪ M.closure X = M.closure X :=
union_eq_self_of_subset_left (M.closure_subset_closure (empty_subset _))
lemma closure_insert_eq_of_mem_closure (he : e ∈ M.closure X) :
M.closure (insert e X) = M.closure X := by
rw [← closure_insert_closure_eq_closure_insert, insert_eq_of_mem he, closure_closure]
lemma mem_closure_self (M : Matroid α) (e : α) (he : e ∈ M.E := by aesop_mat) : e ∈ M.closure {e} :=
mem_closure_of_mem' M rfl
section Indep
variable {ι : Sort*} {I J B : Set α} {f x y : α}
lemma Indep.closure_eq_setOf_basis_insert (hI : M.Indep I) :
M.closure I = {x | M.Basis I (insert x I)} := by
set F := {x | M.Basis I (insert x I)}
have hIF : M.Basis I F := hI.basis_setOf_insert_basis
have hF : M.Flat F := by
refine ⟨fun J X hJF hJX e heX ↦ show M.Basis _ _ from ?_, hIF.subset_ground⟩
exact (hIF.basis_of_basis_of_subset_of_subset (hJX.basis_union hJF) hJF.subset
(hIF.subset.trans subset_union_right)).basis_subset (subset_insert _ _)
(insert_subset (Or.inl heX) (hIF.subset.trans subset_union_right))
rw [subset_antisymm_iff, closure_def, subset_sInter_iff, and_iff_right (sInter_subset_of_mem _)]
· rintro F' ⟨hF', hIF'⟩ e (he : M.Basis I (insert e I))
rw [inter_eq_left.mpr (hIF.subset.trans hIF.subset_ground)] at hIF'
obtain ⟨J, hJ, hIJ⟩ := hI.subset_basis_of_subset hIF' hF'.2
exact (hF'.1 hJ (he.basis_union_of_subset hJ.indep hIJ)) (Or.inr (mem_insert _ _))
exact ⟨hF, inter_subset_left.trans hIF.subset⟩
lemma Indep.insert_basis_iff_mem_closure (hI : M.Indep I) :
M.Basis I (insert e I) ↔ e ∈ M.closure I := by
rw [hI.closure_eq_setOf_basis_insert, mem_setOf]
lemma Indep.basis_closure (hI : M.Indep I) : M.Basis I (M.closure I) := by
rw [hI.closure_eq_setOf_basis_insert]; exact hI.basis_setOf_insert_basis
lemma Basis.closure_eq_closure (h : M.Basis I X) : M.closure I = M.closure X := by
refine subset_antisymm (M.closure_subset_closure h.subset) ?_
rw [← M.closure_closure I, h.indep.closure_eq_setOf_basis_insert]
exact M.closure_subset_closure fun e he ↦ (h.basis_subset (subset_insert _ _)
(insert_subset he h.subset))
lemma Basis.closure_eq_right (h : M.Basis I (M.closure X)) : M.closure I = M.closure X :=
M.closure_closure X ▸ h.closure_eq_closure
lemma Basis'.closure_eq_closure (h : M.Basis' I X) : M.closure I = M.closure X := by
rw [← closure_inter_ground _ X, h.basis_inter_ground.closure_eq_closure]
lemma Basis.subset_closure (h : M.Basis I X) : X ⊆ M.closure I := by
rw [← closure_subset_closure_iff_subset_closure, h.closure_eq_closure]
lemma Basis'.basis_closure_right (h : M.Basis' I X) : M.Basis I (M.closure X) := by
rw [← h.closure_eq_closure]; exact h.indep.basis_closure
lemma Basis.basis_closure_right (h : M.Basis I X) : M.Basis I (M.closure X) :=
h.basis'.basis_closure_right
lemma Indep.mem_closure_iff (hI : M.Indep I) :
x ∈ M.closure I ↔ M.Dep (insert x I) ∨ x ∈ I := by
rwa [hI.closure_eq_setOf_basis_insert, mem_setOf, basis_insert_iff]
lemma Indep.mem_closure_iff' (hI : M.Indep I) :
x ∈ M.closure I ↔ x ∈ M.E ∧ (M.Indep (insert x I) → x ∈ I) := by
rw [hI.mem_closure_iff, dep_iff, insert_subset_iff, and_iff_left hI.subset_ground,
imp_iff_not_or]
have := hI.subset_ground
aesop
lemma Indep.insert_dep_iff (hI : M.Indep I) : M.Dep (insert e I) ↔ e ∈ M.closure I \ I := by
rw [mem_diff, hI.mem_closure_iff, or_and_right, and_not_self_iff, or_false,
iff_self_and, imp_not_comm]
intro heI; rw [insert_eq_of_mem heI]; exact hI.not_dep
lemma Indep.mem_closure_iff_of_not_mem (hI : M.Indep I) (heI : e ∉ I) :
e ∈ M.closure I ↔ M.Dep (insert e I) := by
rw [hI.insert_dep_iff, mem_diff, and_iff_left heI]
lemma Indep.not_mem_closure_iff (hI : M.Indep I) (he : e ∈ M.E := by aesop_mat) :
e ∉ M.closure I ↔ M.Indep (insert e I) ∧ e ∉ I := by
rw [hI.mem_closure_iff, dep_iff, insert_subset_iff, and_iff_right he,
and_iff_left hI.subset_ground]; tauto
lemma Indep.not_mem_closure_iff_of_not_mem (hI : M.Indep I) (heI : e ∉ I)
(he : e ∈ M.E := by aesop_mat) : e ∉ M.closure I ↔ M.Indep (insert e I) := by
rw [hI.not_mem_closure_iff, and_iff_left heI]
lemma Indep.insert_indep_iff_of_not_mem (hI : M.Indep I) (heI : e ∉ I) :
M.Indep (insert e I) ↔ e ∈ M.E \ M.closure I := by
rw [mem_diff, hI.mem_closure_iff_of_not_mem heI, dep_iff, not_and, not_imp_not, insert_subset_iff,
and_iff_left hI.subset_ground]
exact ⟨fun h ↦ ⟨h.subset_ground (mem_insert e I), fun _ ↦ h⟩, fun h ↦ h.2 h.1⟩
lemma Indep.insert_indep_iff (hI : M.Indep I) :
M.Indep (insert e I) ↔ e ∈ M.E \ M.closure I ∨ e ∈ I := by
obtain (h | h) := em (e ∈ I)
· simp_rw [insert_eq_of_mem h, iff_true_intro hI, true_iff, iff_true_intro h, or_true]
rw [hI.insert_indep_iff_of_not_mem h, or_iff_left h]
lemma insert_indep_iff : M.Indep (insert e I) ↔ M.Indep I ∧ (e ∉ I → e ∈ M.E \ M.closure I) := by
by_cases hI : M.Indep I
· rw [hI.insert_indep_iff, and_iff_right hI, or_iff_not_imp_right]
simp [hI, show ¬ M.Indep (insert e I) from fun h ↦ hI <| h.subset <| subset_insert _ _]
/-- This can be used for rewriting if the LHS is inside a binder and whether `f = e` is unknown.-/
lemma Indep.insert_diff_indep_iff (hI : M.Indep (I \ {e})) (heI : e ∈ I) :
M.Indep (insert f I \ {e}) ↔ f ∈ M.E \ M.closure (I \ {e}) ∨ f ∈ I := by
obtain rfl | hne := eq_or_ne e f
· simp [hI, heI]
rw [← insert_diff_singleton_comm hne.symm, hI.insert_indep_iff, mem_diff_singleton,
and_iff_left hne.symm]
lemma Indep.basis_of_subset_of_subset_closure (hI : M.Indep I) (hIX : I ⊆ X)
(hXI : X ⊆ M.closure I) : M.Basis I X :=
hI.basis_closure.basis_subset hIX hXI
lemma basis_iff_indep_subset_closure : M.Basis I X ↔ M.Indep I ∧ I ⊆ X ∧ X ⊆ M.closure I :=
⟨fun h ↦ ⟨h.indep, h.subset, h.subset_closure⟩,
fun h ↦ h.1.basis_of_subset_of_subset_closure h.2.1 h.2.2⟩
lemma Indep.base_of_ground_subset_closure (hI : M.Indep I) (h : M.E ⊆ M.closure I) : M.Base I := by
rw [← basis_ground_iff]; exact hI.basis_of_subset_of_subset_closure hI.subset_ground h
lemma Base.closure_eq (hB : M.Base B) : M.closure B = M.E := by
rw [← basis_ground_iff] at hB; rw [hB.closure_eq_closure, closure_ground]
lemma Base.closure_of_superset (hB : M.Base B) (hBX : B ⊆ X) : M.closure X = M.E :=
(M.closure_subset_ground _).antisymm (hB.closure_eq ▸ M.closure_subset_closure hBX)
lemma base_iff_indep_closure_eq : M.Base B ↔ M.Indep B ∧ M.closure B = M.E := by
rw [← basis_ground_iff, basis_iff_indep_subset_closure, and_congr_right_iff]
exact fun hI ↦ ⟨fun h ↦ (M.closure_subset_ground _).antisymm h.2,
fun h ↦ ⟨(M.subset_closure B).trans_eq h, h.symm.subset⟩⟩
lemma Indep.base_iff_ground_subset_closure (hI : M.Indep I) : M.Base I ↔ M.E ⊆ M.closure I :=
⟨fun h ↦ h.closure_eq.symm.subset, hI.base_of_ground_subset_closure⟩
lemma Indep.closure_inter_eq_self_of_subset (hI : M.Indep I) (hJI : J ⊆ I) :
M.closure J ∩ I = J := by
have hJ := hI.subset hJI
rw [subset_antisymm_iff, and_iff_left (subset_inter (M.subset_closure _) hJI)]
rintro e ⟨heJ, heI⟩
exact hJ.basis_closure.mem_of_insert_indep heJ (hI.subset (insert_subset heI hJI))
/-- For a nonempty collection of subsets of a given independent set,
the closure of the intersection is the intersection of the closure. -/
lemma Indep.closure_sInter_eq_biInter_closure_of_forall_subset {Js : Set (Set α)} (hI : M.Indep I)
(hne : Js.Nonempty) (hIs : ∀ J ∈ Js, J ⊆ I) : M.closure (⋂₀ Js) = (⋂ J ∈ Js, M.closure J) := by
rw [subset_antisymm_iff, subset_iInter₂_iff]
have hiX : ⋂₀ Js ⊆ I := (sInter_subset_of_mem hne.some_mem).trans (hIs _ hne.some_mem)
have hiI := hI.subset hiX
refine ⟨ fun X hX ↦ M.closure_subset_closure (sInter_subset_of_mem hX),
fun e he ↦ by_contra fun he' ↦ ?_⟩
rw [mem_iInter₂] at he
have heEI : e ∈ M.E \ I := by
refine ⟨M.closure_subset_ground _ (he _ hne.some_mem), fun heI ↦ he' ?_⟩
refine mem_closure_of_mem _ (fun X hX' ↦ ?_) hiI.subset_ground
rw [← hI.closure_inter_eq_self_of_subset (hIs X hX')]
exact ⟨he X hX', heI⟩
rw [hiI.not_mem_closure_iff_of_not_mem (not_mem_subset hiX heEI.2)] at he'
obtain ⟨J, hJI, heJ⟩ := he'.subset_basis_of_subset (insert_subset_insert hiX)
(insert_subset heEI.1 hI.subset_ground)
have hIb : M.Basis I (insert e I) := by
rw [hI.insert_basis_iff_mem_closure]
exact (M.closure_subset_closure (hIs _ hne.some_mem)) (he _ hne.some_mem)
obtain ⟨f, hfIJ, hfb⟩ := hJI.exchange hIb ⟨heJ (mem_insert e _), heEI.2⟩
obtain rfl := hI.eq_of_basis (hfb.basis_subset (insert_subset hfIJ.1
(by (rw [diff_subset_iff, singleton_union]; exact hJI.subset))) (subset_insert _ _))
refine hfIJ.2 (heJ (mem_insert_of_mem _ fun X hX' ↦ by_contra fun hfX ↦ ?_))
obtain (hd | heX) := ((hI.subset (hIs X hX')).mem_closure_iff).mp (he _ hX')
· refine (hJI.indep.subset (insert_subset (heJ (mem_insert _ _)) ?_)).not_dep hd
specialize hIs _ hX'
rw [← singleton_union, ← diff_subset_iff, diff_singleton_eq_self hfX] at hIs
exact hIs.trans diff_subset
exact heEI.2 (hIs _ hX' heX)
lemma closure_iInter_eq_iInter_closure_of_iUnion_indep [hι : Nonempty ι] (Is : ι → Set α)
(h : M.Indep (⋃ i, Is i)) : M.closure (⋂ i, Is i) = (⋂ i, M.closure (Is i)) := by
convert h.closure_sInter_eq_biInter_closure_of_forall_subset (range_nonempty Is)
(by simp [subset_iUnion])
simp
lemma closure_sInter_eq_biInter_closure_of_sUnion_indep (Is : Set (Set α)) (hIs : Is.Nonempty)
(h : M.Indep (⋃₀ Is)) : M.closure (⋂₀ Is) = (⋂ I ∈ Is, M.closure I) :=
h.closure_sInter_eq_biInter_closure_of_forall_subset hIs (fun _ ↦ subset_sUnion_of_mem)
lemma closure_biInter_eq_biInter_closure_of_biUnion_indep {ι : Type*} {A : Set ι} (hA : A.Nonempty)
{I : ι → Set α} (h : M.Indep (⋃ i ∈ A, I i)) :
M.closure (⋂ i ∈ A, I i) = ⋂ i ∈ A, M.closure (I i) := by
have := hA.coe_sort
convert closure_iInter_eq_iInter_closure_of_iUnion_indep (Is := fun i : A ↦ I i) (by simpa) <;>
simp
lemma Indep.closure_iInter_eq_biInter_closure_of_forall_subset [hι : Nonempty ι] {Js : ι → Set α}
(hI : M.Indep I) (hJs : ∀ i, Js i ⊆ I) : M.closure (⋂ i, Js i) = ⋂ i, M.closure (Js i) :=
closure_iInter_eq_iInter_closure_of_iUnion_indep _ (hI.subset <| by simpa)
lemma Indep.closure_inter_eq_inter_closure (h : M.Indep (I ∪ J)) :
M.closure (I ∩ J) = M.closure I ∩ M.closure J := by
rw [inter_eq_iInter, closure_iInter_eq_iInter_closure_of_iUnion_indep, inter_eq_iInter]
· exact iInter_congr (by simp)
rwa [← union_eq_iUnion]
lemma basis_iff_basis_closure_of_subset (hIX : I ⊆ X) (hX : X ⊆ M.E := by aesop_mat) :
M.Basis I X ↔ M.Basis I (M.closure X) :=
⟨fun h ↦ h.basis_closure_right, fun h ↦ h.basis_subset hIX (M.subset_closure X hX)⟩
lemma basis_iff_basis_closure_of_subset' (hIX : I ⊆ X) :
M.Basis I X ↔ M.Basis I (M.closure X) ∧ X ⊆ M.E :=
⟨fun h ↦ ⟨h.basis_closure_right, h.subset_ground⟩,
fun h ↦ h.1.basis_subset hIX (M.subset_closure X h.2)⟩
lemma basis'_iff_basis_closure : M.Basis' I X ↔ M.Basis I (M.closure X) ∧ I ⊆ X := by
rw [← closure_inter_ground, basis'_iff_basis_inter_ground]
exact ⟨fun h ↦ ⟨h.basis_closure_right, h.subset.trans inter_subset_left⟩,
fun h ↦ h.1.basis_subset (subset_inter h.2 h.1.indep.subset_ground) (M.subset_closure _)⟩
lemma exists_basis_inter_ground_basis_closure (M : Matroid α) (X : Set α) :
∃ I, M.Basis I (X ∩ M.E) ∧ M.Basis I (M.closure X) := by
obtain ⟨I, hI⟩ := M.exists_basis (X ∩ M.E)
have hI' := hI.basis_closure_right; rw [closure_inter_ground] at hI'
exact ⟨_, hI, hI'⟩
lemma Basis.basis_of_closure_eq_closure (hI : M.Basis I X) (hY : I ⊆ Y)
(h : M.closure X = M.closure Y) (hYE : Y ⊆ M.E := by aesop_mat) : M.Basis I Y := by
refine hI.indep.basis_of_subset_of_subset_closure hY ?_
rw [hI.closure_eq_closure, h]
exact M.subset_closure Y
lemma basis_union_iff_indep_closure : M.Basis I (I ∪ X) ↔ M.Indep I ∧ X ⊆ M.closure I :=
⟨fun h ↦ ⟨h.indep, subset_union_right.trans h.subset_closure⟩, fun ⟨hI, hXI⟩ ↦
hI.basis_closure.basis_subset subset_union_left (union_subset (M.subset_closure I) hXI)⟩
lemma basis_iff_indep_closure : M.Basis I X ↔ M.Indep I ∧ X ⊆ M.closure I ∧ I ⊆ X :=
⟨fun h ↦ ⟨h.indep, h.subset_closure, h.subset⟩, fun h ↦
(basis_union_iff_indep_closure.mpr ⟨h.1, h.2.1⟩).basis_subset h.2.2 subset_union_right⟩
lemma Basis.eq_of_closure_subset (hI : M.Basis I X) (hJI : J ⊆ I) (hJ : X ⊆ M.closure J) :
J = I := by
rw [← hI.indep.closure_inter_eq_self_of_subset hJI, inter_eq_self_of_subset_right]
exact hI.subset.trans hJ
@[simp] lemma empty_basis_iff : M.Basis ∅ X ↔ X ⊆ M.closure ∅ := by
rw [basis_iff_indep_closure, and_iff_right M.empty_indep, and_iff_left (empty_subset _)]
end Indep
end Matroid
|
Data\Matroid\Constructions.lean | /-
Copyright (c) 2024 Peter Nelson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Peter Nelson
-/
import Mathlib.Data.Matroid.Restrict
/-!
# Some constructions of matroids
This file defines some very elementary examples of matroids, namely those with at most one base.
## Main definitions
* `emptyOn α` is the matroid on `α` with empty ground set.
For `E : Set α`, ...
* `loopyOn E` is the matroid on `E` whose elements are all loops, or equivalently in which `∅`
is the only base.
* `freeOn E` is the 'free matroid' whose ground set `E` is the only base.
* For `I ⊆ E`, `uniqueBaseOn I E` is the matroid with ground set `E` in which `I` is the only base.
## Implementation details
To avoid the tedious process of certifying the matroid axioms for each of these easy examples,
we bootstrap the definitions starting with `emptyOn α` (which `simp` can prove is a matroid)
and then construct the other examples using duality and restriction.
-/
variable {α : Type*} {M : Matroid α} {E B I X R J : Set α}
namespace Matroid
open Set
section EmptyOn
/-- The `Matroid α` with empty ground set. -/
def emptyOn (α : Type*) : Matroid α where
E := ∅
Base := (· = ∅)
Indep := (· = ∅)
indep_iff' := by simp [subset_empty_iff]
exists_base := ⟨∅, rfl⟩
base_exchange := by rintro _ _ rfl; simp
maximality := by rintro _ _ _ rfl -; exact ⟨∅, by simp [Maximal]⟩
subset_ground := by simp
@[simp] theorem emptyOn_ground : (emptyOn α).E = ∅ := rfl
@[simp] theorem emptyOn_base_iff : (emptyOn α).Base B ↔ B = ∅ := Iff.rfl
@[simp] theorem emptyOn_indep_iff : (emptyOn α).Indep I ↔ I = ∅ := Iff.rfl
theorem ground_eq_empty_iff : (M.E = ∅) ↔ M = emptyOn α := by
simp only [emptyOn, eq_iff_indep_iff_indep_forall, iff_self_and]
exact fun h ↦ by simp [h, subset_empty_iff]
@[simp] theorem emptyOn_dual_eq : (emptyOn α)✶ = emptyOn α := by
rw [← ground_eq_empty_iff]; rfl
@[simp] theorem restrict_empty (M : Matroid α) : M ↾ (∅ : Set α) = emptyOn α := by
simp [← ground_eq_empty_iff]
theorem eq_emptyOn_or_nonempty (M : Matroid α) : M = emptyOn α ∨ Matroid.Nonempty M := by
rw [← ground_eq_empty_iff]
exact M.E.eq_empty_or_nonempty.elim Or.inl (fun h ↦ Or.inr ⟨h⟩)
theorem eq_emptyOn [IsEmpty α] (M : Matroid α) : M = emptyOn α := by
rw [← ground_eq_empty_iff]
exact M.E.eq_empty_of_isEmpty
instance finite_emptyOn (α : Type*) : (emptyOn α).Finite :=
⟨finite_empty⟩
end EmptyOn
section LoopyOn
/-- The `Matroid α` with ground set `E` whose only base is `∅` -/
def loopyOn (E : Set α) : Matroid α := emptyOn α ↾ E
@[simp] theorem loopyOn_ground (E : Set α) : (loopyOn E).E = E := rfl
@[simp] theorem loopyOn_empty (α : Type*) : loopyOn (∅ : Set α) = emptyOn α := by
rw [← ground_eq_empty_iff, loopyOn_ground]
@[simp] theorem loopyOn_indep_iff : (loopyOn E).Indep I ↔ I = ∅ := by
simp only [loopyOn, restrict_indep_iff, emptyOn_indep_iff, and_iff_left_iff_imp]
rintro rfl; apply empty_subset
theorem eq_loopyOn_iff : M = loopyOn E ↔ M.E = E ∧ ∀ X ⊆ M.E, M.Indep X → X = ∅ := by
simp only [eq_iff_indep_iff_indep_forall, loopyOn_ground, loopyOn_indep_iff, and_congr_right_iff]
rintro rfl
refine ⟨fun h I hI ↦ (h I hI).1, fun h I hIE ↦ ⟨h I hIE, by rintro rfl; simp⟩⟩
@[simp] theorem loopyOn_base_iff : (loopyOn E).Base B ↔ B = ∅ := by
simp [Maximal, base_iff_maximal_indep]
@[simp] theorem loopyOn_basis_iff : (loopyOn E).Basis I X ↔ I = ∅ ∧ X ⊆ E :=
⟨fun h ↦ ⟨loopyOn_indep_iff.mp h.indep, h.subset_ground⟩,
by rintro ⟨rfl, hX⟩; rw [basis_iff]; simp⟩
instance : FiniteRk (loopyOn E) :=
⟨⟨∅, loopyOn_base_iff.2 rfl, finite_empty⟩⟩
theorem Finite.loopyOn_finite (hE : E.Finite) : Matroid.Finite (loopyOn E) :=
⟨hE⟩
@[simp] theorem loopyOn_restrict (E R : Set α) : (loopyOn E) ↾ R = loopyOn R := by
refine eq_of_indep_iff_indep_forall rfl ?_
simp only [restrict_ground_eq, restrict_indep_iff, loopyOn_indep_iff, and_iff_left_iff_imp]
exact fun _ h _ ↦ h
theorem empty_base_iff : M.Base ∅ ↔ M = loopyOn M.E := by
simp only [base_iff_maximal_indep, Maximal, empty_indep, le_eq_subset, empty_subset,
subset_empty_iff, true_implies, true_and, eq_iff_indep_iff_indep_forall, loopyOn_ground,
loopyOn_indep_iff]
exact ⟨fun h I _ ↦ ⟨@h _, fun hI ↦ by simp [hI]⟩, fun h I hI ↦ (h I hI.subset_ground).1 hI⟩
theorem eq_loopyOn_or_rkPos (M : Matroid α) : M = loopyOn M.E ∨ RkPos M := by
rw [← empty_base_iff, rkPos_iff_empty_not_base]; apply em
theorem not_rkPos_iff : ¬RkPos M ↔ M = loopyOn M.E := by
rw [rkPos_iff_empty_not_base, not_iff_comm, empty_base_iff]
end LoopyOn
section FreeOn
/-- The `Matroid α` with ground set `E` whose only base is `E`. -/
def freeOn (E : Set α) : Matroid α := (loopyOn E)✶
@[simp] theorem freeOn_ground : (freeOn E).E = E := rfl
@[simp] theorem freeOn_dual_eq : (freeOn E)✶ = loopyOn E := by
rw [freeOn, dual_dual]
@[simp] theorem loopyOn_dual_eq : (loopyOn E)✶ = freeOn E := rfl
@[simp] theorem freeOn_empty (α : Type*) : freeOn (∅ : Set α) = emptyOn α := by
simp [freeOn]
@[simp] theorem freeOn_base_iff : (freeOn E).Base B ↔ B = E := by
simp only [freeOn, loopyOn_ground, dual_base_iff', loopyOn_base_iff, diff_eq_empty,
← subset_antisymm_iff, eq_comm (a := E)]
@[simp] theorem freeOn_indep_iff : (freeOn E).Indep I ↔ I ⊆ E := by
simp [indep_iff]
theorem freeOn_indep (hIE : I ⊆ E) : (freeOn E).Indep I :=
freeOn_indep_iff.2 hIE
@[simp] theorem freeOn_basis_iff : (freeOn E).Basis I X ↔ I = X ∧ X ⊆ E := by
use fun h ↦ ⟨(freeOn_indep h.subset_ground).eq_of_basis h ,h.subset_ground⟩
rintro ⟨rfl, hIE⟩
exact (freeOn_indep hIE).basis_self
@[simp] theorem freeOn_basis'_iff : (freeOn E).Basis' I X ↔ I = X ∩ E := by
rw [basis'_iff_basis_inter_ground, freeOn_basis_iff, freeOn_ground,
and_iff_left inter_subset_right]
theorem eq_freeOn_iff : M = freeOn E ↔ M.E = E ∧ M.Indep E := by
refine ⟨?_, fun h ↦ ?_⟩
· rintro rfl; simp [Subset.rfl]
simp only [eq_iff_indep_iff_indep_forall, freeOn_ground, freeOn_indep_iff, h.1, true_and]
exact fun I hIX ↦ iff_of_true (h.2.subset hIX) hIX
theorem ground_indep_iff_eq_freeOn : M.Indep M.E ↔ M = freeOn M.E := by
simp [eq_freeOn_iff]
theorem freeOn_restrict (h : R ⊆ E) : (freeOn E) ↾ R = freeOn R := by
simp [h, eq_freeOn_iff, Subset.rfl]
theorem restrict_eq_freeOn_iff : M ↾ I = freeOn I ↔ M.Indep I := by
rw [eq_freeOn_iff, and_iff_right M.restrict_ground_eq, restrict_indep_iff,
and_iff_left Subset.rfl]
theorem Indep.restrict_eq_freeOn (hI : M.Indep I) : M ↾ I = freeOn I := by
rwa [restrict_eq_freeOn_iff]
end FreeOn
section uniqueBaseOn
/-- The matroid on `E` whose unique base is the subset `I` of `E`.
Intended for use when `I ⊆ E`; if this not not the case, then the base is `I ∩ E`. -/
def uniqueBaseOn (I E : Set α) : Matroid α := freeOn I ↾ E
@[simp] theorem uniqueBaseOn_ground : (uniqueBaseOn I E).E = E :=
rfl
theorem uniqueBaseOn_base_iff (hIE : I ⊆ E) : (uniqueBaseOn I E).Base B ↔ B = I := by
rw [uniqueBaseOn, base_restrict_iff', freeOn_basis'_iff, inter_eq_self_of_subset_right hIE]
theorem uniqueBaseOn_inter_ground_eq (I E : Set α) :
uniqueBaseOn (I ∩ E) E = uniqueBaseOn I E := by
simp only [uniqueBaseOn, restrict_eq_restrict_iff, freeOn_indep_iff, subset_inter_iff,
iff_self_and]
tauto
@[simp] theorem uniqueBaseOn_indep_iff' : (uniqueBaseOn I E).Indep J ↔ J ⊆ I ∩ E := by
rw [uniqueBaseOn, restrict_indep_iff, freeOn_indep_iff, subset_inter_iff]
theorem uniqueBaseOn_indep_iff (hIE : I ⊆ E) : (uniqueBaseOn I E).Indep J ↔ J ⊆ I := by
rw [uniqueBaseOn, restrict_indep_iff, freeOn_indep_iff, and_iff_left_iff_imp]
exact fun h ↦ h.trans hIE
theorem uniqueBaseOn_basis_iff (hX : X ⊆ E) : (uniqueBaseOn I E).Basis J X ↔ J = X ∩ I := by
rw [basis_iff_maximal]
exact maximal_iff_eq (by simp [inter_subset_left.trans hX])
(by simp (config := {contextual := true}))
theorem uniqueBaseOn_inter_basis (hX : X ⊆ E) : (uniqueBaseOn I E).Basis (X ∩ I) X := by
rw [uniqueBaseOn_basis_iff hX]
@[simp] theorem uniqueBaseOn_dual_eq (I E : Set α) :
(uniqueBaseOn I E)✶ = uniqueBaseOn (E \ I) E := by
rw [← uniqueBaseOn_inter_ground_eq]
refine eq_of_base_iff_base_forall rfl (fun B (hB : B ⊆ E) ↦ ?_)
rw [dual_base_iff, uniqueBaseOn_base_iff inter_subset_right, uniqueBaseOn_base_iff diff_subset,
uniqueBaseOn_ground]
exact ⟨fun h ↦ by rw [← diff_diff_cancel_left hB, h, diff_inter_self_eq_diff],
fun h ↦ by rw [h, inter_comm I]; simp⟩
@[simp] theorem uniqueBaseOn_self (I : Set α) : uniqueBaseOn I I = freeOn I := by
rw [uniqueBaseOn, freeOn_restrict rfl.subset]
@[simp] theorem uniqueBaseOn_empty (I : Set α) : uniqueBaseOn ∅ I = loopyOn I := by
rw [← dual_inj, uniqueBaseOn_dual_eq, diff_empty, uniqueBaseOn_self, loopyOn_dual_eq]
theorem uniqueBaseOn_restrict' (I E R : Set α) :
(uniqueBaseOn I E) ↾ R = uniqueBaseOn (I ∩ R ∩ E) R := by
simp_rw [eq_iff_indep_iff_indep_forall, restrict_ground_eq, uniqueBaseOn_ground, true_and,
restrict_indep_iff, uniqueBaseOn_indep_iff', subset_inter_iff]
tauto
theorem uniqueBaseOn_restrict (h : I ⊆ E) (R : Set α) :
(uniqueBaseOn I E) ↾ R = uniqueBaseOn (I ∩ R) R := by
rw [uniqueBaseOn_restrict', inter_right_comm, inter_eq_self_of_subset_left h]
end uniqueBaseOn
end Matroid
|
Data\Matroid\Dual.lean | /-
Copyright (c) 2023 Peter Nelson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Peter Nelson
-/
import Mathlib.Data.Matroid.IndepAxioms
/-!
# Matroid Duality
For a matroid `M` on ground set `E`, the collection of complements of the bases of `M` is the
collection of bases of another matroid on `E` called the 'dual' of `M`.
The map from `M` to its dual is an involution, interacts nicely with minors,
and preserves many important matroid properties such as representability and connectivity.
This file defines the dual matroid `M✶` of `M`, and gives associated API. The definition
is in terms of its independent sets, using `IndepMatroid.matroid`.
We also define 'Co-independence' (independence in the dual) of a set as a predicate `M.Coindep X`.
This is an abbreviation for `M✶.Indep X`, but has its own name for the sake of dot notation.
## Main Definitions
* `M.Dual`, written `M✶`, is the matroid in which a set `B` is a base if and only if `B ⊆ M.E`
and `M.E \ B` is a base for `M`.
* `M.Coindep X` means `M✶.Indep X`, or equivalently that `X` is contained in `M.E \ B` for some
base `B` of `M`.
-/
open Set
namespace Matroid
variable {α : Type*} {M : Matroid α} {I B X : Set α}
section dual
/-- Given `M : Matroid α`, the `IndepMatroid α` whose independent sets are
the subsets of `M.E` that are disjoint from some base of `M` -/
@[simps] def dualIndepMatroid (M : Matroid α) : IndepMatroid α where
E := M.E
Indep I := I ⊆ M.E ∧ ∃ B, M.Base B ∧ Disjoint I B
indep_empty := ⟨empty_subset M.E, M.exists_base.imp (fun B hB ↦ ⟨hB, empty_disjoint _⟩)⟩
indep_subset := by
rintro I J ⟨hJE, B, hB, hJB⟩ hIJ
exact ⟨hIJ.trans hJE, ⟨B, hB, disjoint_of_subset_left hIJ hJB⟩⟩
indep_aug := by
rintro I X ⟨hIE, B, hB, hIB⟩ hI_not_max hX_max
have hXE := hX_max.1.1
have hB' := (base_compl_iff_maximal_disjoint_base hXE).mpr hX_max
set B' := M.E \ X with hX
have hI := (not_iff_not.mpr (base_compl_iff_maximal_disjoint_base)).mpr hI_not_max
obtain ⟨B'', hB'', hB''₁, hB''₂⟩ := (hB'.indep.diff I).exists_base_subset_union_base hB
rw [← compl_subset_compl, ← hIB.sdiff_eq_right, ← union_diff_distrib, diff_eq, compl_inter,
compl_compl, union_subset_iff, compl_subset_compl] at hB''₂
have hssu := (subset_inter (hB''₂.2) hIE).ssubset_of_ne
(by { rintro rfl; apply hI; convert hB''; simp [hB''.subset_ground] })
obtain ⟨e, ⟨(heB'' : e ∉ _), heE⟩, heI⟩ := exists_of_ssubset hssu
use e
simp_rw [mem_diff, insert_subset_iff, and_iff_left heI, and_iff_right heE, and_iff_right hIE]
refine ⟨by_contra (fun heX ↦ heB'' (hB''₁ ⟨?_, heI⟩)), ⟨B'', hB'', ?_⟩⟩
· rw [hX]; exact ⟨heE, heX⟩
rw [← union_singleton, disjoint_union_left, disjoint_singleton_left, and_iff_left heB'']
exact disjoint_of_subset_left hB''₂.2 disjoint_compl_left
indep_maximal := by
rintro X - I' ⟨hI'E, B, hB, hI'B⟩ hI'X
obtain ⟨I, hI⟩ := M.exists_basis (M.E \ X)
obtain ⟨B', hB', hIB', hB'IB⟩ := hI.indep.exists_base_subset_union_base hB
obtain rfl : I = B' \ X := hI.eq_of_subset_indep (hB'.indep.diff _)
(subset_diff.2 ⟨hIB', (subset_diff.1 hI.subset).2⟩)
(diff_subset_diff_left hB'.subset_ground)
simp_rw [maximal_subset_iff']
refine ⟨(X \ B') ∩ M.E, ?_, ⟨⟨inter_subset_right, ?_⟩, ?_⟩, ?_⟩
· rw [subset_inter_iff, and_iff_left hI'E, subset_diff, and_iff_right hI'X]
exact Disjoint.mono_right hB'IB <| disjoint_union_right.2
⟨disjoint_sdiff_right.mono_left hI'X , hI'B⟩
· exact ⟨B', hB', (disjoint_sdiff_left (t := X)).mono_left inter_subset_left⟩
· exact inter_subset_left.trans diff_subset
simp only [subset_inter_iff, subset_diff, and_imp, forall_exists_index]
refine fun J hJE B'' hB'' hdj hJX hXJ ↦ ⟨⟨hJX, ?_⟩, hJE⟩
have hI' : (B'' ∩ X) ∪ (B' \ X) ⊆ B' := by
rw [union_subset_iff, and_iff_left diff_subset, ← union_diff_cancel hJX,
inter_union_distrib_left, hdj.symm.inter_eq, empty_union, diff_eq, ← inter_assoc,
← diff_eq, diff_subset_comm, diff_eq, inter_assoc, ← diff_eq, inter_comm]
exact subset_trans (inter_subset_inter_right _ hB''.subset_ground) hXJ
obtain ⟨B₁,hB₁,hI'B₁,hB₁I⟩ := (hB'.indep.subset hI').exists_base_subset_union_base hB''
rw [union_comm, ← union_assoc, union_eq_self_of_subset_right inter_subset_left] at hB₁I
obtain rfl : B₁ = B' := by
refine hB₁.eq_of_subset_indep hB'.indep (fun e he ↦ ?_)
refine (hB₁I he).elim (fun heB'' ↦ ?_) (fun h ↦ h.1)
refine (em (e ∈ X)).elim (fun heX ↦ hI' (Or.inl ⟨heB'', heX⟩)) (fun heX ↦ hIB' ?_)
refine hI.mem_of_insert_indep ⟨hB₁.subset_ground he, heX⟩ ?_
exact hB₁.indep.subset (insert_subset he (subset_union_right.trans hI'B₁))
by_contra hdj'
obtain ⟨e, heJ, heB'⟩ := not_disjoint_iff.mp hdj'
obtain (heB'' | ⟨-,heX⟩ ) := hB₁I heB'
· exact hdj.ne_of_mem heJ heB'' rfl
exact heX (hJX heJ)
subset_ground := by tauto
/-- The dual of a matroid; the bases are the complements (w.r.t `M.E`) of the bases of `M`. -/
def dual (M : Matroid α) : Matroid α := M.dualIndepMatroid.matroid
/-- The `✶` symbol, which denotes matroid duality.
(This is distinct from the usual `*` symbol for multiplication, due to precedence issues. )-/
postfix:max "✶" => Matroid.dual
theorem dual_indep_iff_exists' : (M✶.Indep I) ↔ I ⊆ M.E ∧ (∃ B, M.Base B ∧ Disjoint I B) := Iff.rfl
@[simp] theorem dual_ground : M✶.E = M.E := rfl
@[simp] theorem dual_indep_iff_exists (hI : I ⊆ M.E := by aesop_mat) :
M✶.Indep I ↔ (∃ B, M.Base B ∧ Disjoint I B) := by
rw [dual_indep_iff_exists', and_iff_right hI]
theorem dual_dep_iff_forall : (M✶.Dep I) ↔ (∀ B, M.Base B → (I ∩ B).Nonempty) ∧ I ⊆ M.E := by
simp_rw [dep_iff, dual_indep_iff_exists', dual_ground, and_congr_left_iff, not_and,
not_exists, not_and, not_disjoint_iff_nonempty_inter, Classical.imp_iff_right_iff,
iff_true_intro Or.inl]
instance dual_finite [M.Finite] : M✶.Finite :=
⟨M.ground_finite⟩
instance dual_nonempty [M.Nonempty] : M✶.Nonempty :=
⟨M.ground_nonempty⟩
@[simp] theorem dual_base_iff (hB : B ⊆ M.E := by aesop_mat) : M✶.Base B ↔ M.Base (M.E \ B) := by
rw [base_compl_iff_maximal_disjoint_base, base_iff_maximal_indep, maximal_subset_iff,
maximal_subset_iff]
simp [dual_indep_iff_exists', hB]
theorem dual_base_iff' : M✶.Base B ↔ M.Base (M.E \ B) ∧ B ⊆ M.E :=
(em (B ⊆ M.E)).elim (fun h ↦ by rw [dual_base_iff, and_iff_left h])
(fun h ↦ iff_of_false (h ∘ (fun h' ↦ h'.subset_ground)) (h ∘ And.right))
theorem setOf_dual_base_eq : {B | M✶.Base B} = (fun X ↦ M.E \ X) '' {B | M.Base B} := by
ext B
simp only [mem_setOf_eq, mem_image, dual_base_iff']
refine ⟨fun h ↦ ⟨_, h.1, diff_diff_cancel_left h.2⟩,
fun ⟨B', hB', h⟩ ↦ ⟨?_,h.symm.trans_subset diff_subset⟩⟩
rwa [← h, diff_diff_cancel_left hB'.subset_ground]
@[simp] theorem dual_dual (M : Matroid α) : M✶✶ = M :=
eq_of_base_iff_base_forall rfl (fun B (h : B ⊆ M.E) ↦
by rw [dual_base_iff, dual_base_iff, dual_ground, diff_diff_cancel_left h])
theorem dual_involutive : Function.Involutive (dual : Matroid α → Matroid α) := dual_dual
theorem dual_injective : Function.Injective (dual : Matroid α → Matroid α) :=
dual_involutive.injective
@[simp] theorem dual_inj {M₁ M₂ : Matroid α} : M₁✶ = M₂✶ ↔ M₁ = M₂ :=
dual_injective.eq_iff
theorem eq_dual_comm {M₁ M₂ : Matroid α} : M₁ = M₂✶ ↔ M₂ = M₁✶ := by
rw [← dual_inj, dual_dual, eq_comm]
theorem eq_dual_iff_dual_eq {M₁ M₂ : Matroid α} : M₁ = M₂✶ ↔ M₁✶ = M₂ :=
dual_involutive.eq_iff.symm
theorem Base.compl_base_of_dual (h : M✶.Base B) : M.Base (M.E \ B) :=
(dual_base_iff'.1 h).1
theorem Base.compl_base_dual (h : M.Base B) : M✶.Base (M.E \ B) := by
rwa [dual_base_iff, diff_diff_cancel_left h.subset_ground]
theorem Base.compl_inter_basis_of_inter_basis (hB : M.Base B) (hBX : M.Basis (B ∩ X) X) :
M✶.Basis ((M.E \ B) ∩ (M.E \ X)) (M.E \ X) := by
refine Indep.basis_of_forall_insert ?_ inter_subset_right (fun e he ↦ ?_)
· rw [dual_indep_iff_exists]
exact ⟨B, hB, disjoint_of_subset_left inter_subset_left disjoint_sdiff_left⟩
simp only [diff_inter_self_eq_diff, mem_diff, not_and, not_not, imp_iff_right he.1.1] at he
simp_rw [dual_dep_iff_forall, insert_subset_iff, and_iff_right he.1.1,
and_iff_left (inter_subset_left.trans diff_subset)]
refine fun B' hB' ↦ by_contra (fun hem ↦ ?_)
rw [nonempty_iff_ne_empty, not_ne_iff, ← union_singleton, diff_inter_diff,
union_inter_distrib_right, union_empty_iff, singleton_inter_eq_empty, diff_eq,
inter_right_comm, inter_eq_self_of_subset_right hB'.subset_ground, ← diff_eq,
diff_eq_empty] at hem
obtain ⟨f, hfb, hBf⟩ := hB.exchange hB' ⟨he.2, hem.2⟩
have hi : M.Indep (insert f (B ∩ X)) := by
refine hBf.indep.subset (insert_subset_insert ?_)
simp_rw [subset_diff, and_iff_right inter_subset_left, disjoint_singleton_right,
mem_inter_iff, iff_false_intro he.1.2, and_false, not_false_iff]
exact hfb.2 (hBX.mem_of_insert_indep (Or.elim (hem.1 hfb.1) (False.elim ∘ hfb.2) id) hi).1
theorem Base.inter_basis_iff_compl_inter_basis_dual (hB : M.Base B) (hX : X ⊆ M.E := by aesop_mat) :
M.Basis (B ∩ X) X ↔ M✶.Basis ((M.E \ B) ∩ (M.E \ X)) (M.E \ X) := by
refine ⟨hB.compl_inter_basis_of_inter_basis, fun h ↦ ?_⟩
simpa [inter_eq_self_of_subset_right hX, inter_eq_self_of_subset_right hB.subset_ground] using
hB.compl_base_dual.compl_inter_basis_of_inter_basis h
theorem base_iff_dual_base_compl (hB : B ⊆ M.E := by aesop_mat) :
M.Base B ↔ M✶.Base (M.E \ B) := by
rw [dual_base_iff, diff_diff_cancel_left hB]
theorem ground_not_base (M : Matroid α) [h : RkPos M✶] : ¬M.Base M.E := by
rwa [rkPos_iff_empty_not_base, dual_base_iff, diff_empty] at h
theorem Base.ssubset_ground [h : RkPos M✶] (hB : M.Base B) : B ⊂ M.E :=
hB.subset_ground.ssubset_of_ne (by rintro rfl; exact M.ground_not_base hB)
theorem Indep.ssubset_ground [h : RkPos M✶] (hI : M.Indep I) : I ⊂ M.E := by
obtain ⟨B, hB⟩ := hI.exists_base_superset; exact hB.2.trans_ssubset hB.1.ssubset_ground
/-- A coindependent set of `M` is an independent set of the dual of `M✶`. we give it a separate
definition to enable dot notation. Which spelling is better depends on context. -/
abbrev Coindep (M : Matroid α) (I : Set α) : Prop := M✶.Indep I
theorem coindep_def : M.Coindep X ↔ M✶.Indep X := Iff.rfl
theorem Coindep.indep (hX : M.Coindep X) : M✶.Indep X :=
hX
@[simp] theorem dual_coindep_iff : M✶.Coindep X ↔ M.Indep X := by
rw [Coindep, dual_dual]
theorem Indep.coindep (hI : M.Indep I) : M✶.Coindep I :=
dual_coindep_iff.2 hI
theorem coindep_iff_exists' : M.Coindep X ↔ (∃ B, M.Base B ∧ B ⊆ M.E \ X) ∧ X ⊆ M.E := by
simp_rw [Coindep, dual_indep_iff_exists', and_comm (a := _ ⊆ _), and_congr_left_iff, subset_diff]
exact fun _ ↦ ⟨fun ⟨B, hB, hXB⟩ ↦ ⟨B, hB, hB.subset_ground, hXB.symm⟩,
fun ⟨B, hB, _, hBX⟩ ↦ ⟨B, hB, hBX.symm⟩⟩
theorem coindep_iff_exists (hX : X ⊆ M.E := by aesop_mat) :
M.Coindep X ↔ ∃ B, M.Base B ∧ B ⊆ M.E \ X := by
rw [coindep_iff_exists', and_iff_left hX]
theorem coindep_iff_subset_compl_base : M.Coindep X ↔ ∃ B, M.Base B ∧ X ⊆ M.E \ B := by
simp_rw [coindep_iff_exists', subset_diff]
exact ⟨fun ⟨⟨B, hB, _, hBX⟩, hX⟩ ↦ ⟨B, hB, hX, hBX.symm⟩,
fun ⟨B, hB, hXE, hXB⟩ ↦ ⟨⟨B, hB, hB.subset_ground, hXB.symm⟩, hXE⟩⟩
@[aesop unsafe 10% (rule_sets := [Matroid])]
theorem Coindep.subset_ground (hX : M.Coindep X) : X ⊆ M.E :=
hX.indep.subset_ground
theorem Coindep.exists_base_subset_compl (h : M.Coindep X) : ∃ B, M.Base B ∧ B ⊆ M.E \ X :=
(coindep_iff_exists h.subset_ground).1 h
theorem Coindep.exists_subset_compl_base (h : M.Coindep X) : ∃ B, M.Base B ∧ X ⊆ M.E \ B :=
coindep_iff_subset_compl_base.1 h
end dual
end Matroid
|
Data\Matroid\IndepAxioms.lean | /-
Copyright (c) 2023 Peter Nelson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Peter Nelson
-/
import Mathlib.Data.Matroid.Basic
/-!
# Matroid Independence and Basis axioms
Matroids in mathlib are defined axiomatically in terms of bases,
but can be described just as naturally via their collections of independent sets,
and in fact such a description, being more 'verbose', can often be useful.
As well as this, the definition of a `Matroid` uses an unwieldy 'maximality'
axiom that can be dropped in cases where there is some finiteness assumption.
This file provides several ways to do define a matroid in terms of its independence or base
predicates, using axiom sets that are appropriate in different settings,
and often much simpler than the general definition.
It also contains `simp` lemmas and typeclasses as appropriate.
All the independence axiom sets need nontriviality (the empty set is independent),
monotonicity (subsets of independent sets are independent),
and some form of 'augmentation' axiom, which allows one to enlarge a non-maximal independent set.
This augmentation axiom is still required when there are finiteness assumptions, but is simpler.
It just states that if `I` is a finite independent set and `J` is a larger finite
independent set, then there exists `e ∈ J \ I` for which `insert e I` is independent.
This is the axiom that appears in most of the definitions.
## Implementation Details
To facilitate building a matroid from its independent sets, we define a structure `IndepMatroid`
which has a ground set `E`, an independence predicate `Indep`, and some axioms as its fields.
This structure is another encoding of the data in a `Matroid`; the function `IndepMatroid.matroid`
constructs a `Matroid` from an `IndepMatroid`.
This is convenient because if one wants to define `M : Matroid α` from a known independence
predicate `Ind`, it is easier to define an `M' : IndepMatroid α` so that `M'.Indep = Ind` and
then set `M = M'.matroid` than it is to directly define `M` with the base axioms.
The simp lemma `IndepMatroid.matroid_indep_iff` is important here; it shows that `M.Indep = Ind`,
so the `Matroid` constructed is the right one, and the intermediate `IndepMatroid` can be
made essentially invisible by the simplifier when working with `M`.
Because of this setup, we don't define any API for `IndepMatroid`, as it would be
a redundant copy of the existing API for `Matroid.Indep`.
(In particular, one could define a natural equivalence `e : IndepMatroid α ≃ Matroid α`
with `e.toFun = IndepMatroid.matroid`, but this would be pointless, as there is no need
for the inverse of `e`).
## Main definitions
* `IndepMatroid α` is a matroid structure on `α` described in terms of its independent sets
in full generality, using infinite versions of the axioms.
* `IndepMatroid.matroid` turns `M' : IndepMatroid α` into `M : Matroid α` with `M'.Indep = M.Indep`.
* `IndepMatroid.ofFinitary` constructs an `IndepMatroid` whose associated `Matroid` is `Finitary`
in the special case where independence of a set is determined only by that of its
finite subsets. This construction uses Zorn's lemma.
* `IndepMatroid.ofBdd` constructs an `IndepMatroid` in the case where there is some known
absolute upper bound on the size of an independent set. This uses the infinite version of
the augmentation axiom; the corresponding `Matroid` is `FiniteRk`.
* `IndepMatroid.ofBddAugment` is the same as the above, but with a finite augmentation axiom.
* `IndepMatroid.ofFinite` constructs an `IndepMatroid` from a finite ground set in terms of
its independent sets.
* `IndepMatroid.ofFinset` constructs an `IndepMatroid α` whose corresponding matroid is `Finitary`
from an independence predicate on `Finset α`.
* `Matroid.ofExistsMatroid` constructs a 'copy' of a matroid that is known only
existentially, but whose independence predicate is known explicitly.
* `Matroid.ofExistsFiniteBase` constructs a matroid from its bases, if it is known that one
of them is finite. This gives a `FiniteRk` matroid.
* `Matroid.ofBaseOfFinite` constructs a `Finite` matroid from its bases.
-/
open Set Matroid
variable {α : Type*} {I B X : Set α}
section IndepMatroid
/-- A matroid as defined by the independence axioms. This is the same thing as a `Matroid`,
and so does not need its own API; it exists to make it easier to construct a matroid from its
independent sets. The constructed `IndepMatroid` can then be converted into a matroid
with `IndepMatroid.matroid`. -/
structure IndepMatroid (α : Type*) where
/-- The ground set -/
(E : Set α)
/-- The independence predicate -/
(Indep : Set α → Prop)
(indep_empty : Indep ∅)
(indep_subset : ∀ ⦃I J⦄, Indep J → I ⊆ J → Indep I)
(indep_aug : ∀ ⦃I B⦄, Indep I → ¬ Maximal Indep I →
Maximal Indep B → ∃ x ∈ B \ I, Indep (insert x I))
(indep_maximal : ∀ X, X ⊆ E → ExistsMaximalSubsetProperty Indep X)
(subset_ground : ∀ I, Indep I → I ⊆ E)
namespace IndepMatroid
/-- An `M : IndepMatroid α` gives a `Matroid α` whose bases are the maximal `M`-independent sets. -/
@[simps] protected def matroid (M : IndepMatroid α) : Matroid α where
E := M.E
Base := Maximal M.Indep
Indep := M.Indep
indep_iff' := by
refine fun I ↦ ⟨fun h ↦ ?_, fun ⟨B, ⟨h, _⟩, hIB'⟩ ↦ M.indep_subset h hIB'⟩
obtain ⟨J, hIJ, hmax⟩ := M.indep_maximal M.E rfl.subset I h (M.subset_ground I h)
rw [maximal_and_iff_right_of_imp M.subset_ground] at hmax
exact ⟨J, hmax.1, hIJ⟩
exists_base := by
obtain ⟨B, -, hB⟩ := M.indep_maximal M.E rfl.subset ∅ M.indep_empty <| empty_subset _
rw [maximal_and_iff_right_of_imp M.subset_ground] at hB
exact ⟨B, hB.1⟩
base_exchange B B' hB hB' e he := by
have hnotmax : ¬ Maximal M.Indep (B \ {e}) :=
fun h ↦ h.not_prop_of_ssuperset (diff_singleton_sSubset.2 he.1) hB.prop
obtain ⟨f, hf, hfB⟩ := M.indep_aug (M.indep_subset hB.prop diff_subset) hnotmax hB'
replace hf := show f ∈ B' \ B by simpa [show f ≠ e by rintro rfl; exact he.2 hf.1] using hf
refine ⟨f, hf, by_contra fun hnot ↦ ?_⟩
obtain ⟨x, hxB, hind⟩ := M.indep_aug hfB hnot hB
obtain ⟨-, rfl⟩ : _ ∧ x = e := by simpa [hxB.1] using hxB
refine hB.not_prop_of_ssuperset ?_ hind
rw [insert_comm, insert_diff_singleton, insert_eq_of_mem he.1]
exact ssubset_insert hf.2
maximality := M.indep_maximal
subset_ground B hB := M.subset_ground B hB.1
@[simp] theorem matroid_indep_iff {M : IndepMatroid α} {I : Set α} :
M.matroid.Indep I ↔ M.Indep I := Iff.rfl
/-- An independence predicate satisfying the finite matroid axioms determines a matroid,
provided independence is determined by its behaviour on finite sets.
This fundamentally needs choice, since it can be used to prove that every vector space
has a basis. -/
@[simps E] protected def ofFinitary (E : Set α) (Indep : Set α → Prop)
(indep_empty : Indep ∅)
(indep_subset : ∀ ⦃I J⦄, Indep J → I ⊆ J → Indep I)
(indep_aug : ∀ ⦃I J⦄, Indep I → I.Finite → Indep J → J.Finite → I.ncard < J.ncard →
∃ e ∈ J, e ∉ I ∧ Indep (insert e I))
(indep_compact : ∀ I, (∀ J, J ⊆ I → J.Finite → Indep J) → Indep I)
(subset_ground : ∀ I, Indep I → I ⊆ E) : IndepMatroid α :=
have htofin : ∀ I e, Indep I → ¬ Indep (insert e I) →
∃ I₀, I₀ ⊆ I ∧ I₀.Finite ∧ ¬ Indep (insert e I₀) := by
by_contra h; push_neg at h
obtain ⟨I, e, -, hIe, h⟩ := h
refine hIe <| indep_compact _ fun J hJss hJfin ↦ ?_
exact indep_subset (h (J \ {e}) (by rwa [diff_subset_iff]) (hJfin.diff _)) (by simp)
IndepMatroid.mk
(E := E)
(Indep := Indep)
(indep_empty := indep_empty)
(indep_subset := indep_subset)
(indep_aug := by
intro I B hI hImax hBmax
obtain ⟨e, heI, hins⟩ := exists_insert_of_not_maximal indep_subset hI hImax
by_cases heB : e ∈ B
· exact ⟨e, ⟨heB, heI⟩, hins⟩
by_contra hcon; push_neg at hcon
have heBdep := hBmax.not_prop_of_ssuperset (ssubset_insert heB)
-- There is a finite subset `B₀` of `B` so that `B₀ + e` is dependent
obtain ⟨B₀, hB₀B, hB₀fin, hB₀e⟩ := htofin B e hBmax.1 heBdep
have hB₀ := indep_subset hBmax.1 hB₀B
-- `I` has a finite subset `I₀` that doesn't extend into `B₀`
have hexI₀ : ∃ I₀, I₀ ⊆ I ∧ I₀.Finite ∧ ∀ x, x ∈ B₀ \ I₀ → ¬Indep (insert x I₀) := by
have hchoose : ∀ (b : ↑(B₀ \ I)), ∃ Ib, Ib ⊆ I ∧ Ib.Finite ∧ ¬Indep (insert (b : α) Ib) := by
rintro ⟨b, hb⟩; exact htofin I b hI (hcon b ⟨hB₀B hb.1, hb.2⟩)
choose! f hf using hchoose
have := (hB₀fin.diff I).to_subtype
refine ⟨iUnion f ∪ (B₀ ∩ I),
union_subset (iUnion_subset (fun i ↦ (hf i).1)) inter_subset_right,
(finite_iUnion fun i ↦ (hf i).2.1).union (hB₀fin.subset inter_subset_left),
fun x ⟨hxB₀, hxn⟩ hi ↦ ?_⟩
have hxI : x ∉ I := fun hxI ↦ hxn <| Or.inr ⟨hxB₀, hxI⟩
refine (hf ⟨x, ⟨hxB₀, hxI⟩⟩).2.2 (indep_subset hi <| insert_subset_insert ?_)
apply subset_union_of_subset_left
apply subset_iUnion
obtain ⟨I₀, hI₀I, hI₀fin, hI₀⟩ := hexI₀
set E₀ := insert e (I₀ ∪ B₀)
have hE₀fin : E₀.Finite := (hI₀fin.union hB₀fin).insert e
-- Extend `B₀` to a maximal independent subset of `I₀ ∪ B₀ + e`
obtain ⟨J, ⟨hB₀J, hJ, hJss⟩, hJmax⟩ := Finite.exists_maximal_wrt (f := id)
(s := {J | B₀ ⊆ J ∧ Indep J ∧ J ⊆ E₀})
(hE₀fin.finite_subsets.subset (by simp))
⟨B₀, Subset.rfl, hB₀, subset_union_right.trans (subset_insert _ _)⟩
have heI₀ : e ∉ I₀ := not_mem_subset hI₀I heI
have heI₀i : Indep (insert e I₀) := indep_subset hins (insert_subset_insert hI₀I)
have heJ : e ∉ J := fun heJ ↦ hB₀e (indep_subset hJ <| insert_subset heJ hB₀J)
have hJfin := hE₀fin.subset hJss
-- We have `|I₀ + e| ≤ |J|`, since otherwise we could extend the maximal set `J`
have hcard : (insert e I₀).ncard ≤ J.ncard := by
refine not_lt.1 fun hlt ↦ ?_
obtain ⟨f, hfI, hfJ, hfi⟩ := indep_aug hJ hJfin heI₀i (hI₀fin.insert e) hlt
have hfE₀ : f ∈ E₀ := mem_of_mem_of_subset hfI (insert_subset_insert subset_union_left)
refine hfJ (insert_eq_self.1 <| Eq.symm (hJmax _
⟨hB₀J.trans <| subset_insert _ _,hfi,insert_subset hfE₀ hJss⟩ (subset_insert _ _)))
-- But this means `|I₀| < |J|`, and extending `I₀` into `J` gives a contradiction
rw [ncard_insert_of_not_mem heI₀ hI₀fin, ← Nat.lt_iff_add_one_le] at hcard
obtain ⟨f, hfJ, hfI₀, hfi⟩ := indep_aug (indep_subset hI hI₀I) hI₀fin hJ hJfin hcard
exact hI₀ f ⟨Or.elim (hJss hfJ) (fun hfe ↦ (heJ <| hfe ▸ hfJ).elim) (by aesop), hfI₀⟩ hfi )
(indep_maximal := by
rintro X - I hI hIX
have hzorn := zorn_subset_nonempty {Y | Indep Y ∧ I ⊆ Y ∧ Y ⊆ X} ?_ I ⟨hI, Subset.rfl, hIX⟩
· obtain ⟨J, ⟨hJi, hIJ, hJX⟩, -, hJmax⟩ := hzorn
simp_rw [maximal_subset_iff]
exact ⟨J, hIJ, ⟨hJi, hJX⟩, fun K hK hJK ↦ (hJmax K ⟨hK.1, hIJ.trans hJK, hK.2⟩ hJK).symm⟩
refine fun Is hIs hchain ⟨K, hK⟩ ↦ ⟨⋃₀ Is, ⟨?_,?_,?_⟩, fun _ ↦ subset_sUnion_of_mem⟩
· refine indep_compact _ fun J hJ hJfin ↦ ?_
have hchoose : ∀ e, e ∈ J → ∃ I, I ∈ Is ∧ (e : α) ∈ I := fun _ he ↦ mem_sUnion.1 <| hJ he
choose! f hf using hchoose
refine J.eq_empty_or_nonempty.elim (fun hJ ↦ hJ ▸ indep_empty) (fun hne ↦ ?_)
obtain ⟨x, hxJ, hxmax⟩ := Finite.exists_maximal_wrt f _ hJfin hne
refine indep_subset (hIs (hf x hxJ).1).1 fun y hyJ ↦ ?_
obtain (hle | hle) := hchain.total (hf _ hxJ).1 (hf _ hyJ).1
· rw [hxmax _ hyJ hle]; exact (hf _ hyJ).2
exact hle (hf _ hyJ).2
· exact subset_sUnion_of_subset _ K (hIs hK).2.1 hK
exact sUnion_subset fun X hX ↦ (hIs hX).2.2)
(subset_ground := subset_ground)
@[simp] theorem ofFinitary_indep (E : Set α) (Indep : Set α → Prop)
indep_empty indep_subset indep_aug indep_compact subset_ground : (IndepMatroid.ofFinitary
E Indep indep_empty indep_subset indep_aug indep_compact subset_ground).Indep = Indep := rfl
instance ofFinitary_finitary (E : Set α) (Indep : Set α → Prop)
indep_empty indep_subset indep_aug indep_compact subset_ground : Finitary
(IndepMatroid.ofFinitary
E Indep indep_empty indep_subset indep_aug indep_compact subset_ground).matroid :=
⟨by simpa⟩
/-- If there is an absolute upper bound on the size of a set satisfying `P`, then the
maximal subset property always holds. -/
theorem _root_.Matroid.existsMaximalSubsetProperty_of_bdd {P : Set α → Prop}
(hP : ∃ (n : ℕ), ∀ Y, P Y → Y.encard ≤ n) (X : Set α) : ExistsMaximalSubsetProperty P X := by
obtain ⟨n, hP⟩ := hP
rintro I hI hIX
have hfin : Set.Finite (ncard '' {Y | P Y ∧ I ⊆ Y ∧ Y ⊆ X}) := by
rw [finite_iff_bddAbove, bddAbove_def]
simp_rw [ENat.le_coe_iff] at hP
use n
rintro x ⟨Y, ⟨hY,-,-⟩, rfl⟩
obtain ⟨n₀, heq, hle⟩ := hP Y hY
rwa [ncard_def, heq, ENat.toNat_coe]
obtain ⟨Y, ⟨hY, hIY, hYX⟩, hY'⟩ :=
Finite.exists_maximal_wrt' ncard _ hfin ⟨I, hI, rfl.subset, hIX⟩
refine ⟨Y, hIY, ⟨hY, hYX⟩, fun K ⟨hPK, hKX⟩ hYK ↦ ?_⟩
have hKfin : K.Finite := finite_of_encard_le_coe (hP K hPK)
refine (eq_of_subset_of_ncard_le hYK ?_ hKfin).symm.subset
rw [hY' K ⟨hPK, hIY.trans hYK, hKX⟩ (ncard_le_ncard hYK hKfin)]
/-- If there is an absolute upper bound on the size of an independent set, then the maximality axiom
isn't needed to define a matroid by independent sets. -/
@[simps E] protected def ofBdd (E : Set α) (Indep : Set α → Prop)
(indep_empty : Indep ∅)
(indep_subset : ∀ ⦃I J⦄, Indep J → I ⊆ J → Indep I)
(indep_aug : ∀⦃I B⦄, Indep I → ¬ Maximal Indep I → Maximal Indep B →
∃ x ∈ B \ I, Indep (insert x I))
(subset_ground : ∀ I, Indep I → I ⊆ E)
(indep_bdd : ∃ (n : ℕ), ∀ I, Indep I → I.encard ≤ n ) : IndepMatroid α where
E := E
Indep := Indep
indep_empty := indep_empty
indep_subset := indep_subset
indep_aug := indep_aug
indep_maximal X _ := Matroid.existsMaximalSubsetProperty_of_bdd indep_bdd X
subset_ground := subset_ground
@[simp] theorem ofBdd_indep (E : Set α) Indep indep_empty indep_subset indep_aug
subset_ground h_bdd : (IndepMatroid.ofBdd
E Indep indep_empty indep_subset indep_aug subset_ground h_bdd).Indep = Indep := rfl
/-- `IndepMatroid.ofBdd` constructs a `FiniteRk` matroid. -/
instance (E : Set α) (Indep : Set α → Prop) indep_empty indep_subset indep_aug subset_ground h_bdd :
FiniteRk (IndepMatroid.ofBdd
E Indep indep_empty indep_subset indep_aug subset_ground h_bdd).matroid := by
obtain ⟨B, hB⟩ := (IndepMatroid.ofBdd E Indep _ _ _ _ _).matroid.exists_base
refine hB.finiteRk_of_finite ?_
obtain ⟨n, hn⟩ := h_bdd
exact finite_of_encard_le_coe <| hn B (by simpa using hB.indep)
/-- If there is an absolute upper bound on the size of an independent set, then matroids
can be defined using an 'augmentation' axiom similar to the standard definition of
finite matroids for independent sets. -/
protected def ofBddAugment (E : Set α) (Indep : Set α → Prop)
(indep_empty : Indep ∅)
(indep_subset : ∀ ⦃I J⦄, Indep J → I ⊆ J → Indep I)
(indep_aug : ∀ ⦃I J⦄, Indep I → Indep J → I.encard < J.encard →
∃ e ∈ J, e ∉ I ∧ Indep (insert e I))
(indep_bdd : ∃ (n : ℕ), ∀ I, Indep I → I.encard ≤ n )
(subset_ground : ∀ I, Indep I → I ⊆ E) : IndepMatroid α :=
IndepMatroid.ofBdd (E := E) (Indep := Indep)
(indep_empty := indep_empty)
(indep_subset := indep_subset)
(indep_aug := by
rintro I B hI hImax hBmax
suffices hcard : I.encard < B.encard by
obtain ⟨e, heB, heI, hi⟩ := indep_aug hI hBmax.prop hcard
exact ⟨e, ⟨heB, heI⟩, hi⟩
refine lt_of_not_le fun hle ↦ ?_
obtain ⟨x, hxnot, hxI⟩ := exists_insert_of_not_maximal indep_subset hI hImax
have hlt : B.encard < (insert x I).encard := by
rwa [encard_insert_of_not_mem hxnot, ← not_le, ENat.add_one_le_iff, not_lt]
rw [encard_ne_top_iff]
obtain ⟨n, hn⟩ := indep_bdd
exact finite_of_encard_le_coe (hn _ hI)
obtain ⟨y, -, hyB, hi⟩ := indep_aug hBmax.prop hxI hlt
exact hBmax.not_prop_of_ssuperset (ssubset_insert hyB) hi)
(indep_bdd := indep_bdd) (subset_ground := subset_ground)
@[simp] theorem ofBddAugment_E (E : Set α) Indep indep_empty indep_subset indep_aug
indep_bdd subset_ground : (IndepMatroid.ofBddAugment
E Indep indep_empty indep_subset indep_aug indep_bdd subset_ground).E = E := rfl
@[simp] theorem ofBddAugment_indep (E : Set α) Indep indep_empty indep_subset indep_aug
indep_bdd subset_ground : (IndepMatroid.ofBddAugment
E Indep indep_empty indep_subset indep_aug indep_bdd subset_ground).Indep = Indep := rfl
instance ofBddAugment_finiteRk (E : Set α) Indep indep_empty indep_subset indep_aug
indep_bdd subset_ground : FiniteRk (IndepMatroid.ofBddAugment
E Indep indep_empty indep_subset indep_aug indep_bdd subset_ground).matroid := by
rw [IndepMatroid.ofBddAugment]
infer_instance
/-- If `E` is finite, then any collection of subsets of `E` satisfying
the usual independence axioms determines a matroid -/
protected def ofFinite {E : Set α} (hE : E.Finite) (Indep : Set α → Prop)
(indep_empty : Indep ∅)
(indep_subset : ∀ ⦃I J⦄, Indep J → I ⊆ J → Indep I)
(indep_aug :
∀ ⦃I J⦄, Indep I → Indep J → I.ncard < J.ncard → ∃ e ∈ J, e ∉ I ∧ Indep (insert e I))
(subset_ground : ∀ ⦃I⦄, Indep I → I ⊆ E) : IndepMatroid α :=
IndepMatroid.ofBddAugment (E := E) (Indep := Indep) (indep_empty := indep_empty)
(indep_subset := indep_subset)
(indep_aug := by
refine fun {I J} hI hJ hIJ ↦ indep_aug hI hJ ?_
rwa [← Nat.cast_lt (α := ℕ∞), (hE.subset (subset_ground hJ)).cast_ncard_eq,
(hE.subset (subset_ground hI)).cast_ncard_eq] )
(indep_bdd := ⟨E.ncard, fun I hI ↦ by
rw [hE.cast_ncard_eq]
exact encard_le_card <| subset_ground hI ⟩)
(subset_ground := subset_ground)
@[simp] theorem ofFinite_E {E : Set α} hE Indep indep_empty indep_subset indep_aug subset_ground :
(IndepMatroid.ofFinite
(hE : E.Finite) Indep indep_empty indep_subset indep_aug subset_ground).E = E := rfl
@[simp] theorem ofFinite_indep {E : Set α} hE Indep indep_empty indep_subset indep_aug
subset_ground : (IndepMatroid.ofFinite
(hE : E.Finite) Indep indep_empty indep_subset indep_aug subset_ground).Indep = Indep := rfl
instance ofFinite_finite {E : Set α} hE Indep indep_empty indep_subset indep_aug subset_ground :
(IndepMatroid.ofFinite
(hE : E.Finite) Indep indep_empty indep_subset indep_aug subset_ground).matroid.Finite :=
⟨hE⟩
/-- An independence predicate on `Finset α` that obeys the finite matroid axioms determines a
finitary matroid on `α`. -/
protected def ofFinset [DecidableEq α] (E : Set α) (Indep : Finset α → Prop)
(indep_empty : Indep ∅)
(indep_subset : ∀ ⦃I J⦄, Indep J → I ⊆ J → Indep I)
(indep_aug : ∀ ⦃I J⦄, Indep I → Indep J → I.card < J.card → ∃ e ∈ J, e ∉ I ∧ Indep (insert e I))
(subset_ground : ∀ ⦃I⦄, Indep I → (I : Set α) ⊆ E) : IndepMatroid α :=
IndepMatroid.ofFinitary
(E := E)
(Indep := (fun I ↦ (∀ (J : Finset α), (J : Set α) ⊆ I → Indep J)))
(indep_empty := by simpa [subset_empty_iff])
(indep_subset := ( fun I J hJ hIJ K hKI ↦ hJ _ (hKI.trans hIJ) ))
(indep_aug := by
intro I J hI hIfin hJ hJfin hIJ
rw [ncard_eq_toFinset_card _ hIfin, ncard_eq_toFinset_card _ hJfin] at hIJ
have aug := indep_aug (hI _ (by simp [Subset.rfl])) (hJ _ (by simp [Subset.rfl])) hIJ
simp only [Finite.mem_toFinset] at aug
obtain ⟨e, heJ, heI, hi⟩ := aug
exact ⟨e, heJ, heI, fun K hK ↦ indep_subset hi <| Finset.coe_subset.1 (by simpa)⟩ )
(indep_compact := fun I h J hJ ↦ h _ hJ J.finite_toSet _ Subset.rfl )
(subset_ground := fun I hI x hxI ↦ by simpa using subset_ground <| hI {x} (by simpa) )
@[simp] theorem ofFinset_E [DecidableEq α] (E : Set α) Indep indep_empty indep_subset indep_aug
subset_ground : (IndepMatroid.ofFinset
E Indep indep_empty indep_subset indep_aug subset_ground).E = E := rfl
@[simp] theorem ofFinset_indep [DecidableEq α] (E : Set α) Indep indep_empty indep_subset indep_aug
subset_ground {I : Finset α} : (IndepMatroid.ofFinset
E Indep indep_empty indep_subset indep_aug subset_ground).Indep I ↔ Indep I := by
simp only [IndepMatroid.ofFinset, ofFinitary_indep, Finset.coe_subset]
exact ⟨fun h ↦ h _ Subset.rfl, fun h J hJI ↦ indep_subset h hJI⟩
/-- This can't be `@[simp]`, because it would cause the more useful
`Matroid.ofIndepFinset_apply` not to be in simp normal form. -/
theorem ofFinset_indep' [DecidableEq α] (E : Set α) Indep indep_empty indep_subset indep_aug
subset_ground {I : Set α} : (IndepMatroid.ofFinset
E Indep indep_empty indep_subset indep_aug subset_ground).Indep I ↔
∀ (J : Finset α), (J : Set α) ⊆ I → Indep J := by
simp only [IndepMatroid.ofFinset, ofFinitary_indep]
end IndepMatroid
section Base
namespace Matroid
/-- Construct an `Matroid` from an independence predicate that agrees with that of some matroid `M`.
This is computable even if `M` is only known existentially, or when `M` exists for different
reasons in different cases. This can also be used to change the independence predicate to a
more useful definitional form. -/
@[simps! E] protected def ofExistsMatroid (E : Set α) (Indep : Set α → Prop)
(hM : ∃ (M : Matroid α), E = M.E ∧ ∀ I, M.Indep I ↔ Indep I) : Matroid α :=
IndepMatroid.matroid <|
have hex : ∃ (M : Matroid α), E = M.E ∧ M.Indep = Indep := by
obtain ⟨M, rfl, h⟩ := hM; refine ⟨_, rfl, funext (by simp [h])⟩
IndepMatroid.mk (E := E) (Indep := Indep)
(indep_empty := by obtain ⟨M, -, rfl⟩ := hex; exact M.empty_indep)
(indep_subset := by obtain ⟨M, -, rfl⟩ := hex; exact fun I J hJ hIJ ↦ hJ.subset hIJ)
(indep_aug := by obtain ⟨M, -, rfl⟩ := hex; exact Indep.exists_insert_of_not_maximal M)
(indep_maximal := by obtain ⟨M, rfl, rfl⟩ := hex; exact M.existsMaximalSubsetProperty_indep)
(subset_ground := by obtain ⟨M, rfl, rfl⟩ := hex; exact fun I ↦ Indep.subset_ground)
/-- A matroid defined purely in terms of its bases. -/
@[simps E] protected def ofBase (E : Set α) (Base : Set α → Prop) (exists_base : ∃ B, Base B)
(base_exchange : ExchangeProperty Base)
(maximality : ∀ X, X ⊆ E → Matroid.ExistsMaximalSubsetProperty (∃ B, Base B ∧ · ⊆ B) X)
(subset_ground : ∀ B, Base B → B ⊆ E) : Matroid α where
E := E
Base := Base
Indep I := (∃ B, Base B ∧ I ⊆ B)
indep_iff' _ := Iff.rfl
exists_base := exists_base
base_exchange := base_exchange
maximality := maximality
subset_ground := subset_ground
/-- A collection of bases with the exchange property and at least one finite member is a matroid -/
@[simps! E] protected def ofExistsFiniteBase (E : Set α) (Base : Set α → Prop)
(exists_finite_base : ∃ B, Base B ∧ B.Finite) (base_exchange : ExchangeProperty Base)
(subset_ground : ∀ B, Base B → B ⊆ E) : Matroid α := Matroid.ofBase
(E := E)
(Base := Base)
(exists_base := by obtain ⟨B,h⟩ := exists_finite_base; exact ⟨B, h.1⟩)
(base_exchange := base_exchange)
(maximality := by
obtain ⟨B, hB, hfin⟩ := exists_finite_base
refine fun X _ ↦ Matroid.existsMaximalSubsetProperty_of_bdd
⟨B.ncard, fun Y ⟨B', hB', hYB'⟩ ↦ ?_⟩ X
rw [hfin.cast_ncard_eq, base_exchange.encard_base_eq hB hB']
exact encard_mono hYB')
(subset_ground := subset_ground)
@[simp] theorem ofExistsFiniteBase_base (E : Set α) Base exists_finite_base
base_exchange subset_ground : (Matroid.ofExistsFiniteBase
E Base exists_finite_base base_exchange subset_ground).Base = Base := rfl
instance ofExistsFiniteBase_finiteRk (E : Set α) Base exists_finite_base
base_exchange subset_ground : FiniteRk (Matroid.ofExistsFiniteBase
E Base exists_finite_base base_exchange subset_ground) := by
obtain ⟨B, hB, hfin⟩ := exists_finite_base
exact Matroid.Base.finiteRk_of_finite (by simpa) hfin
/-- If `E` is finite, then any nonempty collection of its subsets
with the exchange property is the collection of bases of a matroid on `E`. -/
protected def ofBaseOfFinite {E : Set α} (hE : E.Finite) (Base : Set α → Prop)
(exists_base : ∃ B, Base B) (base_exchange : ExchangeProperty Base)
(subset_ground : ∀ B, Base B → B ⊆ E) : Matroid α :=
Matroid.ofExistsFiniteBase (E := E) (Base := Base)
(exists_finite_base :=
let ⟨B, hB⟩ := exists_base
⟨B, hB, hE.subset (subset_ground B hB)⟩)
(base_exchange := base_exchange)
(subset_ground := subset_ground)
@[simp] theorem ofBaseOfFinite_E {E : Set α} (hE : E.Finite) Base exists_base base_exchange
subset_ground : (Matroid.ofBaseOfFinite
hE Base exists_base base_exchange subset_ground).E = E := rfl
@[simp] theorem ofBaseOfFinite_base {E : Set α} (hE : E.Finite) Base exists_base
base_exchange subset_ground : (Matroid.ofBaseOfFinite
hE Base exists_base base_exchange subset_ground).Base = Base := rfl
instance ofBaseOfFinite_finite {E : Set α} (hE : E.Finite) Base exists_base
base_exchange subset_ground : (Matroid.ofBaseOfFinite
hE Base exists_base base_exchange subset_ground).Finite :=
⟨hE⟩
end Matroid
end Base
end IndepMatroid
|
Data\Matroid\Init.lean | /-
Copyright (c) 2023 Peter Nelson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Peter Nelson
-/
import Aesop
/-!
# Matroid Rule Set
This module defines the `Matroid` Aesop rule set which is used by the
`aesop_mat` tactic. Aesop rule sets only become visible once the file in which
they're declared is imported, so we must put this declaration into its own file.
-/
declare_aesop_rule_sets [Matroid]
|
Data\Matroid\Map.lean | /-
Copyright (c) 2024 Peter Nelson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Peter Nelson
-/
import Mathlib.Data.Matroid.Constructions
import Mathlib.Data.Set.Notation
/-!
# Maps between matroids
This file defines maps and comaps, which move a matroid on one type to a matroid on another
using a function between the types. The constructions are (up to isomorphism)
just combinations of restrictions and parallel extensions, so are not mathematically difficult.
Because a matroid `M : Matroid α` is defined with am embedded ground set `M.E : Set α`
which contains all the structure of `M`, there are several types of map and comap
one could reasonably ask for;
for instance, we could map `M : Matroid α` to a `Matroid β` using either
a function `f : α → β`, a function `f : ↑M.E → β` or indeed a function `f : ↑M.E → ↑E`
for some `E : Set β`. We attempt to give definitions that capture most reasonable use cases.
`Matroid.map` and `Matroid.comap` are defined in terms of bare functions rather than
functions defined on subtypes, so are often easier to work in practice than the subtype variants.
In fact, the statement that `N = Matroid.map M f _` for some `f : α → β`
is equivalent to the existence of an isomorphism from `M` to `N`,
except in the trivial degenerate case where `M` is an empty matroid on a nonempty type and `N`
is an empty matroid on an empty type.
This can be simpler to use than an actual formal isomorphism, which requires subtypes.
## Main definitions
In the definitions below, `M` and `N` are matroids on `α` and `β` respectively.
* For `f : α → β`, `Matroid.comap N f` is the matroid on `α` with ground set `f ⁻¹' N.E`
in which each `I` is independent if and only if `f` is injective on `I` and
`f '' I` is independent in `N`.
(For each nonloop `x` of `N`, the set `f ⁻¹' {x}` is a parallel class of `N.comap f`)
* `Matroid.comapOn N f E` is the restriction of `N.comap f` to `E` for some `E : Set α`.
* For an embedding `f : M.E ↪ β` defined on the subtype `↑M.E`,
`Matroid.mapSetEmbedding M f` is the matroid on `β` with ground set `range f`
whose independent sets are the images of those in `M`. This matroid is isomorphic to `M`.
* For a function `f : α → β` and a proof `hf` that `f` is injective on `M.E`,
`Matroid.map f hf` is the matroid on `β` with ground set `f '' M.E`
whose independent sets are the images of those in `M`. This matroid is isomorphic to `M`,
and does not depend on the values `f` takes outside `M.E`.
* `Matroid.mapEmbedding f` is a version of `Matroid.map` where `f : α ↪ β` is a bundled embedding.
It is defined separately because the global injectivity of `f` gives some nicer `simp` lemmas.
* `Matroid.mapEquiv f` is a version of `Matroid.map` where `f : α ≃ β` is a bundled equivalence.
It is defined separately because we get even nicer `simp` lemmas.
* `Matroid.mapSetEquiv f` is a version of `Matroid.map` where `f : M.E ≃ E` is an equivalence on
subtypes. It gives a matroid on `β` with ground set `E`.
* For `X : Set α`, `Matroid.restrictSubtype M X` is the `Matroid X` with ground set
`univ : Set X` that is isomorphic to `M ↾ X`.
## Implementation details
The definition of `comap` is the only place where we need to actually define a matroid from scratch.
After `comap` is defined, we can define `map` and its variants indirectly in terms of `comap`.
If `f : α → β` is injective on `M.E`, the independent sets of `M.map f hf` are the images of
the independent set of `M`; i.e. `(M.map f hf).Indep I ↔ ∃ I₀, M.Indep I₀ ∧ I = f '' I₀`.
But if `f` is globally injective, we can phrase this more directly;
indeed, `(M.map f _).Indep I ↔ M.Indep (f ⁻¹' I) ∧ I ⊆ range f`.
If `f` is an equivalence we have `(M.map f _).Indep I ↔ M.Indep (f.symm '' I)`.
In order that these stronger statements can be `@[simp]`,
we define `mapEmbedding` and `mapEquiv` separately from `map`.
## Notes
For finite matroids, both maps and comaps are a special case of a construction of
Perfect [perfect1969matroid] in which a matroid structure can be transported across an arbitrary
bipartite graph that may not correspond to a function at all (See [oxley2011], Theorem 11.2.12).
It would have been nice to use this more general construction as a basis for the definition
of both `Matroid.map` and `Matroid.comap`.
Unfortunately, we can't do this, because the construction doesn't extend to infinite matroids.
Specifically, if `M₁` and `M₂` are matroids on the same type `α`,
and `f` is the natural function from `α ⊕ α` to `α`,
then the images under `f` of the independent sets of the direct sum `M₁ ⊕ M₂` are
the independent sets of a matroid if and only if the union of `M₁` and `M₂` is a matroid,
and unions do not exist for some pairs of infinite matroids: see [aignerhorev2012infinite].
For this reason, `Matroid.map` requires injectivity to be well-defined in general.
## TODO
* Bundled matroid isomorphisms.
* Maps of finite matroids across bipartite graphs.
## References
* [E. Aigner-Horev, J. Carmesin, J. Fröhlic, Infinite Matroid Union][aignerhorev2012infinite]
* [H. Perfect, Independence Spaces and Combinatorial Problems][perfect1969matroid]
* [J. Oxley, Matroid Theory][oxley2011]
-/
open Set Function Set.Notation
namespace Matroid
variable {α β : Type*} {f : α → β} {E I s : Set α} {M : Matroid α} {N : Matroid β}
section comap
/-- The pullback of a matroid on `β` by a function `f : α → β` to a matroid on `α`.
Elements with the same (nonloop) image are parallel and the ground set is `f ⁻¹' M.E`.
The matroids `M.comap f` and `M ↾ range f` have isomorphic simplifications;
the preimage of each nonloop of `M ↾ range f` is a parallel class. -/
def comap (N : Matroid β) (f : α → β) : Matroid α :=
IndepMatroid.matroid <|
{ E := f ⁻¹' N.E
Indep := fun I ↦ N.Indep (f '' I) ∧ InjOn f I
indep_empty := by simp
indep_subset := fun I J h hIJ ↦ ⟨h.1.subset (image_subset _ hIJ), InjOn.mono hIJ h.2⟩
indep_aug := by
rintro I B ⟨hI, hIinj⟩ hImax hBmax
obtain ⟨I', hII', hI', hI'inj⟩ := (not_maximal_subset_iff ⟨hI, hIinj⟩).1 hImax
have h₁ : ¬(N ↾ range f).Base (f '' I) := by
refine fun hB ↦ hII'.ne ?_
have h_im := hB.eq_of_subset_indep (by simpa) (image_subset _ hII'.subset)
rwa [hI'inj.image_eq_image_iff hII'.subset Subset.rfl] at h_im
have h₂ : (N ↾ range f).Base (f '' B) := by
refine Indep.base_of_forall_insert (by simpa using hBmax.1.1) ?_
rintro _ ⟨⟨e, heB, rfl⟩, hfe⟩ hi
rw [restrict_indep_iff, ← image_insert_eq] at hi
have hinj : InjOn f (insert e B) := by
rw [injOn_insert (fun heB ↦ hfe (mem_image_of_mem f heB))]
exact ⟨hBmax.1.2, hfe⟩
refine hBmax.not_prop_of_ssuperset (t := insert e B) (ssubset_insert ?_) ⟨hi.1, hinj⟩
exact fun heB ↦ hfe <| mem_image_of_mem f heB
obtain ⟨_, ⟨⟨e, he, rfl⟩, he'⟩, hei⟩ := Indep.exists_insert_of_not_base (by simpa) h₁ h₂
have heI : e ∉ I := fun heI ↦ he' (mem_image_of_mem f heI)
rw [← image_insert_eq, restrict_indep_iff] at hei
exact ⟨e, ⟨he, heI⟩, hei.1, (injOn_insert heI).2 ⟨hIinj, he'⟩⟩
indep_maximal := by
rintro X - I ⟨hI, hIinj⟩ hIX
obtain ⟨J, hJ⟩ := (N ↾ range f).existsMaximalSubsetProperty_indep (f '' X) (by simp)
(f '' I) (by simpa) (image_subset _ hIX)
simp only [restrict_indep_iff, image_subset_iff, maximal_subset_iff, mem_setOf_eq, and_imp,
and_assoc] at hJ ⊢
obtain ⟨hIJ, hJ, hJf, hJX, hJmax⟩ := hJ
obtain ⟨J₀, hIJ₀, hJ₀X, hbj⟩ := hIinj.bijOn_image.exists_extend_of_subset hIX
(image_subset f hIJ) (image_subset_iff.2 <| preimage_mono hJX)
obtain rfl : f '' J₀ = J := by rw [← image_preimage_eq_of_subset hJf, hbj.image_eq]
refine ⟨J₀, hIJ₀, hJ, hbj.injOn, hJ₀X, fun K hK hKinj hKX hJ₀K ↦ ?_⟩
rw [← hKinj.image_eq_image_iff hJ₀K Subset.rfl, hJmax hK (image_subset_range _ _)
(image_subset f hKX) (image_subset f hJ₀K)]
subset_ground := fun I hI e heI ↦ hI.1.subset_ground ⟨e, heI, rfl⟩ }
@[simp] lemma comap_indep_iff : (N.comap f).Indep I ↔ N.Indep (f '' I) ∧ InjOn f I := Iff.rfl
@[simp] lemma comap_ground_eq (N : Matroid β) (f : α → β) : (N.comap f).E = f ⁻¹' N.E := rfl
@[simp] lemma comap_dep_iff :
(N.comap f).Dep I ↔ N.Dep (f '' I) ∨ (N.Indep (f '' I) ∧ ¬ InjOn f I) := by
rw [Dep, comap_indep_iff, not_and, comap_ground_eq, Dep, image_subset_iff]
refine ⟨fun ⟨hi, h⟩ ↦ ?_, ?_⟩
· rw [and_iff_left h, ← imp_iff_not_or]
exact fun hI ↦ ⟨hI, hi hI⟩
rintro (⟨hI, hIE⟩ | hI)
· exact ⟨fun h ↦ (hI h).elim, hIE⟩
rw [iff_true_intro hI.1, iff_true_intro hI.2, implies_true, true_and]
simpa using hI.1.subset_ground
@[simp] lemma comap_id (N : Matroid β) : N.comap id = N :=
eq_of_indep_iff_indep_forall rfl <| by simp [injective_id.injOn]
lemma comap_indep_iff_of_injOn (hf : InjOn f (f ⁻¹' N.E)) :
(N.comap f).Indep I ↔ N.Indep (f '' I) := by
rw [comap_indep_iff, and_iff_left_iff_imp]
refine fun hi ↦ hf.mono <| subset_trans ?_ (preimage_mono hi.subset_ground)
apply subset_preimage_image
@[simp] lemma comap_emptyOn (f : α → β) : comap (emptyOn β) f = emptyOn α := by
simp [← ground_eq_empty_iff]
@[simp] lemma comap_loopyOn (f : α → β) (E : Set β) : comap (loopyOn E) f = loopyOn (f ⁻¹' E) := by
rw [eq_loopyOn_iff]; aesop
@[simp] lemma comap_basis_iff {I X : Set α} :
(N.comap f).Basis I X ↔ N.Basis (f '' I) (f '' X) ∧ I.InjOn f ∧ I ⊆ X := by
refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩
· obtain ⟨hI, hinj⟩ := comap_indep_iff.1 h.indep
refine ⟨hI.basis_of_forall_insert (image_subset f h.subset) fun e he ↦ ?_, hinj, h.subset⟩
simp only [mem_diff, mem_image, not_exists, not_and, and_imp, forall_exists_index,
forall_apply_eq_imp_iff₂] at he
obtain ⟨⟨e, heX, rfl⟩, he⟩ := he
have heI : e ∉ I := fun heI ↦ (he e heI rfl)
replace h := h.insert_dep ⟨heX, heI⟩
simp only [comap_dep_iff, image_insert_eq, or_iff_not_imp_right, injOn_insert heI,
hinj, mem_image, not_exists, not_and, true_and, not_forall, Classical.not_imp, not_not] at h
exact h (fun _ ↦ he)
refine Indep.basis_of_forall_insert ?_ h.2.2 fun e ⟨heX, heI⟩ ↦ ?_
· simp [comap_indep_iff, h.1.indep, h.2]
have hIE : insert e I ⊆ (N.comap f).E := by
simp_rw [comap_ground_eq, ← image_subset_iff]
exact (image_subset _ (insert_subset heX h.2.2)).trans h.1.subset_ground
suffices N.Indep (insert (f e) (f '' I)) → ∃ x ∈ I, f x = f e
by simpa [← not_indep_iff hIE, injOn_insert heI, h.2.1, image_insert_eq]
exact h.1.mem_of_insert_indep (mem_image_of_mem f heX)
@[simp] lemma comap_base_iff {B : Set α} :
(N.comap f).Base B ↔ N.Basis (f '' B) (f '' (f ⁻¹' N.E)) ∧ B.InjOn f ∧ B ⊆ f ⁻¹' N.E := by
rw [← basis_ground_iff, comap_basis_iff]; rfl
@[simp] lemma comap_basis'_iff {I X : Set α} :
(N.comap f).Basis' I X ↔ N.Basis' (f '' I) (f '' X) ∧ I.InjOn f ∧ I ⊆ X := by
simp only [basis'_iff_basis_inter_ground, comap_ground_eq, comap_basis_iff, image_inter_preimage,
subset_inter_iff, ← and_assoc, and_congr_left_iff, and_iff_left_iff_imp, and_imp]
exact fun h _ _ ↦ (image_subset_iff.1 h.indep.subset_ground)
instance comap_finitary (N : Matroid β) [N.Finitary] (f : α → β) : (N.comap f).Finitary := by
refine ⟨fun I hI ↦ ?_⟩
rw [comap_indep_iff, indep_iff_forall_finite_subset_indep]
simp only [forall_subset_image_iff]
refine ⟨fun J hJ hfin ↦ ?_,
fun x hx y hy ↦ (hI _ (pair_subset hx hy) (by simp)).2 (by simp) (by simp)⟩
obtain ⟨J', hJ'J, hJ'⟩ := (surjOn_image f J).exists_bijOn_subset
rw [← hJ'.image_eq] at hfin ⊢
exact (hI J' (hJ'J.trans hJ) (hfin.of_finite_image hJ'.injOn)).1
instance comap_finiteRk (N : Matroid β) [N.FiniteRk] (f : α → β) : (N.comap f).FiniteRk := by
obtain ⟨B, hB⟩ := (N.comap f).exists_base
refine hB.finiteRk_of_finite ?_
simp only [comap_base_iff] at hB
exact (hB.1.indep.finite.of_finite_image hB.2.1)
end comap
section comapOn
variable {E B I : Set α}
/-- The pullback of a matroid on `β` by a function `f : α → β` to a matroid on `α`,
restricted to a ground set `E`.
The matroids `M.comapOn f E` and `M ↾ (f '' E)` have isomorphic simplifications;
elements with the same nonloop image are parallel. -/
def comapOn (N : Matroid β) (E : Set α) (f : α → β) : Matroid α := (N.comap f) ↾ E
lemma comapOn_preimage_eq (N : Matroid β) (f : α → β) : N.comapOn (f ⁻¹' N.E) f = N.comap f := by
rw [comapOn, restrict_eq_self_iff]; rfl
@[simp] lemma comapOn_indep_iff :
(N.comapOn E f).Indep I ↔ (N.Indep (f '' I) ∧ InjOn f I ∧ I ⊆ E) := by
simp [comapOn, and_assoc]
@[simp] lemma comapOn_ground_eq : (N.comapOn E f).E = E := rfl
lemma comapOn_base_iff :
(N.comapOn E f).Base B ↔ N.Basis' (f '' B) (f '' E) ∧ B.InjOn f ∧ B ⊆ E := by
rw [comapOn, base_restrict_iff', comap_basis'_iff]
lemma comapOn_base_iff_of_surjOn (h : SurjOn f E N.E) :
(N.comapOn E f).Base B ↔ (N.Base (f '' B) ∧ InjOn f B ∧ B ⊆ E) := by
simp_rw [comapOn_base_iff, and_congr_left_iff, and_imp,
basis'_iff_basis_inter_ground, inter_eq_self_of_subset_right h, basis_ground_iff, implies_true]
lemma comapOn_base_iff_of_bijOn (h : BijOn f E N.E) :
(N.comapOn E f).Base B ↔ N.Base (f '' B) ∧ B ⊆ E := by
rw [← and_iff_left_of_imp (Base.subset_ground (M := N.comapOn E f) (B := B)),
comapOn_ground_eq, and_congr_left_iff]
suffices h' : B ⊆ E → InjOn f B from fun hB ↦
by simp [hB, comapOn_base_iff_of_surjOn h.surjOn, h']
exact fun hBE ↦ h.injOn.mono hBE
lemma comapOn_dual_eq_of_bijOn (h : BijOn f E N.E) :
(N.comapOn E f)✶ = N✶.comapOn E f := by
refine eq_of_base_iff_base_forall (by simp) (fun B hB ↦ ?_)
rw [comapOn_base_iff_of_bijOn (by simpa), dual_base_iff, comapOn_base_iff_of_bijOn h,
dual_base_iff _, comapOn_ground_eq, and_iff_left diff_subset, and_iff_left (by simpa),
h.injOn.image_diff_subset (by simpa), h.image_eq]
exact (h.mapsTo.mono_left (show B ⊆ E by simpa)).image_subset
instance comapOn_finitary [N.Finitary] : (N.comapOn E f).Finitary := by
rw [comapOn]; infer_instance
instance comapOn_finiteRk [N.FiniteRk] : (N.comapOn E f).FiniteRk := by
rw [comapOn]; infer_instance
end comapOn
section mapSetEmbedding
/-- Map a matroid `M` to an isomorphic copy in `β` using an embedding `M.E ↪ β`. -/
def mapSetEmbedding (M : Matroid α) (f : M.E ↪ β) : Matroid β := Matroid.ofExistsMatroid
(E := range f)
(Indep := fun I ↦ M.Indep ↑(f ⁻¹' I) ∧ I ⊆ range f)
(hM := by
classical
obtain (rfl | ⟨⟨e,he⟩⟩) := eq_emptyOn_or_nonempty M
· refine ⟨emptyOn β, ?_⟩
simp only [emptyOn_ground] at f
simp [range_eq_empty f, subset_empty_iff]
have _ : Nonempty M.E := ⟨⟨e,he⟩⟩
have _ : Nonempty α := ⟨e⟩
refine ⟨M.comapOn (range f) (fun x ↦ ↑(invFunOn f univ x)), rfl, ?_⟩
simp_rw [comapOn_indep_iff, ← and_assoc, and_congr_left_iff, subset_range_iff_exists_image_eq]
rintro _ ⟨I, rfl⟩
rw [← image_image, InjOn.invFunOn_image f.injective.injOn (subset_univ _),
preimage_image_eq _ f.injective, and_iff_left_iff_imp]
rintro - x hx y hy
simp only [EmbeddingLike.apply_eq_iff_eq, Subtype.val_inj]
exact (invFunOn_injOn_image f univ) (image_subset f (subset_univ I) hx)
(image_subset f (subset_univ I) hy) )
@[simp] lemma mapSetEmbedding_ground (M : Matroid α) (f : M.E ↪ β) :
(M.mapSetEmbedding f).E = range f := rfl
@[simp] lemma mapSetEmbedding_indep_iff {f : M.E ↪ β} {I : Set β} :
(M.mapSetEmbedding f).Indep I ↔ M.Indep ↑(f ⁻¹' I) ∧ I ⊆ range f := Iff.rfl
lemma Indep.exists_eq_image_of_mapSetEmbedding {f : M.E ↪ β} {I : Set β}
(hI : (M.mapSetEmbedding f).Indep I) : ∃ (I₀ : Set M.E), M.Indep I₀ ∧ I = f '' I₀ :=
⟨f ⁻¹' I, hI.1, Eq.symm <| image_preimage_eq_of_subset hI.2⟩
lemma mapSetEmbedding_indep_iff' {f : M.E ↪ β} {I : Set β} :
(M.mapSetEmbedding f).Indep I ↔ ∃ (I₀ : Set M.E), M.Indep ↑I₀ ∧ I = f '' I₀ := by
simp only [mapSetEmbedding_indep_iff, subset_range_iff_exists_image_eq]
constructor
· rintro ⟨hI, I, rfl⟩
exact ⟨I, by rwa [preimage_image_eq _ f.injective] at hI, rfl⟩
rintro ⟨I, hI, rfl⟩
rw [preimage_image_eq _ f.injective]
exact ⟨hI, _, rfl⟩
end mapSetEmbedding
section map
/-- Given a function `f` that is injective on `M.E`, the copy of `M` in `β` whose independent sets
are the images of those in `M`. If `β` is a nonempty type, then `N : Matroid β` is a map of `M`
if and only if `M` and `N` are isomorphic. -/
def map (M : Matroid α) (f : α → β) (hf : InjOn f M.E) : Matroid β := Matroid.ofExistsMatroid
(E := f '' M.E)
(Indep := fun I ↦ ∃ I₀, M.Indep I₀ ∧ I = f '' I₀)
(hM := by
refine ⟨M.mapSetEmbedding ⟨_, hf.injective⟩, by simp, fun I ↦ ?_⟩
simp_rw [mapSetEmbedding_indep_iff', Embedding.coeFn_mk, restrict_apply,
← image_image f Subtype.val, Subtype.exists_set_subtype (p := fun J ↦ M.Indep J ∧ I = f '' J)]
exact ⟨fun ⟨I₀, _, hI₀⟩ ↦ ⟨I₀, hI₀⟩, fun ⟨I₀, hI₀⟩ ↦ ⟨I₀, hI₀.1.subset_ground, hI₀⟩⟩)
@[simp] lemma map_ground (M : Matroid α) (f : α → β) (hf) : (M.map f hf).E = f '' M.E := rfl
@[simp] lemma map_indep_iff {hf} {I : Set β} :
(M.map f hf).Indep I ↔ ∃ I₀, M.Indep I₀ ∧ I = f '' I₀ := Iff.rfl
lemma Indep.map (hI : M.Indep I) (f : α → β) (hf) : (M.map f hf).Indep (f '' I) :=
map_indep_iff.2 ⟨I, hI, rfl⟩
lemma Indep.exists_bijOn_of_map {I : Set β} (hf) (hI : (M.map f hf).Indep I) :
∃ I₀, M.Indep I₀ ∧ BijOn f I₀ I := by
obtain ⟨I₀, hI₀, rfl⟩ := hI
exact ⟨I₀, hI₀, (hf.mono hI₀.subset_ground).bijOn_image⟩
lemma map_image_indep_iff {hf} {I : Set α} (hI : I ⊆ M.E) :
(M.map f hf).Indep (f '' I) ↔ M.Indep I := by
rw [map_indep_iff]
refine ⟨fun ⟨J, hJ, hIJ⟩ ↦ ?_, fun h ↦ ⟨I, h, rfl⟩⟩
rw [hf.image_eq_image_iff hI hJ.subset_ground] at hIJ; rwa [hIJ]
@[simp] lemma map_base_iff (M : Matroid α) (f : α → β) (hf) {B : Set β} :
(M.map f hf).Base B ↔ ∃ B₀, M.Base B₀ ∧ B = f '' B₀ := by
rw [base_iff_maximal_indep]
refine ⟨fun h ↦ ?_, ?_⟩
· obtain ⟨B₀, hB₀, hbij⟩ := h.prop.exists_bijOn_of_map
refine ⟨B₀, hB₀.base_of_maximal fun J hJ hB₀J ↦ ?_, hbij.image_eq.symm⟩
rw [← hf.image_eq_image_iff hB₀.subset_ground hJ.subset_ground, hbij.image_eq]
exact h.eq_of_subset (hJ.map f hf) (hbij.image_eq ▸ image_subset f hB₀J)
rintro ⟨B, hB, rfl⟩
rw [maximal_subset_iff]
refine ⟨hB.indep.map f hf, fun I hI hBI ↦ ?_⟩
obtain ⟨I₀, hI₀, hbij⟩ := hI.exists_bijOn_of_map
rw [← hbij.image_eq, hf.image_subset_image_iff hB.subset_ground hI₀.subset_ground] at hBI
rw [hB.eq_of_subset_indep hI₀ hBI, hbij.image_eq]
lemma Base.map {B : Set α} (hB : M.Base B) {f : α → β} (hf) : (M.map f hf).Base (f '' B) := by
rw [map_base_iff]; exact ⟨B, hB, rfl⟩
lemma map_dep_iff {hf} {D : Set β} :
(M.map f hf).Dep D ↔ ∃ D₀, M.Dep D₀ ∧ D = f '' D₀ := by
simp only [Dep, map_indep_iff, not_exists, not_and, map_ground, subset_image_iff]
constructor
· rintro ⟨h, D₀, hD₀E, rfl⟩
exact ⟨D₀, ⟨fun hd ↦ h _ hd rfl, hD₀E⟩, rfl⟩
rintro ⟨D₀, ⟨hD₀, hD₀E⟩, rfl⟩
refine ⟨fun I hI h_eq ↦ ?_, ⟨_, hD₀E, rfl⟩⟩
rw [hf.image_eq_image_iff hD₀E hI.subset_ground] at h_eq
subst h_eq; contradiction
lemma map_image_base_iff {hf} {B : Set α} (hB : B ⊆ M.E) :
(M.map f hf).Base (f '' B) ↔ M.Base B := by
rw [map_base_iff]
refine ⟨fun ⟨J, hJ, hIJ⟩ ↦ ?_, fun h ↦ ⟨B, h, rfl⟩⟩
rw [hf.image_eq_image_iff hB hJ.subset_ground] at hIJ; rwa [hIJ]
lemma Basis.map {X : Set α} (hIX : M.Basis I X) {f : α → β} (hf) :
(M.map f hf).Basis (f '' I) (f '' X) := by
refine (hIX.indep.map f hf).basis_of_forall_insert (image_subset _ hIX.subset) ?_
rintro _ ⟨⟨e,he,rfl⟩, he'⟩
have hss := insert_subset (hIX.subset_ground he) hIX.indep.subset_ground
rw [← not_indep_iff (by simpa [← image_insert_eq] using image_subset f hss)]
simp only [map_indep_iff, not_exists, not_and]
intro J hJ hins
rw [← image_insert_eq, hf.image_eq_image_iff hss hJ.subset_ground] at hins
obtain rfl := hins
exact he' (mem_image_of_mem f (hIX.mem_of_insert_indep he hJ))
lemma map_basis_iff {I X : Set α} (f : α → β) (hf) (hI : I ⊆ M.E) (hX : X ⊆ M.E) :
(M.map f hf).Basis (f '' I) (f '' X) ↔ M.Basis I X := by
refine ⟨fun h ↦ ?_, fun h ↦ h.map hf⟩
obtain ⟨I', hI', hII'⟩ := map_indep_iff.1 h.indep
rw [hf.image_eq_image_iff hI hI'.subset_ground] at hII'
obtain rfl := hII'
have hss := (hf.image_subset_image_iff hI hX).1 h.subset
refine hI'.basis_of_maximal_subset hss (fun J hJ hIJ hJX ↦ ?_)
have hIJ' := h.eq_of_subset_indep (hJ.map f hf) (image_subset f hIJ) (image_subset f hJX)
rw [hf.image_eq_image_iff hI hJ.subset_ground] at hIJ'
exact hIJ'.symm.subset
lemma map_basis_iff' {I X : Set β} {hf} :
(M.map f hf).Basis I X ↔ ∃ I₀ X₀, M.Basis I₀ X₀ ∧ I = f '' I₀ ∧ X = f '' X₀ := by
refine ⟨fun h ↦ ?_, ?_⟩
· obtain ⟨I, hI, rfl⟩ := subset_image_iff.1 h.indep.subset_ground
obtain ⟨X, hX, rfl⟩ := subset_image_iff.1 h.subset_ground
rw [map_basis_iff _ _ hI hX] at h
exact ⟨I, X, h, rfl, rfl⟩
rintro ⟨I, X, hIX, rfl, rfl⟩
exact hIX.map hf
@[simp] lemma map_dual {hf} : (M.map f hf)✶ = M✶.map f hf := by
apply eq_of_base_iff_base_forall (by simp)
simp only [dual_ground, map_ground, subset_image_iff, forall_exists_index, and_imp,
forall_apply_eq_imp_iff₂, dual_base_iff']
intro B hB
simp_rw [← hf.image_diff_subset hB, map_image_base_iff diff_subset,
map_image_base_iff (show B ⊆ M✶.E from hB), dual_base_iff hB, and_iff_left_iff_imp]
exact fun _ ↦ ⟨B, hB, rfl⟩
@[simp] lemma map_emptyOn (f : α → β) : (emptyOn α).map f (by simp) = emptyOn β := by
simp [← ground_eq_empty_iff]
@[simp] lemma map_loopyOn (f : α → β) (hf) : (loopyOn E).map f hf = loopyOn (f '' E) := by
simp [eq_loopyOn_iff]
@[simp] lemma map_freeOn (f : α → β) (hf) : (freeOn E).map f hf = freeOn (f '' E) := by
rw [← dual_inj]; simp
@[simp] lemma map_id : M.map id (injOn_id M.E) = M := by
simp [eq_iff_indep_iff_indep_forall]
lemma map_comap {f : α → β} (h_range : N.E ⊆ range f) (hf : InjOn f (f ⁻¹' N.E)) :
(N.comap f).map f hf = N := by
refine eq_of_indep_iff_indep_forall (by simpa [image_preimage_eq_iff]) ?_
simp only [map_ground, comap_ground_eq, map_indep_iff, comap_indep_iff, forall_subset_image_iff]
refine fun I hI ↦ ⟨fun ⟨I₀, ⟨hI₀, _⟩, hII₀⟩ ↦ ?_, fun h ↦ ⟨_, ⟨h, hf.mono hI⟩, rfl⟩⟩
suffices h : I₀ ⊆ f ⁻¹' N.E by rw [InjOn.image_eq_image_iff hf hI h] at hII₀; rwa [hII₀]
exact (subset_preimage_image f I₀).trans <| preimage_mono (f := f) hI₀.subset_ground
lemma comap_map {f : α → β} (hf : f.Injective) : (M.map f hf.injOn).comap f = M := by
simp [eq_iff_indep_iff_indep_forall, preimage_image_eq _ hf, and_iff_left hf.injOn,
image_eq_image hf]
instance [M.Nonempty] {f : α → β} (hf) : (M.map f hf).Nonempty :=
⟨by simp [M.ground_nonempty]⟩
instance [M.Finite] {f : α → β} (hf) : (M.map f hf).Finite :=
⟨M.ground_finite.image f⟩
instance [M.Finitary] {f : α → β} (hf) : (M.map f hf).Finitary := by
refine ⟨fun I hI ↦ ?_⟩
simp only [map_indep_iff]
have h' : I ⊆ f '' M.E := by
intro e he
obtain ⟨I₀, hI₀, h_eq⟩ := hI {e} (by simpa) (by simp)
exact image_subset f hI₀.subset_ground <| h_eq.subset rfl
obtain ⟨I₀, hI₀E, rfl⟩ := subset_image_iff.1 h'
refine ⟨I₀, indep_of_forall_finite_subset_indep _ fun J₀ hJ₀I₀ hJ₀ ↦ ?_, rfl⟩
specialize hI (f '' J₀) (image_subset f hJ₀I₀) (hJ₀.image _)
rwa [map_image_indep_iff (hJ₀I₀.trans hI₀E)] at hI
instance [M.FiniteRk] {f : α → β} (hf) : (M.map f hf).FiniteRk :=
let ⟨_, hB⟩ := M.exists_base
(hB.map hf).finiteRk_of_finite (hB.finite.image _)
instance [M.RkPos] {f : α → β} (hf) : (M.map f hf).RkPos :=
let ⟨_, hB⟩ := M.exists_base
(hB.map hf).rkPos_of_nonempty (hB.nonempty.image _)
end map
section mapSetEquiv
/-- Map `M : Matroid α` to a `Matroid β` with ground set `E` using an equivalence `M.E ≃ E`.
Defined using `Matroid.ofExistsMatroid` for better defeq. -/
def mapSetEquiv (M : Matroid α) {E : Set β} (e : M.E ≃ E) : Matroid β :=
Matroid.ofExistsMatroid E (fun I ↦ (M.Indep ↑(e.symm '' (E ↓∩ I)) ∧ I ⊆ E))
⟨M.mapSetEmbedding (e.toEmbedding.trans <| Function.Embedding.subtype _), by
have hrw : ∀ I : Set β, Subtype.val ∘ ⇑e ⁻¹' I = ⇑e.symm '' E ↓∩ I := fun I ↦ by ext; simp
simp [Equiv.toEmbedding, Embedding.subtype, Embedding.trans, hrw]⟩
@[simp] lemma mapSetEquiv_indep_iff (M : Matroid α) {E : Set β} (e : M.E ≃ E) {I : Set β} :
(M.mapSetEquiv e).Indep I ↔ M.Indep ↑(e.symm '' (E ↓∩ I)) ∧ I ⊆ E := Iff.rfl
@[simp] lemma mapSetEquiv.ground (M : Matroid α) {E : Set β} (e : M.E ≃ E) :
(M.mapSetEquiv e).E = E := rfl
end mapSetEquiv
section mapEmbedding
/-- Map `M : Matroid α` across an embedding defined on all of `α` -/
def mapEmbedding (M : Matroid α) (f : α ↪ β) : Matroid β := M.map f f.injective.injOn
@[simp] lemma mapEmbedding_ground_eq (M : Matroid α) (f : α ↪ β) :
(M.mapEmbedding f).E = f '' M.E := rfl
@[simp] lemma mapEmbedding_indep_iff {f : α ↪ β} {I : Set β} :
(M.mapEmbedding f).Indep I ↔ M.Indep (f ⁻¹' I) ∧ I ⊆ range f := by
rw [mapEmbedding, map_indep_iff]
refine ⟨?_, fun ⟨h,h'⟩ ↦ ⟨f ⁻¹' I, h, by rwa [eq_comm, image_preimage_eq_iff]⟩⟩
rintro ⟨I, hI, rfl⟩
rw [preimage_image_eq _ f.injective]
exact ⟨hI, image_subset_range _ _⟩
lemma Indep.mapEmbedding (hI : M.Indep I) (f : α ↪ β) : (M.mapEmbedding f).Indep (f '' I) := by
simpa [preimage_image_eq I f.injective]
lemma Base.mapEmbedding {B : Set α} (hB : M.Base B) (f : α ↪ β) :
(M.mapEmbedding f).Base (f '' B) := by
rw [Matroid.mapEmbedding, map_base_iff]
exact ⟨B, hB, rfl⟩
lemma Basis.mapEmbedding {X : Set α} (hIX : M.Basis I X) (f : α ↪ β) :
(M.mapEmbedding f).Basis (f '' I) (f '' X) := by
apply hIX.map
@[simp] lemma mapEmbedding_base_iff {f : α ↪ β} {B : Set β} :
(M.mapEmbedding f).Base B ↔ M.Base (f ⁻¹' B) ∧ B ⊆ range f := by
rw [mapEmbedding, map_base_iff]
refine ⟨?_, fun ⟨h,h'⟩ ↦ ⟨f ⁻¹' B, h, by rwa [eq_comm, image_preimage_eq_iff]⟩⟩
rintro ⟨B, hB, rfl⟩
rw [preimage_image_eq _ f.injective]
exact ⟨hB, image_subset_range _ _⟩
@[simp] lemma mapEmbedding_basis_iff {f : α ↪ β} {I X : Set β} :
(M.mapEmbedding f).Basis I X ↔ M.Basis (f ⁻¹' I) (f ⁻¹' X) ∧ I ⊆ X ∧ X ⊆ range f := by
rw [mapEmbedding, map_basis_iff']
refine ⟨?_, fun ⟨hb, hIX, hX⟩ ↦ ?_⟩
· rintro ⟨I, X, hIX, rfl, rfl⟩
simp [preimage_image_eq _ f.injective, image_subset f hIX.subset, hIX]
obtain ⟨X, rfl⟩ := subset_range_iff_exists_image_eq.1 hX
obtain ⟨I, -, rfl⟩ := subset_image_iff.1 hIX
exact ⟨I, X, by simpa [preimage_image_eq _ f.injective] using hb⟩
instance [M.Nonempty] {f : α ↪ β} : (M.mapEmbedding f).Nonempty :=
inferInstanceAs (M.map f f.injective.injOn).Nonempty
instance [M.Finite] {f : α ↪ β} : (M.mapEmbedding f).Finite :=
inferInstanceAs (M.map f f.injective.injOn).Finite
instance [M.Finitary] {f : α ↪ β} : (M.mapEmbedding f).Finitary :=
inferInstanceAs (M.map f f.injective.injOn).Finitary
instance [M.FiniteRk] {f : α ↪ β} : (M.mapEmbedding f).FiniteRk :=
inferInstanceAs (M.map f f.injective.injOn).FiniteRk
instance [M.RkPos] {f : α ↪ β} : (M.mapEmbedding f).RkPos :=
inferInstanceAs (M.map f f.injective.injOn).RkPos
end mapEmbedding
section mapEquiv
variable {f : α ≃ β}
/-- Map `M : Matroid α` across an equivalence `α ≃ β` -/
def mapEquiv (M : Matroid α) (f : α ≃ β) : Matroid β := M.mapEmbedding f.toEmbedding
@[simp] lemma mapEquiv_ground_eq (M : Matroid α) (f : α ≃ β) :
(M.mapEquiv f).E = f '' M.E := rfl
lemma mapEquiv_eq_map (f : α ≃ β) : M.mapEquiv f = M.map f f.injective.injOn := rfl
@[simp] lemma mapEquiv_indep_iff {I : Set β} : (M.mapEquiv f).Indep I ↔ M.Indep (f.symm '' I) := by
rw [mapEquiv_eq_map, map_indep_iff]
exact ⟨by rintro ⟨I, hI, rfl⟩; simpa, fun h ↦ ⟨_, h, by simp⟩⟩
@[simp] lemma mapEquiv_dep_iff {D : Set β} : (M.mapEquiv f).Dep D ↔ M.Dep (f.symm '' D) := by
rw [mapEquiv_eq_map, map_dep_iff]
exact ⟨by rintro ⟨I, hI, rfl⟩; simpa, fun h ↦ ⟨_, h, by simp⟩⟩
@[simp] lemma mapEquiv_base_iff {B : Set β} : (M.mapEquiv f).Base B ↔ M.Base (f.symm '' B) := by
rw [mapEquiv_eq_map, map_base_iff]
exact ⟨by rintro ⟨I, hI, rfl⟩; simpa, fun h ↦ ⟨_, h, by simp⟩⟩
@[simp] lemma mapEquiv_basis_iff {α β : Type*} {M : Matroid α} (f : α ≃ β) {I X : Set β} :
(M.mapEquiv f).Basis I X ↔ M.Basis (f.symm '' I) (f.symm '' X) := by
rw [mapEquiv_eq_map, map_basis_iff']
refine ⟨fun h ↦ ?_, fun h ↦ ⟨_, _, h, by simp, by simp⟩⟩
obtain ⟨I, X, hIX, rfl, rfl⟩ := h
simpa
instance [M.Nonempty] {f : α ≃ β} : (M.mapEquiv f).Nonempty :=
inferInstanceAs (M.map f f.injective.injOn).Nonempty
instance [M.Finite] {f : α ≃ β} : (M.mapEquiv f).Finite :=
inferInstanceAs (M.map f f.injective.injOn).Finite
instance [M.Finitary] {f : α ≃ β} : (M.mapEquiv f).Finitary :=
inferInstanceAs (M.map f f.injective.injOn).Finitary
instance [M.FiniteRk] {f : α ≃ β} : (M.mapEquiv f).FiniteRk :=
inferInstanceAs (M.map f f.injective.injOn).FiniteRk
instance [M.RkPos] {f : α ≃ β} : (M.mapEquiv f).RkPos :=
inferInstanceAs (M.map f f.injective.injOn).RkPos
end mapEquiv
section restrictSubtype
variable {E X I : Set α} {M : Matroid α}
/-- Given `M : Matroid α` and `X : Set α`, the restriction of `M` to `X`,
viewed as a matroid on type `X` with ground set `univ`.
Always isomorphic to `M ↾ X`. If `X = M.E`, then isomorphic to `M`. -/
def restrictSubtype (M : Matroid α) (X : Set α) : Matroid X := (M ↾ X).comap (↑)
@[simp] lemma restrictSubtype_ground : (M.restrictSubtype X).E = univ := by
simp [restrictSubtype]
@[simp] lemma restrictSubtype_indep_iff {I : Set X} :
(M.restrictSubtype X).Indep I ↔ M.Indep ((↑) '' I) := by
simp [restrictSubtype, Subtype.val_injective.injOn]
lemma restrictSubtype_indep_iff_of_subset (hIX : I ⊆ X) :
(M.restrictSubtype X).Indep (X ↓∩ I) ↔ M.Indep I := by
rw [restrictSubtype_indep_iff, image_preimage_eq_iff.2]; simpa
lemma restrictSubtype_inter_indep_iff :
(M.restrictSubtype X).Indep (X ↓∩ I) ↔ M.Indep (X ∩ I) := by
simp [restrictSubtype, Subtype.val_injective.injOn]
lemma restrictSubtype_basis_iff {Y : Set α} {I X : Set Y} :
(M.restrictSubtype Y).Basis I X ↔ M.Basis' I X := by
rw [restrictSubtype, comap_basis_iff, and_iff_right Subtype.val_injective.injOn,
and_iff_left_of_imp, basis_restrict_iff', basis'_iff_basis_inter_ground]
· simp
exact fun h ↦ (image_subset_image_iff Subtype.val_injective).1 h.subset
lemma restrictSubtype_base_iff {B : Set X} : (M.restrictSubtype X).Base B ↔ M.Basis' B X := by
rw [restrictSubtype, comap_base_iff]
simp [Subtype.val_injective.injOn, Subset.rfl, basis_restrict_iff', basis'_iff_basis_inter_ground]
@[simp] lemma restrictSubtype_ground_base_iff {B : Set M.E} :
(M.restrictSubtype M.E).Base B ↔ M.Base B := by
rw [restrictSubtype_base_iff, basis'_iff_basis, basis_ground_iff]
@[simp] lemma restrictSubtype_ground_basis_iff {I X : Set M.E} :
(M.restrictSubtype M.E).Basis I X ↔ M.Basis I X := by
rw [restrictSubtype_basis_iff, basis'_iff_basis]
lemma eq_of_restrictSubtype_eq {N : Matroid α} (hM : M.E = E) (hN : N.E = E)
(h : M.restrictSubtype E = N.restrictSubtype E) : M = N := by
subst hM
refine eq_of_indep_iff_indep_forall (by rw [hN]) (fun I hI ↦ ?_)
rwa [← restrictSubtype_indep_iff_of_subset hI, h, restrictSubtype_indep_iff_of_subset]
@[simp] lemma restrictSubtype_dual : (M.restrictSubtype M.E)✶ = M✶.restrictSubtype M.E := by
rw [restrictSubtype, ← comapOn_preimage_eq, comapOn_dual_eq_of_bijOn, restrict_ground_eq_self,
← dual_ground, comapOn_preimage_eq, restrictSubtype, restrict_ground_eq_self]
exact ⟨by simp [MapsTo], Subtype.val_injective.injOn, by simp [SurjOn, Subset.rfl]⟩
lemma restrictSubtype_dual' (hM : M.E = E) : (M.restrictSubtype E)✶ = M✶.restrictSubtype E := by
rw [← hM, restrictSubtype_dual]
/-- `M.restrictSubtype X` is isomorphic to `M ↾ X`. -/
@[simp] lemma map_val_restrictSubtype_eq (M : Matroid α) (X : Set α) :
(M.restrictSubtype X).map (↑) Subtype.val_injective.injOn = M ↾ X := by
simp [restrictSubtype, map_comap, Subset.rfl]
/-- `M.restrictSubtype M.E` is isomorphic to `M`. -/
lemma map_val_restrictSubtype_ground_eq (M : Matroid α) :
(M.restrictSubtype M.E).map (↑) Subtype.val_injective.injOn = M := by
simp
instance [M.Finitary] {X : Set α} : (M.restrictSubtype X).Finitary := by
rw [restrictSubtype]; infer_instance
instance [M.FiniteRk] {X : Set α} : (M.restrictSubtype X).FiniteRk := by
rw [restrictSubtype]; infer_instance
instance [M.Finite] : (M.restrictSubtype M.E).Finite :=
have := M.ground_finite.to_subtype
⟨Finite.ground_finite⟩
instance [M.Nonempty] : (M.restrictSubtype M.E).Nonempty :=
have := M.ground_nonempty.coe_sort
⟨by simp⟩
instance [M.RkPos] : (M.restrictSubtype M.E).RkPos := by
obtain ⟨B, hB⟩ := (M.restrictSubtype M.E).exists_base
have hB' : M.Base ↑B := by simpa using hB.map Subtype.val_injective.injOn
exact hB.rkPos_of_nonempty <| by simpa using hB'.nonempty
end restrictSubtype
end Matroid
|
Data\Matroid\Restrict.lean | /-
Copyright (c) 2023 Peter Nelson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Peter Nelson
-/
import Mathlib.Data.Matroid.Dual
/-!
# Matroid Restriction
Given `M : Matroid α` and `R : Set α`, the independent sets of `M` that are contained in `R`
are the independent sets of another matroid `M ↾ R` with ground set `R`,
called the 'restriction' of `M` to `R`.
For `I, R ⊆ M.E`, `I` is a basis of `R` in `M` if and only if `I` is a base
of the restriction `M ↾ R`, so this construction relates `Matroid.Basis` to `Matroid.Base`.
If `N M : Matroid α` satisfy `N = M ↾ R` for some `R ⊆ M.E`,
then we call `N` a 'restriction of `M`', and write `N ≤r M`. This is a partial order.
This file proves that the restriction is a matroid and that the `≤r` order is a partial order,
and gives related API.
It also proves some `Basis` analogues of `Base` lemmas that, while they could be stated in
`Data.Matroid.Basic`, are hard to prove without `Matroid.restrict` API.
## Main Definitions
* `M.restrict R`, written `M ↾ R`, is the restriction of `M : Matroid α` to `R : Set α`: i.e.
the matroid with ground set `R` whose independent sets are the `M`-independent subsets of `R`.
* `Matroid.Restriction N M`, written `N ≤r M`, means that `N = M ↾ R` for some `R ⊆ M.E`.
* `Matroid.StrictRestriction N M`, written `N <r M`, means that `N = M ↾ R` for some `R ⊂ M.E`.
* `Matroidᵣ α` is a type synonym for `Matroid α`, equipped with the `PartialOrder` `≤r`.
## Implementation Notes
Since `R` and `M.E` are both terms in `Set α`, to define the restriction `M ↾ R`,
we need to either insist that `R ⊆ M.E`, or to say what happens when `R` contains the junk
outside `M.E`.
It turns out that `R ⊆ M.E` is just an unnecessary hypothesis; if we say the restriction
`M ↾ R` has ground set `R` and its independent sets are the `M`-independent subsets of `R`,
we always get a matroid, in which the elements of `R \ M.E` aren't in any independent sets.
We could instead define this matroid to always be 'smaller' than `M` by setting
`(M ↾ R).E := R ∩ M.E`, but this is worse definitionally, and more generally less convenient.
This makes it possible to actually restrict a matroid 'upwards'; for instance, if `M : Matroid α`
satisfies `M.E = ∅`, then `M ↾ Set.univ` is the matroid on `α` whose ground set is all of `α`,
where the empty set is only the independent set.
(Elements of `R` outside the ground set are all 'loops' of the matroid.)
This is mathematically strange, but is useful for API building.
The cost of allowing a restriction of `M` to be 'bigger' than the `M` itself is that
the statement `M ↾ R ≤r M` is only true with the hypothesis `R ⊆ M.E`
(at least, if we want `≤r` to be a partial order).
But this isn't too inconvenient in practice. Indeed `(· ⊆ M.E)` proofs
can often be automatically provided by `aesop_mat`.
We define the restriction order `≤r` to give a `PartialOrder` instance on the type synonym
`Matroidᵣ α` rather than `Matroid α` itself, because the `PartialOrder (Matroid α)` instance is
reserved for the more mathematically important 'minor' order.
-/
open Set
namespace Matroid
variable {α : Type*} {M : Matroid α} {R I J X Y : Set α}
section restrict
/-- The `IndepMatroid` whose independent sets are the independent subsets of `R`. -/
@[simps] def restrictIndepMatroid (M : Matroid α) (R : Set α) : IndepMatroid α where
E := R
Indep I := M.Indep I ∧ I ⊆ R
indep_empty := ⟨M.empty_indep, empty_subset _⟩
indep_subset := fun I J h hIJ ↦ ⟨h.1.subset hIJ, hIJ.trans h.2⟩
indep_aug := by
rintro I I' ⟨hI, hIY⟩ (hIn : ¬ M.Basis' I R) (hI' : M.Basis' I' R)
rw [basis'_iff_basis_inter_ground] at hIn hI'
obtain ⟨B', hB', rfl⟩ := hI'.exists_base
obtain ⟨B, hB, hIB, hBIB'⟩ := hI.exists_base_subset_union_base hB'
rw [hB'.inter_basis_iff_compl_inter_basis_dual, diff_inter_diff] at hI'
have hss : M.E \ (B' ∪ (R ∩ M.E)) ⊆ M.E \ (B ∪ (R ∩ M.E)) := by
apply diff_subset_diff_right
rw [union_subset_iff, and_iff_left subset_union_right, union_comm]
exact hBIB'.trans (union_subset_union_left _ (subset_inter hIY hI.subset_ground))
have hi : M✶.Indep (M.E \ (B ∪ (R ∩ M.E))) := by
rw [dual_indep_iff_exists]
exact ⟨B, hB, disjoint_of_subset_right subset_union_left disjoint_sdiff_left⟩
have h_eq := hI'.eq_of_subset_indep hi hss
(diff_subset_diff_right subset_union_right)
rw [h_eq, ← diff_inter_diff, ← hB.inter_basis_iff_compl_inter_basis_dual] at hI'
obtain ⟨J, hJ, hIJ⟩ := hI.subset_basis_of_subset
(subset_inter hIB (subset_inter hIY hI.subset_ground))
obtain rfl := hI'.indep.eq_of_basis hJ
have hIJ' : I ⊂ B ∩ (R ∩ M.E) := hIJ.ssubset_of_ne (fun he ↦ hIn (by rwa [he]))
obtain ⟨e, he⟩ := exists_of_ssubset hIJ'
exact ⟨e, ⟨⟨(hBIB' he.1.1).elim (fun h ↦ (he.2 h).elim) id,he.1.2⟩, he.2⟩,
hI'.indep.subset (insert_subset he.1 hIJ), insert_subset he.1.2.1 hIY⟩
indep_maximal := by
rintro A hAR I ⟨hI, _⟩ hIA
obtain ⟨J, hJ, hIJ⟩ := hI.subset_basis'_of_subset hIA
use J
simp only [hIJ, and_assoc, maximal_subset_iff, hJ.indep, hJ.subset, and_imp, true_and,
hJ.subset.trans hAR]
exact fun K hK _ hKA hJK ↦ hJ.eq_of_subset_indep hK hJK hKA
subset_ground I := And.right
/-- Change the ground set of a matroid to some `R : Set α`. The independent sets of the restriction
are the independent subsets of the new ground set. Most commonly used when `R ⊆ M.E`,
but it is convenient not to require this. The elements of `R \ M.E` become 'loops'. -/
def restrict (M : Matroid α) (R : Set α) : Matroid α := (M.restrictIndepMatroid R).matroid
/-- `M ↾ R` means `M.restrict R`. -/
scoped infixl:65 " ↾ " => Matroid.restrict
@[simp] theorem restrict_indep_iff : (M ↾ R).Indep I ↔ M.Indep I ∧ I ⊆ R := Iff.rfl
theorem Indep.indep_restrict_of_subset (h : M.Indep I) (hIR : I ⊆ R) : (M ↾ R).Indep I :=
restrict_indep_iff.mpr ⟨h,hIR⟩
theorem Indep.of_restrict (hI : (M ↾ R).Indep I) : M.Indep I :=
(restrict_indep_iff.1 hI).1
@[simp] theorem restrict_ground_eq : (M ↾ R).E = R := rfl
theorem restrict_finite {R : Set α} (hR : R.Finite) : (M ↾ R).Finite :=
⟨hR⟩
@[simp] theorem restrict_dep_iff : (M ↾ R).Dep X ↔ ¬ M.Indep X ∧ X ⊆ R := by
rw [Dep, restrict_indep_iff, restrict_ground_eq]; tauto
@[simp] theorem restrict_ground_eq_self (M : Matroid α) : (M ↾ M.E) = M := by
refine eq_of_indep_iff_indep_forall rfl ?_; aesop
theorem restrict_restrict_eq {R₁ R₂ : Set α} (M : Matroid α) (hR : R₂ ⊆ R₁) :
(M ↾ R₁) ↾ R₂ = M ↾ R₂ := by
refine eq_of_indep_iff_indep_forall rfl ?_
simp only [restrict_ground_eq, restrict_indep_iff, and_congr_left_iff, and_iff_left_iff_imp]
exact fun _ h _ _ ↦ h.trans hR
@[simp] theorem restrict_idem (M : Matroid α) (R : Set α) : M ↾ R ↾ R = M ↾ R := by
rw [M.restrict_restrict_eq Subset.rfl]
@[simp] theorem base_restrict_iff (hX : X ⊆ M.E := by aesop_mat) :
(M ↾ X).Base I ↔ M.Basis I X := by
simp_rw [base_iff_maximal_indep, Basis, and_iff_left hX, maximal_iff, restrict_indep_iff]
theorem base_restrict_iff' : (M ↾ X).Base I ↔ M.Basis' I X := by
simp_rw [base_iff_maximal_indep, Basis', maximal_iff, restrict_indep_iff]
theorem Basis.restrict_base (h : M.Basis I X) : (M ↾ X).Base I :=
(base_restrict_iff h.subset_ground).2 h
instance restrict_finiteRk [M.FiniteRk] (R : Set α) : (M ↾ R).FiniteRk :=
let ⟨_, hB⟩ := (M ↾ R).exists_base
hB.finiteRk_of_finite (hB.indep.of_restrict.finite)
instance restrict_finitary [Finitary M] (R : Set α) : Finitary (M ↾ R) := by
refine ⟨fun I hI ↦ ?_⟩
simp only [restrict_indep_iff] at *
rw [indep_iff_forall_finite_subset_indep]
exact ⟨fun J hJ hJfin ↦ (hI J hJ hJfin).1,
fun e heI ↦ singleton_subset_iff.1 (hI _ (by simpa) (toFinite _)).2⟩
@[simp] theorem Basis.base_restrict (h : M.Basis I X) : (M ↾ X).Base I :=
(base_restrict_iff h.subset_ground).mpr h
theorem Basis.basis_restrict_of_subset (hI : M.Basis I X) (hXY : X ⊆ Y) : (M ↾ Y).Basis I X := by
rwa [← base_restrict_iff, M.restrict_restrict_eq hXY, base_restrict_iff]
theorem basis'_restrict_iff : (M ↾ R).Basis' I X ↔ M.Basis' I (X ∩ R) ∧ I ⊆ R := by
simp_rw [Basis', maximal_iff, restrict_indep_iff, subset_inter_iff, and_imp]
tauto
theorem basis_restrict_iff' : (M ↾ R).Basis I X ↔ M.Basis I (X ∩ M.E) ∧ X ⊆ R := by
rw [basis_iff_basis'_subset_ground, basis'_restrict_iff, restrict_ground_eq, and_congr_left_iff,
← basis'_iff_basis_inter_ground]
intro hXR
rw [inter_eq_self_of_subset_left hXR, and_iff_left_iff_imp]
exact fun h ↦ h.subset.trans hXR
theorem basis_restrict_iff (hR : R ⊆ M.E := by aesop_mat) :
(M ↾ R).Basis I X ↔ M.Basis I X ∧ X ⊆ R := by
rw [basis_restrict_iff', and_congr_left_iff]
intro hXR
rw [← basis'_iff_basis_inter_ground, basis'_iff_basis]
theorem restrict_eq_restrict_iff (M M' : Matroid α) (X : Set α) :
M ↾ X = M' ↾ X ↔ ∀ I, I ⊆ X → (M.Indep I ↔ M'.Indep I) := by
refine ⟨fun h I hIX ↦ ?_, fun h ↦ eq_of_indep_iff_indep_forall rfl fun I (hI : I ⊆ X) ↦ ?_⟩
· rw [← and_iff_left (a := (M.Indep I)) hIX, ← and_iff_left (a := (M'.Indep I)) hIX,
← restrict_indep_iff, h, restrict_indep_iff]
rw [restrict_indep_iff, and_iff_left hI, restrict_indep_iff, and_iff_left hI, h _ hI]
@[simp] theorem restrict_eq_self_iff : M ↾ R = M ↔ R = M.E :=
⟨fun h ↦ by rw [← h]; rfl, fun h ↦ by simp [h]⟩
end restrict
section Restriction
variable {N : Matroid α}
/-- `Restriction N M` means that `N = M ↾ R` for some subset `R` of `M.E` -/
def Restriction (N M : Matroid α) : Prop := ∃ R ⊆ M.E, N = M ↾ R
/-- `StrictRestriction N M` means that `N = M ↾ R` for some strict subset `R` of `M.E` -/
def StrictRestriction (N M : Matroid α) : Prop := Restriction N M ∧ ¬ Restriction M N
/-- `N ≤r M` means that `N` is a `Restriction` of `M`. -/
scoped infix:50 " ≤r " => Restriction
/-- `N <r M` means that `N` is a `StrictRestriction` of `M`. -/
scoped infix:50 " <r " => StrictRestriction
/-- A type synonym for matroids with the restriction order.
(The `PartialOrder` on `Matroid α` is reserved for the minor order) -/
@[ext] structure Matroidᵣ (α : Type*) where ofMatroid ::
/-- The underlying `Matroid`.-/
toMatroid : Matroid α
instance {α : Type*} : CoeOut (Matroidᵣ α) (Matroid α) where
coe := Matroidᵣ.toMatroid
@[simp] theorem Matroidᵣ.coe_inj {M₁ M₂ : Matroidᵣ α} :
(M₁ : Matroid α) = (M₂ : Matroid α) ↔ M₁ = M₂ := by
cases M₁; cases M₂; simp
instance {α : Type*} : PartialOrder (Matroidᵣ α) where
le := (· ≤r ·)
le_refl M := ⟨(M : Matroid α).E, Subset.rfl, (M : Matroid α).restrict_ground_eq_self.symm⟩
le_trans M₁ M₂ M₃ := by
rintro ⟨R, hR, h₁⟩ ⟨R', hR', h₂⟩
change _ ≤r _
rw [h₂] at h₁ hR
rw [h₁, restrict_restrict_eq _ (show R ⊆ R' from hR)]
exact ⟨R, hR.trans hR', rfl⟩
le_antisymm M₁ M₂ := by
rintro ⟨R, hR, h⟩ ⟨R', hR', h'⟩
rw [h', restrict_ground_eq] at hR
rw [h, restrict_ground_eq] at hR'
rw [← Matroidᵣ.coe_inj, h, h', hR.antisymm hR', restrict_idem]
@[simp] protected theorem Matroidᵣ.le_iff {M M' : Matroidᵣ α} :
M ≤ M' ↔ (M : Matroid α) ≤r (M' : Matroid α) := Iff.rfl
@[simp] protected theorem Matroidᵣ.lt_iff {M M' : Matroidᵣ α} :
M < M' ↔ (M : Matroid α) <r (M' : Matroid α) := Iff.rfl
theorem ofMatroid_le_iff {M M' : Matroid α} :
Matroidᵣ.ofMatroid M ≤ Matroidᵣ.ofMatroid M' ↔ M ≤r M' := by
simp
theorem ofMatroid_lt_iff {M M' : Matroid α} :
Matroidᵣ.ofMatroid M < Matroidᵣ.ofMatroid M' ↔ M <r M' := by
simp
theorem Restriction.refl : M ≤r M :=
le_refl (Matroidᵣ.ofMatroid M)
theorem Restriction.antisymm {M' : Matroid α} (h : M ≤r M') (h' : M' ≤r M) : M = M' := by
simpa using (ofMatroid_le_iff.2 h).antisymm (ofMatroid_le_iff.2 h')
theorem Restriction.trans {M₁ M₂ M₃ : Matroid α} (h : M₁ ≤r M₂) (h' : M₂ ≤r M₃) : M₁ ≤r M₃ :=
le_trans (α := Matroidᵣ α) h h'
theorem restrict_restriction (M : Matroid α) (R : Set α) (hR : R ⊆ M.E := by aesop_mat) :
M ↾ R ≤r M :=
⟨R, hR, rfl⟩
theorem Restriction.eq_restrict (h : N ≤r M) : M ↾ N.E = N := by
obtain ⟨R, -, rfl⟩ := h; rw [restrict_ground_eq]
theorem Restriction.subset (h : N ≤r M) : N.E ⊆ M.E := by
obtain ⟨R, hR, rfl⟩ := h; exact hR
theorem Restriction.exists_eq_restrict (h : N ≤r M) : ∃ R ⊆ M.E, N = M ↾ R :=
h
theorem Restriction.of_subset {R' : Set α} (M : Matroid α) (h : R ⊆ R') : (M ↾ R) ≤r (M ↾ R') := by
rw [← restrict_restrict_eq M h]; exact restrict_restriction _ _ h
theorem restriction_iff_exists : (N ≤r M) ↔ ∃ R, R ⊆ M.E ∧ N = M ↾ R := by
use Restriction.exists_eq_restrict; rintro ⟨R, hR, rfl⟩; exact restrict_restriction M R hR
theorem StrictRestriction.restriction (h : N <r M) : N ≤r M :=
h.1
theorem StrictRestriction.ne (h : N <r M) : N ≠ M := by
rintro rfl; rw [← ofMatroid_lt_iff] at h; simp at h
theorem StrictRestriction.irrefl (M : Matroid α) : ¬ (M <r M) :=
fun h ↦ h.ne rfl
theorem StrictRestriction.ssubset (h : N <r M) : N.E ⊂ M.E := by
obtain ⟨R, -, rfl⟩ := h.1
refine h.restriction.subset.ssubset_of_ne (fun h' ↦ h.2 ⟨R, Subset.rfl, ?_⟩)
rw [show R = M.E from h', restrict_idem, restrict_ground_eq_self]
theorem StrictRestriction.eq_restrict (h : N <r M) : M ↾ N.E = N :=
h.restriction.eq_restrict
theorem StrictRestriction.exists_eq_restrict (h : N <r M) : ∃ R, R ⊂ M.E ∧ N = M ↾ R :=
⟨N.E, h.ssubset, by rw [h.eq_restrict]⟩
theorem Restriction.strictRestriction_of_ne (h : N ≤r M) (hne : N ≠ M) : N <r M :=
⟨h, fun h' ↦ hne <| h.antisymm h'⟩
theorem Restriction.eq_or_strictRestriction (h : N ≤r M) : N = M ∨ N <r M := by
simpa using eq_or_lt_of_le (ofMatroid_le_iff.2 h)
theorem restrict_strictRestriction {M : Matroid α} (hR : R ⊂ M.E) : M ↾ R <r M := by
refine (M.restrict_restriction R hR.subset).strictRestriction_of_ne (fun h ↦ ?_)
rw [← h, restrict_ground_eq] at hR
exact hR.ne rfl
theorem Restriction.strictRestriction_of_ground_ne (h : N ≤r M) (hne : N.E ≠ M.E) : N <r M := by
rw [← h.eq_restrict]
exact restrict_strictRestriction (h.subset.ssubset_of_ne hne)
theorem StrictRestriction.of_ssubset {R' : Set α} (M : Matroid α) (h : R ⊂ R') :
(M ↾ R) <r (M ↾ R') :=
(Restriction.of_subset M h.subset).strictRestriction_of_ground_ne h.ne
theorem Restriction.finite {M : Matroid α} [M.Finite] (h : N ≤r M) : N.Finite := by
obtain ⟨R, hR, rfl⟩ := h
exact restrict_finite <| M.ground_finite.subset hR
theorem Restriction.finiteRk {M : Matroid α} [FiniteRk M] (h : N ≤r M) : N.FiniteRk := by
obtain ⟨R, -, rfl⟩ := h
infer_instance
theorem Restriction.finitary {M : Matroid α} [Finitary M] (h : N ≤r M) : N.Finitary := by
obtain ⟨R, -, rfl⟩ := h
infer_instance
theorem finite_setOf_restriction (M : Matroid α) [M.Finite] : {N | N ≤r M}.Finite :=
(M.ground_finite.finite_subsets.image (fun R ↦ M ↾ R)).subset <|
by rintro _ ⟨R, hR, rfl⟩; exact ⟨_, hR, rfl⟩
theorem Indep.of_restriction (hI : N.Indep I) (hNM : N ≤r M) : M.Indep I := by
obtain ⟨R, -, rfl⟩ := hNM; exact hI.of_restrict
theorem Indep.indep_restriction (hI : M.Indep I) (hNM : N ≤r M) (hIN : I ⊆ N.E) : N.Indep I := by
obtain ⟨R, -, rfl⟩ := hNM; simpa [hI]
theorem Basis.basis_restriction (hI : M.Basis I X) (hNM : N ≤r M) (hX : X ⊆ N.E) : N.Basis I X := by
obtain ⟨R, hR, rfl⟩ := hNM; rwa [basis_restrict_iff, and_iff_left (show X ⊆ R from hX)]
theorem Basis.of_restriction (hI : N.Basis I X) (hNM : N ≤r M) : M.Basis I X := by
obtain ⟨R, hR, rfl⟩ := hNM; exact ((basis_restrict_iff hR).1 hI).1
theorem Base.basis_of_restriction (hI : N.Base I) (hNM : N ≤r M) : M.Basis I N.E := by
obtain ⟨R, hR, rfl⟩ := hNM; rwa [base_restrict_iff] at hI
theorem Dep.of_restriction (hX : N.Dep X) (hNM : N ≤r M) : M.Dep X := by
obtain ⟨R, hR, rfl⟩ := hNM
rw [restrict_dep_iff] at hX
exact ⟨hX.1, hX.2.trans hR⟩
theorem Dep.dep_restriction (hX : M.Dep X) (hNM : N ≤r M) (hXE : X ⊆ N.E := by aesop_mat) :
N.Dep X := by
obtain ⟨R, -, rfl⟩ := hNM; simpa [hX.not_indep]
end Restriction
/-!
### `Basis` and `Base`
The lemmas below exploit the fact that `(M ↾ X).Base I ↔ M.Basis I X` to transfer facts about
`Matroid.Base` to facts about `Matroid.Basis`.
Their statements thematically belong in `Data.Matroid.Basic`, but they appear here because their
proofs depend on the API for `Matroid.restrict`,
-/
section Basis
variable {B J : Set α} {e : α}
theorem Basis.transfer (hIX : M.Basis I X) (hJX : M.Basis J X) (hXY : X ⊆ Y) (hJY : M.Basis J Y) :
M.Basis I Y := by
rw [← base_restrict_iff]; rw [← base_restrict_iff] at hJY
exact hJY.base_of_basis_superset hJX.subset (hIX.basis_restrict_of_subset hXY)
theorem Basis.basis_of_basis_of_subset_of_subset (hI : M.Basis I X) (hJ : M.Basis J Y) (hJX : J ⊆ X)
(hIY : I ⊆ Y) : M.Basis I Y := by
have hI' := hI.basis_subset (subset_inter hI.subset hIY) inter_subset_left
have hJ' := hJ.basis_subset (subset_inter hJX hJ.subset) inter_subset_right
exact hI'.transfer hJ' inter_subset_right hJ
theorem Indep.exists_basis_subset_union_basis (hI : M.Indep I) (hIX : I ⊆ X) (hJ : M.Basis J X) :
∃ I', M.Basis I' X ∧ I ⊆ I' ∧ I' ⊆ I ∪ J := by
obtain ⟨I', hI', hII', hI'IJ⟩ :=
(hI.indep_restrict_of_subset hIX).exists_base_subset_union_base (Basis.base_restrict hJ)
rw [base_restrict_iff] at hI'
exact ⟨I', hI', hII', hI'IJ⟩
theorem Indep.exists_insert_of_not_basis (hI : M.Indep I) (hIX : I ⊆ X) (hI' : ¬M.Basis I X)
(hJ : M.Basis J X) : ∃ e ∈ J \ I, M.Indep (insert e I) := by
rw [← base_restrict_iff] at hI'; rw [← base_restrict_iff] at hJ
obtain ⟨e, he, hi⟩ := (hI.indep_restrict_of_subset hIX).exists_insert_of_not_base hI' hJ
exact ⟨e, he, (restrict_indep_iff.mp hi).1⟩
theorem Basis.base_of_base_subset (hIX : M.Basis I X) (hB : M.Base B) (hBX : B ⊆ X) : M.Base I :=
hB.base_of_basis_superset hBX hIX
theorem Basis.exchange (hIX : M.Basis I X) (hJX : M.Basis J X) (he : e ∈ I \ J) :
∃ f ∈ J \ I, M.Basis (insert f (I \ {e})) X := by
obtain ⟨y,hy, h⟩ := hIX.restrict_base.exchange hJX.restrict_base he
exact ⟨y, hy, by rwa [base_restrict_iff] at h⟩
theorem Basis.eq_exchange_of_diff_eq_singleton (hI : M.Basis I X) (hJ : M.Basis J X)
(hIJ : I \ J = {e}) : ∃ f ∈ J \ I, J = insert f I \ {e} := by
rw [← base_restrict_iff] at hI hJ; exact hI.eq_exchange_of_diff_eq_singleton hJ hIJ
theorem Basis'.encard_eq_encard (hI : M.Basis' I X) (hJ : M.Basis' J X) : I.encard = J.encard := by
rw [← base_restrict_iff'] at hI hJ; exact hI.card_eq_card_of_base hJ
theorem Basis.encard_eq_encard (hI : M.Basis I X) (hJ : M.Basis J X) : I.encard = J.encard :=
hI.basis'.encard_eq_encard hJ.basis'
/-- Any independent set can be extended into a larger independent set. -/
theorem Indep.augment (hI : M.Indep I) (hJ : M.Indep J) (hIJ : I.encard < J.encard) :
∃ e ∈ J \ I, M.Indep (insert e I) := by
by_contra! he
have hb : M.Basis I (I ∪ J) := by
simp_rw [hI.basis_iff_forall_insert_dep subset_union_left, union_diff_left, mem_diff,
and_imp, dep_iff, insert_subset_iff, and_iff_left hI.subset_ground]
exact fun e heJ heI ↦ ⟨he e ⟨heJ, heI⟩, hJ.subset_ground heJ⟩
obtain ⟨J', hJ', hJJ'⟩ := hJ.subset_basis_of_subset I.subset_union_right
rw [← hJ'.encard_eq_encard hb] at hIJ
exact hIJ.not_le (encard_mono hJJ')
end Basis
end Matroid
|
Data\Matroid\Sum.lean | /-
Copyright (c) 2024 Peter Nelson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Peter Nelson
-/
import Mathlib.Data.Matroid.Map
import Mathlib.Logic.Embedding.Set
/-!
# Sums of matroids
The *sum* `M` of a collection `M₁, M₂, ..` of matroids is a matroid on the disjoint union of
the ground sets of the summands, in which the independent sets are precisely the unions of
independent sets of the summands.
We can ask for such a sum both for pairs and for arbitrary indexed collections of matroids,
and we can also ask for the 'disjoint union' to be either set-theoretic or type-theoretic.
To this end, we define five separate versions of the sum construction.
## Main definitions
* For an indexed collection `M : (i : ι) → Matroid (α i)` of matroids on different types,
`Matroid.sigma M` is the sum of the `M i`, as a matroid on the sigma type `(Σ i, α i)`.
* For an indexed collection `M : ι → Matroid α` of matroids on the same type,
`Matroid.sum' M` is the sum of the `M i`, as a matroid on the product type `ι × α`.
* For an indexed collection `M : ι → Matroid α` of matroids on the same type, and a
proof `h : Pairwise (Disjoint on fun i ↦ (M i).E)` that they have disjoint ground sets,
`Matroid.disjointSigma M h` is the sum of the `M` as a `Matroid α` with ground set `⋃ i, (M i).E`.
* `Matroid.sum (M : Matroid α) (N : Matroid β)` is the sum of `M` and `N` as a matroid on `α ⊕ β`.
* If `M N : Matroid α` and `h : Disjoint M.E N.E`, then `Matroid.disjointSum M N h` is the sum
of `M` and `N` as a `Matroid α` with ground set `M.E ∪ N.E`.
## Implementation details
We only directly define a matroid for `Matroid.sigma`. All other versions of sum are
defined indirectly, using `Matroid.sigma` and the API in `Matroid.map`.
-/
universe u v
open Set
namespace Matroid
section Sigma
variable {ι : Type*} {α : ι → Type*} {M : (i : ι) → Matroid (α i)}
/-- The sum of an indexed collection of matroids, as a matroid on the sigma-type. -/
protected def sigma (M : (i : ι) → Matroid (α i)) : Matroid ((i : ι) × α i) where
E := univ.sigma (fun i ↦ (M i).E)
Indep I := ∀ i, (M i).Indep (Sigma.mk i ⁻¹' I)
Base B := ∀ i, (M i).Base (Sigma.mk i ⁻¹' B)
indep_iff' I := by
refine ⟨fun h ↦ ?_, fun ⟨B, hB, hIB⟩ i ↦ (hB i).indep.subset (preimage_mono hIB)⟩
choose Bs hBs using fun i ↦ (h i).exists_base_superset
refine ⟨univ.sigma Bs, fun i ↦ by simpa using (hBs i).1, ?_⟩
rw [← univ_sigma_preimage_mk I]
refine sigma_mono rfl.subset fun i ↦ (hBs i).2
exists_base := by
choose B hB using fun i ↦ (M i).exists_base
exact ⟨univ.sigma B, by simpa⟩
base_exchange B₁ B₂ h₁ h₂ := by
simp only [mem_diff, Sigma.exists, and_imp, Sigma.forall]
intro i e he₁ he₂
have hf_ex := (h₁ i).exchange (h₂ i) ⟨he₁, by simpa⟩
obtain ⟨f, ⟨hf₁, hf₂⟩, hfB⟩ := hf_ex
refine ⟨i, f, ⟨hf₁, hf₂⟩, fun j ↦ ?_⟩
rw [← union_singleton, preimage_union, preimage_diff]
obtain (rfl | hne) := eq_or_ne i j
· simpa only [ show ∀ x, {⟨i,x⟩} = Sigma.mk i '' {x} by simp,
preimage_image_eq _ sigma_mk_injective, union_singleton]
rw [preimage_singleton_eq_empty.2 (by simpa), preimage_singleton_eq_empty.2 (by simpa),
diff_empty, union_empty]
exact h₁ j
maximality X _ I hI hIX := by
choose Js hJs using
fun i ↦ (hI i).subset_basis'_of_subset (preimage_mono (f := Sigma.mk i) hIX)
use univ.sigma Js
simp only [maximal_subset_iff', mem_univ, mk_preimage_sigma, le_eq_subset, and_imp]
refine ⟨?_, ⟨fun i ↦ (hJs i).1.indep, ?_⟩, fun S hS hSX hJS ↦ ?_⟩
· rw [← univ_sigma_preimage_mk I]
exact sigma_mono rfl.subset fun i ↦ (hJs i).2
· rw [← univ_sigma_preimage_mk X]
exact sigma_mono rfl.subset fun i ↦ (hJs i).1.subset
rw [← univ_sigma_preimage_mk S]
refine sigma_mono rfl.subset fun i ↦ ?_
rw [sigma_subset_iff] at hJS
rw [(hJs i).1.eq_of_subset_indep (hS i) (hJS <| mem_univ i)]
exact preimage_mono hSX
subset_ground B hB := by
rw [← univ_sigma_preimage_mk B]
apply sigma_mono Subset.rfl fun i ↦ (hB i).subset_ground
@[simp] lemma sigma_indep_iff {I} :
(Matroid.sigma M).Indep I ↔ ∀ i, (M i).Indep (Sigma.mk i ⁻¹' I) := Iff.rfl
@[simp] lemma sigma_base_iff {B} :
(Matroid.sigma M).Base B ↔ ∀ i, (M i).Base (Sigma.mk i ⁻¹' B) := Iff.rfl
@[simp] lemma sigma_ground_eq : (Matroid.sigma M).E = univ.sigma fun i ↦ (M i).E := rfl
@[simp] lemma sigma_basis_iff {I X} :
(Matroid.sigma M).Basis I X ↔ ∀ i, (M i).Basis (Sigma.mk i ⁻¹' I) (Sigma.mk i ⁻¹' X) := by
simp only [Basis, sigma_indep_iff, maximal_subset_iff, and_imp, and_assoc, sigma_ground_eq,
forall_and, and_congr_right_iff]
refine fun hI ↦ ⟨fun ⟨hIX, h, h'⟩ ↦ ⟨fun i ↦ preimage_mono hIX, fun i I₀ hI₀ hI₀X hII₀ ↦ ?_, ?_⟩,
fun ⟨hIX, h', h''⟩ ↦ ⟨?_, ?_, ?_⟩⟩
· refine hII₀.antisymm ?_
specialize h (t := I ∪ Sigma.mk i '' I₀)
simp only [preimage_union, union_subset_iff, hIX, image_subset_iff, hI₀X, and_self,
subset_union_left, true_implies] at h
rw [h, preimage_union, sigma_mk_preimage_image_eq_self]
· exact subset_union_right
intro j
obtain (rfl | hij) := eq_or_ne i j
· rwa [sigma_mk_preimage_image_eq_self, union_eq_self_of_subset_left hII₀]
rw [sigma_mk_preimage_image' hij, union_empty]
apply hI
· exact fun i ↦ by simpa using preimage_mono (f := Sigma.mk i) h'
· exact fun ⟨i, x⟩ hx ↦ by simpa using hIX i hx
· refine fun J hJ hJX hIJ ↦ hIJ.antisymm fun ⟨i,x⟩ hx ↦ ?_
simpa using (h' i (hJ i) (preimage_mono hJX) (preimage_mono hIJ)).symm.subset hx
exact fun ⟨i,x⟩ hx ↦ by simpa using h'' i hx
lemma Finitary.sigma (h : ∀ i, (M i).Finitary) : (Matroid.sigma M).Finitary := by
refine ⟨fun I hI ↦ ?_⟩
simp only [sigma_indep_iff] at hI ⊢
intro i
apply indep_of_forall_finite_subset_indep
intro J hJI hJ
convert hI (Sigma.mk i '' J) (by simpa) (hJ.image _) i
rw [sigma_mk_preimage_image_eq_self]
end Sigma
section sum'
variable {α ι : Type*} {M : ι → Matroid α}
/-- The sum of an indexed family `M : ι → Matroid α` of matroids on the same type,
as a matroid on the product type `ι × α`. -/
protected def sum' (M : ι → Matroid α) : Matroid (ι × α) :=
(Matroid.sigma M).mapEquiv <| Equiv.sigmaEquivProd ι α
@[simp] lemma sum'_indep_iff {I} :
(Matroid.sum' M).Indep I ↔ ∀ i, (M i).Indep (Prod.mk i ⁻¹' I) := by
simp only [Matroid.sum', mapEquiv_indep_iff, Equiv.sigmaEquivProd_symm_apply, sigma_indep_iff]
convert Iff.rfl
ext
simp
@[simp] lemma sum'_ground_eq (M : ι → Matroid α) :
(Matroid.sum' M).E = ⋃ i, Prod.mk i '' (M i).E := by
ext
simp [Matroid.sum']
@[simp] lemma sum'_base_iff {B} : (Matroid.sum' M).Base B ↔ ∀ i, (M i).Base (Prod.mk i ⁻¹' B) := by
simp only [Matroid.sum', mapEquiv_base_iff, Equiv.sigmaEquivProd_symm_apply, sigma_base_iff]
convert Iff.rfl
ext
simp
@[simp] lemma sum'_basis_iff {I X} :
(Matroid.sum' M).Basis I X ↔ ∀ i, (M i).Basis (Prod.mk i ⁻¹' I) (Prod.mk i ⁻¹' X) := by
simp [Matroid.sum']
convert Iff.rfl <;>
exact ext <| by simp
lemma Finitary.sum' (h : ∀ i, (M i).Finitary) : (Matroid.sum' M).Finitary := by
have := Finitary.sigma h
rw [Matroid.sum']
infer_instance
end sum'
section disjointSigma
variable {α ι : Type*} {M : ι → Matroid α}
/-- The sum of an indexed collection of matroids on `α` with pairwise disjoint ground sets,
as a matroid on `α` -/
protected def disjointSigma (M : ι → Matroid α) (h : Pairwise (Disjoint on fun i ↦ (M i).E)) :
Matroid α :=
(Matroid.sigma (fun i ↦ (M i).restrictSubtype (M i).E)).mapEmbedding
(Function.Embedding.sigmaSet h)
@[simp] lemma disjointSigma_ground_eq {h} : (Matroid.disjointSigma M h).E = ⋃ i : ι, (M i).E := by
ext; simp [Matroid.disjointSigma, mapEmbedding, restrictSubtype]
@[simp] lemma disjointSigma_indep_iff {h I} :
(Matroid.disjointSigma M h).Indep I ↔
(∀ i, (M i).Indep (I ∩ (M i).E)) ∧ I ⊆ ⋃ i, (M i).E := by
simp [Matroid.disjointSigma, (Function.Embedding.sigmaSet_preimage h)]
@[simp] lemma disjointSigma_base_iff {h B} :
(Matroid.disjointSigma M h).Base B ↔
(∀ i, (M i).Base (B ∩ (M i).E)) ∧ B ⊆ ⋃ i, (M i).E := by
simp [Matroid.disjointSigma, (Function.Embedding.sigmaSet_preimage h)]
@[simp] lemma disjointSigma_basis_iff {h I X} :
(Matroid.disjointSigma M h).Basis I X ↔
(∀ i, (M i).Basis (I ∩ (M i).E) (X ∩ (M i).E)) ∧ I ⊆ X ∧ X ⊆ ⋃ i, (M i).E := by
simp [Matroid.disjointSigma, Function.Embedding.sigmaSet_preimage h]
end disjointSigma
section Sum
variable {α : Type u} {β : Type v} {M N : Matroid α}
/-- The sum of two matroids as a matroid on the sum type. -/
protected def sum (M : Matroid α) (N : Matroid β) : Matroid (α ⊕ β) :=
let S := Matroid.sigma (Bool.rec (M.mapEquiv Equiv.ulift.symm) (N.mapEquiv Equiv.ulift.symm))
let e := Equiv.sumEquivSigmaBool (ULift.{v} α) (ULift.{u} β)
(S.mapEquiv e.symm).mapEquiv (Equiv.sumCongr Equiv.ulift Equiv.ulift)
@[simp] lemma sum_ground (M : Matroid α) (N : Matroid β) :
(M.sum N).E = (.inl '' M.E) ∪ (.inr '' N.E) := by
simp [Matroid.sum, Set.ext_iff, mapEquiv, mapEmbedding, Equiv.ulift, Equiv.sumEquivSigmaBool]
@[simp] lemma sum_indep_iff (M : Matroid α) (N : Matroid β) {I : Set (α ⊕ β)} :
(M.sum N).Indep I ↔ M.Indep (.inl ⁻¹' I) ∧ N.Indep (.inr ⁻¹' I) := by
simp only [Matroid.sum, mapEquiv_indep_iff, Equiv.sumCongr_symm, Equiv.sumCongr_apply,
Equiv.symm_symm, sigma_indep_iff, Bool.forall_bool, Equiv.ulift_apply]
convert Iff.rfl <;>
simp [Set.ext_iff, Equiv.ulift, Equiv.sumEquivSigmaBool]
@[simp] lemma sum_base_iff {M : Matroid α} {N : Matroid β} {B : Set (α ⊕ β)} :
(M.sum N).Base B ↔ M.Base (.inl ⁻¹' B) ∧ N.Base (.inr ⁻¹' B) := by
simp only [Matroid.sum, mapEquiv_base_iff, Equiv.sumCongr_symm, Equiv.sumCongr_apply,
Equiv.symm_symm, sigma_base_iff, Bool.forall_bool, Equiv.ulift_apply]
convert Iff.rfl <;>
simp [Set.ext_iff, Equiv.ulift, Equiv.sumEquivSigmaBool]
@[simp] lemma sum_basis_iff {M : Matroid α} {N : Matroid β} {I X : Set (α ⊕ β)} :
(M.sum N).Basis I X ↔
(M.Basis (Sum.inl ⁻¹' I) (Sum.inl ⁻¹' X) ∧ N.Basis (Sum.inr ⁻¹' I) (Sum.inr ⁻¹' X)) := by
simp only [Matroid.sum, mapEquiv_basis_iff, Equiv.sumCongr_symm,
Equiv.sumCongr_apply, Equiv.symm_symm, sigma_basis_iff, Bool.forall_bool, Equiv.ulift_apply,
Equiv.sumEquivSigmaBool, Equiv.coe_fn_mk, Equiv.ulift]
convert Iff.rfl <;> exact ext <| by simp
end Sum
section disjointSum
variable {α : Type*} {M N : Matroid α}
/-- The sum of two matroids on `α` with disjoint ground sets, as a `Matroid α`. -/
def disjointSum (M N : Matroid α) (h : Disjoint M.E N.E) : Matroid α :=
((M.restrictSubtype M.E).sum (N.restrictSubtype N.E)).mapEmbedding <| Function.Embedding.sumSet h
@[simp] lemma disjointSum_ground_eq {h} : (M.disjointSum N h).E = M.E ∪ N.E := by
simp [disjointSum, restrictSubtype, mapEmbedding]
@[simp] lemma disjointSum_indep_iff {h I} :
(M.disjointSum N h).Indep I ↔ M.Indep (I ∩ M.E) ∧ N.Indep (I ∩ N.E) ∧ I ⊆ M.E ∪ N.E := by
simp [disjointSum, and_assoc]
@[simp] lemma disjointSum_base_iff {h B} :
(M.disjointSum N h).Base B ↔ M.Base (B ∩ M.E) ∧ N.Base (B ∩ N.E) ∧ B ⊆ M.E ∪ N.E := by
simp [disjointSum, and_assoc]
@[simp] lemma disjointSum_basis_iff {h I X} :
(M.disjointSum N h).Basis I X ↔ M.Basis (I ∩ M.E) (X ∩ M.E) ∧
N.Basis (I ∩ N.E) (X ∩ N.E) ∧ I ⊆ X ∧ X ⊆ M.E ∪ N.E := by
simp [disjointSum, and_assoc]
lemma Indep.eq_union_image_of_disjointSum {h I} (hI : (disjointSum M N h).Indep I) :
∃ IM IN, M.Indep IM ∧ N.Indep IN ∧ Disjoint IM IN ∧ I = IM ∪ IN := by
rw [disjointSum_indep_iff] at hI
refine ⟨_, _, hI.1, hI.2.1, h.mono inter_subset_right inter_subset_right, ?_⟩
rw [← inter_union_distrib_left, inter_eq_self_of_subset_left hI.2.2]
lemma Base.eq_union_image_of_disjointSum {h B} (hB : (disjointSum M N h).Base B) :
∃ BM BN, M.Base BM ∧ N.Base BN ∧ Disjoint BM BN ∧ B = BM ∪ BN := by
rw [disjointSum_base_iff] at hB
refine ⟨_, _, hB.1, hB.2.1, h.mono inter_subset_right inter_subset_right, ?_⟩
rw [← inter_union_distrib_left, inter_eq_self_of_subset_left hB.2.2]
end disjointSum
end Matroid
|
Data\MLList\BestFirst.lean | /-
Copyright (c) 2023 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Batteries.Data.MLList.Basic
import Mathlib.Data.Prod.Lex
import Mathlib.Order.Estimator
import Mathlib.Data.Set.Finite
/-!
# Best first search
We perform best first search of a tree or graph,
where the neighbours of a vertex are provided by a lazy list `α → MLList m α`.
We maintain a priority queue of visited-but-not-exhausted nodes,
and at each step take the next child of the highest priority node in the queue.
This is useful in meta code for searching for solutions in the presence of alternatives.
It can be nice to represent the choices via a lazy list,
so the later choices don't need to be evaluated while we do depth first search on earlier choices.
Options:
* `maxDepth` allows bounding the search depth
* `maxQueued` implements "beam" search,
by discarding elements from the priority queue when it grows too large
* `removeDuplicatesBy?` maintains an `RBSet` of previously visited nodes;
otherwise if the graph is not a tree nodes may be visited multiple times.
-/
open Batteries EstimatorData Estimator Set
/-!
We begin by defining a best-first queue of `MLList`s.
This is a somewhat baroque data structure designed for the application in this file
(and in particularly for the implementation of `rewrite_search`).
If someone would like to generalize appropriately that would be great.
We want to maintain a priority queue of `MLList m β`, each indexed by some `a : α` with a priority.
(One could simplify matters here by simply flattening this out to a priority queue of pairs `α × β`,
with the priority determined by the `α` factor.
However the lazyness of `MLList` is essential to performance here:
we will extract elements from these lists one at a time,
and only when they at the head of the queue.
If another item arrives at the head of the queue,
we may not need to continue calculate the previous head's elements.)
To complicate matters, the priorities might be expensive to calculate,
so we instead keep track of a lower bound (where less is better) for each such `a : α`.
The priority queue maintains the `MLList m β` in order of the current best lower bound for the
corresponding `a : α`.
When we insert a new `α × MLList m β` into the queue, we have to provide a lower bound,
and we just insert it at a position depending on the estimate.
When it is time to pop a `β` off the queue, we iteratively improve the lower bound for the
front element of the queue, until we decide that either it must be the least element,
or we can exchange it with the second element of the queue and continue.
A `BestFirstQueue prio ε m β maxSize` consists of an `RBMap`,
where the keys are in `BestFirstNode prio ε`
and the values are `MLList m β`.
A `BestFirstNode prio ε` consists of a `key : α` and an estimator `ε : key`.
Here `ε` provides the current best lower bound for `prio key : Thunk ω`.
(The actual priority is hidden behind a `Thunk` to avoid evaluating it, in case it is expensive.)
We ask for the type classes `LinearOrder ω` and `∀ a : α, Estimator (prio a) (ε a)`.
This later typeclass ensures that we can always produce progressively better estimates
for a priority. We also need a `WellFounded` instance to ensure that improving estimates terminates.
This whole structure is designed around the problem of searching rewrite graphs,
prioritising according to edit distances (either between sides of an equation,
or from a goal to a target). Edit distance computations are particularly suited to this design
because the usual algorithm for computing them produces improving lower bounds at each step.
With this design, it is okay if we visit nodes with very large edit distances:
while these would be expensive to compute, we never actually finish the computation
except in cases where the node arrives at the front of the queue.
-/
section
/-- A node in a `BestFirstQueue`. -/
structure BestFirstNode {α : Sort*} {ω : Type*} (prio : α → Thunk ω) (ε : α → Type) where
/-- The data to store at a node, from which we can calculate a priority using `prio`. -/
key : α
/-- An estimator for the priority of the key.
(We will assume we have `[∀ a : α, Estimator (prio a) (ε a)]`.) -/
estimator : ε key
set_option autoImplicit true
variable {α : Type} {prio : α → Thunk ω} {ε : α → Type} [LinearOrder ω]
[∀ a, Estimator (prio a) (ε a)]
[I : ∀ a : α, WellFoundedGT (range (bound (prio a) : ε a → ω))]
{m : Type → Type} [Monad m] {β : Type}
/-- Calculate the current best lower bound for the priority of a node. -/
def BestFirstNode.estimate (n : BestFirstNode prio ε) : ω := bound (prio n.key) n.estimator
instance [Ord ω] [Ord α] : Ord (BestFirstNode prio ε) where
compare :=
compareLex
(compareOn BestFirstNode.estimate)
(compareOn BestFirstNode.key)
set_option linter.unusedVariables false in
variable (prio ε m β) [Ord ω] [Ord α] in
/-- A queue of `MLList m β`s, lazily prioritized by lower bounds. -/
@[nolint unusedArguments]
def BestFirstQueue (maxSize : Option Nat) := RBMap (BestFirstNode prio ε) (MLList m β) compare
variable [Ord ω] [Ord α] {maxSize : Option Nat}
namespace BestFirstQueue
/--
Add a new `MLList m β` to the `BestFirstQueue`, and if this takes the size above `maxSize`,
eject a `MLList` from the tail of the queue.
-/
-- Note this ejects the element with the greatest estimated priority,
-- not necessarily the greatest priority!
def insertAndEject
(q : BestFirstQueue prio ε m β maxSize) (n : BestFirstNode prio ε) (l : MLList m β) :
BestFirstQueue prio ε m β maxSize :=
match maxSize with
| none => q.insert n l
| some max =>
if q.size < max then
q.insert n l
else
match q.max? with
| none => RBMap.empty
| some m => q.insert n l |>.erase m.1
/--
By improving priority estimates as needed, and permuting elements,
ensure that the first element of the queue has the greatest priority.
-/
partial def ensureFirstIsBest (q : BestFirstQueue prio ε m β maxSize) :
m (BestFirstQueue prio ε m β maxSize) := do
let s := @toStream (RBMap _ _ _) _ _ q
match s.next? with
| none =>
-- The queue is empty, nothing to do.
return q
| some ((n, l), s') => match s'.next? with
| none => do
-- There's only one element in the queue, no reordering necessary.
return q
| some ((m, _), _) =>
-- `n` is the first index, `m` is the second index.
-- We need to improve our estimate of the priority for `n` to make sure
-- it really should come before `m`.
match improveUntil (prio n.key) (m.estimate < ·) n.estimator with
| .error none =>
-- If we couldn't improve the estimate at all, it is exact, and hence the best element.
return q
| .error (some e') =>
-- If we improve the estimate, but it is still at most the estimate for `m`,
-- this is the best element, so all we need to do is store the updated estimate.
return q.erase n |>.insert ⟨n.key, e'⟩ l
| .ok e' =>
-- If we improved the estimate and it becomes greater than the estimate for `m`,
-- we re-insert `n` with its new estimate, and then try again.
ensureFirstIsBest (q.erase n |>.insert ⟨n.key, e'⟩ l)
/--
Pop a `β` off the `MLList m β` with lowest priority,
also returning the index in `α` and the current best lower bound for its priority.
This may require improving estimates of priorities and shuffling the queue.
-/
partial def popWithBound (q : BestFirstQueue prio ε m β maxSize) :
m (Option (((a : α) × (ε a) × β) × BestFirstQueue prio ε m β maxSize)) := do
let q' ← ensureFirstIsBest q
match q'.min? with
| none =>
-- The queue is empty, nothing to return.
return none
| some (n, l) =>
match ← l.uncons with
| none =>
-- The `MLList` associated to `n` was actually empty, so we remove `n` and try again.
popWithBound (q'.erase n)
| some (b, l') =>
-- Return the initial element `b` along with the current estimator,
-- and replace the `MLList` associated with `n` with its tail.
return some (⟨n.key, n.estimator, b⟩, q'.modify n fun _ => l')
/--
Pop a `β` off the `MLList m β` with lowest priority,
also returning the index in `α` and the value of the current best lower bound for its priority.
-/
def popWithPriority (q : BestFirstQueue prio ε m β maxSize) :
m (Option (((α × ω) × β) × BestFirstQueue prio ε m β maxSize)) := do
match ← q.popWithBound with
| none => pure none
| some (⟨a, e, b⟩, q') => pure (some (((a, bound (prio a) e), b), q'))
/--
Pop a `β` off the `MLList m β` with lowest priority.
-/
def pop (q : BestFirstQueue prio ε m β maxSize) :
m (Option ((α × β) × BestFirstQueue prio ε m β maxSize)) := do
match ← q.popWithBound with
| none => pure none
| some (⟨a, _, b⟩, q') => pure (some ((a, b), q'))
/--
Convert a `BestFirstQueue` to a `MLList ((α × ω) × β)`, by popping off all elements,
recording also the values in `ω` of the best current lower bounds.
-/
-- This is not used in the algorithms below, but can be useful for debugging.
partial def toMLListWithPriority (q : BestFirstQueue prio ε m β maxSize) : MLList m ((α × ω) × β) :=
.squash fun _ => do
match ← q.popWithPriority with
| none => pure .nil
| some (p, q') => pure <| MLList.cons p q'.toMLListWithPriority
/--
Convert a `BestFirstQueue` to a `MLList (α × β)`, by popping off all elements.
-/
def toMLList (q : BestFirstQueue prio ε m β maxSize) : MLList m (α × β) :=
q.toMLListWithPriority.map fun t => (t.1.1, t.2)
end BestFirstQueue
open MLList
variable {m : Type → Type} [Monad m] [Alternative m] [∀ a, Bot (ε a)] (prio ε)
/--
Core implementation of `bestFirstSearch`, that works by iteratively updating an internal state,
consisting of a priority queue of `MLList m α`.
At each step we pop an element off the queue,
compute its children (lazily) and put these back on the queue.
-/
def impl (maxSize : Option Nat) (f : α → MLList m α) (a : α) : MLList m α :=
let init : BestFirstQueue prio ε m α maxSize := RBMap.single ⟨a, ⊥⟩ (f a)
cons a (iterate go |>.runState' init)
where
/-- A single step of the best first search.
Pop an element, and insert its children back into the queue,
with a trivial estimator for their priority. -/
go : StateT (BestFirstQueue prio ε m α maxSize) m α := fun s => do
match ← s.pop with
| none => failure
| some ((_, b), s') => pure (b, s'.insertAndEject ⟨b, ⊥⟩ (f b))
/--
Wrapper for `impl` implementing the `maxDepth` option.
-/
def implMaxDepth (maxSize : Option Nat) (maxDepth : Option Nat) (f : α → MLList m α) (a : α) :
MLList m α :=
match maxDepth with
| none => impl prio ε maxSize f a
| some max =>
let f' : α ×ₗ Nat → MLList m (α × Nat) := fun ⟨a, n⟩ =>
if max < n then
nil
else
(f a).map fun a' => (a', n + 1)
impl (fun p : α ×ₗ Nat => prio p.1) (fun p : α ×ₗ Nat => ε p.1) maxSize f' (a, 0) |>.map (·.1)
/--
A lazy list recording the best first search of a graph generated by a function
`f : α → MLList m α`.
We maintain a priority queue of visited-but-not-exhausted nodes,
and at each step take the next child of the highest priority node in the queue.
The option `maxDepth` limits the search depth.
The option `maxQueued` bounds the size of the priority queue,
discarding the lowest priority nodes as needed.
This implements a "beam" search, which may be incomplete but uses bounded memory.
The option `removeDuplicates` keeps an `RBSet` of previously visited nodes.
Otherwise, if the graph is not a tree then nodes will be visited multiple times.
This version allows specifying a custom priority function `prio : α → Thunk ω`
along with estimators `ε : α → Type` equipped with `[∀ a, Estimator (prio a) (ε a)]`
that control the behaviour of the priority queue.
This function returns values `a : α` that have
the lowest possible `prio a` amongst unvisited neighbours of visited nodes,
but lazily estimates these priorities to avoid unnecessary computations.
-/
def bestFirstSearchCore (f : α → MLList m α) (a : α)
(β : Type _) [Ord β] (removeDuplicatesBy? : Option (α → β) := none)
(maxQueued : Option Nat := none) (maxDepth : Option Nat := none) :
MLList m α :=
match removeDuplicatesBy? with
| some g =>
let f' : α → MLList (StateT (RBSet β compare) m) α := fun a =>
(f a).liftM >>= fun a' => do
let b := g a'
guard !(← get).contains b
modify fun s => s.insert b
pure a'
implMaxDepth prio ε maxQueued maxDepth f' a |>.runState' (RBSet.empty.insert (g a))
| none =>
implMaxDepth prio ε maxQueued maxDepth f a
end
variable {m : Type → Type} {α : Type} [Monad m] [Alternative m] [LinearOrder α]
/-- A local instance that enables using "the actual value" as a priority estimator,
for simple use cases. -/
local instance instOrderBotEq {a : α} : OrderBot { x : α // x = a } where
bot := ⟨a, rfl⟩
bot_le := by aesop
/--
A lazy list recording the best first search of a graph generated by a function
`f : α → MLList m α`.
We maintain a priority queue of visited-but-not-exhausted nodes,
and at each step take the next child of the highest priority node in the queue.
The option `maxDepth` limits the search depth.
The option `maxQueued` bounds the size of the priority queue,
discarding the lowest priority nodes as needed.
This implements a "beam" search, which may be incomplete but uses bounded memory.
The option `removeDuplicates` keeps an `RBSet` of previously visited nodes.
Otherwise, if the graph is not a tree then nodes will be visited multiple times.
This function returns values `a : α` that are least in the `[LinearOrder α]`
amongst unvisited neighbours of visited nodes.
-/
-- Although the core implementation lazily computes estimates of priorities,
-- this version does not take advantage of those features.
def bestFirstSearch (f : α → MLList m α) (a : α)
(maxQueued : Option Nat := none) (maxDepth : Option Nat := none) (removeDuplicates := true) :
MLList m α :=
bestFirstSearchCore Thunk.pure (fun a : α => { x // x = a }) f a
(β := α) (removeDuplicatesBy? := if removeDuplicates then some id else none)
maxQueued maxDepth
|
Data\MLList\Dedup.lean | /-
Copyright (c) 2023 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Batteries.Data.MLList.Basic
import Batteries.Data.HashMap.Basic
/-!
# Lazy deduplication of lazy lists
-/
open Batteries
namespace MLList
variable {α β : Type} {m : Type → Type} [Monad m] [BEq β] [Hashable β]
/-- Lazily deduplicate a lazy list, using a stored `HashMap`. -/
-- We choose `HashMap` here instead of `RBSet` as the initial application is `Expr`.
def dedupBy (L : MLList m α) (f : α → m β) : MLList m α :=
((L.liftM : MLList (StateT (HashMap β Unit) m) α) >>= fun a => do
let b ← f a
guard !(← get).contains b
modify fun s => s.insert b ()
pure a)
|>.runState' ∅
/-- Lazily deduplicate a lazy list, using a stored `HashMap`. -/
def dedup (L : MLList m β) : MLList m β :=
L.dedupBy (fun b => pure b)
end MLList
|
Data\MLList\DepthFirst.lean | /-
Copyright (c) 2023 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Lean.Data.HashSet
import Batteries.Data.MLList.Basic
import Mathlib.Control.Combinators
/-!
# Depth first search
We perform depth first search of a tree or graph,
where the neighbours of a vertex are provided either by list `α → List α`
or a lazy list `α → MLList MetaM α`.
This is useful in meta code for searching for solutions in the presence of alternatives.
It can be nice to represent the choices via a lazy list,
so the later choices don't need to be evaluated while we do depth first search on earlier choices.
-/
universe u
variable {α : Type u} {m : Type u → Type u}
section
variable [Monad m] [Alternative m]
/-- A generalisation of `depthFirst`, which allows the generation function to know the current
depth, and to count the depth starting from a specified value. -/
partial def depthFirst' (f : Nat → α → m α) (n : Nat) (a : α) : m α :=
pure a <|> joinM ((f n a) <&> (depthFirst' f (n+1)))
/--
Depth first search of a graph generated by a function
`f : α → m α`.
Here `m` must be an `Alternative` `Monad`,
and perhaps the only sensible values are `List` and `MLList MetaM`.
The option `maxDepth` limits the search depth.
Note that if the graph is not a tree then elements will be visited multiple times.
(See `depthFirstRemovingDuplicates`)
-/
def depthFirst (f : α → m α) (a : α) (maxDepth : Option Nat := none) : m α :=
match maxDepth with
| some d => depthFirst' (fun n a => if n ≤ d then f a else failure) 0 a
| none => depthFirst' (fun _ a => f a) 0 a
end
variable [Monad m]
open Lean in
/--
Variant of `depthFirst`,
using an internal `HashSet` to record and avoid already visited nodes.
This version describes the graph using `α → MLList m α`,
and returns the monadic lazy list of nodes visited in order.
This is potentially very expensive.
If you want to do efficient enumerations from a generation function,
avoiding duplication up to equality or isomorphism,
use Brendan McKay's method of "generation by canonical construction path".
-/
-- TODO can you make this work in `List` and `MLList m` simultaneously, by being tricky with monads?
def depthFirstRemovingDuplicates {α : Type u} [BEq α] [Hashable α]
(f : α → MLList m α) (a : α) (maxDepth : Option Nat := none) : MLList m α :=
let f' : α → MLList (StateT.{u} (HashSet α) m) α := fun a =>
(f a).liftM >>= fun b => do
let s ← get
if s.contains b then failure
set <| s.insert b
pure b
(depthFirst f' a maxDepth).runState' (HashSet.empty.insert a)
/--
Variant of `depthFirst`,
using an internal `HashSet` to record and avoid already visited nodes.
This version describes the graph using `α → List α`, and returns the list of nodes visited in order.
-/
def depthFirstRemovingDuplicates' [BEq α] [Hashable α]
(f : α → List α) (a : α) (maxDepth : Option Nat := none) : List α :=
depthFirstRemovingDuplicates
(fun a => (.ofList (f a) : MLList Option α)) a maxDepth |>.force |>.get!
|
Data\MLList\IO.lean | /-
Copyright (c) 2023 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Batteries.Data.MLList.Basic
/-!
# Reading from handles, files, and processes as lazy lists.
-/
open System IO.FS
namespace MLList
/-- Read lines of text from a handle, as a lazy list in `IO`. -/
def linesFromHandle (h : Handle) : MLList IO String :=
MLList.iterate (do
let line ← h.getLine
-- This copies the logic from `IO.FS.lines`.
if line.length == 0 then
return none
else if line.back == '\n' then
let line := line.dropRight 1
let line :=
if System.Platform.isWindows && line.back == '\x0d' then line.dropRight 1 else line
return some line
else
return some line)
|>.takeWhile (·.isSome) |>.map (fun o => o.getD "")
/-- Read lines of text from a file, as a lazy list in `IO`. -/
def lines (f : FilePath) : MLList IO String := .squash fun _ => do
return linesFromHandle (← Handle.mk f Mode.read)
open IO.Process in
/--
Run a command with given input on `stdio`,
returning `stdout` as a lazy list in `IO`.
-/
def runCmd (cmd : String) (args : Array String) (input : String := "") : MLList IO String := do
let child ← spawn
{ cmd := cmd, args := args, stdin := .piped, stdout := .piped, stderr := .piped }
linesFromHandle (← put child input).stdout
where put
(child : Child { stdin := .piped, stdout := .piped, stderr := .piped }) (input : String) :
IO (Child { stdin := .null, stdout := .piped, stderr := .piped }) := do
let (stdin, child) ← child.takeStdin
stdin.putStr input
stdin.flush
return child
|
Data\MLList\Split.lean | /-
Copyright (c) 2023 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Batteries.Data.MLList.Basic
import Mathlib.Data.ULift
/-!
# Functions for splitting monadic lazy lists.
-/
namespace MLList
universe u
variable {α β : Type u} {m : Type u → Type u} [Monad m]
/--
Extract the prefix of a lazy list consisting of elements up to and including
the first element satisfying a monadic predicate.
Return (in the monad) the prefix as a `List`, along with the remaining elements as a `MLList`.
-/
partial def getUpToFirstM (L : MLList m α) (p : α → m (ULift Bool)) : m (List α × MLList m α) := do
match ← L.uncons with
| none => return ([], nil)
| some (x, xs) => (if (← p x).down then
return ([x], xs)
else do
let (acc, R) ← getUpToFirstM xs p
return (x :: acc, R))
/--
Extract the prefix of a lazy list consisting of elements up to and including
the first element satisfying a predicate.
Return (in the monad) the prefix as a `List`, along with the remaining elements as a `MLList`.
-/
def getUpToFirst (L : MLList m α) (p : α → Bool) : m (List α × MLList m α) :=
L.getUpToFirstM fun a => pure (.up (p a))
/--
Extract a maximal prefix of a lazy list consisting of elements
satisfying a monadic predicate.
Return (in the monad) the prefix as a `List`, along with the remaining elements as a `MLList`.
(Note that the first element *not* satisfying the predicate will be generated,
and pushed back on to the remaining lazy list.)
-/
partial def splitWhileM (L : MLList m α) (p : α → m (ULift Bool)) :
m (List α × MLList m α) := do
match ← L.uncons with
| none => return ([], nil)
| some (x, xs) => (if (← p x).down then do
let (acc, R) ← splitWhileM xs p
return (x :: acc, R)
else
return ([], cons x xs))
/--
Extract a maximal prefix of a lazy list consisting of elements
satisfying a predicate.
Return (in the monad) the prefix as a `List`, along with the remaining elements as a `MLList`.
(Note that the first element *not* satisfying the predicate will be generated,
and pushed back on to the remaining lazy list.)
-/
def splitWhile (L : MLList m α) (p : α → Bool) : m (List α × MLList m α) :=
L.splitWhileM fun a => pure (.up (p a))
/--
Splits a lazy list into contiguous sublists of elements with the same value under
a monadic function.
Return a lazy lists of pairs, consisting of a value under that function,
and a maximal list of elements having that value.
-/
partial def groupByM [DecidableEq β] (L : MLList m α) (f : α → m β) : MLList m (β × List α) :=
L.cases (fun _ => nil) fun a t => squash fun _ => do
let b ← f a
let (l, t') ← t.splitWhileM (fun a => do return .up ((← f a) = b))
return cons (b, a :: l) (t'.groupByM f)
/--
Splits a lazy list into contiguous sublists of elements with the same value under a function.
Return a lazy lists of pairs, consisting of a value under that function,
and a maximal list of elements having that value.
-/
def groupBy [DecidableEq β] (L : MLList m α) (f : α → β) : MLList m (β × List α) :=
L.groupByM fun a => pure (f a)
-- local instance : DecidableEq (ULift Bool) := fun a b => by
-- cases' a with a; cases' b with b; cases a <;> cases b <;>
/--
Split a lazy list into contiguous sublists,
starting a new sublist each time a monadic predicate changes from `false` to `true`.
-/
partial def splitAtBecomesTrueM (L : MLList m α) (p : α → m (ULift Bool)) : MLList m (List α) :=
aux (L.groupByM p)
where aux (M : MLList m (ULift.{u} Bool × List α)) : MLList m (List α) :=
M.cases (fun _ => nil) fun (b, l) t => (if b.down then
t.cases (fun _ => cons l nil)
fun (_, l') t' => cons (l ++ l') (aux t')
else
cons l (aux t))
/--
Split a lazy list into contiguous sublists,
starting a new sublist each time a predicate changes from `false` to `true`.
-/
def splitAtBecomesTrue (L : MLList m α) (p : α → Bool) : MLList m (List α) :=
L.splitAtBecomesTrueM fun a => pure (.up (p a))
|
Data\Multiset\Antidiagonal.lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.Multiset.Powerset
/-!
# The antidiagonal on a multiset.
The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)`
such that `t₁ + t₂ = s`. These pairs are counted with multiplicities.
-/
assert_not_exists Ring
universe u
namespace Multiset
open List
variable {α β : Type*}
/-- The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)`
such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/
def antidiagonal (s : Multiset α) : Multiset (Multiset α × Multiset α) :=
Quot.liftOn s (fun l ↦ (revzip (powersetAux l) : Multiset (Multiset α × Multiset α)))
fun _ _ h ↦ Quot.sound (revzip_powersetAux_perm h)
theorem antidiagonal_coe (l : List α) : @antidiagonal α l = revzip (powersetAux l) :=
rfl
@[simp]
theorem antidiagonal_coe' (l : List α) : @antidiagonal α l = revzip (powersetAux' l) :=
Quot.sound revzip_powersetAux_perm_aux'
/- Porting note: `simp` seemed to be applying `antidiagonal_coe'` instead of `antidiagonal_coe`
in what used to be `simp [antidiagonal_coe]`. -/
/-- A pair `(t₁, t₂)` of multisets is contained in `antidiagonal s`
if and only if `t₁ + t₂ = s`. -/
@[simp]
theorem mem_antidiagonal {s : Multiset α} {x : Multiset α × Multiset α} :
x ∈ antidiagonal s ↔ x.1 + x.2 = s :=
Quotient.inductionOn s fun l ↦ by
dsimp only [quot_mk_to_coe, antidiagonal_coe]
refine ⟨fun h => revzip_powersetAux h, fun h ↦ ?_⟩
haveI := Classical.decEq α
simp only [revzip_powersetAux_lemma l revzip_powersetAux, h.symm, mem_coe,
List.mem_map, mem_powersetAux]
cases' x with x₁ x₂
exact ⟨x₁, le_add_right _ _, by rw [add_tsub_cancel_left x₁ x₂]⟩
@[simp]
theorem antidiagonal_map_fst (s : Multiset α) : (antidiagonal s).map Prod.fst = powerset s :=
Quotient.inductionOn s fun l ↦ by simp [powersetAux']
@[simp]
theorem antidiagonal_map_snd (s : Multiset α) : (antidiagonal s).map Prod.snd = powerset s :=
Quotient.inductionOn s fun l ↦ by simp [powersetAux']
@[simp]
theorem antidiagonal_zero : @antidiagonal α 0 = {(0, 0)} :=
rfl
@[simp]
theorem antidiagonal_cons (a : α) (s) :
antidiagonal (a ::ₘ s) =
map (Prod.map id (cons a)) (antidiagonal s) + map (Prod.map (cons a) id) (antidiagonal s) :=
Quotient.inductionOn s fun l ↦ by
simp only [revzip, reverse_append, quot_mk_to_coe, coe_eq_coe, powersetAux'_cons, cons_coe,
map_coe, antidiagonal_coe', coe_add]
rw [← zip_map, ← zip_map, zip_append, (_ : _ ++ _ = _)]
· congr
· simp only [List.map_id]
· rw [map_reverse]
· simp
· simp
theorem antidiagonal_eq_map_powerset [DecidableEq α] (s : Multiset α) :
s.antidiagonal = s.powerset.map fun t ↦ (s - t, t) := by
induction' s using Multiset.induction_on with a s hs
· simp only [antidiagonal_zero, powerset_zero, zero_tsub, map_singleton]
· simp_rw [antidiagonal_cons, powerset_cons, map_add, hs, map_map, Function.comp, Prod.map_mk,
id, sub_cons, erase_cons_head]
rw [add_comm]
congr 1
refine Multiset.map_congr rfl fun x hx ↦ ?_
rw [cons_sub_of_le _ (mem_powerset.mp hx)]
@[simp]
theorem card_antidiagonal (s : Multiset α) : card (antidiagonal s) = 2 ^ card s := by
have := card_powerset s
rwa [← antidiagonal_map_fst, card_map] at this
end Multiset
|
Data\Multiset\Basic.lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Algebra.Group.Nat
import Mathlib.Algebra.Order.Sub.Canonical
import Mathlib.Data.List.Perm
import Mathlib.Data.Set.List
import Mathlib.Init.Quot
import Mathlib.Order.Hom.Basic
/-!
# Multisets
These are implemented as the quotient of a list by permutations.
## Notation
We define the global infix notation `::ₘ` for `Multiset.cons`.
-/
universe v
open List Subtype Nat Function
variable {α : Type*} {β : Type v} {γ : Type*}
/-- `Multiset α` is the quotient of `List α` by list permutation. The result
is a type of finite sets with duplicates allowed. -/
def Multiset.{u} (α : Type u) : Type u :=
Quotient (List.isSetoid α)
namespace Multiset
-- Porting note: new
/-- The quotient map from `List α` to `Multiset α`. -/
@[coe]
def ofList : List α → Multiset α :=
Quot.mk _
instance : Coe (List α) (Multiset α) :=
⟨ofList⟩
@[simp]
theorem quot_mk_to_coe (l : List α) : @Eq (Multiset α) ⟦l⟧ l :=
rfl
@[simp]
theorem quot_mk_to_coe' (l : List α) : @Eq (Multiset α) (Quot.mk (· ≈ ·) l) l :=
rfl
@[simp]
theorem quot_mk_to_coe'' (l : List α) : @Eq (Multiset α) (Quot.mk Setoid.r l) l :=
rfl
@[simp]
theorem lift_coe {α β : Type*} (x : List α) (f : List α → β)
(h : ∀ a b : List α, a ≈ b → f a = f b) : Quotient.lift f h (x : Multiset α) = f x :=
Quotient.lift_mk _ _ _
@[simp]
theorem coe_eq_coe {l₁ l₂ : List α} : (l₁ : Multiset α) = l₂ ↔ l₁ ~ l₂ :=
Quotient.eq
-- Porting note: new instance;
-- Porting note (#11215): TODO: move to better place
instance [DecidableEq α] (l₁ l₂ : List α) : Decidable (l₁ ≈ l₂) :=
inferInstanceAs (Decidable (l₁ ~ l₂))
-- Porting note: `Quotient.recOnSubsingleton₂ s₁ s₂` was in parens which broke elaboration
instance decidableEq [DecidableEq α] : DecidableEq (Multiset α)
| s₁, s₂ => Quotient.recOnSubsingleton₂ s₁ s₂ fun _ _ => decidable_of_iff' _ Quotient.eq
/-- defines a size for a multiset by referring to the size of the underlying list -/
protected
def sizeOf [SizeOf α] (s : Multiset α) : ℕ :=
(Quot.liftOn s SizeOf.sizeOf) fun _ _ => Perm.sizeOf_eq_sizeOf
instance [SizeOf α] : SizeOf (Multiset α) :=
⟨Multiset.sizeOf⟩
/-! ### Empty multiset -/
/-- `0 : Multiset α` is the empty set -/
protected def zero : Multiset α :=
@nil α
instance : Zero (Multiset α) :=
⟨Multiset.zero⟩
instance : EmptyCollection (Multiset α) :=
⟨0⟩
instance inhabitedMultiset : Inhabited (Multiset α) :=
⟨0⟩
instance [IsEmpty α] : Unique (Multiset α) where
default := 0
uniq := by rintro ⟨_ | ⟨a, l⟩⟩; exacts [rfl, isEmptyElim a]
@[simp]
theorem coe_nil : (@nil α : Multiset α) = 0 :=
rfl
@[simp]
theorem empty_eq_zero : (∅ : Multiset α) = 0 :=
rfl
@[simp]
theorem coe_eq_zero (l : List α) : (l : Multiset α) = 0 ↔ l = [] :=
Iff.trans coe_eq_coe perm_nil
theorem coe_eq_zero_iff_isEmpty (l : List α) : (l : Multiset α) = 0 ↔ l.isEmpty :=
Iff.trans (coe_eq_zero l) isEmpty_iff_eq_nil.symm
/-! ### `Multiset.cons` -/
/-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/
def cons (a : α) (s : Multiset α) : Multiset α :=
Quot.liftOn s (fun l => (a :: l : Multiset α)) fun _ _ p => Quot.sound (p.cons a)
@[inherit_doc Multiset.cons]
infixr:67 " ::ₘ " => Multiset.cons
instance : Insert α (Multiset α) :=
⟨cons⟩
@[simp]
theorem insert_eq_cons (a : α) (s : Multiset α) : insert a s = a ::ₘ s :=
rfl
@[simp]
theorem cons_coe (a : α) (l : List α) : (a ::ₘ l : Multiset α) = (a :: l : List α) :=
rfl
@[simp]
theorem cons_inj_left {a b : α} (s : Multiset α) : a ::ₘ s = b ::ₘ s ↔ a = b :=
⟨Quot.inductionOn s fun l e =>
have : [a] ++ l ~ [b] ++ l := Quotient.exact e
singleton_perm_singleton.1 <| (perm_append_right_iff _).1 this,
congr_arg (· ::ₘ _)⟩
@[simp]
theorem cons_inj_right (a : α) : ∀ {s t : Multiset α}, a ::ₘ s = a ::ₘ t ↔ s = t := by
rintro ⟨l₁⟩ ⟨l₂⟩; simp
@[elab_as_elim]
protected theorem induction {p : Multiset α → Prop} (empty : p 0)
(cons : ∀ (a : α) (s : Multiset α), p s → p (a ::ₘ s)) : ∀ s, p s := by
rintro ⟨l⟩; induction' l with _ _ ih <;> [exact empty; exact cons _ _ ih]
@[elab_as_elim]
protected theorem induction_on {p : Multiset α → Prop} (s : Multiset α) (empty : p 0)
(cons : ∀ (a : α) (s : Multiset α), p s → p (a ::ₘ s)) : p s :=
Multiset.induction empty cons s
theorem cons_swap (a b : α) (s : Multiset α) : a ::ₘ b ::ₘ s = b ::ₘ a ::ₘ s :=
Quot.inductionOn s fun _ => Quotient.sound <| Perm.swap _ _ _
section Rec
variable {C : Multiset α → Sort*}
/-- Dependent recursor on multisets.
TODO: should be @[recursor 6], but then the definition of `Multiset.pi` fails with a stack
overflow in `whnf`.
-/
protected
def rec (C_0 : C 0) (C_cons : ∀ a m, C m → C (a ::ₘ m))
(C_cons_heq :
∀ a a' m b, HEq (C_cons a (a' ::ₘ m) (C_cons a' m b)) (C_cons a' (a ::ₘ m) (C_cons a m b)))
(m : Multiset α) : C m :=
Quotient.hrecOn m (@List.rec α (fun l => C ⟦l⟧) C_0 fun a l b => C_cons a ⟦l⟧ b) fun l l' h =>
h.rec_heq
(fun hl _ ↦ by congr 1; exact Quot.sound hl)
(C_cons_heq _ _ ⟦_⟧ _)
/-- Companion to `Multiset.rec` with more convenient argument order. -/
@[elab_as_elim]
protected
def recOn (m : Multiset α) (C_0 : C 0) (C_cons : ∀ a m, C m → C (a ::ₘ m))
(C_cons_heq :
∀ a a' m b, HEq (C_cons a (a' ::ₘ m) (C_cons a' m b)) (C_cons a' (a ::ₘ m) (C_cons a m b))) :
C m :=
Multiset.rec C_0 C_cons C_cons_heq m
variable {C_0 : C 0} {C_cons : ∀ a m, C m → C (a ::ₘ m)}
{C_cons_heq :
∀ a a' m b, HEq (C_cons a (a' ::ₘ m) (C_cons a' m b)) (C_cons a' (a ::ₘ m) (C_cons a m b))}
@[simp]
theorem recOn_0 : @Multiset.recOn α C (0 : Multiset α) C_0 C_cons C_cons_heq = C_0 :=
rfl
@[simp]
theorem recOn_cons (a : α) (m : Multiset α) :
(a ::ₘ m).recOn C_0 C_cons C_cons_heq = C_cons a m (m.recOn C_0 C_cons C_cons_heq) :=
Quotient.inductionOn m fun _ => rfl
end Rec
section Mem
/-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/
def Mem (a : α) (s : Multiset α) : Prop :=
Quot.liftOn s (fun l => a ∈ l) fun l₁ l₂ (e : l₁ ~ l₂) => propext <| e.mem_iff
instance : Membership α (Multiset α) :=
⟨Mem⟩
@[simp]
theorem mem_coe {a : α} {l : List α} : a ∈ (l : Multiset α) ↔ a ∈ l :=
Iff.rfl
instance decidableMem [DecidableEq α] (a : α) (s : Multiset α) : Decidable (a ∈ s) :=
Quot.recOnSubsingleton' s fun l ↦ inferInstanceAs (Decidable (a ∈ l))
@[simp]
theorem mem_cons {a b : α} {s : Multiset α} : a ∈ b ::ₘ s ↔ a = b ∨ a ∈ s :=
Quot.inductionOn s fun _ => List.mem_cons
theorem mem_cons_of_mem {a b : α} {s : Multiset α} (h : a ∈ s) : a ∈ b ::ₘ s :=
mem_cons.2 <| Or.inr h
-- @[simp] -- Porting note (#10618): simp can prove this
theorem mem_cons_self (a : α) (s : Multiset α) : a ∈ a ::ₘ s :=
mem_cons.2 (Or.inl rfl)
theorem forall_mem_cons {p : α → Prop} {a : α} {s : Multiset α} :
(∀ x ∈ a ::ₘ s, p x) ↔ p a ∧ ∀ x ∈ s, p x :=
Quotient.inductionOn' s fun _ => List.forall_mem_cons
theorem exists_cons_of_mem {s : Multiset α} {a : α} : a ∈ s → ∃ t, s = a ::ₘ t :=
Quot.inductionOn s fun l (h : a ∈ l) =>
let ⟨l₁, l₂, e⟩ := append_of_mem h
e.symm ▸ ⟨(l₁ ++ l₂ : List α), Quot.sound perm_middle⟩
@[simp]
theorem not_mem_zero (a : α) : a ∉ (0 : Multiset α) :=
List.not_mem_nil _
theorem eq_zero_of_forall_not_mem {s : Multiset α} : (∀ x, x ∉ s) → s = 0 :=
Quot.inductionOn s fun l H => by rw [eq_nil_iff_forall_not_mem.mpr H]; rfl
theorem eq_zero_iff_forall_not_mem {s : Multiset α} : s = 0 ↔ ∀ a, a ∉ s :=
⟨fun h => h.symm ▸ fun _ => not_mem_zero _, eq_zero_of_forall_not_mem⟩
theorem exists_mem_of_ne_zero {s : Multiset α} : s ≠ 0 → ∃ a : α, a ∈ s :=
Quot.inductionOn s fun l hl =>
match l, hl with
| [], h => False.elim <| h rfl
| a :: l, _ => ⟨a, by simp⟩
theorem empty_or_exists_mem (s : Multiset α) : s = 0 ∨ ∃ a, a ∈ s :=
or_iff_not_imp_left.mpr Multiset.exists_mem_of_ne_zero
@[simp]
theorem zero_ne_cons {a : α} {m : Multiset α} : 0 ≠ a ::ₘ m := fun h =>
have : a ∈ (0 : Multiset α) := h.symm ▸ mem_cons_self _ _
not_mem_zero _ this
@[simp]
theorem cons_ne_zero {a : α} {m : Multiset α} : a ::ₘ m ≠ 0 :=
zero_ne_cons.symm
theorem cons_eq_cons {a b : α} {as bs : Multiset α} :
a ::ₘ as = b ::ₘ bs ↔ a = b ∧ as = bs ∨ a ≠ b ∧ ∃ cs, as = b ::ₘ cs ∧ bs = a ::ₘ cs := by
haveI : DecidableEq α := Classical.decEq α
constructor
· intro eq
by_cases h : a = b
· subst h
simp_all
· have : a ∈ b ::ₘ bs := eq ▸ mem_cons_self _ _
have : a ∈ bs := by simpa [h]
rcases exists_cons_of_mem this with ⟨cs, hcs⟩
simp only [h, hcs, false_and, ne_eq, not_false_eq_true, cons_inj_right, exists_eq_right',
true_and, false_or]
have : a ::ₘ as = b ::ₘ a ::ₘ cs := by simp [eq, hcs]
have : a ::ₘ as = a ::ₘ b ::ₘ cs := by rwa [cons_swap]
simpa using this
· intro h
rcases h with (⟨eq₁, eq₂⟩ | ⟨_, cs, eq₁, eq₂⟩)
· simp [*]
· simp [*, cons_swap a b]
end Mem
/-! ### Singleton -/
instance : Singleton α (Multiset α) :=
⟨fun a => a ::ₘ 0⟩
instance : LawfulSingleton α (Multiset α) :=
⟨fun _ => rfl⟩
@[simp]
theorem cons_zero (a : α) : a ::ₘ 0 = {a} :=
rfl
@[simp, norm_cast]
theorem coe_singleton (a : α) : ([a] : Multiset α) = {a} :=
rfl
@[simp]
theorem mem_singleton {a b : α} : b ∈ ({a} : Multiset α) ↔ b = a := by
simp only [← cons_zero, mem_cons, iff_self_iff, or_false_iff, not_mem_zero]
theorem mem_singleton_self (a : α) : a ∈ ({a} : Multiset α) := by
rw [← cons_zero]
exact mem_cons_self _ _
@[simp]
theorem singleton_inj {a b : α} : ({a} : Multiset α) = {b} ↔ a = b := by
simp_rw [← cons_zero]
exact cons_inj_left _
@[simp, norm_cast]
theorem coe_eq_singleton {l : List α} {a : α} : (l : Multiset α) = {a} ↔ l = [a] := by
rw [← coe_singleton, coe_eq_coe, List.perm_singleton]
@[simp]
theorem singleton_eq_cons_iff {a b : α} (m : Multiset α) : {a} = b ::ₘ m ↔ a = b ∧ m = 0 := by
rw [← cons_zero, cons_eq_cons]
simp [eq_comm]
theorem pair_comm (x y : α) : ({x, y} : Multiset α) = {y, x} :=
cons_swap x y 0
/-! ### `Multiset.Subset` -/
section Subset
variable {s : Multiset α} {a : α}
/-- `s ⊆ t` is the lift of the list subset relation. It means that any
element with nonzero multiplicity in `s` has nonzero multiplicity in `t`,
but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`;
see `s ≤ t` for this relation. -/
protected def Subset (s t : Multiset α) : Prop :=
∀ ⦃a : α⦄, a ∈ s → a ∈ t
instance : HasSubset (Multiset α) :=
⟨Multiset.Subset⟩
instance : HasSSubset (Multiset α) :=
⟨fun s t => s ⊆ t ∧ ¬t ⊆ s⟩
instance instIsNonstrictStrictOrder : IsNonstrictStrictOrder (Multiset α) (· ⊆ ·) (· ⊂ ·) where
right_iff_left_not_left _ _ := Iff.rfl
@[simp]
theorem coe_subset {l₁ l₂ : List α} : (l₁ : Multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ :=
Iff.rfl
@[simp]
theorem Subset.refl (s : Multiset α) : s ⊆ s := fun _ h => h
theorem Subset.trans {s t u : Multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := fun h₁ h₂ _ m => h₂ (h₁ m)
theorem subset_iff {s t : Multiset α} : s ⊆ t ↔ ∀ ⦃x⦄, x ∈ s → x ∈ t :=
Iff.rfl
theorem mem_of_subset {s t : Multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t :=
@h _
@[simp]
theorem zero_subset (s : Multiset α) : 0 ⊆ s := fun a => (not_mem_nil a).elim
theorem subset_cons (s : Multiset α) (a : α) : s ⊆ a ::ₘ s := fun _ => mem_cons_of_mem
theorem ssubset_cons {s : Multiset α} {a : α} (ha : a ∉ s) : s ⊂ a ::ₘ s :=
⟨subset_cons _ _, fun h => ha <| h <| mem_cons_self _ _⟩
@[simp]
theorem cons_subset {a : α} {s t : Multiset α} : a ::ₘ s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by
simp [subset_iff, or_imp, forall_and]
theorem cons_subset_cons {a : α} {s t : Multiset α} : s ⊆ t → a ::ₘ s ⊆ a ::ₘ t :=
Quotient.inductionOn₂ s t fun _ _ => List.cons_subset_cons _
theorem eq_zero_of_subset_zero {s : Multiset α} (h : s ⊆ 0) : s = 0 :=
eq_zero_of_forall_not_mem fun _ hx ↦ not_mem_zero _ (h hx)
@[simp] lemma subset_zero : s ⊆ 0 ↔ s = 0 :=
⟨eq_zero_of_subset_zero, fun xeq => xeq.symm ▸ Subset.refl 0⟩
@[simp] lemma zero_ssubset : 0 ⊂ s ↔ s ≠ 0 := by simp [ssubset_iff_subset_not_subset]
@[simp] lemma singleton_subset : {a} ⊆ s ↔ a ∈ s := by simp [subset_iff]
theorem induction_on' {p : Multiset α → Prop} (S : Multiset α) (h₁ : p 0)
(h₂ : ∀ {a s}, a ∈ S → s ⊆ S → p s → p (insert a s)) : p S :=
@Multiset.induction_on α (fun T => T ⊆ S → p T) S (fun _ => h₁)
(fun _ _ hps hs =>
let ⟨hS, sS⟩ := cons_subset.1 hs
h₂ hS sS (hps sS))
(Subset.refl S)
end Subset
/-! ### `Multiset.toList` -/
section ToList
/-- Produces a list of the elements in the multiset using choice. -/
noncomputable def toList (s : Multiset α) :=
s.out'
@[simp, norm_cast]
theorem coe_toList (s : Multiset α) : (s.toList : Multiset α) = s :=
s.out_eq'
@[simp]
theorem toList_eq_nil {s : Multiset α} : s.toList = [] ↔ s = 0 := by
rw [← coe_eq_zero, coe_toList]
theorem empty_toList {s : Multiset α} : s.toList.isEmpty ↔ s = 0 := by simp
@[simp]
theorem toList_zero : (Multiset.toList 0 : List α) = [] :=
toList_eq_nil.mpr rfl
@[simp]
theorem mem_toList {a : α} {s : Multiset α} : a ∈ s.toList ↔ a ∈ s := by
rw [← mem_coe, coe_toList]
@[simp]
theorem toList_eq_singleton_iff {a : α} {m : Multiset α} : m.toList = [a] ↔ m = {a} := by
rw [← perm_singleton, ← coe_eq_coe, coe_toList, coe_singleton]
@[simp]
theorem toList_singleton (a : α) : ({a} : Multiset α).toList = [a] :=
Multiset.toList_eq_singleton_iff.2 rfl
end ToList
/-! ### Partial order on `Multiset`s -/
/-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation).
Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/
protected def Le (s t : Multiset α) : Prop :=
(Quotient.liftOn₂ s t (· <+~ ·)) fun _ _ _ _ p₁ p₂ =>
propext (p₂.subperm_left.trans p₁.subperm_right)
instance : PartialOrder (Multiset α) where
le := Multiset.Le
le_refl := by rintro ⟨l⟩; exact Subperm.refl _
le_trans := by rintro ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @Subperm.trans _ _ _ _
le_antisymm := by rintro ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact Quot.sound (Subperm.antisymm h₁ h₂)
instance decidableLE [DecidableEq α] : DecidableRel ((· ≤ ·) : Multiset α → Multiset α → Prop) :=
fun s t => Quotient.recOnSubsingleton₂ s t List.decidableSubperm
section
variable {s t : Multiset α} {a : α}
theorem subset_of_le : s ≤ t → s ⊆ t :=
Quotient.inductionOn₂ s t fun _ _ => Subperm.subset
alias Le.subset := subset_of_le
theorem mem_of_le (h : s ≤ t) : a ∈ s → a ∈ t :=
mem_of_subset (subset_of_le h)
theorem not_mem_mono (h : s ⊆ t) : a ∉ t → a ∉ s :=
mt <| @h _
@[simp]
theorem coe_le {l₁ l₂ : List α} : (l₁ : Multiset α) ≤ l₂ ↔ l₁ <+~ l₂ :=
Iff.rfl
@[elab_as_elim]
theorem leInductionOn {C : Multiset α → Multiset α → Prop} {s t : Multiset α} (h : s ≤ t)
(H : ∀ {l₁ l₂ : List α}, l₁ <+ l₂ → C l₁ l₂) : C s t :=
Quotient.inductionOn₂ s t (fun l₁ _ ⟨l, p, s⟩ => (show ⟦l⟧ = ⟦l₁⟧ from Quot.sound p) ▸ H s) h
theorem zero_le (s : Multiset α) : 0 ≤ s :=
Quot.inductionOn s fun l => (nil_sublist l).subperm
instance : OrderBot (Multiset α) where
bot := 0
bot_le := zero_le
/-- This is a `rfl` and `simp` version of `bot_eq_zero`. -/
@[simp]
theorem bot_eq_zero : (⊥ : Multiset α) = 0 :=
rfl
theorem le_zero : s ≤ 0 ↔ s = 0 :=
le_bot_iff
theorem lt_cons_self (s : Multiset α) (a : α) : s < a ::ₘ s :=
Quot.inductionOn s fun l =>
suffices l <+~ a :: l ∧ ¬l ~ a :: l by simpa [lt_iff_le_and_ne]
⟨(sublist_cons_self _ _).subperm,
fun p => _root_.ne_of_lt (lt_succ_self (length l)) p.length_eq⟩
theorem le_cons_self (s : Multiset α) (a : α) : s ≤ a ::ₘ s :=
le_of_lt <| lt_cons_self _ _
theorem cons_le_cons_iff (a : α) : a ::ₘ s ≤ a ::ₘ t ↔ s ≤ t :=
Quotient.inductionOn₂ s t fun _ _ => subperm_cons a
theorem cons_le_cons (a : α) : s ≤ t → a ::ₘ s ≤ a ::ₘ t :=
(cons_le_cons_iff a).2
@[simp] lemma cons_lt_cons_iff : a ::ₘ s < a ::ₘ t ↔ s < t :=
lt_iff_lt_of_le_iff_le' (cons_le_cons_iff _) (cons_le_cons_iff _)
lemma cons_lt_cons (a : α) (h : s < t) : a ::ₘ s < a ::ₘ t := cons_lt_cons_iff.2 h
theorem le_cons_of_not_mem (m : a ∉ s) : s ≤ a ::ₘ t ↔ s ≤ t := by
refine ⟨?_, fun h => le_trans h <| le_cons_self _ _⟩
suffices ∀ {t'}, s ≤ t' → a ∈ t' → a ::ₘ s ≤ t' by
exact fun h => (cons_le_cons_iff a).1 (this h (mem_cons_self _ _))
introv h
revert m
refine leInductionOn h ?_
introv s m₁ m₂
rcases append_of_mem m₂ with ⟨r₁, r₂, rfl⟩
exact
perm_middle.subperm_left.2
((subperm_cons _).2 <| ((sublist_or_mem_of_sublist s).resolve_right m₁).subperm)
@[simp]
theorem singleton_ne_zero (a : α) : ({a} : Multiset α) ≠ 0 :=
ne_of_gt (lt_cons_self _ _)
@[simp]
theorem singleton_le {a : α} {s : Multiset α} : {a} ≤ s ↔ a ∈ s :=
⟨fun h => mem_of_le h (mem_singleton_self _), fun h =>
let ⟨_t, e⟩ := exists_cons_of_mem h
e.symm ▸ cons_le_cons _ (zero_le _)⟩
@[simp] lemma le_singleton : s ≤ {a} ↔ s = 0 ∨ s = {a} :=
Quot.induction_on s fun l ↦ by simp only [cons_zero, ← coe_singleton, quot_mk_to_coe'', coe_le,
coe_eq_zero, coe_eq_coe, perm_singleton, subperm_singleton_iff]
@[simp] lemma lt_singleton : s < {a} ↔ s = 0 := by
simp only [lt_iff_le_and_ne, le_singleton, or_and_right, Ne, and_not_self, or_false,
and_iff_left_iff_imp]
rintro rfl
exact (singleton_ne_zero _).symm
@[simp] lemma ssubset_singleton_iff : s ⊂ {a} ↔ s = 0 := by
refine ⟨fun hs ↦ eq_zero_of_subset_zero fun b hb ↦ (hs.2 ?_).elim, ?_⟩
· obtain rfl := mem_singleton.1 (hs.1 hb)
rwa [singleton_subset]
· rintro rfl
simp
end
/-! ### Additive monoid -/
/-- The sum of two multisets is the lift of the list append operation.
This adds the multiplicities of each element,
i.e. `count a (s + t) = count a s + count a t`. -/
protected def add (s₁ s₂ : Multiset α) : Multiset α :=
(Quotient.liftOn₂ s₁ s₂ fun l₁ l₂ => ((l₁ ++ l₂ : List α) : Multiset α)) fun _ _ _ _ p₁ p₂ =>
Quot.sound <| p₁.append p₂
instance : Add (Multiset α) :=
⟨Multiset.add⟩
@[simp]
theorem coe_add (s t : List α) : (s + t : Multiset α) = (s ++ t : List α) :=
rfl
@[simp]
theorem singleton_add (a : α) (s : Multiset α) : {a} + s = a ::ₘ s :=
rfl
private theorem add_le_add_iff_left' {s t u : Multiset α} : s + t ≤ s + u ↔ t ≤ u :=
Quotient.inductionOn₃ s t u fun _ _ _ => subperm_append_left _
instance : CovariantClass (Multiset α) (Multiset α) (· + ·) (· ≤ ·) :=
⟨fun _s _t _u => add_le_add_iff_left'.2⟩
instance : ContravariantClass (Multiset α) (Multiset α) (· + ·) (· ≤ ·) :=
⟨fun _s _t _u => add_le_add_iff_left'.1⟩
instance : OrderedCancelAddCommMonoid (Multiset α) where
zero := 0
add := (· + ·)
add_comm := fun s t => Quotient.inductionOn₂ s t fun l₁ l₂ => Quot.sound perm_append_comm
add_assoc := fun s₁ s₂ s₃ =>
Quotient.inductionOn₃ s₁ s₂ s₃ fun l₁ l₂ l₃ => congr_arg _ <| append_assoc l₁ l₂ l₃
zero_add := fun s => Quot.inductionOn s fun l => rfl
add_zero := fun s => Quotient.inductionOn s fun l => congr_arg _ <| append_nil l
add_le_add_left := fun s₁ s₂ => add_le_add_left
le_of_add_le_add_left := fun s₁ s₂ s₃ => le_of_add_le_add_left
nsmul := nsmulRec
theorem le_add_right (s t : Multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s
theorem le_add_left (s t : Multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s
theorem le_iff_exists_add {s t : Multiset α} : s ≤ t ↔ ∃ u, t = s + u :=
⟨fun h =>
leInductionOn h fun s =>
let ⟨l, p⟩ := s.exists_perm_append
⟨l, Quot.sound p⟩,
fun ⟨_u, e⟩ => e.symm ▸ le_add_right _ _⟩
instance : CanonicallyOrderedAddCommMonoid (Multiset α) where
__ := inferInstanceAs (OrderBot (Multiset α))
le_self_add := le_add_right
exists_add_of_le h := leInductionOn h fun s =>
let ⟨l, p⟩ := s.exists_perm_append
⟨l, Quot.sound p⟩
@[simp]
theorem cons_add (a : α) (s t : Multiset α) : a ::ₘ s + t = a ::ₘ (s + t) := by
rw [← singleton_add, ← singleton_add, add_assoc]
@[simp]
theorem add_cons (a : α) (s t : Multiset α) : s + a ::ₘ t = a ::ₘ (s + t) := by
rw [add_comm, cons_add, add_comm]
@[simp]
theorem mem_add {a : α} {s t : Multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t :=
Quotient.inductionOn₂ s t fun _l₁ _l₂ => mem_append
theorem mem_of_mem_nsmul {a : α} {s : Multiset α} {n : ℕ} (h : a ∈ n • s) : a ∈ s := by
induction' n with n ih
· rw [zero_nsmul] at h
exact absurd h (not_mem_zero _)
· rw [succ_nsmul, mem_add] at h
exact h.elim ih id
@[simp]
theorem mem_nsmul {a : α} {s : Multiset α} {n : ℕ} : a ∈ n • s ↔ n ≠ 0 ∧ a ∈ s := by
refine ⟨fun ha ↦ ⟨?_, mem_of_mem_nsmul ha⟩, fun h => ?_⟩
· rintro rfl
simp [zero_nsmul] at ha
obtain ⟨n, rfl⟩ := exists_eq_succ_of_ne_zero h.1
rw [succ_nsmul, mem_add]
exact Or.inr h.2
lemma mem_nsmul_of_ne_zero {a : α} {s : Multiset α} {n : ℕ} (h0 : n ≠ 0) : a ∈ n • s ↔ a ∈ s := by
simp [*]
theorem nsmul_cons {s : Multiset α} (n : ℕ) (a : α) :
n • (a ::ₘ s) = n • ({a} : Multiset α) + n • s := by
rw [← singleton_add, nsmul_add]
/-! ### Cardinality -/
/-- The cardinality of a multiset is the sum of the multiplicities
of all its elements, or simply the length of the underlying list. -/
def card : Multiset α →+ ℕ where
toFun s := (Quot.liftOn s length) fun _l₁ _l₂ => Perm.length_eq
map_zero' := rfl
map_add' s t := Quotient.inductionOn₂ s t length_append
@[simp]
theorem coe_card (l : List α) : card (l : Multiset α) = length l :=
rfl
@[simp]
theorem length_toList (s : Multiset α) : s.toList.length = card s := by
rw [← coe_card, coe_toList]
@[simp]
theorem card_zero : @card α 0 = 0 :=
rfl
theorem card_add (s t : Multiset α) : card (s + t) = card s + card t :=
card.map_add s t
theorem card_nsmul (s : Multiset α) (n : ℕ) : card (n • s) = n * card s := by
rw [card.map_nsmul s n, Nat.nsmul_eq_mul]
@[simp]
theorem card_cons (a : α) (s : Multiset α) : card (a ::ₘ s) = card s + 1 :=
Quot.inductionOn s fun _l => rfl
@[simp]
theorem card_singleton (a : α) : card ({a} : Multiset α) = 1 := by
simp only [← cons_zero, card_zero, eq_self_iff_true, zero_add, card_cons]
theorem card_pair (a b : α) : card {a, b} = 2 := by
rw [insert_eq_cons, card_cons, card_singleton]
theorem card_eq_one {s : Multiset α} : card s = 1 ↔ ∃ a, s = {a} :=
⟨Quot.inductionOn s fun _l h => (List.length_eq_one.1 h).imp fun _a => congr_arg _,
fun ⟨_a, e⟩ => e.symm ▸ rfl⟩
theorem card_le_card {s t : Multiset α} (h : s ≤ t) : card s ≤ card t :=
leInductionOn h Sublist.length_le
@[mono]
theorem card_mono : Monotone (@card α) := fun _a _b => card_le_card
theorem eq_of_le_of_card_le {s t : Multiset α} (h : s ≤ t) : card t ≤ card s → s = t :=
leInductionOn h fun s h₂ => congr_arg _ <| s.eq_of_length_le h₂
theorem card_lt_card {s t : Multiset α} (h : s < t) : card s < card t :=
lt_of_not_ge fun h₂ => _root_.ne_of_lt h <| eq_of_le_of_card_le (le_of_lt h) h₂
lemma card_strictMono : StrictMono (card : Multiset α → ℕ) := fun _ _ ↦ card_lt_card
theorem lt_iff_cons_le {s t : Multiset α} : s < t ↔ ∃ a, a ::ₘ s ≤ t :=
⟨Quotient.inductionOn₂ s t fun _l₁ _l₂ h =>
Subperm.exists_of_length_lt (le_of_lt h) (card_lt_card h),
fun ⟨_a, h⟩ => lt_of_lt_of_le (lt_cons_self _ _) h⟩
@[simp]
theorem card_eq_zero {s : Multiset α} : card s = 0 ↔ s = 0 :=
⟨fun h => (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, fun e => by simp [e]⟩
theorem card_pos {s : Multiset α} : 0 < card s ↔ s ≠ 0 :=
Nat.pos_iff_ne_zero.trans <| not_congr card_eq_zero
theorem card_pos_iff_exists_mem {s : Multiset α} : 0 < card s ↔ ∃ a, a ∈ s :=
Quot.inductionOn s fun _l => length_pos_iff_exists_mem
theorem card_eq_two {s : Multiset α} : card s = 2 ↔ ∃ x y, s = {x, y} :=
⟨Quot.inductionOn s fun _l h =>
(List.length_eq_two.mp h).imp fun _a => Exists.imp fun _b => congr_arg _,
fun ⟨_a, _b, e⟩ => e.symm ▸ rfl⟩
theorem card_eq_three {s : Multiset α} : card s = 3 ↔ ∃ x y z, s = {x, y, z} :=
⟨Quot.inductionOn s fun _l h =>
(List.length_eq_three.mp h).imp fun _a =>
Exists.imp fun _b => Exists.imp fun _c => congr_arg _,
fun ⟨_a, _b, _c, e⟩ => e.symm ▸ rfl⟩
/-! ### Induction principles -/
/-- The strong induction principle for multisets. -/
@[elab_as_elim]
def strongInductionOn {p : Multiset α → Sort*} (s : Multiset α) (ih : ∀ s, (∀ t < s, p t) → p s) :
p s :=
(ih s) fun t _h =>
strongInductionOn t ih
termination_by card s
decreasing_by exact card_lt_card _h
theorem strongInductionOn_eq {p : Multiset α → Sort*} (s : Multiset α) (H) :
@strongInductionOn _ p s H = H s fun t _h => @strongInductionOn _ p t H := by
rw [strongInductionOn]
@[elab_as_elim]
theorem case_strongInductionOn {p : Multiset α → Prop} (s : Multiset α) (h₀ : p 0)
(h₁ : ∀ a s, (∀ t ≤ s, p t) → p (a ::ₘ s)) : p s :=
Multiset.strongInductionOn s fun s =>
Multiset.induction_on s (fun _ => h₀) fun _a _s _ ih =>
(h₁ _ _) fun _t h => ih _ <| lt_of_le_of_lt h <| lt_cons_self _ _
/-- 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 multisets `s` of
cardinality less than `n`, starting from multisets of card `n` and iterating. This
can be used either to define data, or to prove properties. -/
def strongDownwardInduction {p : Multiset α → Sort*} {n : ℕ}
(H : ∀ t₁, (∀ {t₂ : Multiset α}, card t₂ ≤ n → t₁ < t₂ → p t₂) → card t₁ ≤ n → p t₁)
(s : Multiset α) :
card s ≤ n → p s :=
H s fun {t} ht _h =>
strongDownwardInduction H t ht
termination_by n - card s
decreasing_by simp_wf; have := (card_lt_card _h); omega
-- Porting note: reorderd universes
theorem strongDownwardInduction_eq {p : Multiset α → Sort*} {n : ℕ}
(H : ∀ t₁, (∀ {t₂ : Multiset α}, card t₂ ≤ n → t₁ < t₂ → p t₂) → card t₁ ≤ n → p t₁)
(s : Multiset α) :
strongDownwardInduction H s = H s fun ht _hst => strongDownwardInduction H _ ht := by
rw [strongDownwardInduction]
/-- Analogue of `strongDownwardInduction` with order of arguments swapped. -/
@[elab_as_elim]
def strongDownwardInductionOn {p : Multiset α → Sort*} {n : ℕ} :
∀ s : Multiset α,
(∀ t₁, (∀ {t₂ : Multiset α}, card t₂ ≤ n → t₁ < t₂ → p t₂) → card t₁ ≤ n → p t₁) →
card s ≤ n → p s :=
fun s H => strongDownwardInduction H s
theorem strongDownwardInductionOn_eq {p : Multiset α → Sort*} (s : Multiset α) {n : ℕ}
(H : ∀ t₁, (∀ {t₂ : Multiset α}, card t₂ ≤ n → t₁ < t₂ → p t₂) → card t₁ ≤ n → p t₁) :
s.strongDownwardInductionOn H = H s fun {t} ht _h => t.strongDownwardInductionOn H ht := by
dsimp only [strongDownwardInductionOn]
rw [strongDownwardInduction]
/-- Another way of expressing `strongInductionOn`: the `(<)` relation is well-founded. -/
instance instWellFoundedLT : WellFoundedLT (Multiset α) :=
⟨Subrelation.wf Multiset.card_lt_card (measure Multiset.card).2⟩
/-! ### `Multiset.replicate` -/
/-- `replicate n a` is the multiset containing only `a` with multiplicity `n`. -/
def replicate (n : ℕ) (a : α) : Multiset α :=
List.replicate n a
theorem coe_replicate (n : ℕ) (a : α) : (List.replicate n a : Multiset α) = replicate n a := rfl
@[simp] theorem replicate_zero (a : α) : replicate 0 a = 0 := rfl
@[simp] theorem replicate_succ (a : α) (n) : replicate (n + 1) a = a ::ₘ replicate n a := rfl
theorem replicate_add (m n : ℕ) (a : α) : replicate (m + n) a = replicate m a + replicate n a :=
congr_arg _ <| List.replicate_add ..
/-- `Multiset.replicate` as an `AddMonoidHom`. -/
@[simps]
def replicateAddMonoidHom (a : α) : ℕ →+ Multiset α where
toFun := fun n => replicate n a
map_zero' := replicate_zero a
map_add' := fun _ _ => replicate_add _ _ a
theorem replicate_one (a : α) : replicate 1 a = {a} := rfl
@[simp] theorem card_replicate (n) (a : α) : card (replicate n a) = n :=
length_replicate n a
theorem mem_replicate {a b : α} {n : ℕ} : b ∈ replicate n a ↔ n ≠ 0 ∧ b = a :=
List.mem_replicate
theorem eq_of_mem_replicate {a b : α} {n} : b ∈ replicate n a → b = a :=
List.eq_of_mem_replicate
theorem eq_replicate_card {a : α} {s : Multiset α} : s = replicate (card s) a ↔ ∀ b ∈ s, b = a :=
Quot.inductionOn s fun _l => coe_eq_coe.trans <| perm_replicate.trans eq_replicate_length
alias ⟨_, eq_replicate_of_mem⟩ := eq_replicate_card
theorem eq_replicate {a : α} {n} {s : Multiset α} :
s = replicate n a ↔ card s = n ∧ ∀ b ∈ s, b = a :=
⟨fun h => h.symm ▸ ⟨card_replicate _ _, fun _b => eq_of_mem_replicate⟩,
fun ⟨e, al⟩ => e ▸ eq_replicate_of_mem al⟩
theorem replicate_right_injective {n : ℕ} (hn : n ≠ 0) : Injective (@replicate α n) :=
fun _ _ h => (eq_replicate.1 h).2 _ <| mem_replicate.2 ⟨hn, rfl⟩
@[simp] theorem replicate_right_inj {a b : α} {n : ℕ} (h : n ≠ 0) :
replicate n a = replicate n b ↔ a = b :=
(replicate_right_injective h).eq_iff
theorem replicate_left_injective (a : α) : Injective (replicate · a) :=
-- Porting note: was `fun m n h => by rw [← (eq_replicate.1 h).1, card_replicate]`
LeftInverse.injective (card_replicate · a)
theorem replicate_subset_singleton (n : ℕ) (a : α) : replicate n a ⊆ {a} :=
List.replicate_subset_singleton n a
theorem replicate_le_coe {a : α} {n} {l : List α} : replicate n a ≤ l ↔ List.replicate n a <+ l :=
⟨fun ⟨_l', p, s⟩ => perm_replicate.1 p ▸ s, Sublist.subperm⟩
theorem nsmul_replicate {a : α} (n m : ℕ) : n • replicate m a = replicate (n * m) a :=
((replicateAddMonoidHom a).map_nsmul _ _).symm
theorem nsmul_singleton (a : α) (n) : n • ({a} : Multiset α) = replicate n a := by
rw [← replicate_one, nsmul_replicate, mul_one]
theorem replicate_le_replicate (a : α) {k n : ℕ} : replicate k a ≤ replicate n a ↔ k ≤ n :=
_root_.trans (by rw [← replicate_le_coe, coe_replicate]) (List.replicate_sublist_replicate a)
theorem le_replicate_iff {m : Multiset α} {a : α} {n : ℕ} :
m ≤ replicate n a ↔ ∃ k ≤ n, m = replicate k a :=
⟨fun h => ⟨card m, (card_mono h).trans_eq (card_replicate _ _),
eq_replicate_card.2 fun _ hb => eq_of_mem_replicate <| subset_of_le h hb⟩,
fun ⟨_, hkn, hm⟩ => hm.symm ▸ (replicate_le_replicate _).2 hkn⟩
theorem lt_replicate_succ {m : Multiset α} {x : α} {n : ℕ} :
m < replicate (n + 1) x ↔ m ≤ replicate n x := by
rw [lt_iff_cons_le]
constructor
· rintro ⟨x', hx'⟩
have := eq_of_mem_replicate (mem_of_le hx' (mem_cons_self _ _))
rwa [this, replicate_succ, cons_le_cons_iff] at hx'
· intro h
rw [replicate_succ]
exact ⟨x, cons_le_cons _ h⟩
/-! ### Erasing one copy of an element -/
section Erase
variable [DecidableEq α] {s t : Multiset α} {a b : α}
/-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/
def erase (s : Multiset α) (a : α) : Multiset α :=
Quot.liftOn s (fun l => (l.erase a : Multiset α)) fun _l₁ _l₂ p => Quot.sound (p.erase a)
@[simp]
theorem coe_erase (l : List α) (a : α) : erase (l : Multiset α) a = l.erase a :=
rfl
@[simp]
theorem erase_zero (a : α) : (0 : Multiset α).erase a = 0 :=
rfl
@[simp]
theorem erase_cons_head (a : α) (s : Multiset α) : (a ::ₘ s).erase a = s :=
Quot.inductionOn s fun l => congr_arg _ <| List.erase_cons_head a l
@[simp]
theorem erase_cons_tail {a b : α} (s : Multiset α) (h : b ≠ a) :
(b ::ₘ s).erase a = b ::ₘ s.erase a :=
Quot.inductionOn s fun _ => congr_arg _ <| List.erase_cons_tail (not_beq_of_ne h)
@[simp]
theorem erase_singleton (a : α) : ({a} : Multiset α).erase a = 0 :=
erase_cons_head a 0
@[simp]
theorem erase_of_not_mem {a : α} {s : Multiset α} : a ∉ s → s.erase a = s :=
Quot.inductionOn s fun _l h => congr_arg _ <| List.erase_of_not_mem h
@[simp]
theorem cons_erase {s : Multiset α} {a : α} : a ∈ s → a ::ₘ s.erase a = s :=
Quot.inductionOn s fun _l h => Quot.sound (perm_cons_erase h).symm
theorem erase_cons_tail_of_mem (h : a ∈ s) :
(b ::ₘ s).erase a = b ::ₘ s.erase a := by
rcases eq_or_ne a b with rfl | hab
· simp [cons_erase h]
· exact s.erase_cons_tail hab.symm
theorem le_cons_erase (s : Multiset α) (a : α) : s ≤ a ::ₘ s.erase a :=
if h : a ∈ s then le_of_eq (cons_erase h).symm
else by rw [erase_of_not_mem h]; apply le_cons_self
theorem add_singleton_eq_iff {s t : Multiset α} {a : α} : s + {a} = t ↔ a ∈ t ∧ s = t.erase a := by
rw [add_comm, singleton_add]; constructor
· rintro rfl
exact ⟨s.mem_cons_self a, (s.erase_cons_head a).symm⟩
· rintro ⟨h, rfl⟩
exact cons_erase h
theorem erase_add_left_pos {a : α} {s : Multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t :=
Quotient.inductionOn₂ s t fun _l₁ l₂ h => congr_arg _ <| erase_append_left l₂ h
theorem erase_add_right_pos {a : α} (s) {t : Multiset α} (h : a ∈ t) :
(s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm]
theorem erase_add_right_neg {a : α} {s : Multiset α} (t) :
a ∉ s → (s + t).erase a = s + t.erase a :=
Quotient.inductionOn₂ s t fun _l₁ l₂ h => congr_arg _ <| erase_append_right l₂ h
theorem erase_add_left_neg {a : α} (s) {t : Multiset α} (h : a ∉ t) :
(s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm]
theorem erase_le (a : α) (s : Multiset α) : s.erase a ≤ s :=
Quot.inductionOn s fun l => (erase_sublist a l).subperm
@[simp]
theorem erase_lt {a : α} {s : Multiset α} : s.erase a < s ↔ a ∈ s :=
⟨fun h => not_imp_comm.1 erase_of_not_mem (ne_of_lt h), fun h => by
simpa [h] using lt_cons_self (s.erase a) a⟩
theorem erase_subset (a : α) (s : Multiset α) : s.erase a ⊆ s :=
subset_of_le (erase_le a s)
theorem mem_erase_of_ne {a b : α} {s : Multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s :=
Quot.inductionOn s fun _l => List.mem_erase_of_ne ab
theorem mem_of_mem_erase {a b : α} {s : Multiset α} : a ∈ s.erase b → a ∈ s :=
mem_of_subset (erase_subset _ _)
theorem erase_comm (s : Multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a :=
Quot.inductionOn s fun l => congr_arg _ <| l.erase_comm a b
theorem erase_le_erase {s t : Multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a :=
leInductionOn h fun h => (h.erase _).subperm
theorem erase_le_iff_le_cons {s t : Multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a ::ₘ t :=
⟨fun h => le_trans (le_cons_erase _ _) (cons_le_cons _ h), fun h =>
if m : a ∈ s then by rw [← cons_erase m] at h; exact (cons_le_cons_iff _).1 h
else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩
@[simp]
theorem card_erase_of_mem {a : α} {s : Multiset α} : a ∈ s → card (s.erase a) = pred (card s) :=
Quot.inductionOn s fun _l => length_erase_of_mem
@[simp]
theorem card_erase_add_one {a : α} {s : Multiset α} : a ∈ s → card (s.erase a) + 1 = card s :=
Quot.inductionOn s fun _l => length_erase_add_one
theorem card_erase_lt_of_mem {a : α} {s : Multiset α} : a ∈ s → card (s.erase a) < card s :=
fun h => card_lt_card (erase_lt.mpr h)
theorem card_erase_le {a : α} {s : Multiset α} : card (s.erase a) ≤ card s :=
card_le_card (erase_le a s)
theorem card_erase_eq_ite {a : α} {s : Multiset α} :
card (s.erase a) = if a ∈ s then pred (card s) else card s := by
by_cases h : a ∈ s
· rwa [card_erase_of_mem h, if_pos]
· rwa [erase_of_not_mem h, if_neg]
end Erase
@[simp]
theorem coe_reverse (l : List α) : (reverse l : Multiset α) = l :=
Quot.sound <| reverse_perm _
/-! ### `Multiset.map` -/
/-- `map f s` is the lift of the list `map` operation. The multiplicity
of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity)
such that `f a = b`. -/
def map (f : α → β) (s : Multiset α) : Multiset β :=
Quot.liftOn s (fun l : List α => (l.map f : Multiset β)) fun _l₁ _l₂ p => Quot.sound (p.map f)
@[congr]
theorem map_congr {f g : α → β} {s t : Multiset α} :
s = t → (∀ x ∈ t, f x = g x) → map f s = map g t := by
rintro rfl h
induction s using Quot.inductionOn
exact congr_arg _ (List.map_congr_left h)
theorem map_hcongr {β' : Type v} {m : Multiset α} {f : α → β} {f' : α → β'} (h : β = β')
(hf : ∀ a ∈ m, HEq (f a) (f' a)) : HEq (map f m) (map f' m) := by
subst h; simp at hf
simp [map_congr rfl hf]
theorem forall_mem_map_iff {f : α → β} {p : β → Prop} {s : Multiset α} :
(∀ y ∈ s.map f, p y) ↔ ∀ x ∈ s, p (f x) :=
Quotient.inductionOn' s fun _L => List.forall_mem_map
@[simp, norm_cast] lemma map_coe (f : α → β) (l : List α) : map f l = l.map f := rfl
@[simp]
theorem map_zero (f : α → β) : map f 0 = 0 :=
rfl
@[simp]
theorem map_cons (f : α → β) (a s) : map f (a ::ₘ s) = f a ::ₘ map f s :=
Quot.inductionOn s fun _l => rfl
theorem map_comp_cons (f : α → β) (t) : map f ∘ cons t = cons (f t) ∘ map f := by
ext
simp
@[simp]
theorem map_singleton (f : α → β) (a : α) : ({a} : Multiset α).map f = {f a} :=
rfl
@[simp]
theorem map_replicate (f : α → β) (k : ℕ) (a : α) : (replicate k a).map f = replicate k (f a) := by
simp only [← coe_replicate, map_coe, List.map_replicate]
@[simp]
theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t :=
Quotient.inductionOn₂ s t fun _l₁ _l₂ => congr_arg _ <| map_append _ _ _
/-- If each element of `s : Multiset α` can be lifted to `β`, then `s` can be lifted to
`Multiset β`. -/
instance canLift (c) (p) [CanLift α β c p] :
CanLift (Multiset α) (Multiset β) (map c) fun s => ∀ x ∈ s, p x where
prf := by
rintro ⟨l⟩ hl
lift l to List β using hl
exact ⟨l, map_coe _ _⟩
/-- `Multiset.map` as an `AddMonoidHom`. -/
def mapAddMonoidHom (f : α → β) : Multiset α →+ Multiset β where
toFun := map f
map_zero' := map_zero _
map_add' := map_add _
@[simp]
theorem coe_mapAddMonoidHom (f : α → β) :
(mapAddMonoidHom f : Multiset α → Multiset β) = map f :=
rfl
theorem map_nsmul (f : α → β) (n : ℕ) (s) : map f (n • s) = n • map f s :=
(mapAddMonoidHom f).map_nsmul _ _
@[simp]
theorem mem_map {f : α → β} {b : β} {s : Multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b :=
Quot.inductionOn s fun _l => List.mem_map
@[simp]
theorem card_map (f : α → β) (s) : card (map f s) = card s :=
Quot.inductionOn s fun _l => length_map _ _
@[simp]
theorem map_eq_zero {s : Multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 := by
rw [← Multiset.card_eq_zero, Multiset.card_map, Multiset.card_eq_zero]
theorem mem_map_of_mem (f : α → β) {a : α} {s : Multiset α} (h : a ∈ s) : f a ∈ map f s :=
mem_map.2 ⟨_, h, rfl⟩
theorem map_eq_singleton {f : α → β} {s : Multiset α} {b : β} :
map f s = {b} ↔ ∃ a : α, s = {a} ∧ f a = b := by
constructor
· intro h
obtain ⟨a, ha⟩ : ∃ a, s = {a} := by rw [← card_eq_one, ← card_map, h, card_singleton]
refine ⟨a, ha, ?_⟩
rw [← mem_singleton, ← h, ha, map_singleton, mem_singleton]
· rintro ⟨a, rfl, rfl⟩
simp
theorem map_eq_cons [DecidableEq α] (f : α → β) (s : Multiset α) (t : Multiset β) (b : β) :
(∃ a ∈ s, f a = b ∧ (s.erase a).map f = t) ↔ s.map f = b ::ₘ t := by
constructor
· rintro ⟨a, ha, rfl, rfl⟩
rw [← map_cons, Multiset.cons_erase ha]
· intro h
have : b ∈ s.map f := by
rw [h]
exact mem_cons_self _ _
obtain ⟨a, h1, rfl⟩ := mem_map.mp this
obtain ⟨u, rfl⟩ := exists_cons_of_mem h1
rw [map_cons, cons_inj_right] at h
refine ⟨a, mem_cons_self _ _, rfl, ?_⟩
rw [Multiset.erase_cons_head, h]
-- The simpNF linter says that the LHS can be simplified via `Multiset.mem_map`.
-- However this is a higher priority lemma.
-- https://github.com/leanprover/std4/issues/207
@[simp 1100, nolint simpNF]
theorem mem_map_of_injective {f : α → β} (H : Function.Injective f) {a : α} {s : Multiset α} :
f a ∈ map f s ↔ a ∈ s :=
Quot.inductionOn s fun _l => List.mem_map_of_injective H
@[simp]
theorem map_map (g : β → γ) (f : α → β) (s : Multiset α) : map g (map f s) = map (g ∘ f) s :=
Quot.inductionOn s fun _l => congr_arg _ <| List.map_map _ _ _
theorem map_id (s : Multiset α) : map id s = s :=
Quot.inductionOn s fun _l => congr_arg _ <| List.map_id _
@[simp]
theorem map_id' (s : Multiset α) : map (fun x => x) s = s :=
map_id s
-- Porting note: was a `simp` lemma in mathlib3
theorem map_const (s : Multiset α) (b : β) : map (const α b) s = replicate (card s) b :=
Quot.inductionOn s fun _ => congr_arg _ <| List.map_const' _ _
-- Porting note: was not a `simp` lemma in mathlib3 because `Function.const` was reducible
@[simp] theorem map_const' (s : Multiset α) (b : β) : map (fun _ ↦ b) s = replicate (card s) b :=
map_const _ _
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : List α} (h : b₁ ∈ map (Function.const α b₂) l) :
b₁ = b₂ :=
eq_of_mem_replicate (n := card (l : Multiset α)) <| by rwa [map_const] at h
@[simp]
theorem map_le_map {f : α → β} {s t : Multiset α} (h : s ≤ t) : map f s ≤ map f t :=
leInductionOn h fun h => (h.map f).subperm
@[simp]
theorem map_lt_map {f : α → β} {s t : Multiset α} (h : s < t) : s.map f < t.map f := by
refine (map_le_map h.le).lt_of_not_le fun H => h.ne <| eq_of_le_of_card_le h.le ?_
rw [← s.card_map f, ← t.card_map f]
exact card_le_card H
theorem map_mono (f : α → β) : Monotone (map f) := fun _ _ => map_le_map
theorem map_strictMono (f : α → β) : StrictMono (map f) := fun _ _ => map_lt_map
@[simp]
theorem map_subset_map {f : α → β} {s t : Multiset α} (H : s ⊆ t) : map f s ⊆ map f t := fun _b m =>
let ⟨a, h, e⟩ := mem_map.1 m
mem_map.2 ⟨a, H h, e⟩
theorem map_erase [DecidableEq α] [DecidableEq β] (f : α → β) (hf : Function.Injective f) (x : α)
(s : Multiset α) : (s.erase x).map f = (s.map f).erase (f x) := by
induction' s using Multiset.induction_on with y s ih
· simp
by_cases hxy : y = x
· cases hxy
simp
· rw [s.erase_cons_tail hxy, map_cons, map_cons, (s.map f).erase_cons_tail (hf.ne hxy), ih]
theorem map_erase_of_mem [DecidableEq α] [DecidableEq β] (f : α → β)
(s : Multiset α) {x : α} (h : x ∈ s) : (s.erase x).map f = (s.map f).erase (f x) := by
induction' s using Multiset.induction_on with y s ih
· simp
rcases eq_or_ne y x with rfl | hxy
· simp
replace h : x ∈ s := by simpa [hxy.symm] using h
rw [s.erase_cons_tail hxy, map_cons, map_cons, ih h, erase_cons_tail_of_mem (mem_map_of_mem f h)]
theorem map_surjective_of_surjective {f : α → β} (hf : Function.Surjective f) :
Function.Surjective (map f) := by
intro s
induction' s using Multiset.induction_on with x s ih
· exact ⟨0, map_zero _⟩
· obtain ⟨y, rfl⟩ := hf x
obtain ⟨t, rfl⟩ := ih
exact ⟨y ::ₘ t, map_cons _ _ _⟩
/-! ### `Multiset.fold` -/
/-- `foldl f H b s` is the lift of the list operation `foldl f b l`,
which folds `f` over the multiset. It is well defined when `f` is right-commutative,
that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/
def foldl (f : β → α → β) (H : RightCommutative f) (b : β) (s : Multiset α) : β :=
Quot.liftOn s (fun l => List.foldl f b l) fun _l₁ _l₂ p => p.foldl_eq H b
@[simp]
theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b :=
rfl
@[simp]
theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a ::ₘ s) = foldl f H (f b a) s :=
Quot.inductionOn s fun _l => rfl
@[simp]
theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t :=
Quotient.inductionOn₂ s t fun _l₁ _l₂ => foldl_append _ _ _ _
/-- `foldr f H b s` is the lift of the list operation `foldr f b l`,
which folds `f` over the multiset. It is well defined when `f` is left-commutative,
that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/
def foldr (f : α → β → β) (H : LeftCommutative f) (b : β) (s : Multiset α) : β :=
Quot.liftOn s (fun l => List.foldr f b l) fun _l₁ _l₂ p => p.foldr_eq H b
@[simp]
theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b :=
rfl
@[simp]
theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a ::ₘ s) = f a (foldr f H b s) :=
Quot.inductionOn s fun _l => rfl
@[simp]
theorem foldr_singleton (f : α → β → β) (H b a) : foldr f H b ({a} : Multiset α) = f a b :=
rfl
@[simp]
theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s :=
Quotient.inductionOn₂ s t fun _l₁ _l₂ => foldr_append _ _ _ _
@[simp]
theorem coe_foldr (f : α → β → β) (H : LeftCommutative f) (b : β) (l : List α) :
foldr f H b l = l.foldr f b :=
rfl
@[simp]
theorem coe_foldl (f : β → α → β) (H : RightCommutative f) (b : β) (l : List α) :
foldl f H b l = l.foldl f b :=
rfl
theorem coe_foldr_swap (f : α → β → β) (H : LeftCommutative f) (b : β) (l : List α) :
foldr f H b l = l.foldl (fun x y => f y x) b :=
(congr_arg (foldr f H b) (coe_reverse l)).symm.trans <| foldr_reverse _ _ _
theorem foldr_swap (f : α → β → β) (H : LeftCommutative f) (b : β) (s : Multiset α) :
foldr f H b s = foldl (fun x y => f y x) (fun _x _y _z => (H _ _ _).symm) b s :=
Quot.inductionOn s fun _l => coe_foldr_swap _ _ _ _
theorem foldl_swap (f : β → α → β) (H : RightCommutative f) (b : β) (s : Multiset α) :
foldl f H b s = foldr (fun x y => f y x) (fun _x _y _z => (H _ _ _).symm) b s :=
(foldr_swap _ _ _ _).symm
theorem foldr_induction' (f : α → β → β) (H : LeftCommutative f) (x : β) (q : α → Prop)
(p : β → Prop) (s : Multiset α) (hpqf : ∀ a b, q a → p b → p (f a b)) (px : p x)
(q_s : ∀ a ∈ s, q a) : p (foldr f H x s) := by
induction s using Multiset.induction with
| empty => simpa
| cons a s ihs =>
simp only [forall_mem_cons, foldr_cons] at q_s ⊢
exact hpqf _ _ q_s.1 (ihs q_s.2)
theorem foldr_induction (f : α → α → α) (H : LeftCommutative f) (x : α) (p : α → Prop)
(s : Multiset α) (p_f : ∀ a b, p a → p b → p (f a b)) (px : p x) (p_s : ∀ a ∈ s, p a) :
p (foldr f H x s) :=
foldr_induction' f H x p p s p_f px p_s
theorem foldl_induction' (f : β → α → β) (H : RightCommutative f) (x : β) (q : α → Prop)
(p : β → Prop) (s : Multiset α) (hpqf : ∀ a b, q a → p b → p (f b a)) (px : p x)
(q_s : ∀ a ∈ s, q a) : p (foldl f H x s) := by
rw [foldl_swap]
exact foldr_induction' (fun x y => f y x) (fun x y z => (H _ _ _).symm) x q p s hpqf px q_s
theorem foldl_induction (f : α → α → α) (H : RightCommutative f) (x : α) (p : α → Prop)
(s : Multiset α) (p_f : ∀ a b, p a → p b → p (f b a)) (px : p x) (p_s : ∀ a ∈ s, p a) :
p (foldl f H x s) :=
foldl_induction' f H x p p s p_f px p_s
/-! ### Map for partial functions -/
/-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset
`s` whose elements are all in the domain of `f`. -/
nonrec def pmap {p : α → Prop} (f : ∀ a, p a → β) (s : Multiset α) : (∀ a ∈ s, p a) → Multiset β :=
Quot.recOn' s (fun l H => ↑(pmap f l H)) fun l₁ l₂ (pp : l₁ ~ l₂) =>
funext fun H₂ : ∀ a ∈ l₂, p a =>
have H₁ : ∀ a ∈ l₁, p a := fun a h => H₂ a (pp.subset h)
have : ∀ {s₂ e H}, @Eq.ndrec (Multiset α) l₁ (fun s => (∀ a ∈ s, p a) → Multiset β)
(fun _ => ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁) := by
intro s₂ e _; subst e; rfl
this.trans <| Quot.sound <| pp.pmap f
@[simp]
theorem coe_pmap {p : α → Prop} (f : ∀ a, p a → β) (l : List α) (H : ∀ a ∈ l, p a) :
pmap f l H = l.pmap f H :=
rfl
@[simp]
theorem pmap_zero {p : α → Prop} (f : ∀ a, p a → β) (h : ∀ a ∈ (0 : Multiset α), p a) :
pmap f 0 h = 0 :=
rfl
@[simp]
theorem pmap_cons {p : α → Prop} (f : ∀ a, p a → β) (a : α) (m : Multiset α) :
∀ h : ∀ b ∈ a ::ₘ m, p b,
pmap f (a ::ₘ m) h =
f a (h a (mem_cons_self a m)) ::ₘ pmap f m fun a ha => h a <| mem_cons_of_mem ha :=
Quotient.inductionOn m fun _l _h => rfl
/-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce
a multiset on `{x // x ∈ s}`. -/
def attach (s : Multiset α) : Multiset { x // x ∈ s } :=
pmap Subtype.mk s fun _a => id
@[simp]
theorem coe_attach (l : List α) : @Eq (Multiset { x // x ∈ l }) (@attach α l) l.attach :=
rfl
theorem sizeOf_lt_sizeOf_of_mem [SizeOf α] {x : α} {s : Multiset α} (hx : x ∈ s) :
SizeOf.sizeOf x < SizeOf.sizeOf s := by
induction' s using Quot.inductionOn with l a b
exact List.sizeOf_lt_sizeOf_of_mem hx
theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : Multiset α) :
∀ H, @pmap _ _ p (fun a _ => f a) s H = map f s :=
Quot.inductionOn s fun l H => congr_arg _ <| List.pmap_eq_map p f l H
theorem pmap_congr {p q : α → Prop} {f : ∀ a, p a → β} {g : ∀ a, q a → β} (s : Multiset α) :
∀ {H₁ H₂}, (∀ a ∈ s, ∀ (h₁ h₂), f a h₁ = g a h₂) → pmap f s H₁ = pmap g s H₂ :=
@(Quot.inductionOn s (fun l _H₁ _H₂ h => congr_arg _ <| List.pmap_congr l h))
theorem map_pmap {p : α → Prop} (g : β → γ) (f : ∀ a, p a → β) (s) :
∀ H, map g (pmap f s H) = pmap (fun a h => g (f a h)) s H :=
Quot.inductionOn s fun l H => congr_arg _ <| List.map_pmap g f l H
theorem pmap_eq_map_attach {p : α → Prop} (f : ∀ a, p a → β) (s) :
∀ H, pmap f s H = s.attach.map fun x => f x.1 (H _ x.2) :=
Quot.inductionOn s fun l H => congr_arg _ <| List.pmap_eq_map_attach f l H
-- @[simp] -- Porting note: Left hand does not simplify
theorem attach_map_val' (s : Multiset α) (f : α → β) : (s.attach.map fun i => f i.val) = s.map f :=
Quot.inductionOn s fun l => congr_arg _ <| List.attach_map_coe l f
@[simp]
theorem attach_map_val (s : Multiset α) : s.attach.map Subtype.val = s :=
(attach_map_val' _ _).trans s.map_id
@[simp]
theorem mem_attach (s : Multiset α) : ∀ x, x ∈ s.attach :=
Quot.inductionOn s fun _l => List.mem_attach _
@[simp]
theorem mem_pmap {p : α → Prop} {f : ∀ a, p a → β} {s H b} :
b ∈ pmap f s H ↔ ∃ (a : _) (h : a ∈ s), f a (H a h) = b :=
Quot.inductionOn s (fun _l _H => List.mem_pmap) H
@[simp]
theorem card_pmap {p : α → Prop} (f : ∀ a, p a → β) (s H) : card (pmap f s H) = card s :=
Quot.inductionOn s (fun _l _H => length_pmap) H
@[simp]
theorem card_attach {m : Multiset α} : card (attach m) = card m :=
card_pmap _ _ _
@[simp]
theorem attach_zero : (0 : Multiset α).attach = 0 :=
rfl
theorem attach_cons (a : α) (m : Multiset α) :
(a ::ₘ m).attach =
⟨a, mem_cons_self a m⟩ ::ₘ m.attach.map fun p => ⟨p.1, mem_cons_of_mem p.2⟩ :=
Quotient.inductionOn m fun l =>
congr_arg _ <|
congr_arg (List.cons _) <| by
rw [List.map_pmap]; exact List.pmap_congr _ fun _ _ _ _ => Subtype.eq rfl
section DecidablePiExists
variable {m : Multiset α}
/-- If `p` is a decidable predicate,
so is the predicate that all elements of a multiset satisfy `p`. -/
protected def decidableForallMultiset {p : α → Prop} [hp : ∀ a, Decidable (p a)] :
Decidable (∀ a ∈ m, p a) :=
Quotient.recOnSubsingleton m fun l => decidable_of_iff (∀ a ∈ l, p a) <| by simp
instance decidableDforallMultiset {p : ∀ a ∈ m, Prop} [_hp : ∀ (a) (h : a ∈ m), Decidable (p a h)] :
Decidable (∀ (a) (h : a ∈ m), p a h) :=
@decidable_of_iff _ _
(Iff.intro (fun h a ha => h ⟨a, ha⟩ (mem_attach _ _)) fun h ⟨_a, _ha⟩ _ => h _ _)
(@Multiset.decidableForallMultiset _ m.attach (fun a => p a.1 a.2) _)
/-- decidable equality for functions whose domain is bounded by multisets -/
instance decidableEqPiMultiset {β : α → Type*} [h : ∀ a, DecidableEq (β a)] :
DecidableEq (∀ a ∈ m, β a) := fun f g =>
decidable_of_iff (∀ (a) (h : a ∈ m), f a h = g a h) (by simp [Function.funext_iff])
/-- If `p` is a decidable predicate,
so is the existence of an element in a multiset satisfying `p`. -/
protected def decidableExistsMultiset {p : α → Prop} [DecidablePred p] : Decidable (∃ x ∈ m, p x) :=
Quotient.recOnSubsingleton m fun l => decidable_of_iff (∃ a ∈ l, p a) <| by simp
instance decidableDexistsMultiset {p : ∀ a ∈ m, Prop} [_hp : ∀ (a) (h : a ∈ m), Decidable (p a h)] :
Decidable (∃ (a : _) (h : a ∈ m), p a h) :=
@decidable_of_iff _ _
(Iff.intro (fun ⟨⟨a, ha₁⟩, _, ha₂⟩ => ⟨a, ha₁, ha₂⟩) fun ⟨a, ha₁, ha₂⟩ =>
⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩)
(@Multiset.decidableExistsMultiset { a // a ∈ m } m.attach (fun a => p a.1 a.2) _)
end DecidablePiExists
/-! ### Subtraction -/
section
variable [DecidableEq α] {s t u : Multiset α} {a b : α}
/-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`
(note that it is truncated subtraction, so it is `0` if `count a t ≥ count a s`). -/
protected def sub (s t : Multiset α) : Multiset α :=
(Quotient.liftOn₂ s t fun l₁ l₂ => (l₁.diff l₂ : Multiset α)) fun _v₁ _v₂ _w₁ _w₂ p₁ p₂ =>
Quot.sound <| p₁.diff p₂
instance : Sub (Multiset α) :=
⟨Multiset.sub⟩
@[simp]
theorem coe_sub (s t : List α) : (s - t : Multiset α) = (s.diff t : List α) :=
rfl
/-- This is a special case of `tsub_zero`, which should be used instead of this.
This is needed to prove `OrderedSub (Multiset α)`. -/
protected theorem sub_zero (s : Multiset α) : s - 0 = s :=
Quot.inductionOn s fun _l => rfl
@[simp]
theorem sub_cons (a : α) (s t : Multiset α) : s - a ::ₘ t = s.erase a - t :=
Quotient.inductionOn₂ s t fun _l₁ _l₂ => congr_arg _ <| diff_cons _ _ _
/-- This is a special case of `tsub_le_iff_right`, which should be used instead of this.
This is needed to prove `OrderedSub (Multiset α)`. -/
protected theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by
revert s
exact @(Multiset.induction_on t (by simp [Multiset.sub_zero]) fun a t IH s => by
simp [IH, erase_le_iff_le_cons])
instance : OrderedSub (Multiset α) :=
⟨fun _n _m _k => Multiset.sub_le_iff_le_add⟩
theorem cons_sub_of_le (a : α) {s t : Multiset α} (h : t ≤ s) : a ::ₘ s - t = a ::ₘ (s - t) := by
rw [← singleton_add, ← singleton_add, add_tsub_assoc_of_le h]
theorem sub_eq_fold_erase (s t : Multiset α) : s - t = foldl erase erase_comm s t :=
Quotient.inductionOn₂ s t fun l₁ l₂ => by
show ofList (l₁.diff l₂) = foldl erase erase_comm l₁ l₂
rw [diff_eq_foldl l₁ l₂]
symm
exact foldl_hom _ _ _ _ _ fun x y => rfl
@[simp]
theorem card_sub {s t : Multiset α} (h : t ≤ s) : card (s - t) = card s - card t :=
Nat.eq_sub_of_add_eq $ by rw [← card_add, tsub_add_cancel_of_le h]
/-! ### Union -/
/-- `s ∪ t` is the lattice join operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum
of the multiplicities in `s` and `t`. -/
def union (s t : Multiset α) : Multiset α :=
s - t + t
instance : Union (Multiset α) :=
⟨union⟩
theorem union_def (s t : Multiset α) : s ∪ t = s - t + t :=
rfl
theorem le_union_left (s t : Multiset α) : s ≤ s ∪ t :=
le_tsub_add
theorem le_union_right (s t : Multiset α) : t ≤ s ∪ t :=
le_add_left _ _
theorem eq_union_left : t ≤ s → s ∪ t = s :=
tsub_add_cancel_of_le
theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u :=
add_le_add_right (tsub_le_tsub_right h _) u
theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by
rw [← eq_union_left h₂]; exact union_le_union_right h₁ t
@[simp]
theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t :=
⟨fun h => (mem_add.1 h).imp_left (mem_of_le tsub_le_self),
(Or.elim · (mem_of_le <| le_union_left _ _) (mem_of_le <| le_union_right _ _))⟩
@[simp]
theorem map_union [DecidableEq β] {f : α → β} (finj : Function.Injective f) {s t : Multiset α} :
map f (s ∪ t) = map f s ∪ map f t :=
Quotient.inductionOn₂ s t fun l₁ l₂ =>
congr_arg ofList (by rw [List.map_append f, List.map_diff finj])
@[simp] theorem zero_union : 0 ∪ s = s := by
simp [union_def]
@[simp] theorem union_zero : s ∪ 0 = s := by
simp [union_def]
/-! ### Intersection -/
/-- `s ∩ t` is the lattice meet operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum
of the multiplicities in `s` and `t`. -/
def inter (s t : Multiset α) : Multiset α :=
Quotient.liftOn₂ s t (fun l₁ l₂ => (l₁.bagInter l₂ : Multiset α)) fun _v₁ _v₂ _w₁ _w₂ p₁ p₂ =>
Quot.sound <| p₁.bagInter p₂
instance : Inter (Multiset α) :=
⟨inter⟩
@[simp]
theorem inter_zero (s : Multiset α) : s ∩ 0 = 0 :=
Quot.inductionOn s fun l => congr_arg ofList l.bagInter_nil
@[simp]
theorem zero_inter (s : Multiset α) : 0 ∩ s = 0 :=
Quot.inductionOn s fun l => congr_arg ofList l.nil_bagInter
@[simp]
theorem cons_inter_of_pos {a} (s : Multiset α) {t} : a ∈ t → (a ::ₘ s) ∩ t = a ::ₘ s ∩ t.erase a :=
Quotient.inductionOn₂ s t fun _l₁ _l₂ h => congr_arg ofList <| cons_bagInter_of_pos _ h
@[simp]
theorem cons_inter_of_neg {a} (s : Multiset α) {t} : a ∉ t → (a ::ₘ s) ∩ t = s ∩ t :=
Quotient.inductionOn₂ s t fun _l₁ _l₂ h => congr_arg ofList <| cons_bagInter_of_neg _ h
theorem inter_le_left (s t : Multiset α) : s ∩ t ≤ s :=
Quotient.inductionOn₂ s t fun _l₁ _l₂ => (bagInter_sublist_left _ _).subperm
theorem inter_le_right (s : Multiset α) : ∀ t, s ∩ t ≤ t :=
Multiset.induction_on s (fun t => (zero_inter t).symm ▸ zero_le _) fun a s IH t =>
if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH]
theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := by
revert s u; refine @(Multiset.induction_on t ?_ fun a t IH => ?_) <;> intros s u h₁ h₂
· simpa only [zero_inter, nonpos_iff_eq_zero] using h₁
by_cases h : a ∈ u
· rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons]
exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂)
· rw [cons_inter_of_neg _ h]
exact IH ((le_cons_of_not_mem <| mt (mem_of_le h₂) h).1 h₁) h₂
@[simp]
theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t :=
⟨fun h => ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, fun ⟨h₁, h₂⟩ => by
rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩
instance : Lattice (Multiset α) :=
{ sup := (· ∪ ·)
sup_le := @union_le _ _
le_sup_left := le_union_left
le_sup_right := le_union_right
inf := (· ∩ ·)
le_inf := @le_inter _ _
inf_le_left := inter_le_left
inf_le_right := inter_le_right }
@[simp]
theorem sup_eq_union (s t : Multiset α) : s ⊔ t = s ∪ t :=
rfl
@[simp]
theorem inf_eq_inter (s t : Multiset α) : s ⊓ t = s ∩ t :=
rfl
@[simp]
theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u :=
le_inf_iff
@[simp]
theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u :=
sup_le_iff
theorem union_comm (s t : Multiset α) : s ∪ t = t ∪ s := sup_comm _ _
theorem inter_comm (s t : Multiset α) : s ∩ t = t ∩ s := inf_comm _ _
theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h]
theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t :=
sup_le_sup_left h _
theorem union_le_add (s t : Multiset α) : s ∪ t ≤ s + t :=
union_le (le_add_right _ _) (le_add_left _ _)
theorem union_add_distrib (s t u : Multiset α) : s ∪ t + u = s + u ∪ (t + u) := by
simpa [(· ∪ ·), union, eq_comm, add_assoc] using
show s + u - (t + u) = s - t by rw [add_comm t, tsub_add_eq_tsub_tsub, add_tsub_cancel_right]
theorem add_union_distrib (s t u : Multiset α) : s + (t ∪ u) = s + t ∪ (s + u) := by
rw [add_comm, union_add_distrib, add_comm s, add_comm s]
theorem cons_union_distrib (a : α) (s t : Multiset α) : a ::ₘ (s ∪ t) = a ::ₘ s ∪ a ::ₘ t := by
simpa using add_union_distrib (a ::ₘ 0) s t
theorem inter_add_distrib (s t u : Multiset α) : s ∩ t + u = (s + u) ∩ (t + u) := by
by_contra h
cases'
lt_iff_cons_le.1
(lt_of_le_of_ne
(le_inter (add_le_add_right (inter_le_left s t) u)
(add_le_add_right (inter_le_right s t) u))
h) with
a hl
rw [← cons_add] at hl
exact
not_le_of_lt (lt_cons_self (s ∩ t) a)
(le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _)))
(le_of_add_le_add_right (le_trans hl (inter_le_right _ _))))
theorem add_inter_distrib (s t u : Multiset α) : s + t ∩ u = (s + t) ∩ (s + u) := by
rw [add_comm, inter_add_distrib, add_comm s, add_comm s]
theorem cons_inter_distrib (a : α) (s t : Multiset α) : a ::ₘ s ∩ t = (a ::ₘ s) ∩ (a ::ₘ t) := by
simp
theorem union_add_inter (s t : Multiset α) : s ∪ t + s ∩ t = s + t := by
apply _root_.le_antisymm
· rw [union_add_distrib]
refine union_le (add_le_add_left (inter_le_right _ _) _) ?_
rw [add_comm]
exact add_le_add_right (inter_le_left _ _) _
· rw [add_comm, add_inter_distrib]
refine le_inter (add_le_add_right (le_union_right _ _) _) ?_
rw [add_comm]
exact add_le_add_right (le_union_left _ _) _
theorem sub_add_inter (s t : Multiset α) : s - t + s ∩ t = s := by
rw [inter_comm]
revert s; refine Multiset.induction_on t (by simp) fun a t IH s => ?_
by_cases h : a ∈ s
· rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h]
· rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH]
theorem sub_inter (s t : Multiset α) : s - s ∩ t = s - t :=
add_right_cancel (b := s ∩ t) <| by
rw [sub_add_inter s t, tsub_add_cancel_of_le (inter_le_left s t)]
end
/-! ### `Multiset.filter` -/
section
variable (p : α → Prop) [DecidablePred p]
/-- `Filter p s` returns the elements in `s` (with the same multiplicities)
which satisfy `p`, and removes the rest. -/
def filter (s : Multiset α) : Multiset α :=
Quot.liftOn s (fun l => (List.filter p l : Multiset α)) fun _l₁ _l₂ h => Quot.sound <| h.filter p
@[simp, norm_cast] lemma filter_coe (l : List α) : filter p l = l.filter p := rfl
@[simp]
theorem filter_zero : filter p 0 = 0 :=
rfl
#adaptation_note
/--
Please re-enable the linter once we moved to `nightly-2024-06-22` or later.
-/
set_option linter.deprecated false in
theorem filter_congr {p q : α → Prop} [DecidablePred p] [DecidablePred q] {s : Multiset α} :
(∀ x ∈ s, p x ↔ q x) → filter p s = filter q s :=
Quot.inductionOn s fun _l h => congr_arg ofList <| filter_congr' <| by simpa using h
@[simp]
theorem filter_add (s t : Multiset α) : filter p (s + t) = filter p s + filter p t :=
Quotient.inductionOn₂ s t fun _l₁ _l₂ => congr_arg ofList <| filter_append _ _
@[simp]
theorem filter_le (s : Multiset α) : filter p s ≤ s :=
Quot.inductionOn s fun _l => (filter_sublist _).subperm
@[simp]
theorem filter_subset (s : Multiset α) : filter p s ⊆ s :=
subset_of_le <| filter_le _ _
theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t :=
leInductionOn h fun h => (h.filter (p ·)).subperm
theorem monotone_filter_left : Monotone (filter p) := fun _s _t => filter_le_filter p
theorem monotone_filter_right (s : Multiset α) ⦃p q : α → Prop⦄ [DecidablePred p] [DecidablePred q]
(h : ∀ b, p b → q b) :
s.filter p ≤ s.filter q :=
Quotient.inductionOn s fun l => (l.monotone_filter_right <| by simpa using h).subperm
variable {p}
@[simp]
theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a ::ₘ s) = a ::ₘ filter p s :=
Quot.inductionOn s fun l h => congr_arg ofList <| List.filter_cons_of_pos <| by simpa using h
@[simp]
theorem filter_cons_of_neg {a : α} (s) : ¬p a → filter p (a ::ₘ s) = filter p s :=
Quot.inductionOn s fun l h => congr_arg ofList <| List.filter_cons_of_neg <| by simpa using h
@[simp]
theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a :=
Quot.inductionOn s fun _l => by simp
theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a :=
(mem_filter.1 h).2
theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s :=
(mem_filter.1 h).1
theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l :=
mem_filter.2 ⟨m, h⟩
theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a :=
Quot.inductionOn s fun _l =>
Iff.trans ⟨fun h => (filter_sublist _).eq_of_length (@congr_arg _ _ _ _ card h),
congr_arg ofList⟩ <| by simp
theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a :=
Quot.inductionOn s fun _l =>
Iff.trans ⟨fun h => eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg ofList⟩ <|
by simpa using List.filter_eq_nil (p := (p ·))
theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a :=
⟨fun h => ⟨le_trans h (filter_le _ _), fun _a m => of_mem_filter (mem_of_le h m)⟩, fun ⟨h, al⟩ =>
filter_eq_self.2 al ▸ filter_le_filter p h⟩
theorem filter_cons {a : α} (s : Multiset α) :
filter p (a ::ₘ s) = (if p a then {a} else 0) + filter p s := by
split_ifs with h
· rw [filter_cons_of_pos _ h, singleton_add]
· rw [filter_cons_of_neg _ h, zero_add]
theorem filter_singleton {a : α} (p : α → Prop) [DecidablePred p] :
filter p {a} = if p a then {a} else ∅ := by
simp only [singleton, filter_cons, filter_zero, add_zero, empty_eq_zero]
theorem filter_nsmul (s : Multiset α) (n : ℕ) : filter p (n • s) = n • filter p s := by
refine s.induction_on ?_ ?_
· simp only [filter_zero, nsmul_zero]
· intro a ha ih
rw [nsmul_cons, filter_add, ih, filter_cons, nsmul_add]
congr
split_ifs with hp <;>
· simp only [filter_eq_self, nsmul_zero, filter_eq_nil]
intro b hb
rwa [mem_singleton.mp (mem_of_mem_nsmul hb)]
variable (p)
@[simp]
theorem filter_sub [DecidableEq α] (s t : Multiset α) :
filter p (s - t) = filter p s - filter p t := by
revert s; refine Multiset.induction_on t (by simp) fun a t IH s => ?_
rw [sub_cons, IH]
by_cases h : p a
· rw [filter_cons_of_pos _ h, sub_cons]
congr
by_cases m : a ∈ s
· rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h),
cons_erase m]
· rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)]
· rw [filter_cons_of_neg _ h]
by_cases m : a ∈ s
· rw [(by rw [filter_cons_of_neg _ h] : filter p (erase s a) = filter p (a ::ₘ erase s a)),
cons_erase m]
· rw [erase_of_not_mem m]
@[simp]
theorem filter_union [DecidableEq α] (s t : Multiset α) :
filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(· ∪ ·), union]
@[simp]
theorem filter_inter [DecidableEq α] (s t : Multiset α) :
filter p (s ∩ t) = filter p s ∩ filter p t :=
le_antisymm
(le_inter (filter_le_filter _ <| inter_le_left _ _)
(filter_le_filter _ <| inter_le_right _ _)) <|
le_filter.2
⟨inf_le_inf (filter_le _ _) (filter_le _ _), fun _a h =>
of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩
@[simp]
theorem filter_filter (q) [DecidablePred q] (s : Multiset α) :
filter p (filter q s) = filter (fun a => p a ∧ q a) s :=
Quot.inductionOn s fun l => by simp
lemma filter_comm (q) [DecidablePred q] (s : Multiset α) :
filter p (filter q s) = filter q (filter p s) := by simp [and_comm]
theorem filter_add_filter (q) [DecidablePred q] (s : Multiset α) :
filter p s + filter q s = filter (fun a => p a ∨ q a) s + filter (fun a => p a ∧ q a) s :=
Multiset.induction_on s rfl fun a s IH => by by_cases p a <;> by_cases q a <;> simp [*]
theorem filter_add_not (s : Multiset α) : filter p s + filter (fun a => ¬p a) s = s := by
rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]
· simp only [add_zero]
· simp [Decidable.em, -Bool.not_eq_true, -not_and, not_and_or, or_comm]
· simp only [Bool.not_eq_true, decide_eq_true_eq, Bool.eq_false_or_eq_true,
decide_True, implies_true, Decidable.em]
theorem filter_map (f : β → α) (s : Multiset β) : filter p (map f s) = map f (filter (p ∘ f) s) :=
Quot.inductionOn s fun l => by simp [List.filter_map]; rfl
@[deprecated (since := "2024-06-16")] alias map_filter := filter_map
-- TODO: rename to `map_filter` when the deprecated alias above is removed.
lemma map_filter' {f : α → β} (hf : Injective f) (s : Multiset α)
[DecidablePred fun b => ∃ a, p a ∧ f a = b] :
(s.filter p).map f = (s.map f).filter fun b => ∃ a, p a ∧ f a = b := by
simp [(· ∘ ·), filter_map, hf.eq_iff]
lemma card_filter_le_iff (s : Multiset α) (P : α → Prop) [DecidablePred P] (n : ℕ) :
card (s.filter P) ≤ n ↔ ∀ s' ≤ s, n < card s' → ∃ a ∈ s', ¬ P a := by
fconstructor
· intro H s' hs' s'_card
by_contra! rid
have card := card_le_card (monotone_filter_left P hs') |>.trans H
exact s'_card.not_le (filter_eq_self.mpr rid ▸ card)
· contrapose!
exact fun H ↦ ⟨s.filter P, filter_le _ _, H, fun a ha ↦ (mem_filter.mp ha).2⟩
/-! ### Simultaneously filter and map elements of a multiset -/
/-- `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 added to the result, otherwise
`a` is removed from the resulting multiset. -/
def filterMap (f : α → Option β) (s : Multiset α) : Multiset β :=
Quot.liftOn s (fun l => (List.filterMap f l : Multiset β))
fun _l₁ _l₂ h => Quot.sound <| h.filterMap f
@[simp, norm_cast]
lemma filterMap_coe (f : α → Option β) (l : List α) : filterMap f l = l.filterMap f := rfl
@[simp]
theorem filterMap_zero (f : α → Option β) : filterMap f 0 = 0 :=
rfl
@[simp]
theorem filterMap_cons_none {f : α → Option β} (a : α) (s : Multiset α) (h : f a = none) :
filterMap f (a ::ₘ s) = filterMap f s :=
Quot.inductionOn s fun _ => congr_arg ofList <| List.filterMap_cons_none h
@[simp]
theorem filterMap_cons_some (f : α → Option β) (a : α) (s : Multiset α) {b : β}
(h : f a = some b) : filterMap f (a ::ₘ s) = b ::ₘ filterMap f s :=
Quot.inductionOn s fun _ => congr_arg ofList <| List.filterMap_cons_some h
theorem filterMap_eq_map (f : α → β) : filterMap (some ∘ f) = map f :=
funext fun s =>
Quot.inductionOn s fun l => congr_arg ofList <| congr_fun (List.filterMap_eq_map f) l
theorem filterMap_eq_filter : filterMap (Option.guard p) = filter p :=
funext fun s =>
Quot.inductionOn s fun l => congr_arg ofList <| by
rw [← List.filterMap_eq_filter]
congr; funext a; simp
theorem filterMap_filterMap (f : α → Option β) (g : β → Option γ) (s : Multiset α) :
filterMap g (filterMap f s) = filterMap (fun x => (f x).bind g) s :=
Quot.inductionOn s fun l => congr_arg ofList <| List.filterMap_filterMap f g l
theorem map_filterMap (f : α → Option β) (g : β → γ) (s : Multiset α) :
map g (filterMap f s) = filterMap (fun x => (f x).map g) s :=
Quot.inductionOn s fun l => congr_arg ofList <| List.map_filterMap f g l
theorem filterMap_map (f : α → β) (g : β → Option γ) (s : Multiset α) :
filterMap g (map f s) = filterMap (g ∘ f) s :=
Quot.inductionOn s fun l => congr_arg ofList <| List.filterMap_map f g l
theorem filter_filterMap (f : α → Option β) (p : β → Prop) [DecidablePred p] (s : Multiset α) :
filter p (filterMap f s) = filterMap (fun x => (f x).filter p) s :=
Quot.inductionOn s fun l => congr_arg ofList <| List.filter_filterMap f p l
theorem filterMap_filter (f : α → Option β) (s : Multiset α) :
filterMap f (filter p s) = filterMap (fun x => if p x then f x else none) s :=
Quot.inductionOn s fun l => congr_arg ofList <| by simpa using List.filterMap_filter p f l
@[simp]
theorem filterMap_some (s : Multiset α) : filterMap some s = s :=
Quot.inductionOn s fun l => congr_arg ofList <| List.filterMap_some l
@[simp]
theorem mem_filterMap (f : α → Option β) (s : Multiset α) {b : β} :
b ∈ filterMap f s ↔ ∃ a, a ∈ s ∧ f a = some b :=
Quot.inductionOn s fun _ => List.mem_filterMap
theorem map_filterMap_of_inv (f : α → Option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x)
(s : Multiset α) : map g (filterMap f s) = s :=
Quot.inductionOn s fun l => congr_arg ofList <| List.map_filterMap_of_inv f g H l
theorem filterMap_le_filterMap (f : α → Option β) {s t : Multiset α} (h : s ≤ t) :
filterMap f s ≤ filterMap f t :=
leInductionOn h fun h => (h.filterMap _).subperm
/-! ### countP -/
/-- `countP p s` counts the number of elements of `s` (with multiplicity) that
satisfy `p`. -/
def countP (s : Multiset α) : ℕ :=
Quot.liftOn s (List.countP p) fun _l₁ _l₂ => Perm.countP_eq (p ·)
@[simp]
theorem coe_countP (l : List α) : countP p l = l.countP p :=
rfl
@[simp]
theorem countP_zero : countP p 0 = 0 :=
rfl
variable {p}
@[simp]
theorem countP_cons_of_pos {a : α} (s) : p a → countP p (a ::ₘ s) = countP p s + 1 :=
Quot.inductionOn s <| by simpa using List.countP_cons_of_pos (p ·)
@[simp]
theorem countP_cons_of_neg {a : α} (s) : ¬p a → countP p (a ::ₘ s) = countP p s :=
Quot.inductionOn s <| by simpa using List.countP_cons_of_neg (p ·)
variable (p)
theorem countP_cons (b : α) (s) : countP p (b ::ₘ s) = countP p s + if p b then 1 else 0 :=
Quot.inductionOn s <| by simp [List.countP_cons]
theorem countP_eq_card_filter (s) : countP p s = card (filter p s) :=
Quot.inductionOn s fun l => l.countP_eq_length_filter (p ·)
theorem countP_le_card (s) : countP p s ≤ card s :=
Quot.inductionOn s fun _l => countP_le_length (p ·)
@[simp]
theorem countP_add (s t) : countP p (s + t) = countP p s + countP p t := by
simp [countP_eq_card_filter]
@[simp]
theorem countP_nsmul (s) (n : ℕ) : countP p (n • s) = n * countP p s := by
induction n <;> simp [*, succ_nsmul, succ_mul, zero_nsmul]
theorem card_eq_countP_add_countP (s) : card s = countP p s + countP (fun x => ¬p x) s :=
Quot.inductionOn s fun l => by simp [l.length_eq_countP_add_countP p]
/-- `countP p`, the number of elements of a multiset satisfying `p`, promoted to an
`AddMonoidHom`. -/
def countPAddMonoidHom : Multiset α →+ ℕ where
toFun := countP p
map_zero' := countP_zero _
map_add' := countP_add _
@[simp]
theorem coe_countPAddMonoidHom : (countPAddMonoidHom p : Multiset α → ℕ) = countP p :=
rfl
@[simp]
theorem countP_sub [DecidableEq α] {s t : Multiset α} (h : t ≤ s) :
countP p (s - t) = countP p s - countP p t := by
simp [countP_eq_card_filter, h, filter_le_filter]
theorem countP_le_of_le {s t} (h : s ≤ t) : countP p s ≤ countP p t := by
simpa [countP_eq_card_filter] using card_le_card (filter_le_filter p h)
@[simp]
theorem countP_filter (q) [DecidablePred q] (s : Multiset α) :
countP p (filter q s) = countP (fun a => p a ∧ q a) s := by simp [countP_eq_card_filter]
theorem countP_eq_countP_filter_add (s) (p q : α → Prop) [DecidablePred p] [DecidablePred q] :
countP p s = (filter q s).countP p + (filter (fun a => ¬q a) s).countP p :=
Quot.inductionOn s fun l => by
convert l.countP_eq_countP_filter_add (p ·) (q ·)
simp [countP_filter]
@[simp]
theorem countP_True {s : Multiset α} : countP (fun _ => True) s = card s :=
Quot.inductionOn s fun _l => List.countP_true
@[simp]
theorem countP_False {s : Multiset α} : countP (fun _ => False) s = 0 :=
Quot.inductionOn s fun _l => List.countP_false
theorem countP_map (f : α → β) (s : Multiset α) (p : β → Prop) [DecidablePred p] :
countP p (map f s) = card (s.filter fun a => p (f a)) := by
refine Multiset.induction_on s ?_ fun a t IH => ?_
· rw [map_zero, countP_zero, filter_zero, card_zero]
· rw [map_cons, countP_cons, IH, filter_cons, card_add, apply_ite card, card_zero, card_singleton,
add_comm]
-- Porting note: `Lean.Internal.coeM` forces us to type-ascript `{a // a ∈ s}`
lemma countP_attach (s : Multiset α) : s.attach.countP (fun a : {a // a ∈ s} ↦ p a) = s.countP p :=
Quotient.inductionOn s fun l => by
simp only [quot_mk_to_coe, coe_countP]
-- Porting note: was
-- rw [quot_mk_to_coe, coe_attach, coe_countP]
-- exact List.countP_attach _ _
rw [coe_attach]
refine (coe_countP _ _).trans ?_
convert List.countP_attach _ _
rfl
lemma filter_attach (s : Multiset α) (p : α → Prop) [DecidablePred p] :
(s.attach.filter fun a : {a // a ∈ s} ↦ p ↑a) =
(s.filter p).attach.map (Subtype.map id fun _ ↦ Multiset.mem_of_mem_filter) :=
Quotient.inductionOn s fun l ↦ congr_arg _ (List.filter_attach l p)
variable {p}
theorem countP_pos {s} : 0 < countP p s ↔ ∃ a ∈ s, p a :=
Quot.inductionOn s fun _l => by simpa using List.countP_pos (p ·)
theorem countP_eq_zero {s} : countP p s = 0 ↔ ∀ a ∈ s, ¬p a :=
Quot.inductionOn s fun _l => by simp [List.countP_eq_zero]
theorem countP_eq_card {s} : countP p s = card s ↔ ∀ a ∈ s, p a :=
Quot.inductionOn s fun _l => by simp [List.countP_eq_length]
theorem countP_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countP p s :=
countP_pos.2 ⟨_, h, pa⟩
theorem countP_congr {s s' : Multiset α} (hs : s = s')
{p p' : α → Prop} [DecidablePred p] [DecidablePred p']
(hp : ∀ x ∈ s, p x = p' x) : s.countP p = s'.countP p' := by
revert hs hp
exact Quot.induction_on₂ s s'
(fun l l' hs hp => by
simp only [quot_mk_to_coe'', coe_eq_coe] at hs
apply hs.countP_congr
simpa using hp)
end
/-! ### Multiplicity of an element -/
section
variable [DecidableEq α] {s : Multiset α}
/-- `count a s` is the multiplicity of `a` in `s`. -/
def count (a : α) : Multiset α → ℕ :=
countP (a = ·)
@[simp]
theorem coe_count (a : α) (l : List α) : count a (ofList l) = l.count a := by
simp_rw [count, List.count, coe_countP (a = ·) l, @eq_comm _ a]
rfl
@[simp]
theorem count_zero (a : α) : count a 0 = 0 :=
rfl
@[simp]
theorem count_cons_self (a : α) (s : Multiset α) : count a (a ::ₘ s) = count a s + 1 :=
countP_cons_of_pos _ <| rfl
@[simp]
theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : Multiset α) : count a (b ::ₘ s) = count a s :=
countP_cons_of_neg _ <| h
theorem count_le_card (a : α) (s) : count a s ≤ card s :=
countP_le_card _ _
theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t :=
countP_le_of_le _
theorem count_le_count_cons (a b : α) (s : Multiset α) : count a s ≤ count a (b ::ₘ s) :=
count_le_of_le _ (le_cons_self _ _)
theorem count_cons (a b : α) (s : Multiset α) :
count a (b ::ₘ s) = count a s + if a = b then 1 else 0 :=
countP_cons (a = ·) _ _
theorem count_singleton_self (a : α) : count a ({a} : Multiset α) = 1 :=
count_eq_one_of_mem (nodup_singleton a) <| mem_singleton_self a
theorem count_singleton (a b : α) : count a ({b} : Multiset α) = if a = b then 1 else 0 := by
simp only [count_cons, ← cons_zero, count_zero, zero_add]
@[simp]
theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t :=
countP_add _
/-- `count a`, the multiplicity of `a` in a multiset, promoted to an `AddMonoidHom`. -/
def countAddMonoidHom (a : α) : Multiset α →+ ℕ :=
countPAddMonoidHom (a = ·)
@[simp]
theorem coe_countAddMonoidHom {a : α} : (countAddMonoidHom a : Multiset α → ℕ) = count a :=
rfl
@[simp]
theorem count_nsmul (a : α) (n s) : count a (n • s) = n * count a s := by
induction n <;> simp [*, succ_nsmul, succ_mul, zero_nsmul]
@[simp]
lemma count_attach (a : {x // x ∈ s}) : s.attach.count a = s.count ↑a :=
Eq.trans (countP_congr rfl fun _ _ => by simp [Subtype.ext_iff]) <| countP_attach _ _
theorem count_pos {a : α} {s : Multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countP_pos]
theorem one_le_count_iff_mem {a : α} {s : Multiset α} : 1 ≤ count a s ↔ a ∈ s := by
rw [succ_le_iff, count_pos]
@[simp]
theorem count_eq_zero_of_not_mem {a : α} {s : Multiset α} (h : a ∉ s) : count a s = 0 :=
by_contradiction fun h' => h <| count_pos.1 (Nat.pos_of_ne_zero h')
lemma count_ne_zero {a : α} : count a s ≠ 0 ↔ a ∈ s := Nat.pos_iff_ne_zero.symm.trans count_pos
@[simp] lemma count_eq_zero {a : α} : count a s = 0 ↔ a ∉ s := count_ne_zero.not_right
theorem count_eq_card {a : α} {s} : count a s = card s ↔ ∀ x ∈ s, a = x := by
simp [countP_eq_card, count, @eq_comm _ a]
@[simp]
theorem count_replicate_self (a : α) (n : ℕ) : count a (replicate n a) = n := by
convert List.count_replicate_self a n
rw [← coe_count, coe_replicate]
theorem count_replicate (a b : α) (n : ℕ) : count a (replicate n b) = if b = a then n else 0 := by
convert List.count_replicate a b n
rw [← coe_count, coe_replicate]
simp
@[simp]
theorem count_erase_self (a : α) (s : Multiset α) : count a (erase s a) = count a s - 1 :=
Quotient.inductionOn s fun l => by
convert List.count_erase_self a l <;> rw [← coe_count] <;> simp
@[simp]
theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : Multiset α) :
count a (erase s b) = count a s :=
Quotient.inductionOn s fun l => by
convert List.count_erase_of_ne ab l <;> rw [← coe_count] <;> simp
@[simp]
theorem count_sub (a : α) (s t : Multiset α) : count a (s - t) = count a s - count a t := by
revert s; refine Multiset.induction_on t (by simp) fun b t IH s => ?_
rw [sub_cons, IH]
rcases Decidable.eq_or_ne a b with rfl | ab
· rw [count_erase_self, count_cons_self, Nat.sub_sub, add_comm]
· rw [count_erase_of_ne ab, count_cons_of_ne ab]
@[simp]
theorem count_union (a : α) (s t : Multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by
simp [(· ∪ ·), union, Nat.sub_add_eq_max]
@[simp]
theorem count_inter (a : α) (s t : Multiset α) : count a (s ∩ t) = min (count a s) (count a t) := by
apply @Nat.add_left_cancel (count a (s - t))
rw [← count_add, sub_add_inter, count_sub, Nat.sub_add_min_cancel]
theorem le_count_iff_replicate_le {a : α} {s : Multiset α} {n : ℕ} :
n ≤ count a s ↔ replicate n a ≤ s :=
Quot.inductionOn s fun _l => by
simp only [quot_mk_to_coe'', mem_coe, coe_count]
exact le_count_iff_replicate_sublist.trans replicate_le_coe.symm
@[simp]
theorem count_filter_of_pos {p} [DecidablePred p] {a} {s : Multiset α} (h : p a) :
count a (filter p s) = count a s :=
Quot.inductionOn s fun _l => by
simp only [quot_mk_to_coe'', filter_coe, mem_coe, coe_count, decide_eq_true_eq]
apply count_filter
simpa using h
@[simp]
theorem count_filter_of_neg {p} [DecidablePred p] {a} {s : Multiset α} (h : ¬p a) :
count a (filter p s) = 0 :=
Multiset.count_eq_zero_of_not_mem fun t => h (of_mem_filter t)
theorem count_filter {p} [DecidablePred p] {a} {s : Multiset α} :
count a (filter p s) = if p a then count a s else 0 := by
split_ifs with h
· exact count_filter_of_pos h
· exact count_filter_of_neg h
theorem ext {s t : Multiset α} : s = t ↔ ∀ a, count a s = count a t :=
Quotient.inductionOn₂ s t fun _l₁ _l₂ => Quotient.eq.trans <| by
simp only [quot_mk_to_coe, filter_coe, mem_coe, coe_count, decide_eq_true_eq]
apply perm_iff_count
@[ext]
theorem ext' {s t : Multiset α} : (∀ a, count a s = count a t) → s = t :=
ext.2
lemma count_injective : Injective fun (s : Multiset α) a ↦ s.count a :=
fun _s _t hst ↦ ext' $ congr_fun hst
@[simp]
theorem coe_inter (s t : List α) : (s ∩ t : Multiset α) = (s.bagInter t : List α) := by ext; simp
theorem le_iff_count {s t : Multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t :=
⟨fun h a => count_le_of_le a h, fun al => by
rw [← (ext.2 fun a => by simp [max_eq_right (al a)] : s ∪ t = t)]; apply le_union_left⟩
instance : DistribLattice (Multiset α) :=
{ le_sup_inf := fun s t u =>
le_of_eq <|
Eq.symm <|
ext.2 fun a => by
simp only [max_min_distrib_left, Multiset.count_inter, Multiset.sup_eq_union,
Multiset.count_union, Multiset.inf_eq_inter] }
theorem count_map {α β : Type*} (f : α → β) (s : Multiset α) [DecidableEq β] (b : β) :
count b (map f s) = card (s.filter fun a => b = f a) := by
simp [Bool.beq_eq_decide_eq, eq_comm, count, countP_map]
/-- `Multiset.map f` preserves `count` if `f` is injective on the set of elements contained in
the multiset -/
theorem count_map_eq_count [DecidableEq β] (f : α → β) (s : Multiset α)
(hf : Set.InjOn f { x : α | x ∈ s }) (x) (H : x ∈ s) : (s.map f).count (f x) = s.count x := by
suffices (filter (fun a : α => f x = f a) s).count x = card (filter (fun a : α => f x = f a) s) by
rw [count, countP_map, ← this]
exact count_filter_of_pos <| rfl
· rw [eq_replicate_card.2 fun b hb => (hf H (mem_filter.1 hb).left _).symm]
· simp only [count_replicate, eq_self_iff_true, if_true, card_replicate]
· simp only [mem_filter, beq_iff_eq, and_imp, @eq_comm _ (f x), imp_self, implies_true]
/-- `Multiset.map f` preserves `count` if `f` is injective -/
theorem count_map_eq_count' [DecidableEq β] (f : α → β) (s : Multiset α) (hf : Function.Injective f)
(x : α) : (s.map f).count (f x) = s.count x := by
by_cases H : x ∈ s
· exact count_map_eq_count f _ hf.injOn _ H
· rw [count_eq_zero_of_not_mem H, count_eq_zero, mem_map]
rintro ⟨k, hks, hkx⟩
rw [hf hkx] at hks
contradiction
@[simp]
theorem sub_filter_eq_filter_not (p) [DecidablePred p] (s : Multiset α) :
s - s.filter p = s.filter (fun a ↦ ¬ p a) := by
ext a; by_cases h : p a <;> simp [h]
theorem filter_eq' (s : Multiset α) (b : α) : s.filter (· = b) = replicate (count b s) b :=
Quotient.inductionOn s fun l => by
simp only [quot_mk_to_coe, filter_coe, mem_coe, coe_count]
rw [List.filter_eq l b, coe_replicate]
theorem filter_eq (s : Multiset α) (b : α) : s.filter (Eq b) = replicate (count b s) b := by
simp_rw [← filter_eq', eq_comm]
@[simp]
theorem replicate_inter (n : ℕ) (x : α) (s : Multiset α) :
replicate n x ∩ s = replicate (min n (s.count x)) x := by
ext y
rw [count_inter, count_replicate, count_replicate]
by_cases h : x = y
· simp only [h, if_true]
· simp only [h, if_false, Nat.zero_min]
@[simp]
theorem inter_replicate (s : Multiset α) (n : ℕ) (x : α) :
s ∩ replicate n x = replicate (min (s.count x) n) x := by
rw [inter_comm, replicate_inter, min_comm]
theorem erase_attach_map_val (s : Multiset α) (x : {x // x ∈ s}) :
(s.attach.erase x).map (↑) = s.erase x := by
rw [Multiset.map_erase _ val_injective, attach_map_val]
theorem erase_attach_map (s : Multiset α) (f : α → β) (x : {x // x ∈ s}) :
(s.attach.erase x).map (fun j : {x // x ∈ s} ↦ f j) = (s.erase x).map f := by
simp only [← Function.comp_apply (f := f)]
rw [← map_map, erase_attach_map_val]
end
@[ext]
theorem addHom_ext [AddZeroClass β] ⦃f g : Multiset α →+ β⦄ (h : ∀ x, f {x} = g {x}) : f = g := by
ext s
induction' s using Multiset.induction_on with a s ih
· simp only [_root_.map_zero]
· simp only [← singleton_add, _root_.map_add, ih, h]
section Embedding
@[simp]
theorem map_le_map_iff {f : α → β} (hf : Function.Injective f) {s t : Multiset α} :
s.map f ≤ t.map f ↔ s ≤ t := by
classical
refine ⟨fun h => le_iff_count.mpr fun a => ?_, map_le_map⟩
simpa [count_map_eq_count' f _ hf] using le_iff_count.mp h (f a)
/-- Associate to an embedding `f` from `α` to `β` the order embedding that maps a multiset to its
image under `f`. -/
@[simps!]
def mapEmbedding (f : α ↪ β) : Multiset α ↪o Multiset β :=
OrderEmbedding.ofMapLEIff (map f) fun _ _ => map_le_map_iff f.inj'
end Embedding
theorem count_eq_card_filter_eq [DecidableEq α] (s : Multiset α) (a : α) :
s.count a = card (s.filter (a = ·)) := by rw [count, countP_eq_card_filter]
/--
Mapping a multiset through a predicate and counting the `True`s yields the cardinality of the set
filtered by the predicate. Note that this uses the notion of a multiset of `Prop`s - due to the
decidability requirements of `count`, the decidability instance on the LHS is different from the
RHS. In particular, the decidability instance on the left leaks `Classical.decEq`.
See [here](https://github.com/leanprover-community/mathlib/pull/11306#discussion_r782286812)
for more discussion.
-/
@[simp]
theorem map_count_True_eq_filter_card (s : Multiset α) (p : α → Prop) [DecidablePred p] :
(s.map p).count True = card (s.filter p) := by
simp only [count_eq_card_filter_eq, filter_map, card_map, Function.id_comp,
eq_true_eq_id, Function.comp_apply]
/-! ### Lift a relation to `Multiset`s -/
section Rel
/-- `Rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`,
s.t. there is a one-to-one mapping between elements in `s` and `t` following `r`. -/
@[mk_iff]
inductive Rel (r : α → β → Prop) : Multiset α → Multiset β → Prop
| zero : Rel r 0 0
| cons {a b as bs} : r a b → Rel r as bs → Rel r (a ::ₘ as) (b ::ₘ bs)
variable {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
private theorem rel_flip_aux {s t} (h : Rel r s t) : Rel (flip r) t s :=
Rel.recOn h Rel.zero fun h₀ _h₁ ih => Rel.cons h₀ ih
theorem rel_flip {s t} : Rel (flip r) s t ↔ Rel r t s :=
⟨rel_flip_aux, rel_flip_aux⟩
theorem rel_refl_of_refl_on {m : Multiset α} {r : α → α → Prop} : (∀ x ∈ m, r x x) → Rel r m m := by
refine m.induction_on ?_ ?_
· intros
apply Rel.zero
· intro a m ih h
exact Rel.cons (h _ (mem_cons_self _ _)) (ih fun _ ha => h _ (mem_cons_of_mem ha))
theorem rel_eq_refl {s : Multiset α} : Rel (· = ·) s s :=
rel_refl_of_refl_on fun _x _hx => rfl
theorem rel_eq {s t : Multiset α} : Rel (· = ·) s t ↔ s = t := by
constructor
· intro h
induction h <;> simp [*]
· intro h
subst h
exact rel_eq_refl
theorem Rel.mono {r p : α → β → Prop} {s t} (hst : Rel r s t)
(h : ∀ a ∈ s, ∀ b ∈ t, r a b → p a b) : Rel p s t := by
induction hst with
| zero => exact Rel.zero
| @cons a b s t hab _hst ih =>
apply Rel.cons (h a (mem_cons_self _ _) b (mem_cons_self _ _) hab)
exact ih fun a' ha' b' hb' h' => h a' (mem_cons_of_mem ha') b' (mem_cons_of_mem hb') h'
theorem Rel.add {s t u v} (hst : Rel r s t) (huv : Rel r u v) : Rel r (s + u) (t + v) := by
induction hst with
| zero => simpa using huv
| cons hab hst ih => simpa using ih.cons hab
theorem rel_flip_eq {s t : Multiset α} : Rel (fun a b => b = a) s t ↔ s = t :=
show Rel (flip (· = ·)) s t ↔ s = t by rw [rel_flip, rel_eq, eq_comm]
@[simp]
theorem rel_zero_left {b : Multiset β} : Rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp
@[simp]
theorem rel_zero_right {a : Multiset α} : Rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp
theorem rel_cons_left {a as bs} :
Rel r (a ::ₘ as) bs ↔ ∃ b bs', r a b ∧ Rel r as bs' ∧ bs = b ::ₘ bs' := by
constructor
· generalize hm : a ::ₘ as = m
intro h
induction h generalizing as with
| zero => simp at hm
| @cons a' b as' bs ha'b h ih =>
rcases cons_eq_cons.1 hm with (⟨eq₁, eq₂⟩ | ⟨_h, cs, eq₁, eq₂⟩)
· subst eq₁
subst eq₂
exact ⟨b, bs, ha'b, h, rfl⟩
· rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩
exact ⟨b', b ::ₘ bs', h₁, eq₁.symm ▸ Rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩
· exact fun ⟨b, bs', hab, h, Eq⟩ => Eq.symm ▸ Rel.cons hab h
theorem rel_cons_right {as b bs} :
Rel r as (b ::ₘ bs) ↔ ∃ a as', r a b ∧ Rel r as' bs ∧ as = a ::ₘ as' := by
rw [← rel_flip, rel_cons_left]
refine exists₂_congr fun a as' => ?_
rw [rel_flip, flip]
theorem rel_add_left {as₀ as₁} :
∀ {bs}, Rel r (as₀ + as₁) bs ↔ ∃ bs₀ bs₁, Rel r as₀ bs₀ ∧ Rel r as₁ bs₁ ∧ bs = bs₀ + bs₁ :=
@(Multiset.induction_on as₀ (by simp) fun a s ih bs ↦ by
simp only [ih, cons_add, rel_cons_left]
constructor
· intro h
rcases h with ⟨b, bs', hab, h, rfl⟩
rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩
exact ⟨b ::ₘ bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩
· intro h
rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩
rcases h with ⟨b, bs, hab, h₀, rfl⟩
exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩)
theorem rel_add_right {as bs₀ bs₁} :
Rel r as (bs₀ + bs₁) ↔ ∃ as₀ as₁, Rel r as₀ bs₀ ∧ Rel r as₁ bs₁ ∧ as = as₀ + as₁ := by
rw [← rel_flip, rel_add_left]; simp [rel_flip]
theorem rel_map_left {s : Multiset γ} {f : γ → α} :
∀ {t}, Rel r (s.map f) t ↔ Rel (fun a b => r (f a) b) s t :=
@(Multiset.induction_on s (by simp) (by simp (config := { contextual := true }) [rel_cons_left]))
theorem rel_map_right {s : Multiset α} {t : Multiset γ} {f : γ → β} :
Rel r s (t.map f) ↔ Rel (fun a b => r a (f b)) s t := by
rw [← rel_flip, rel_map_left, ← rel_flip]; rfl
theorem rel_map {s : Multiset α} {t : Multiset β} {f : α → γ} {g : β → δ} :
Rel p (s.map f) (t.map g) ↔ Rel (fun a b => p (f a) (g b)) s t :=
rel_map_left.trans rel_map_right
theorem card_eq_card_of_rel {r : α → β → Prop} {s : Multiset α} {t : Multiset β} (h : Rel r s t) :
card s = card t := by induction h <;> simp [*]
theorem exists_mem_of_rel_of_mem {r : α → β → Prop} {s : Multiset α} {t : Multiset β}
(h : Rel r s t) : ∀ {a : α}, a ∈ s → ∃ b ∈ t, r a b := by
induction' h with x y s t hxy _hst ih
· simp
· intro a ha
cases' mem_cons.1 ha with ha ha
· exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩
· rcases ih ha with ⟨b, hbt, hab⟩
exact ⟨b, mem_cons.2 (Or.inr hbt), hab⟩
theorem rel_of_forall {m1 m2 : Multiset α} {r : α → α → Prop} (h : ∀ a b, a ∈ m1 → b ∈ m2 → r a b)
(hc : card m1 = card m2) : m1.Rel r m2 := by
revert m1
refine @(m2.induction_on ?_ ?_)
· intro m _h hc
rw [rel_zero_right, ← card_eq_zero, hc, card_zero]
· intro a t ih m h hc
rw [card_cons] at hc
obtain ⟨b, hb⟩ := card_pos_iff_exists_mem.1 (show 0 < card m from hc.symm ▸ Nat.succ_pos _)
obtain ⟨m', rfl⟩ := exists_cons_of_mem hb
refine rel_cons_right.mpr ⟨b, m', h _ _ hb (mem_cons_self _ _), ih ?_ ?_, rfl⟩
· exact fun _ _ ha hb => h _ _ (mem_cons_of_mem ha) (mem_cons_of_mem hb)
· simpa using hc
theorem rel_replicate_left {m : Multiset α} {a : α} {r : α → α → Prop} {n : ℕ} :
(replicate n a).Rel r m ↔ card m = n ∧ ∀ x, x ∈ m → r a x :=
⟨fun h =>
⟨(card_eq_card_of_rel h).symm.trans (card_replicate _ _), fun x hx => by
obtain ⟨b, hb1, hb2⟩ := exists_mem_of_rel_of_mem (rel_flip.2 h) hx
rwa [eq_of_mem_replicate hb1] at hb2⟩,
fun h =>
rel_of_forall (fun x y hx hy => (eq_of_mem_replicate hx).symm ▸ h.2 _ hy)
(Eq.trans (card_replicate _ _) h.1.symm)⟩
theorem rel_replicate_right {m : Multiset α} {a : α} {r : α → α → Prop} {n : ℕ} :
m.Rel r (replicate n a) ↔ card m = n ∧ ∀ x, x ∈ m → r x a :=
rel_flip.trans rel_replicate_left
protected nonrec -- Porting note: added
theorem Rel.trans (r : α → α → Prop) [IsTrans α r] {s t u : Multiset α} (r1 : Rel r s t)
(r2 : Rel r t u) : Rel r s u := by
induction' t using Multiset.induction_on with x t ih generalizing s u
· rw [rel_zero_right.mp r1, rel_zero_left.mp r2, rel_zero_left]
· obtain ⟨a, as, ha1, ha2, rfl⟩ := rel_cons_right.mp r1
obtain ⟨b, bs, hb1, hb2, rfl⟩ := rel_cons_left.mp r2
exact Multiset.Rel.cons (_root_.trans ha1 hb1) (ih ha2 hb2)
theorem Rel.countP_eq (r : α → α → Prop) [IsTrans α r] [IsSymm α r] {s t : Multiset α} (x : α)
[DecidablePred (r x)] (h : Rel r s t) : countP (r x) s = countP (r x) t := by
induction' s using Multiset.induction_on with y s ih generalizing t
· rw [rel_zero_left.mp h]
· obtain ⟨b, bs, hb1, hb2, rfl⟩ := rel_cons_left.mp h
rw [countP_cons, countP_cons, ih hb2]
simp only [decide_eq_true_eq, Nat.add_right_inj]
exact (if_congr ⟨fun h => _root_.trans h hb1, fun h => _root_.trans h (symm hb1)⟩ rfl rfl)
end Rel
section Map
theorem map_eq_map {f : α → β} (hf : Function.Injective f) {s t : Multiset α} :
s.map f = t.map f ↔ s = t := by
rw [← rel_eq, ← rel_eq, rel_map]
simp only [hf.eq_iff]
theorem map_injective {f : α → β} (hf : Function.Injective f) :
Function.Injective (Multiset.map f) := fun _x _y => (map_eq_map hf).1
lemma filter_attach' (s : Multiset α) (p : {a // a ∈ s} → Prop) [DecidableEq α]
[DecidablePred p] :
s.attach.filter p =
(s.filter fun x ↦ ∃ h, p ⟨x, h⟩).attach.map (Subtype.map id fun x ↦ mem_of_mem_filter) := by
classical
refine Multiset.map_injective Subtype.val_injective ?_
rw [map_filter' _ Subtype.val_injective]
simp only [Function.comp, Subtype.exists, coe_mk, Subtype.map,
exists_and_right, exists_eq_right, attach_map_val, map_map, map_coe, id]
end Map
section Quot
theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : Multiset α} (hst : s.Rel r t) :
s.map (Quot.mk r) = t.map (Quot.mk r) :=
Rel.recOn hst rfl fun hab _hst ih => by simp [ih, Quot.sound hab]
theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : Multiset (Quot r)) :
∃ t : Multiset α, s = t.map (Quot.mk r) :=
Multiset.induction_on s ⟨0, rfl⟩ fun a _s ⟨t, ht⟩ =>
Quot.inductionOn a fun a => ht.symm ▸ ⟨a ::ₘ t, (map_cons _ _ _).symm⟩
theorem induction_on_multiset_quot {r : α → α → Prop} {p : Multiset (Quot r) → Prop}
(s : Multiset (Quot r)) : (∀ s : Multiset α, p (s.map (Quot.mk r))) → p s :=
match s, exists_multiset_eq_map_quot_mk s with
| _, ⟨_t, rfl⟩ => fun h => h _
end Quot
/-! ### Disjoint multisets -/
/-- `Disjoint s t` means that `s` and `t` have no elements in common. -/
def Disjoint (s t : Multiset α) : Prop :=
∀ ⦃a⦄, a ∈ s → a ∈ t → False
@[simp]
theorem coe_disjoint (l₁ l₂ : List α) : @Disjoint α l₁ l₂ ↔ l₁.Disjoint l₂ :=
Iff.rfl
@[symm]
theorem Disjoint.symm {s t : Multiset α} (d : Disjoint s t) : Disjoint t s
| _a, i₂, i₁ => d i₁ i₂
theorem disjoint_comm {s t : Multiset α} : Disjoint s t ↔ Disjoint t s :=
⟨Disjoint.symm, Disjoint.symm⟩
theorem disjoint_left {s t : Multiset α} : Disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t :=
Iff.rfl
theorem disjoint_right {s t : Multiset α} : Disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
disjoint_comm
theorem disjoint_iff_ne {s t : Multiset α} : Disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by
simp [disjoint_left, imp_not_comm]
theorem disjoint_of_subset_left {s t u : Multiset α} (h : s ⊆ u) (d : Disjoint u t) : Disjoint s t
| _x, m₁ => d (h m₁)
theorem disjoint_of_subset_right {s t u : Multiset α} (h : t ⊆ u) (d : Disjoint s u) : Disjoint s t
| _x, m, m₁ => d m (h m₁)
theorem disjoint_of_le_left {s t u : Multiset α} (h : s ≤ u) : Disjoint u t → Disjoint s t :=
disjoint_of_subset_left (subset_of_le h)
theorem disjoint_of_le_right {s t u : Multiset α} (h : t ≤ u) : Disjoint s u → Disjoint s t :=
disjoint_of_subset_right (subset_of_le h)
@[simp]
theorem zero_disjoint (l : Multiset α) : Disjoint 0 l
| a => (not_mem_nil a).elim
@[simp]
theorem singleton_disjoint {l : Multiset α} {a : α} : Disjoint {a} l ↔ a ∉ l := by
simp [Disjoint]
@[simp]
theorem disjoint_singleton {l : Multiset α} {a : α} : Disjoint l {a} ↔ a ∉ l := by
rw [disjoint_comm, singleton_disjoint]
@[simp]
theorem disjoint_add_left {s t u : Multiset α} :
Disjoint (s + t) u ↔ Disjoint s u ∧ Disjoint t u := by simp [Disjoint, or_imp, forall_and]
@[simp]
theorem disjoint_add_right {s t u : Multiset α} :
Disjoint s (t + u) ↔ Disjoint s t ∧ Disjoint s u := by
rw [disjoint_comm, disjoint_add_left]; tauto
@[simp]
theorem disjoint_cons_left {a : α} {s t : Multiset α} :
Disjoint (a ::ₘ s) t ↔ a ∉ t ∧ Disjoint s t :=
(@disjoint_add_left _ {a} s t).trans <| by rw [singleton_disjoint]
@[simp]
theorem disjoint_cons_right {a : α} {s t : Multiset α} :
Disjoint s (a ::ₘ t) ↔ a ∉ s ∧ Disjoint s t := by
rw [disjoint_comm, disjoint_cons_left]; tauto
theorem inter_eq_zero_iff_disjoint [DecidableEq α] {s t : Multiset α} :
s ∩ t = 0 ↔ Disjoint s t := by rw [← subset_zero]; simp [subset_iff, Disjoint]
@[simp]
theorem disjoint_union_left [DecidableEq α] {s t u : Multiset α} :
Disjoint (s ∪ t) u ↔ Disjoint s u ∧ Disjoint t u := by simp [Disjoint, or_imp, forall_and]
@[simp]
theorem disjoint_union_right [DecidableEq α] {s t u : Multiset α} :
Disjoint s (t ∪ u) ↔ Disjoint s t ∧ Disjoint s u := by simp [Disjoint, or_imp, forall_and]
theorem add_eq_union_iff_disjoint [DecidableEq α] {s t : Multiset α} :
s + t = s ∪ t ↔ Disjoint s t := by
simp_rw [← inter_eq_zero_iff_disjoint, ext, count_add, count_union, count_inter, count_zero,
Nat.min_eq_zero_iff, Nat.add_eq_max_iff]
lemma add_eq_union_left_of_le [DecidableEq α] {s t u : Multiset α} (h : t ≤ s) :
u + s = u ∪ t ↔ u.Disjoint s ∧ s = t := by
rw [← add_eq_union_iff_disjoint]
refine ⟨fun h0 ↦ ?_, ?_⟩
· rw [and_iff_right_of_imp]
· exact (le_of_add_le_add_left <| h0.trans_le <| union_le_add u t).antisymm h
· rintro rfl
exact h0
· rintro ⟨h0, rfl⟩
exact h0
lemma add_eq_union_right_of_le [DecidableEq α] {x y z : Multiset α} (h : z ≤ y) :
x + y = x ∪ z ↔ y = z ∧ x.Disjoint y := by
simpa only [and_comm] using add_eq_union_left_of_le h
theorem disjoint_map_map {f : α → γ} {g : β → γ} {s : Multiset α} {t : Multiset β} :
Disjoint (s.map f) (t.map g) ↔ ∀ a ∈ s, ∀ b ∈ t, f a ≠ g b := by
simp [Disjoint, @eq_comm _ (f _) (g _)]
/-- `Pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this
list. -/
def Pairwise (r : α → α → Prop) (m : Multiset α) : Prop :=
∃ l : List α, m = l ∧ l.Pairwise r
@[simp]
theorem pairwise_zero (r : α → α → Prop) : Multiset.Pairwise r 0 :=
⟨[], rfl, List.Pairwise.nil⟩
theorem pairwise_coe_iff {r : α → α → Prop} {l : List α} :
Multiset.Pairwise r l ↔ ∃ l' : List α, l ~ l' ∧ l'.Pairwise r :=
exists_congr <| by simp
theorem pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : Symmetric r) {l : List α} :
Multiset.Pairwise r l ↔ l.Pairwise r :=
Iff.intro (fun ⟨_l', Eq, h⟩ => ((Quotient.exact Eq).pairwise_iff @hr).2 h) fun h => ⟨l, rfl, h⟩
theorem map_set_pairwise {f : α → β} {r : β → β → Prop} {m : Multiset α}
(h : { a | a ∈ m }.Pairwise fun a₁ a₂ => r (f a₁) (f a₂)) : { b | b ∈ m.map f }.Pairwise r :=
fun b₁ h₁ b₂ h₂ hn => by
obtain ⟨⟨a₁, H₁, rfl⟩, a₂, H₂, rfl⟩ := Multiset.mem_map.1 h₁, Multiset.mem_map.1 h₂
exact h H₁ H₂ (mt (congr_arg f) hn)
end Multiset
namespace Multiset
section Choose
variable (p : α → Prop) [DecidablePred p] (l : Multiset α)
/-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `chooseX p l hp` returns
that `a` together with proofs of `a ∈ l` and `p a`. -/
def chooseX : ∀ _hp : ∃! a, a ∈ l ∧ p a, { a // a ∈ l ∧ p a } :=
Quotient.recOn l (fun l' ex_unique => List.chooseX p l' (ExistsUnique.exists ex_unique))
(by
intros a b _
funext hp
suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y by
apply all_equal
rintro ⟨x, px⟩ ⟨y, py⟩
rcases hp with ⟨z, ⟨_z_mem_l, _pz⟩, z_unique⟩
congr
calc
x = z := z_unique x px
_ = y := (z_unique y py).symm
)
/-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose p l hp` returns
that `a`. -/
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
variable (α)
set_option linter.deprecated false in
/-- The equivalence between lists and multisets of a subsingleton type. -/
def subsingletonEquiv [Subsingleton α] : List α ≃ Multiset α where
toFun := ofList
invFun :=
(Quot.lift id) fun (a b : List α) (h : a ~ b) =>
(List.ext_nthLe h.length_eq) fun _ _ _ => Subsingleton.elim _ _
left_inv _ := rfl
right_inv m := Quot.inductionOn m fun _ => rfl
variable {α}
@[simp]
theorem coe_subsingletonEquiv [Subsingleton α] :
(subsingletonEquiv α : List α → Multiset α) = ofList :=
rfl
@[deprecated (since := "2023-12-27")] alias card_le_of_le := card_le_card
@[deprecated (since := "2023-12-27")] alias card_lt_of_lt := card_lt_card
end Multiset
|
Data\Multiset\Bind.lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Algebra.BigOperators.Group.Multiset
import Mathlib.Data.Multiset.Dedup
/-!
# Bind operation for multisets
This file defines a few basic operations on `Multiset`, notably the monadic bind.
## Main declarations
* `Multiset.join`: The join, aka union or sum, of multisets.
* `Multiset.bind`: The bind of a multiset-indexed family of multisets.
* `Multiset.product`: Cartesian product of two multisets.
* `Multiset.sigma`: Disjoint sum of multisets in a sigma type.
-/
assert_not_exists MonoidWithZero
assert_not_exists MulAction
universe v
variable {α : Type*} {β : Type v} {γ δ : Type*}
namespace Multiset
/-! ### Join -/
/-- `join S`, where `S` is a multiset of multisets, is the lift of the list join
operation, that is, the union of all the sets.
join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/
def join : Multiset (Multiset α) → Multiset α :=
sum
theorem coe_join :
∀ L : List (List α), join (L.map ((↑) : List α → Multiset α) : Multiset (Multiset α)) = L.join
| [] => rfl
| l :: L => by
exact congr_arg (fun s : Multiset α => ↑l + s) (coe_join L)
@[simp]
theorem join_zero : @join α 0 = 0 :=
rfl
@[simp]
theorem join_cons (s S) : @join α (s ::ₘ S) = s + join S :=
sum_cons _ _
@[simp]
theorem join_add (S T) : @join α (S + T) = join S + join T :=
sum_add _ _
@[simp]
theorem singleton_join (a) : join ({a} : Multiset (Multiset α)) = a :=
sum_singleton _
@[simp]
theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s :=
Multiset.induction_on S (by simp) <| by
simp (config := { contextual := true }) [or_and_right, exists_or]
@[simp]
theorem card_join (S) : card (@join α S) = sum (map card S) :=
Multiset.induction_on S (by simp) (by simp)
@[simp]
theorem map_join (f : α → β) (S : Multiset (Multiset α)) :
map f (join S) = join (map (map f) S) := by
induction S using Multiset.induction with
| empty => simp
| cons _ _ ih => simp [ih]
@[to_additive (attr := simp)]
theorem prod_join [CommMonoid α] {S : Multiset (Multiset α)} :
prod (join S) = prod (map prod S) := by
induction S using Multiset.induction with
| empty => simp
| cons _ _ ih => simp [ih]
theorem rel_join {r : α → β → Prop} {s t} (h : Rel (Rel r) s t) : Rel r s.join t.join := by
induction h with
| zero => simp
| cons hab hst ih => simpa using hab.add ih
/-! ### Bind -/
section Bind
variable (a : α) (s t : Multiset α) (f g : α → Multiset β)
/-- `s.bind f` is the monad bind operation, defined as `(s.map f).join`. It is the union of `f a` as
`a` ranges over `s`. -/
def bind (s : Multiset α) (f : α → Multiset β) : Multiset β :=
(s.map f).join
@[simp]
theorem coe_bind (l : List α) (f : α → List β) : (@bind α β l fun a => f a) = l.bind f := by
rw [List.bind, ← coe_join, List.map_map]
rfl
@[simp]
theorem zero_bind : bind 0 f = 0 :=
rfl
@[simp]
theorem cons_bind : (a ::ₘ s).bind f = f a + s.bind f := by simp [bind]
@[simp]
theorem singleton_bind : bind {a} f = f a := by simp [bind]
@[simp]
theorem add_bind : (s + t).bind f = s.bind f + t.bind f := by simp [bind]
@[simp]
theorem bind_zero : s.bind (fun _ => 0 : α → Multiset β) = 0 := by simp [bind, join, nsmul_zero]
@[simp]
theorem bind_add : (s.bind fun a => f a + g a) = s.bind f + s.bind g := by simp [bind, join]
@[simp]
theorem bind_cons (f : α → β) (g : α → Multiset β) :
(s.bind fun a => f a ::ₘ g a) = map f s + s.bind g :=
Multiset.induction_on s (by simp)
(by simp (config := { contextual := true }) [add_comm, add_left_comm, add_assoc])
@[simp]
theorem bind_singleton (f : α → β) : (s.bind fun x => ({f x} : Multiset β)) = map f s :=
Multiset.induction_on s (by rw [zero_bind, map_zero]) (by simp [singleton_add])
@[simp]
theorem mem_bind {b s} {f : α → Multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by
simp [bind]
@[simp]
theorem card_bind : card (s.bind f) = (s.map (card ∘ f)).sum := by simp [bind]
theorem bind_congr {f g : α → Multiset β} {m : Multiset α} :
(∀ a ∈ m, f a = g a) → bind m f = bind m g := by simp (config := { contextual := true }) [bind]
theorem bind_hcongr {β' : Type v} {m : Multiset α} {f : α → Multiset β} {f' : α → Multiset β'}
(h : β = β') (hf : ∀ a ∈ m, HEq (f a) (f' a)) : HEq (bind m f) (bind m f') := by
subst h
simp only [heq_eq_eq] at hf
simp [bind_congr hf]
theorem map_bind (m : Multiset α) (n : α → Multiset β) (f : β → γ) :
map f (bind m n) = bind m fun a => map f (n a) := by simp [bind]
theorem bind_map (m : Multiset α) (n : β → Multiset γ) (f : α → β) :
bind (map f m) n = bind m fun a => n (f a) :=
Multiset.induction_on m (by simp) (by simp (config := { contextual := true }))
theorem bind_assoc {s : Multiset α} {f : α → Multiset β} {g : β → Multiset γ} :
(s.bind f).bind g = s.bind fun a => (f a).bind g :=
Multiset.induction_on s (by simp) (by simp (config := { contextual := true }))
theorem bind_bind (m : Multiset α) (n : Multiset β) {f : α → β → Multiset γ} :
((bind m) fun a => (bind n) fun b => f a b) = (bind n) fun b => (bind m) fun a => f a b :=
Multiset.induction_on m (by simp) (by simp (config := { contextual := true }))
theorem bind_map_comm (m : Multiset α) (n : Multiset β) {f : α → β → γ} :
((bind m) fun a => n.map fun b => f a b) = (bind n) fun b => m.map fun a => f a b :=
Multiset.induction_on m (by simp) (by simp (config := { contextual := true }))
@[to_additive (attr := simp)]
theorem prod_bind [CommMonoid β] (s : Multiset α) (t : α → Multiset β) :
(s.bind t).prod = (s.map fun a => (t a).prod).prod := by simp [bind]
theorem rel_bind {r : α → β → Prop} {p : γ → δ → Prop} {s t} {f : α → Multiset γ}
{g : β → Multiset δ} (h : (r ⇒ Rel p) f g) (hst : Rel r s t) :
Rel p (s.bind f) (t.bind g) := by
apply rel_join
rw [rel_map]
exact hst.mono fun a _ b _ hr => h hr
theorem count_sum [DecidableEq α] {m : Multiset β} {f : β → Multiset α} {a : α} :
count a (map f m).sum = sum (m.map fun b => count a <| f b) :=
Multiset.induction_on m (by simp) (by simp)
theorem count_bind [DecidableEq α] {m : Multiset β} {f : β → Multiset α} {a : α} :
count a (bind m f) = sum (m.map fun b => count a <| f b) :=
count_sum
theorem le_bind {α β : Type*} {f : α → Multiset β} (S : Multiset α) {x : α} (hx : x ∈ S) :
f x ≤ S.bind f := by
classical
refine le_iff_count.2 fun a ↦ ?_
obtain ⟨m', hm'⟩ := exists_cons_of_mem $ mem_map_of_mem (fun b ↦ count a (f b)) hx
rw [count_bind, hm', sum_cons]
exact Nat.le_add_right _ _
-- Porting note (#11119): @[simp] removed because not in normal form
theorem attach_bind_coe (s : Multiset α) (f : α → Multiset β) :
(s.attach.bind fun i => f i) = s.bind f :=
congr_arg join <| attach_map_val' _ _
variable {f s t}
@[simp] lemma nodup_bind :
Nodup (bind s f) ↔ (∀ a ∈ s, Nodup (f a)) ∧ s.Pairwise fun a b => Disjoint (f a) (f b) := by
have : ∀ a, ∃ l : List β, f a = l := fun a => Quot.induction_on (f a) fun l => ⟨l, rfl⟩
choose f' h' using this
have : f = fun a ↦ ofList (f' a) := funext h'
have hd : Symmetric fun a b ↦ List.Disjoint (f' a) (f' b) := fun a b h ↦ h.symm
exact Quot.induction_on s <| by simp [this, List.nodup_bind, pairwise_coe_iff_pairwise hd]
@[simp]
lemma dedup_bind_dedup [DecidableEq α] [DecidableEq β] (s : Multiset α) (f : α → Multiset β) :
(s.dedup.bind f).dedup = (s.bind f).dedup := by
ext x
-- Porting note: was `simp_rw [count_dedup, mem_bind, mem_dedup]`
simp_rw [count_dedup]
refine if_congr ?_ rfl rfl
simp
end Bind
/-! ### Product of two multisets -/
section Product
variable (a : α) (b : β) (s : Multiset α) (t : Multiset β)
/-- The multiplicity of `(a, b)` in `s ×ˢ t` is
the product of the multiplicity of `a` in `s` and `b` in `t`. -/
def product (s : Multiset α) (t : Multiset β) : Multiset (α × β) :=
s.bind fun a => t.map <| Prod.mk a
instance instSProd : SProd (Multiset α) (Multiset β) (Multiset (α × β)) where
sprod := Multiset.product
@[simp]
theorem coe_product (l₁ : List α) (l₂ : List β) :
(l₁ : Multiset α) ×ˢ (l₂ : Multiset β) = (l₁ ×ˢ l₂) := by
dsimp only [SProd.sprod]
rw [product, List.product, ← coe_bind]
simp
@[simp]
theorem zero_product : (0 : Multiset α) ×ˢ t = 0 :=
rfl
@[simp]
theorem cons_product : (a ::ₘ s) ×ˢ t = map (Prod.mk a) t + s ×ˢ t := by simp [SProd.sprod, product]
@[simp]
theorem product_zero : s ×ˢ (0 : Multiset β) = 0 := by simp [SProd.sprod, product]
@[simp]
theorem product_cons : s ×ˢ (b ::ₘ t) = (s.map fun a => (a, b)) + s ×ˢ t := by
simp [SProd.sprod, product]
@[simp]
theorem product_singleton : ({a} : Multiset α) ×ˢ ({b} : Multiset β) = {(a, b)} := by
simp only [SProd.sprod, product, bind_singleton, map_singleton]
@[simp]
theorem add_product (s t : Multiset α) (u : Multiset β) : (s + t) ×ˢ u = s ×ˢ u + t ×ˢ u := by
simp [SProd.sprod, product]
@[simp]
theorem product_add (s : Multiset α) : ∀ t u : Multiset β, s ×ˢ (t + u) = s ×ˢ t + s ×ˢ u :=
Multiset.induction_on s (fun t u => rfl) fun a s IH t u => by
rw [cons_product, IH]
simp [add_comm, add_left_comm, add_assoc]
@[simp]
theorem card_product : card (s ×ˢ t) = card s * card t := by simp [SProd.sprod, product]
variable {s t}
@[simp] lemma mem_product : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t
| (a, b) => by simp [product, and_left_comm]
protected theorem Nodup.product : Nodup s → Nodup t → Nodup (s ×ˢ t) :=
Quotient.inductionOn₂ s t fun l₁ l₂ d₁ d₂ => by simp [List.Nodup.product d₁ d₂]
end Product
/-! ### Disjoint sum of multisets -/
section Sigma
variable {σ : α → Type*} (a : α) (s : Multiset α) (t : ∀ a, Multiset (σ a))
/-- `Multiset.sigma s t` is the dependent version of `Multiset.product`. It is the sum of
`(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/
protected def sigma (s : Multiset α) (t : ∀ a, Multiset (σ a)) : Multiset (Σa, σ a) :=
s.bind fun a => (t a).map <| Sigma.mk a
@[simp]
theorem coe_sigma (l₁ : List α) (l₂ : ∀ a, List (σ a)) :
(@Multiset.sigma α σ l₁ fun a => l₂ a) = l₁.sigma l₂ := by
rw [Multiset.sigma, List.sigma, ← coe_bind]
simp
@[simp]
theorem zero_sigma : @Multiset.sigma α σ 0 t = 0 :=
rfl
@[simp]
theorem cons_sigma : (a ::ₘ s).sigma t = (t a).map (Sigma.mk a) + s.sigma t := by
simp [Multiset.sigma]
@[simp]
theorem sigma_singleton (b : α → β) :
(({a} : Multiset α).sigma fun a => ({b a} : Multiset β)) = {⟨a, b a⟩} :=
rfl
@[simp]
theorem add_sigma (s t : Multiset α) (u : ∀ a, Multiset (σ a)) :
(s + t).sigma u = s.sigma u + t.sigma u := by simp [Multiset.sigma]
@[simp]
theorem sigma_add :
∀ t u : ∀ a, Multiset (σ a), (s.sigma fun a => t a + u a) = s.sigma t + s.sigma u :=
Multiset.induction_on s (fun t u => rfl) fun a s IH t u => by
rw [cons_sigma, IH]
simp [add_comm, add_left_comm, add_assoc]
@[simp]
theorem card_sigma : card (s.sigma t) = sum (map (fun a => card (t a)) s) := by
simp [Multiset.sigma, (· ∘ ·)]
variable {s t}
@[simp] lemma mem_sigma : ∀ {p : Σa, σ a}, p ∈ @Multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1
| ⟨a, b⟩ => by simp [Multiset.sigma, and_assoc, and_left_comm]
protected theorem Nodup.sigma {σ : α → Type*} {t : ∀ a, Multiset (σ a)} :
Nodup s → (∀ a, Nodup (t a)) → Nodup (s.sigma t) :=
Quot.induction_on s fun l₁ => by
choose f hf using fun a => Quotient.exists_rep (t a)
simpa [← funext hf] using List.Nodup.sigma
end Sigma
end Multiset
|
Data\Multiset\Dedup.lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.Multiset.Nodup
/-!
# Erasing duplicates in a multiset.
-/
namespace Multiset
open List
variable {α β : Type*} [DecidableEq α]
/-! ### dedup -/
/-- `dedup s` removes duplicates from `s`, yielding a `nodup` multiset. -/
def dedup (s : Multiset α) : Multiset α :=
Quot.liftOn s (fun l => (l.dedup : Multiset α)) fun _ _ p => Quot.sound p.dedup
@[simp]
theorem coe_dedup (l : List α) : @dedup α _ l = l.dedup :=
rfl
@[simp]
theorem dedup_zero : @dedup α _ 0 = 0 :=
rfl
@[simp]
theorem mem_dedup {a : α} {s : Multiset α} : a ∈ dedup s ↔ a ∈ s :=
Quot.induction_on s fun _ => List.mem_dedup
@[simp]
theorem dedup_cons_of_mem {a : α} {s : Multiset α} : a ∈ s → dedup (a ::ₘ s) = dedup s :=
Quot.induction_on s fun _ m => @congr_arg _ _ _ _ ofList <| List.dedup_cons_of_mem m
@[simp]
theorem dedup_cons_of_not_mem {a : α} {s : Multiset α} : a ∉ s → dedup (a ::ₘ s) = a ::ₘ dedup s :=
Quot.induction_on s fun _ m => congr_arg ofList <| List.dedup_cons_of_not_mem m
theorem dedup_le (s : Multiset α) : dedup s ≤ s :=
Quot.induction_on s fun _ => (dedup_sublist _).subperm
theorem dedup_subset (s : Multiset α) : dedup s ⊆ s :=
subset_of_le <| dedup_le _
theorem subset_dedup (s : Multiset α) : s ⊆ dedup s := fun _ => mem_dedup.2
@[simp]
theorem dedup_subset' {s t : Multiset α} : dedup s ⊆ t ↔ s ⊆ t :=
⟨Subset.trans (subset_dedup _), Subset.trans (dedup_subset _)⟩
@[simp]
theorem subset_dedup' {s t : Multiset α} : s ⊆ dedup t ↔ s ⊆ t :=
⟨fun h => Subset.trans h (dedup_subset _), fun h => Subset.trans h (subset_dedup _)⟩
@[simp]
theorem nodup_dedup (s : Multiset α) : Nodup (dedup s) :=
Quot.induction_on s List.nodup_dedup
theorem dedup_eq_self {s : Multiset α} : dedup s = s ↔ Nodup s :=
⟨fun e => e ▸ nodup_dedup s, Quot.induction_on s fun _ h => congr_arg ofList h.dedup⟩
alias ⟨_, Nodup.dedup⟩ := dedup_eq_self
theorem count_dedup (m : Multiset α) (a : α) : m.dedup.count a = if a ∈ m then 1 else 0 :=
Quot.induction_on m fun _ => by
simp only [quot_mk_to_coe'', coe_dedup, mem_coe, List.mem_dedup, coe_nodup, coe_count]
apply List.count_dedup _ _
@[simp]
theorem dedup_idem {m : Multiset α} : m.dedup.dedup = m.dedup :=
Quot.induction_on m fun _ => @congr_arg _ _ _ _ ofList List.dedup_idem
theorem dedup_eq_zero {s : Multiset α} : dedup s = 0 ↔ s = 0 :=
⟨fun h => eq_zero_of_subset_zero <| h ▸ subset_dedup _, fun h => h.symm ▸ dedup_zero⟩
@[simp]
theorem dedup_singleton {a : α} : dedup ({a} : Multiset α) = {a} :=
(nodup_singleton _).dedup
theorem le_dedup {s t : Multiset α} : s ≤ dedup t ↔ s ≤ t ∧ Nodup s :=
⟨fun h => ⟨le_trans h (dedup_le _), nodup_of_le h (nodup_dedup _)⟩,
fun ⟨l, d⟩ => (le_iff_subset d).2 <| Subset.trans (subset_of_le l) (subset_dedup _)⟩
theorem le_dedup_self {s : Multiset α} : s ≤ dedup s ↔ Nodup s := by
rw [le_dedup, and_iff_right le_rfl]
theorem dedup_ext {s t : Multiset α} : dedup s = dedup t ↔ ∀ a, a ∈ s ↔ a ∈ t := by
simp [Nodup.ext]
theorem dedup_map_of_injective [DecidableEq β] {f : α → β} (hf : Function.Injective f)
(s : Multiset α) :
(s.map f).dedup = s.dedup.map f :=
Quot.induction_on s fun l => by simp [List.dedup_map_of_injective hf l]
theorem dedup_map_dedup_eq [DecidableEq β] (f : α → β) (s : Multiset α) :
dedup (map f (dedup s)) = dedup (map f s) := by
simp [dedup_ext]
@[simp]
theorem dedup_nsmul {s : Multiset α} {n : ℕ} (h0 : n ≠ 0) : (n • s).dedup = s.dedup := by
ext a
by_cases h : a ∈ s <;> simp [h, h0]
theorem Nodup.le_dedup_iff_le {s t : Multiset α} (hno : s.Nodup) : s ≤ t.dedup ↔ s ≤ t := by
simp [le_dedup, hno]
theorem Subset.dedup_add_right {s t : Multiset α} (h : s ⊆ t) :
dedup (s + t) = dedup t := by
induction s, t using Quot.induction_on₂
exact congr_arg ((↑) : List α → Multiset α) <| List.Subset.dedup_append_right h
theorem Subset.dedup_add_left {s t : Multiset α} (h : t ⊆ s) :
dedup (s + t) = dedup s := by
rw [add_comm, Subset.dedup_add_right h]
theorem Disjoint.dedup_add {s t : Multiset α} (h : Disjoint s t) :
dedup (s + t) = dedup s + dedup t := by
induction s, t using Quot.induction_on₂
exact congr_arg ((↑) : List α → Multiset α) <| List.Disjoint.dedup_append h
/-- Note that the stronger `List.Subset.dedup_append_right` is proved earlier. -/
theorem _root_.List.Subset.dedup_append_left {s t : List α} (h : t ⊆ s) :
List.dedup (s ++ t) ~ List.dedup s := by
rw [← coe_eq_coe, ← coe_dedup, ← coe_add, Subset.dedup_add_left h, coe_dedup]
end Multiset
theorem Multiset.Nodup.le_nsmul_iff_le {α : Type*} {s t : Multiset α} {n : ℕ} (h : s.Nodup)
(hn : n ≠ 0) : s ≤ n • t ↔ s ≤ t := by
classical
rw [← h.le_dedup_iff_le, Iff.comm, ← h.le_dedup_iff_le]
simp [hn]
|
Data\Multiset\FinsetOps.lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.Multiset.Dedup
import Mathlib.Data.List.Infix
/-!
# Preparations for defining operations on `Finset`.
The operations here ignore multiplicities,
and preparatory for defining the corresponding operations on `Finset`.
-/
namespace Multiset
open List
variable {α : Type*} [DecidableEq α] {s : Multiset α}
/-! ### finset insert -/
/-- `ndinsert a s` is the lift of the list `insert` operation. This operation
does not respect multiplicities, unlike `cons`, but it is suitable as
an insert operation on `Finset`. -/
def ndinsert (a : α) (s : Multiset α) : Multiset α :=
Quot.liftOn s (fun l => (l.insert a : Multiset α)) fun _ _ p => Quot.sound (p.insert a)
@[simp]
theorem coe_ndinsert (a : α) (l : List α) : ndinsert a l = (insert a l : List α) :=
rfl
@[simp]
theorem ndinsert_zero (a : α) : ndinsert a 0 = {a} :=
rfl
@[simp]
theorem ndinsert_of_mem {a : α} {s : Multiset α} : a ∈ s → ndinsert a s = s :=
Quot.inductionOn s fun _ h => congr_arg ((↑) : List α → Multiset α) <| insert_of_mem h
@[simp]
theorem ndinsert_of_not_mem {a : α} {s : Multiset α} : a ∉ s → ndinsert a s = a ::ₘ s :=
Quot.inductionOn s fun _ h => congr_arg ((↑) : List α → Multiset α) <| insert_of_not_mem h
@[simp]
theorem mem_ndinsert {a b : α} {s : Multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s :=
Quot.inductionOn s fun _ => mem_insert_iff
@[simp]
theorem le_ndinsert_self (a : α) (s : Multiset α) : s ≤ ndinsert a s :=
Quot.inductionOn s fun _ => (sublist_insert _ _).subperm
-- Porting note: removing @[simp], simp can prove it
theorem mem_ndinsert_self (a : α) (s : Multiset α) : a ∈ ndinsert a s :=
mem_ndinsert.2 (Or.inl rfl)
theorem mem_ndinsert_of_mem {a b : α} {s : Multiset α} (h : a ∈ s) : a ∈ ndinsert b s :=
mem_ndinsert.2 (Or.inr h)
@[simp]
theorem length_ndinsert_of_mem {a : α} {s : Multiset α} (h : a ∈ s) :
card (ndinsert a s) = card s := by simp [h]
@[simp]
theorem length_ndinsert_of_not_mem {a : α} {s : Multiset α} (h : a ∉ s) :
card (ndinsert a s) = card s + 1 := by simp [h]
theorem dedup_cons {a : α} {s : Multiset α} : dedup (a ::ₘ s) = ndinsert a (dedup s) := by
by_cases h : a ∈ s <;> simp [h]
theorem Nodup.ndinsert (a : α) : Nodup s → Nodup (ndinsert a s) :=
Quot.inductionOn s fun _ => Nodup.insert
theorem ndinsert_le {a : α} {s t : Multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t :=
⟨fun h => ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩, fun ⟨l, m⟩ =>
if h : a ∈ s then by simp [h, l]
else by
rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff, ← le_cons_of_not_mem h,
cons_erase m]
exact l⟩
theorem attach_ndinsert (a : α) (s : Multiset α) :
(s.ndinsert a).attach =
ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map fun p => ⟨p.1, mem_ndinsert_of_mem p.2⟩) :=
have eq :
∀ h : ∀ p : { x // x ∈ s }, p.1 ∈ s,
(fun p : { x // x ∈ s } => ⟨p.val, h p⟩ : { x // x ∈ s } → { x // x ∈ s }) = id :=
fun h => funext fun p => Subtype.eq rfl
have : ∀ (t) (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩
(s.attach.map fun p => ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩) := by
intro t ht
by_cases h : a ∈ s
· rw [ndinsert_of_mem h] at ht
subst ht
rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)]
· rw [ndinsert_of_not_mem h] at ht
subst ht
simp [attach_cons, h]
this _ rfl
@[simp]
theorem disjoint_ndinsert_left {a : α} {s t : Multiset α} :
Disjoint (ndinsert a s) t ↔ a ∉ t ∧ Disjoint s t :=
Iff.trans (by simp [Disjoint]) disjoint_cons_left
@[simp]
theorem disjoint_ndinsert_right {a : α} {s t : Multiset α} :
Disjoint s (ndinsert a t) ↔ a ∉ s ∧ Disjoint s t := by
rw [disjoint_comm, disjoint_ndinsert_left]; tauto
/-! ### finset union -/
/-- `ndunion s t` is the lift of the list `union` operation. This operation
does not respect multiplicities, unlike `s ∪ t`, but it is suitable as
a union operation on `Finset`. (`s ∪ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndunion (s t : Multiset α) : Multiset α :=
(Quotient.liftOn₂ s t fun l₁ l₂ => (l₁.union l₂ : Multiset α)) fun _ _ _ _ p₁ p₂ =>
Quot.sound <| p₁.union p₂
@[simp]
theorem coe_ndunion (l₁ l₂ : List α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : List α) :=
rfl
-- Porting note: removing @[simp], simp can prove it
theorem zero_ndunion (s : Multiset α) : ndunion 0 s = s :=
Quot.inductionOn s fun _ => rfl
@[simp]
theorem cons_ndunion (s t : Multiset α) (a : α) : ndunion (a ::ₘ s) t = ndinsert a (ndunion s t) :=
Quot.induction_on₂ s t fun _ _ => rfl
@[simp]
theorem mem_ndunion {s t : Multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t :=
Quot.induction_on₂ s t fun _ _ => List.mem_union_iff
theorem le_ndunion_right (s t : Multiset α) : t ≤ ndunion s t :=
Quot.induction_on₂ s t fun _ _ => (suffix_union_right _ _).sublist.subperm
theorem subset_ndunion_right (s t : Multiset α) : t ⊆ ndunion s t :=
subset_of_le (le_ndunion_right s t)
theorem ndunion_le_add (s t : Multiset α) : ndunion s t ≤ s + t :=
Quot.induction_on₂ s t fun _ _ => (union_sublist_append _ _).subperm
theorem ndunion_le {s t u : Multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u :=
Multiset.induction_on s (by simp [zero_ndunion])
(fun _ _ h =>
by simp only [cons_ndunion, mem_ndunion, ndinsert_le, and_comm, cons_subset, and_left_comm, h,
and_assoc])
theorem subset_ndunion_left (s t : Multiset α) : s ⊆ ndunion s t := fun _ h =>
mem_ndunion.2 <| Or.inl h
theorem le_ndunion_left {s} (t : Multiset α) (d : Nodup s) : s ≤ ndunion s t :=
(le_iff_subset d).2 <| subset_ndunion_left _ _
theorem ndunion_le_union (s t : Multiset α) : ndunion s t ≤ s ∪ t :=
ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩
theorem Nodup.ndunion (s : Multiset α) {t : Multiset α} : Nodup t → Nodup (ndunion s t) :=
Quot.induction_on₂ s t fun _ _ => List.Nodup.union _
@[simp]
theorem ndunion_eq_union {s t : Multiset α} (d : Nodup s) : ndunion s t = s ∪ t :=
le_antisymm (ndunion_le_union _ _) <| union_le (le_ndunion_left _ d) (le_ndunion_right _ _)
theorem dedup_add (s t : Multiset α) : dedup (s + t) = ndunion s (dedup t) :=
Quot.induction_on₂ s t fun _ _ => congr_arg ((↑) : List α → Multiset α) <| dedup_append _ _
theorem Disjoint.ndunion_eq {s t : Multiset α} (h : Disjoint s t) :
s.ndunion t = s.dedup + t := by
induction s, t using Quot.induction_on₂
exact congr_arg ((↑) : List α → Multiset α) <| List.Disjoint.union_eq h
theorem Subset.ndunion_eq_right {s t : Multiset α} (h : s ⊆ t) : s.ndunion t = t := by
induction s, t using Quot.induction_on₂
exact congr_arg ((↑) : List α → Multiset α) <| List.Subset.union_eq_right h
/-! ### finset inter -/
/-- `ndinter s t` is the lift of the list `∩` operation. This operation
does not respect multiplicities, unlike `s ∩ t`, but it is suitable as
an intersection operation on `Finset`. (`s ∩ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndinter (s t : Multiset α) : Multiset α :=
filter (· ∈ t) s
@[simp]
theorem coe_ndinter (l₁ l₂ : List α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : List α) := by
simp only [ndinter, mem_coe, filter_coe, coe_eq_coe, ← elem_eq_mem]
apply Perm.refl
@[simp]
theorem zero_ndinter (s : Multiset α) : ndinter 0 s = 0 :=
rfl
@[simp]
theorem cons_ndinter_of_mem {a : α} (s : Multiset α) {t : Multiset α} (h : a ∈ t) :
ndinter (a ::ₘ s) t = a ::ₘ ndinter s t := by simp [ndinter, h]
@[simp]
theorem ndinter_cons_of_not_mem {a : α} (s : Multiset α) {t : Multiset α} (h : a ∉ t) :
ndinter (a ::ₘ s) t = ndinter s t := by simp [ndinter, h]
@[simp]
theorem mem_ndinter {s t : Multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t := by
simp [ndinter, mem_filter]
@[simp]
theorem Nodup.ndinter {s : Multiset α} (t : Multiset α) : Nodup s → Nodup (ndinter s t) :=
Nodup.filter _
theorem le_ndinter {s t u : Multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u := by
simp [ndinter, le_filter, subset_iff]
theorem ndinter_le_left (s t : Multiset α) : ndinter s t ≤ s :=
(le_ndinter.1 le_rfl).1
theorem ndinter_subset_left (s t : Multiset α) : ndinter s t ⊆ s :=
subset_of_le (ndinter_le_left s t)
theorem ndinter_subset_right (s t : Multiset α) : ndinter s t ⊆ t :=
(le_ndinter.1 le_rfl).2
theorem ndinter_le_right {s} (t : Multiset α) (d : Nodup s) : ndinter s t ≤ t :=
(le_iff_subset <| d.ndinter _).2 <| ndinter_subset_right _ _
theorem inter_le_ndinter (s t : Multiset α) : s ∩ t ≤ ndinter s t :=
le_ndinter.2 ⟨inter_le_left _ _, subset_of_le <| inter_le_right _ _⟩
@[simp]
theorem ndinter_eq_inter {s t : Multiset α} (d : Nodup s) : ndinter s t = s ∩ t :=
le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _)
theorem ndinter_eq_zero_iff_disjoint {s t : Multiset α} : ndinter s t = 0 ↔ Disjoint s t := by
rw [← subset_zero]; simp [subset_iff, Disjoint]
alias ⟨_, Disjoint.ndinter_eq_zero⟩ := ndinter_eq_zero_iff_disjoint
theorem Subset.ndinter_eq_left {s t : Multiset α} (h : s ⊆ t) : s.ndinter t = s := by
induction s, t using Quot.induction_on₂
rw [quot_mk_to_coe'', quot_mk_to_coe'', coe_ndinter, List.Subset.inter_eq_left h]
end Multiset
-- Assert that we define `Finset` without the material on the set lattice.
-- Note that we cannot put this in `Data.Finset.Basic` because we proved relevant lemmas there.
assert_not_exists Set.sInter
|
Data\Multiset\Fintype.lean | /-
Copyright (c) 2022 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller
-/
import Mathlib.Algebra.BigOperators.Group.Finset
import Mathlib.Data.Fintype.Card
/-!
# Multiset coercion to type
This module defines a `CoeSort` instance for multisets and gives it a `Fintype` instance.
It also defines `Multiset.toEnumFinset`, which is another way to enumerate the elements of
a multiset. These coercions and definitions make it easier to sum over multisets using existing
`Finset` theory.
## Main definitions
* A coercion from `m : Multiset α` to a `Type*`. Each `x : m` has two components.
The first, `x.1`, can be obtained via the coercion `↑x : α`,
and it yields the underlying element of the multiset.
The second, `x.2`, is a term of `Fin (m.count x)`,
and its function is to ensure each term appears with the correct multiplicity.
Note that this coercion requires `DecidableEq α` due to the definition using `Multiset.count`.
* `Multiset.toEnumFinset` is a `Finset` version of this.
* `Multiset.coeEmbedding` is the embedding `m ↪ α × ℕ`, whose first component is the coercion
and whose second component enumerates elements with multiplicity.
* `Multiset.coeEquiv` is the equivalence `m ≃ m.toEnumFinset`.
## Tags
multiset enumeration
-/
variable {α : Type*} [DecidableEq α] {m : Multiset α}
/-- Auxiliary definition for the `CoeSort` instance. This prevents the `CoeOut m α`
instance from inadvertently applying to other sigma types. -/
def Multiset.ToType (m : Multiset α) : Type _ := (x : α) × Fin (m.count x)
/-- Create a type that has the same number of elements as the multiset.
Terms of this type are triples `⟨x, ⟨i, h⟩⟩` where `x : α`, `i : ℕ`, and `h : i < m.count x`.
This way repeated elements of a multiset appear multiple times from different values of `i`. -/
instance : CoeSort (Multiset α) (Type _) := ⟨Multiset.ToType⟩
example : DecidableEq m := inferInstanceAs <| DecidableEq ((x : α) × Fin (m.count x))
-- Porting note: syntactic equality
/-- Constructor for terms of the coercion of `m` to a type.
This helps Lean pick up the correct instances. -/
@[reducible, match_pattern]
def Multiset.mkToType (m : Multiset α) (x : α) (i : Fin (m.count x)) : m :=
⟨x, i⟩
/-- As a convenience, there is a coercion from `m : Type*` to `α` by projecting onto the first
component. -/
instance instCoeSortMultisetType.instCoeOutToType : CoeOut m α :=
⟨fun x ↦ x.1⟩
-- Porting note: syntactic equality
-- Syntactic equality
-- @[simp] -- Porting note (#10685): dsimp can prove this
theorem Multiset.coe_mk {x : α} {i : Fin (m.count x)} : ↑(m.mkToType x i) = x :=
rfl
@[simp] lemma Multiset.coe_mem {x : m} : ↑x ∈ m := Multiset.count_pos.mp (by have := x.2.2; omega)
@[simp]
protected theorem Multiset.forall_coe (p : m → Prop) :
(∀ x : m, p x) ↔ ∀ (x : α) (i : Fin (m.count x)), p ⟨x, i⟩ :=
Sigma.forall
@[simp]
protected theorem Multiset.exists_coe (p : m → Prop) :
(∃ x : m, p x) ↔ ∃ (x : α) (i : Fin (m.count x)), p ⟨x, i⟩ :=
Sigma.exists
instance : Fintype { p : α × ℕ | p.2 < m.count p.1 } :=
Fintype.ofFinset
(m.toFinset.biUnion fun x ↦ (Finset.range (m.count x)).map ⟨Prod.mk x, Prod.mk.inj_left x⟩)
(by
rintro ⟨x, i⟩
simp only [Finset.mem_biUnion, Multiset.mem_toFinset, Finset.mem_map, Finset.mem_range,
Function.Embedding.coeFn_mk, Prod.mk.inj_iff, Set.mem_setOf_eq]
simp only [← and_assoc, exists_eq_right, and_iff_right_iff_imp]
exact fun h ↦ Multiset.count_pos.mp (by omega))
/-- Construct a finset whose elements enumerate the elements of the multiset `m`.
The `ℕ` component is used to differentiate between equal elements: if `x` appears `n` times
then `(x, 0)`, ..., and `(x, n-1)` appear in the `Finset`. -/
def Multiset.toEnumFinset (m : Multiset α) : Finset (α × ℕ) :=
{ p : α × ℕ | p.2 < m.count p.1 }.toFinset
@[simp]
theorem Multiset.mem_toEnumFinset (m : Multiset α) (p : α × ℕ) :
p ∈ m.toEnumFinset ↔ p.2 < m.count p.1 :=
Set.mem_toFinset
theorem Multiset.mem_of_mem_toEnumFinset {p : α × ℕ} (h : p ∈ m.toEnumFinset) : p.1 ∈ m :=
have := (m.mem_toEnumFinset p).mp h; Multiset.count_pos.mp (by omega)
namespace Multiset
@[simp] lemma toEnumFinset_filter_eq (m : Multiset α) (a : α) :
m.toEnumFinset.filter (·.1 = a) = {a} ×ˢ Finset.range (m.count a) := by aesop
@[simp] lemma map_toEnumFinset_fst (m : Multiset α) : m.toEnumFinset.val.map Prod.fst = m := by
ext a; simp [count_map, ← Finset.filter_val, eq_comm (a := a)]
@[simp] lemma image_toEnumFinset_fst (m : Multiset α) :
m.toEnumFinset.image Prod.fst = m.toFinset := by
rw [Finset.image, Multiset.map_toEnumFinset_fst]
@[simp] lemma map_fst_le_of_subset_toEnumFinset {s : Finset (α × ℕ)} (hsm : s ⊆ m.toEnumFinset) :
s.1.map Prod.fst ≤ m := by
simp_rw [le_iff_count, count_map]
rintro a
obtain ha | ha := (s.1.filter fun x ↦ a = x.1).card.eq_zero_or_pos
· rw [ha]
exact Nat.zero_le _
obtain ⟨n, han, hn⟩ : ∃ n ≥ card (s.1.filter fun x ↦ a = x.1) - 1, (a, n) ∈ s := by
by_contra! h
replace h : s.filter (·.1 = a) ⊆ {a} ×ˢ .range (card (s.1.filter fun x ↦ a = x.1) - 1) := by
simpa (config := { contextual := true }) [forall_swap (β := _ = a), Finset.subset_iff,
imp_not_comm, not_le, Nat.lt_sub_iff_add_lt] using h
have : card (s.1.filter fun x ↦ a = x.1) ≤ card (s.1.filter fun x ↦ a = x.1) - 1 := by
simpa [Finset.card, eq_comm] using Finset.card_mono h
omega
exact Nat.le_of_pred_lt (han.trans_lt $ by simpa using hsm hn)
end Multiset
@[mono]
theorem Multiset.toEnumFinset_mono {m₁ m₂ : Multiset α} (h : m₁ ≤ m₂) :
m₁.toEnumFinset ⊆ m₂.toEnumFinset := by
intro p
simp only [Multiset.mem_toEnumFinset]
exact gt_of_ge_of_gt (Multiset.le_iff_count.mp h p.1)
@[simp]
theorem Multiset.toEnumFinset_subset_iff {m₁ m₂ : Multiset α} :
m₁.toEnumFinset ⊆ m₂.toEnumFinset ↔ m₁ ≤ m₂ :=
⟨fun h ↦ by simpa using map_fst_le_of_subset_toEnumFinset h, Multiset.toEnumFinset_mono⟩
/-- The embedding from a multiset into `α × ℕ` where the second coordinate enumerates repeats.
If you are looking for the function `m → α`, that would be plain `(↑)`. -/
@[simps]
def Multiset.coeEmbedding (m : Multiset α) : m ↪ α × ℕ where
toFun x := (x, x.2)
inj' := by
intro ⟨x, i, hi⟩ ⟨y, j, hj⟩
rintro ⟨⟩
rfl
/-- Another way to coerce a `Multiset` to a type is to go through `m.toEnumFinset` and coerce
that `Finset` to a type. -/
@[simps]
def Multiset.coeEquiv (m : Multiset α) : m ≃ m.toEnumFinset where
toFun x :=
⟨m.coeEmbedding x, by
rw [Multiset.mem_toEnumFinset]
exact x.2.2⟩
invFun x :=
⟨x.1.1, x.1.2, by
rw [← Multiset.mem_toEnumFinset]
exact x.2⟩
left_inv := by
rintro ⟨x, i, h⟩
rfl
right_inv := by
rintro ⟨⟨x, i⟩, h⟩
rfl
@[simp]
theorem Multiset.toEmbedding_coeEquiv_trans (m : Multiset α) :
m.coeEquiv.toEmbedding.trans (Function.Embedding.subtype _) = m.coeEmbedding := by ext <;> rfl
@[irreducible]
instance Multiset.fintypeCoe : Fintype m :=
Fintype.ofEquiv m.toEnumFinset m.coeEquiv.symm
theorem Multiset.map_univ_coeEmbedding (m : Multiset α) :
(Finset.univ : Finset m).map m.coeEmbedding = m.toEnumFinset := by
ext ⟨x, i⟩
simp only [Fin.exists_iff, Finset.mem_map, Finset.mem_univ, Multiset.coeEmbedding_apply,
Prod.mk.inj_iff, exists_true_left, Multiset.exists_coe, Multiset.coe_mk, Fin.val_mk,
exists_prop, exists_eq_right_right, exists_eq_right, Multiset.mem_toEnumFinset, iff_self_iff,
true_and_iff]
@[simp]
theorem Multiset.map_univ_coe (m : Multiset α) :
(Finset.univ : Finset m).val.map (fun x : m ↦ (x : α)) = m := by
have := m.map_toEnumFinset_fst
rw [← m.map_univ_coeEmbedding] at this
simpa only [Finset.map_val, Multiset.coeEmbedding_apply, Multiset.map_map,
Function.comp_apply] using this
@[simp]
theorem Multiset.map_univ {β : Type*} (m : Multiset α) (f : α → β) :
((Finset.univ : Finset m).val.map fun (x : m) ↦ f (x : α)) = m.map f := by
erw [← Multiset.map_map, Multiset.map_univ_coe]
@[simp]
theorem Multiset.card_toEnumFinset (m : Multiset α) : m.toEnumFinset.card = Multiset.card m := by
rw [Finset.card, ← Multiset.card_map Prod.fst m.toEnumFinset.val]
congr
exact m.map_toEnumFinset_fst
@[simp]
theorem Multiset.card_coe (m : Multiset α) : Fintype.card m = Multiset.card m := by
rw [Fintype.card_congr m.coeEquiv]
simp only [Fintype.card_coe, card_toEnumFinset]
@[to_additive]
theorem Multiset.prod_eq_prod_coe [CommMonoid α] (m : Multiset α) : m.prod = ∏ x : m, (x : α) := by
congr
-- Porting note: `simp` fails with "maximum recursion depth has been reached"
erw [map_univ_coe]
@[to_additive]
theorem Multiset.prod_eq_prod_toEnumFinset [CommMonoid α] (m : Multiset α) :
m.prod = ∏ x ∈ m.toEnumFinset, x.1 := by
congr
simp
@[to_additive]
theorem Multiset.prod_toEnumFinset {β : Type*} [CommMonoid β] (m : Multiset α) (f : α → ℕ → β) :
∏ x ∈ m.toEnumFinset, f x.1 x.2 = ∏ x : m, f x x.2 := by
rw [Fintype.prod_equiv m.coeEquiv (fun x ↦ f x x.2) fun x ↦ f x.1.1 x.1.2]
· rw [← m.toEnumFinset.prod_coe_sort fun x ↦ f x.1 x.2]
· intro x
rfl
|
Data\Multiset\Fold.lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.Multiset.Bind
/-!
# The fold operation for a commutative associative operation over a multiset.
-/
namespace 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 s` folds a commutative associative operation `op` over
the multiset `s`. -/
def fold : α → Multiset α → α :=
foldr op (left_comm _ hc.comm ha.assoc)
theorem fold_eq_foldr (b : α) (s : Multiset α) :
fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s :=
rfl
@[simp]
theorem coe_fold_r (b : α) (l : List α) : fold op b l = l.foldr op b :=
rfl
theorem coe_fold_l (b : α) (l : List α) : fold op b l = l.foldl op b :=
(coe_foldr_swap op _ b l).trans <| by simp [hc.comm]
theorem fold_eq_foldl (b : α) (s : Multiset α) :
fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s :=
Quot.inductionOn s fun _ => coe_fold_l _ _ _
@[simp]
theorem fold_zero (b : α) : (0 : Multiset α).fold op b = b :=
rfl
@[simp]
theorem fold_cons_left : ∀ (b a : α) (s : Multiset α), (a ::ₘ s).fold op b = a * s.fold op b :=
foldr_cons _ _
theorem fold_cons_right (b a : α) (s : Multiset α) : (a ::ₘ s).fold op b = s.fold op b * a := by
simp [hc.comm]
theorem fold_cons'_right (b a : α) (s : Multiset α) : (a ::ₘ s).fold op b = s.fold op (b * a) := by
rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl]
theorem fold_cons'_left (b a : α) (s : Multiset α) : (a ::ₘ s).fold op b = s.fold op (a * b) := by
rw [fold_cons'_right, hc.comm]
theorem fold_add (b₁ b₂ : α) (s₁ s₂ : Multiset α) :
(s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ :=
Multiset.induction_on s₂ (by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op])
(fun a b h => by rw [fold_cons_left, add_cons, fold_cons_left, h, ← ha.assoc, hc.comm a,
ha.assoc])
theorem fold_bind {ι : Type*} (s : Multiset ι) (t : ι → Multiset α) (b : ι → α) (b₀ : α) :
(s.bind t).fold op ((s.map b).fold op b₀) =
(s.map fun i => (t i).fold op (b i)).fold op b₀ := by
induction' s using Multiset.induction_on with a ha ih
· rw [zero_bind, map_zero, map_zero, fold_zero]
· rw [cons_bind, map_cons, map_cons, fold_cons_left, fold_cons_left, fold_add, ih]
theorem fold_singleton (b a : α) : ({a} : Multiset α).fold op b = a * b :=
foldr_singleton _ _ _ _
theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : Multiset β) :
(s.map fun x => f x * g x).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ :=
Multiset.induction_on s (by simp) (fun a b h => by
rw [map_cons, fold_cons_left, h, map_cons, fold_cons_left, map_cons,
fold_cons_right, ha.assoc, ← ha.assoc (g a), hc.comm (g a),
ha.assoc, hc.comm (g a), ha.assoc])
theorem fold_hom {op' : β → β → β} [Std.Commutative op'] [Std.Associative op'] {m : α → β}
(hm : ∀ x y, m (op x y) = op' (m x) (m y)) (b : α) (s : Multiset α) :
(s.map m).fold op' (m b) = m (s.fold op b) :=
Multiset.induction_on s (by simp) (by simp (config := { contextual := true }) [hm])
theorem fold_union_inter [DecidableEq α] (s₁ s₂ : Multiset α) (b₁ b₂ : α) :
((s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂) = s₁.fold op b₁ * s₂.fold op b₂ := by
rw [← fold_add op, union_add_inter, fold_add op]
@[simp]
theorem fold_dedup_idem [DecidableEq α] [hi : Std.IdempotentOp op] (s : Multiset α) (b : α) :
(dedup s).fold op b = s.fold op b :=
Multiset.induction_on s (by simp) fun a s IH => by
by_cases h : a ∈ s <;> simp [IH, h]
show fold op b s = op a (fold op b s)
rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent]
end Fold
open Nat
theorem le_smul_dedup [DecidableEq α] (s : Multiset α) : ∃ n : ℕ, s ≤ n • dedup s :=
⟨(s.map fun a => count a s).fold max 0,
le_iff_count.2 fun a => by
rw [count_nsmul]; by_cases h : a ∈ s
· refine le_trans ?_ (Nat.mul_le_mul_left _ <| count_pos.2 <| mem_dedup.2 h)
have : count a s ≤ fold max 0 (map (fun a => count a s) (a ::ₘ erase s a)) := by
simp [le_max_left]
rw [cons_erase h] at this
simpa [mul_succ] using this
· simp [count_eq_zero.2 h, Nat.zero_le]⟩
end Multiset
|
Data\Multiset\Functor.lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johannes Hölzl, Simon Hudon, Kenny Lau
-/
import Mathlib.Data.Multiset.Bind
import Mathlib.Control.Traversable.Lemmas
import Mathlib.Control.Traversable.Instances
/-!
# Functoriality of `Multiset`.
-/
universe u
namespace Multiset
open List
instance functor : Functor Multiset where map := @map
@[simp]
theorem fmap_def {α' β'} {s : Multiset α'} (f : α' → β') : f <$> s = s.map f :=
rfl
instance : LawfulFunctor Multiset where
id_map := by simp
comp_map := by simp
map_const {_ _} := rfl
open LawfulTraversable CommApplicative
variable {F : Type u → Type u} [Applicative F] [CommApplicative F]
variable {α' β' : Type u} (f : α' → F β')
/-- Map each element of a `Multiset` to an action, evaluate these actions in order,
and collect the results.
-/
def traverse : Multiset α' → F (Multiset β') := by
refine Quotient.lift (Functor.map Coe.coe ∘ Traversable.traverse f) ?_
introv p; unfold Function.comp
induction p with
| nil => rfl
| @cons x l₁ l₂ _ h =>
have :
Multiset.cons <$> f x <*> Coe.coe <$> Traversable.traverse f l₁ =
Multiset.cons <$> f x <*> Coe.coe <$> Traversable.traverse f l₂ := by rw [h]
simpa [functor_norm] using this
| swap x y l =>
have :
(fun a b (l : List β') ↦ (↑(a :: b :: l) : Multiset β')) <$> f y <*> f x =
(fun a b l ↦ ↑(a :: b :: l)) <$> f x <*> f y := by
rw [CommApplicative.commutative_map]
congr
funext a b l
simpa [flip] using Perm.swap a b l
simp [(· ∘ ·), this, functor_norm, Coe.coe]
| trans => simp [*]
instance : Monad Multiset :=
{ Multiset.functor with
pure := fun x ↦ {x}
bind := @bind }
@[simp]
theorem pure_def {α} : (pure : α → Multiset α) = singleton :=
rfl
@[simp]
theorem bind_def {α β} : (· >>= ·) = @bind α β :=
rfl
instance : LawfulMonad Multiset := LawfulMonad.mk'
(bind_pure_comp := fun _ _ ↦ by simp only [pure_def, bind_def, bind_singleton, fmap_def])
(id_map := fun _ ↦ by simp only [fmap_def, id_eq, map_id'])
(pure_bind := fun _ _ ↦ by simp only [pure_def, bind_def, singleton_bind])
(bind_assoc := @bind_assoc)
open Functor
open Traversable LawfulTraversable
@[simp]
theorem map_comp_coe {α β} (h : α → β) :
Functor.map h ∘ Coe.coe = (Coe.coe ∘ Functor.map h : List α → Multiset β) := by
funext; simp only [Function.comp_apply, Coe.coe, fmap_def, map_coe, List.map_eq_map]
theorem id_traverse {α : Type*} (x : Multiset α) : traverse (pure : α → Id α) x = x := by
refine Quotient.inductionOn x ?_
intro
simp [traverse, Coe.coe]
theorem comp_traverse {G H : Type _ → Type _} [Applicative G] [Applicative H] [CommApplicative G]
[CommApplicative H] {α β γ : Type _} (g : α → G β) (h : β → H γ) (x : Multiset α) :
traverse (Comp.mk ∘ Functor.map h ∘ g) x =
Comp.mk (Functor.map (traverse h) (traverse g x)) := by
refine Quotient.inductionOn x ?_
intro
simp only [traverse, quot_mk_to_coe, lift_coe, Coe.coe, Function.comp_apply, Functor.map_map,
functor_norm]
simp only [Function.comp, lift_coe]
theorem map_traverse {G : Type* → Type _} [Applicative G] [CommApplicative G] {α β γ : Type _}
(g : α → G β) (h : β → γ) (x : Multiset α) :
Functor.map (Functor.map h) (traverse g x) = traverse (Functor.map h ∘ g) x := by
refine Quotient.inductionOn x ?_
intro
simp only [traverse, quot_mk_to_coe, lift_coe, Function.comp_apply, Functor.map_map, map_comp_coe]
rw [LawfulFunctor.comp_map, Traversable.map_traverse']
rfl
theorem traverse_map {G : Type* → Type _} [Applicative G] [CommApplicative G] {α β γ : Type _}
(g : α → β) (h : β → G γ) (x : Multiset α) : traverse h (map g x) = traverse (h ∘ g) x := by
refine Quotient.inductionOn x ?_
intro
simp only [traverse, quot_mk_to_coe, map_coe, lift_coe, Function.comp_apply]
rw [← Traversable.traverse_map h g, List.map_eq_map]
theorem naturality {G H : Type _ → Type _} [Applicative G] [Applicative H] [CommApplicative G]
[CommApplicative H] (eta : ApplicativeTransformation G H) {α β : Type _} (f : α → G β)
(x : Multiset α) : eta (traverse f x) = traverse (@eta _ ∘ f) x := by
refine Quotient.inductionOn x ?_
intro
simp only [quot_mk_to_coe, traverse, lift_coe, Function.comp_apply,
ApplicativeTransformation.preserves_map, LawfulTraversable.naturality]
end Multiset
|
Data\Multiset\Interval.lean | /-
Copyright (c) 2022 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import Mathlib.Data.DFinsupp.Interval
import Mathlib.Data.DFinsupp.Multiset
import Mathlib.Order.Interval.Finset.Nat
/-!
# Finite intervals of multisets
This file provides the `LocallyFiniteOrder` instance for `Multiset α` and calculates the
cardinality of its finite intervals.
## Implementation notes
We implement the intervals via the intervals on `DFinsupp`, rather than via filtering
`Multiset.Powerset`; this is because `(Multiset.replicate n x).Powerset` has `2^n` entries not `n+1`
entries as it contains duplicates. We do not go via `Finsupp` as this would be noncomputable, and
multisets are typically used computationally.
-/
open Finset DFinsupp Function
open Pointwise
variable {α : Type*}
namespace Multiset
variable [DecidableEq α] (s t : Multiset α)
instance instLocallyFiniteOrder : LocallyFiniteOrder (Multiset α) :=
LocallyFiniteOrder.ofIcc (Multiset α)
(fun s t => (Finset.Icc (toDFinsupp s) (toDFinsupp t)).map
Multiset.equivDFinsupp.toEquiv.symm.toEmbedding)
fun s t x => by simp
theorem Icc_eq :
Finset.Icc s t = (Finset.Icc (toDFinsupp s) (toDFinsupp t)).map
Multiset.equivDFinsupp.toEquiv.symm.toEmbedding :=
rfl
theorem uIcc_eq :
uIcc s t =
(uIcc (toDFinsupp s) (toDFinsupp t)).map Multiset.equivDFinsupp.toEquiv.symm.toEmbedding :=
(Icc_eq _ _).trans <| by simp [uIcc]
theorem card_Icc :
(Finset.Icc s t).card = ∏ i ∈ s.toFinset ∪ t.toFinset, (t.count i + 1 - s.count i) := by
simp_rw [Icc_eq, Finset.card_map, DFinsupp.card_Icc, Nat.card_Icc, Multiset.toDFinsupp_apply,
toDFinsupp_support]
theorem card_Ico :
(Finset.Ico s t).card = ∏ i ∈ s.toFinset ∪ t.toFinset, (t.count i + 1 - s.count i) - 1 := by
rw [Finset.card_Ico_eq_card_Icc_sub_one, card_Icc]
theorem card_Ioc :
(Finset.Ioc s t).card = ∏ i ∈ s.toFinset ∪ t.toFinset, (t.count i + 1 - s.count i) - 1 := by
rw [Finset.card_Ioc_eq_card_Icc_sub_one, card_Icc]
theorem card_Ioo :
(Finset.Ioo s t).card = ∏ i ∈ s.toFinset ∪ t.toFinset, (t.count i + 1 - s.count i) - 2 := by
rw [Finset.card_Ioo_eq_card_Icc_sub_two, card_Icc]
theorem card_uIcc :
(uIcc s t).card = ∏ i ∈ s.toFinset ∪ t.toFinset, ((t.count i - s.count i : ℤ).natAbs + 1) := by
simp_rw [uIcc_eq, Finset.card_map, DFinsupp.card_uIcc, Nat.card_uIcc, Multiset.toDFinsupp_apply,
toDFinsupp_support]
theorem card_Iic : (Finset.Iic s).card = ∏ i ∈ s.toFinset, (s.count i + 1) := by
simp_rw [Iic_eq_Icc, card_Icc, bot_eq_zero, toFinset_zero, empty_union, count_zero, tsub_zero]
end Multiset
|
Data\Multiset\Lattice.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.Multiset.FinsetOps
import Mathlib.Data.Multiset.Fold
/-!
# Lattice operations on multisets
-/
namespace Multiset
variable {α : Type*}
/-! ### sup -/
section Sup
-- can be defined with just `[Bot α]` where some lemmas hold without requiring `[OrderBot α]`
variable [SemilatticeSup α] [OrderBot α]
/-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/
def sup (s : Multiset α) : α :=
s.fold (· ⊔ ·) ⊥
@[simp]
theorem sup_coe (l : List α) : sup (l : Multiset α) = l.foldr (· ⊔ ·) ⊥ :=
rfl
@[simp]
theorem sup_zero : (0 : Multiset α).sup = ⊥ :=
fold_zero _ _
@[simp]
theorem sup_cons (a : α) (s : Multiset α) : (a ::ₘ s).sup = a ⊔ s.sup :=
fold_cons_left _ _ _ _
@[simp]
theorem sup_singleton {a : α} : ({a} : Multiset α).sup = a := sup_bot_eq _
@[simp]
theorem sup_add (s₁ s₂ : Multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup :=
Eq.trans (by simp [sup]) (fold_add _ _ _ _ _)
@[simp]
theorem sup_le {s : Multiset α} {a : α} : s.sup ≤ a ↔ ∀ b ∈ s, b ≤ a :=
Multiset.induction_on s (by simp)
(by simp (config := { contextual := true }) [or_imp, forall_and])
theorem le_sup {s : Multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup :=
sup_le.1 le_rfl _ h
theorem sup_mono {s₁ s₂ : Multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup :=
sup_le.2 fun _ hb => le_sup (h hb)
variable [DecidableEq α]
@[simp]
theorem sup_dedup (s : Multiset α) : (dedup s).sup = s.sup :=
fold_dedup_idem _ _ _
@[simp]
theorem sup_ndunion (s₁ s₂ : Multiset α) : (ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup := by
rw [← sup_dedup, dedup_ext.2, sup_dedup, sup_add]; simp
@[simp]
theorem sup_union (s₁ s₂ : Multiset α) : (s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup := by
rw [← sup_dedup, dedup_ext.2, sup_dedup, sup_add]; simp
@[simp]
theorem sup_ndinsert (a : α) (s : Multiset α) : (ndinsert a s).sup = a ⊔ s.sup := by
rw [← sup_dedup, dedup_ext.2, sup_dedup, sup_cons]; simp
theorem nodup_sup_iff {α : Type*} [DecidableEq α] {m : Multiset (Multiset α)} :
m.sup.Nodup ↔ ∀ a : Multiset α, a ∈ m → a.Nodup := by
-- Porting note: this was originally `apply m.induction_on`, which failed due to
-- `failed to elaborate eliminator, expected type is not available`
induction' m using Multiset.induction_on with _ _ h
· simp
· simp [h]
end Sup
/-! ### inf -/
section Inf
-- can be defined with just `[Top α]` where some lemmas hold without requiring `[OrderTop α]`
variable [SemilatticeInf α] [OrderTop α]
/-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/
def inf (s : Multiset α) : α :=
s.fold (· ⊓ ·) ⊤
@[simp]
theorem inf_coe (l : List α) : inf (l : Multiset α) = l.foldr (· ⊓ ·) ⊤ :=
rfl
@[simp]
theorem inf_zero : (0 : Multiset α).inf = ⊤ :=
fold_zero _ _
@[simp]
theorem inf_cons (a : α) (s : Multiset α) : (a ::ₘ s).inf = a ⊓ s.inf :=
fold_cons_left _ _ _ _
@[simp]
theorem inf_singleton {a : α} : ({a} : Multiset α).inf = a := inf_top_eq _
@[simp]
theorem inf_add (s₁ s₂ : Multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf :=
Eq.trans (by simp [inf]) (fold_add _ _ _ _ _)
@[simp]
theorem le_inf {s : Multiset α} {a : α} : a ≤ s.inf ↔ ∀ b ∈ s, a ≤ b :=
Multiset.induction_on s (by simp)
(by simp (config := { contextual := true }) [or_imp, forall_and])
theorem inf_le {s : Multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a :=
le_inf.1 le_rfl _ h
theorem inf_mono {s₁ s₂ : Multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf :=
le_inf.2 fun _ hb => inf_le (h hb)
variable [DecidableEq α]
@[simp]
theorem inf_dedup (s : Multiset α) : (dedup s).inf = s.inf :=
fold_dedup_idem _ _ _
@[simp]
theorem inf_ndunion (s₁ s₂ : Multiset α) : (ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf := by
rw [← inf_dedup, dedup_ext.2, inf_dedup, inf_add]; simp
@[simp]
theorem inf_union (s₁ s₂ : Multiset α) : (s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf := by
rw [← inf_dedup, dedup_ext.2, inf_dedup, inf_add]; simp
@[simp]
theorem inf_ndinsert (a : α) (s : Multiset α) : (ndinsert a s).inf = a ⊓ s.inf := by
rw [← inf_dedup, dedup_ext.2, inf_dedup, inf_cons]; simp
end Inf
end Multiset
|
Data\Multiset\NatAntidiagonal.lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import Mathlib.Data.Multiset.Nodup
import Mathlib.Data.List.NatAntidiagonal
/-!
# Antidiagonals in ℕ × ℕ as multisets
This file defines the antidiagonals of ℕ × ℕ as multisets: the `n`-th antidiagonal is the multiset
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 file `Data.List.NatAntidiagonal` and is further refined by file
`Data.Finset.NatAntidiagonal`.
-/
namespace Multiset
namespace Nat
/-- The antidiagonal of a natural number `n` is
the multiset of pairs `(i, j)` such that `i + j = n`. -/
def antidiagonal (n : ℕ) : Multiset (ℕ × ℕ) :=
List.Nat.antidiagonal n
/-- A pair (i, j) is contained in the antidiagonal of `n` if and only if `i + j = n`. -/
@[simp]
theorem mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := by
rw [antidiagonal, mem_coe, List.Nat.mem_antidiagonal]
/-- The cardinality of the antidiagonal of `n` is `n+1`. -/
@[simp]
theorem card_antidiagonal (n : ℕ) : card (antidiagonal n) = n + 1 := by
rw [antidiagonal, coe_card, List.Nat.length_antidiagonal]
/-- The antidiagonal of `0` is the list `[(0, 0)]` -/
@[simp]
theorem antidiagonal_zero : antidiagonal 0 = {(0, 0)} :=
rfl
/-- The antidiagonal of `n` does not contain duplicate entries. -/
@[simp]
theorem nodup_antidiagonal (n : ℕ) : Nodup (antidiagonal n) :=
coe_nodup.2 <| List.Nat.nodup_antidiagonal n
@[simp]
theorem antidiagonal_succ {n : ℕ} :
antidiagonal (n + 1) = (0, n + 1) ::ₘ (antidiagonal n).map (Prod.map Nat.succ id) := by
simp only [antidiagonal, List.Nat.antidiagonal_succ, map_coe, cons_coe]
theorem antidiagonal_succ' {n : ℕ} :
antidiagonal (n + 1) = (n + 1, 0) ::ₘ (antidiagonal n).map (Prod.map id Nat.succ) := by
rw [antidiagonal, List.Nat.antidiagonal_succ', ← coe_add, add_comm, antidiagonal, map_coe,
coe_add, List.singleton_append, cons_coe]
theorem antidiagonal_succ_succ' {n : ℕ} :
antidiagonal (n + 2) =
(0, n + 2) ::ₘ (n + 2, 0) ::ₘ (antidiagonal n).map (Prod.map Nat.succ Nat.succ) := by
rw [antidiagonal_succ, antidiagonal_succ', map_cons, map_map, Prod.map_apply]
rfl
theorem map_swap_antidiagonal {n : ℕ} : (antidiagonal n).map Prod.swap = antidiagonal n := by
rw [antidiagonal, map_coe, List.Nat.map_swap_antidiagonal, coe_reverse]
end Nat
end Multiset
|
Data\Multiset\Nodup.lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.Multiset.Range
import Mathlib.Data.List.Pairwise
/-!
# The `Nodup` predicate for multisets without duplicate elements.
-/
namespace Multiset
open Function List
variable {α β γ : Type*} {r : α → α → Prop} {s t : Multiset α} {a : α}
-- nodup
/-- `Nodup s` means that `s` has no duplicates, i.e. the multiplicity of
any element is at most 1. -/
def Nodup (s : Multiset α) : Prop :=
Quot.liftOn s List.Nodup fun _ _ p => propext p.nodup_iff
@[simp]
theorem coe_nodup {l : List α} : @Nodup α l ↔ l.Nodup :=
Iff.rfl
@[simp]
theorem nodup_zero : @Nodup α 0 :=
Pairwise.nil
@[simp]
theorem nodup_cons {a : α} {s : Multiset α} : Nodup (a ::ₘ s) ↔ a ∉ s ∧ Nodup s :=
Quot.induction_on s fun _ => List.nodup_cons
theorem Nodup.cons (m : a ∉ s) (n : Nodup s) : Nodup (a ::ₘ s) :=
nodup_cons.2 ⟨m, n⟩
@[simp]
theorem nodup_singleton : ∀ a : α, Nodup ({a} : Multiset α) :=
List.nodup_singleton
theorem Nodup.of_cons (h : Nodup (a ::ₘ s)) : Nodup s :=
(nodup_cons.1 h).2
theorem Nodup.not_mem (h : Nodup (a ::ₘ s)) : a ∉ s :=
(nodup_cons.1 h).1
theorem nodup_of_le {s t : Multiset α} (h : s ≤ t) : Nodup t → Nodup s :=
Multiset.leInductionOn h fun {_ _} => Nodup.sublist
theorem not_nodup_pair : ∀ a : α, ¬Nodup (a ::ₘ a ::ₘ 0) :=
List.not_nodup_pair
theorem nodup_iff_le {s : Multiset α} : Nodup s ↔ ∀ a : α, ¬a ::ₘ a ::ₘ 0 ≤ s :=
Quot.induction_on s fun _ =>
nodup_iff_sublist.trans <| forall_congr' fun a => not_congr (@replicate_le_coe _ a 2 _).symm
theorem nodup_iff_ne_cons_cons {s : Multiset α} : s.Nodup ↔ ∀ a t, s ≠ a ::ₘ a ::ₘ t :=
nodup_iff_le.trans
⟨fun h a t s_eq => h a (s_eq.symm ▸ cons_le_cons a (cons_le_cons a (zero_le _))), fun h a le =>
let ⟨t, s_eq⟩ := le_iff_exists_add.mp le
h a t (by rwa [cons_add, cons_add, zero_add] at s_eq)⟩
theorem nodup_iff_count_le_one [DecidableEq α] {s : Multiset α} : Nodup s ↔ ∀ a, count a s ≤ 1 :=
Quot.induction_on s fun _l => by
simp only [quot_mk_to_coe'', coe_nodup, mem_coe, coe_count]
exact List.nodup_iff_count_le_one
theorem nodup_iff_count_eq_one [DecidableEq α] : Nodup s ↔ ∀ a ∈ s, count a s = 1 :=
Quot.induction_on s fun _l => by simpa using List.nodup_iff_count_eq_one
@[simp]
theorem count_eq_one_of_mem [DecidableEq α] {a : α} {s : Multiset α} (d : Nodup s) (h : a ∈ s) :
count a s = 1 :=
nodup_iff_count_eq_one.mp d a h
theorem count_eq_of_nodup [DecidableEq α] {a : α} {s : Multiset α} (d : Nodup s) :
count a s = if a ∈ s then 1 else 0 := by
split_ifs with h
· exact count_eq_one_of_mem d h
· exact count_eq_zero_of_not_mem h
theorem nodup_iff_pairwise {α} {s : Multiset α} : Nodup s ↔ Pairwise (· ≠ ·) s :=
Quotient.inductionOn s fun _ => (pairwise_coe_iff_pairwise fun _ _ => Ne.symm).symm
protected theorem Nodup.pairwise : (∀ a ∈ s, ∀ b ∈ s, a ≠ b → r a b) → Nodup s → Pairwise r s :=
Quotient.inductionOn s fun l h hl => ⟨l, rfl, hl.imp_of_mem fun {a b} ha hb => h a ha b hb⟩
theorem Pairwise.forall (H : Symmetric r) (hs : Pairwise r s) :
∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → a ≠ b → r a b :=
let ⟨_, hl₁, hl₂⟩ := hs
hl₁.symm ▸ hl₂.forall H
theorem nodup_add {s t : Multiset α} : Nodup (s + t) ↔ Nodup s ∧ Nodup t ∧ Disjoint s t :=
Quotient.inductionOn₂ s t fun _ _ => nodup_append
theorem disjoint_of_nodup_add {s t : Multiset α} (d : Nodup (s + t)) : Disjoint s t :=
(nodup_add.1 d).2.2
theorem Nodup.add_iff (d₁ : Nodup s) (d₂ : Nodup t) : Nodup (s + t) ↔ Disjoint s t := by
simp [nodup_add, d₁, d₂]
theorem Nodup.of_map (f : α → β) : Nodup (map f s) → Nodup s :=
Quot.induction_on s fun _ => List.Nodup.of_map f
theorem Nodup.map_on {f : α → β} :
(∀ x ∈ s, ∀ y ∈ s, f x = f y → x = y) → Nodup s → Nodup (map f s) :=
Quot.induction_on s fun _ => List.Nodup.map_on
theorem Nodup.map {f : α → β} {s : Multiset α} (hf : Injective f) : Nodup s → Nodup (map f s) :=
Nodup.map_on fun _ _ _ _ h => hf h
theorem nodup_map_iff_of_inj_on {f : α → β} (d : ∀ x ∈ s, ∀ y ∈ s, f x = f y → x = y) :
Nodup (map f s) ↔ Nodup s :=
⟨Nodup.of_map _, fun h => h.map_on d⟩
theorem nodup_map_iff_of_injective {f : α → β} (d : Function.Injective f) :
Nodup (map f s) ↔ Nodup s :=
⟨Nodup.of_map _, fun h => h.map d⟩
theorem inj_on_of_nodup_map {f : α → β} {s : Multiset α} :
Nodup (map f s) → ∀ x ∈ s, ∀ y ∈ s, f x = f y → x = y :=
Quot.induction_on s fun _ => List.inj_on_of_nodup_map
theorem nodup_map_iff_inj_on {f : α → β} {s : Multiset α} (d : Nodup s) :
Nodup (map f s) ↔ ∀ x ∈ s, ∀ y ∈ s, f x = f y → x = y :=
⟨inj_on_of_nodup_map, fun h => d.map_on h⟩
theorem Nodup.filter (p : α → Prop) [DecidablePred p] {s} : Nodup s → Nodup (filter p s) :=
Quot.induction_on s fun _ => List.Nodup.filter (p ·)
@[simp]
theorem nodup_attach {s : Multiset α} : Nodup (attach s) ↔ Nodup s :=
Quot.induction_on s fun _ => List.nodup_attach
protected alias ⟨_, Nodup.attach⟩ := nodup_attach
theorem Nodup.pmap {p : α → Prop} {f : ∀ a, p a → β} {s : Multiset α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) : Nodup s → Nodup (pmap f s H) :=
Quot.induction_on s (fun _ _ => List.Nodup.pmap hf) H
instance nodupDecidable [DecidableEq α] (s : Multiset α) : Decidable (Nodup s) :=
Quotient.recOnSubsingleton s fun l => l.nodupDecidable
theorem Nodup.erase_eq_filter [DecidableEq α] (a : α) {s} :
Nodup s → s.erase a = Multiset.filter (· ≠ a) s :=
Quot.induction_on s fun _ d =>
congr_arg ((↑) : List α → Multiset α) <| by simpa using List.Nodup.erase_eq_filter d a
theorem Nodup.erase [DecidableEq α] (a : α) {l} : Nodup l → Nodup (l.erase a) :=
nodup_of_le (erase_le _ _)
theorem Nodup.mem_erase_iff [DecidableEq α] {a b : α} {l} (d : Nodup l) :
a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by
rw [d.erase_eq_filter b, mem_filter, and_comm]
theorem Nodup.not_mem_erase [DecidableEq α] {a : α} {s} (h : Nodup s) : a ∉ s.erase a := fun ha =>
(h.mem_erase_iff.1 ha).1 rfl
protected theorem Nodup.filterMap (f : α → Option β) (H : ∀ a a' b, b ∈ f a → b ∈ f a' → a = a') :
Nodup s → Nodup (filterMap f s) :=
Quot.induction_on s fun _ => List.Nodup.filterMap H
theorem nodup_range (n : ℕ) : Nodup (range n) :=
List.nodup_range _
theorem Nodup.inter_left [DecidableEq α] (t) : Nodup s → Nodup (s ∩ t) :=
nodup_of_le <| inter_le_left _ _
theorem Nodup.inter_right [DecidableEq α] (s) : Nodup t → Nodup (s ∩ t) :=
nodup_of_le <| inter_le_right _ _
@[simp]
theorem nodup_union [DecidableEq α] {s t : Multiset α} : Nodup (s ∪ t) ↔ Nodup s ∧ Nodup t :=
⟨fun h => ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩, fun ⟨h₁, h₂⟩ =>
nodup_iff_count_le_one.2 fun a => by
rw [count_union]
exact max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩
theorem Nodup.ext {s t : Multiset α} : Nodup s → Nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) :=
Quotient.inductionOn₂ s t fun _ _ d₁ d₂ => Quotient.eq.trans <| perm_ext_iff_of_nodup d₁ d₂
theorem le_iff_subset {s t : Multiset α} : Nodup s → (s ≤ t ↔ s ⊆ t) :=
Quotient.inductionOn₂ s t fun _ _ d => ⟨subset_of_le, d.subperm⟩
theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n :=
(le_iff_subset (nodup_range _)).trans range_subset
theorem mem_sub_of_nodup [DecidableEq α] {a : α} {s t : Multiset α} (d : Nodup s) :
a ∈ s - t ↔ a ∈ s ∧ a ∉ t :=
⟨fun h =>
⟨mem_of_le tsub_le_self h, fun h' => by
refine count_eq_zero.1 ?_ h
rw [count_sub a s t, Nat.sub_eq_zero_iff_le]
exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩,
fun ⟨h₁, h₂⟩ => Or.resolve_right (mem_add.1 <| mem_of_le le_tsub_add h₁) h₂⟩
theorem map_eq_map_of_bij_of_nodup (f : α → γ) (g : β → γ) {s : Multiset α} {t : Multiset β}
(hs : s.Nodup) (ht : t.Nodup) (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) (h : ∀ a ha, f a = g (i a ha)) : s.map f = t.map g := by
have : t = s.attach.map fun x => i x.1 x.2 := by
rw [ht.ext]
· aesop
· exact hs.attach.map fun x y hxy ↦ Subtype.ext <| i_inj _ x.2 _ y.2 hxy
calc
s.map f = s.pmap (fun x _ => f x) fun _ => id := by rw [pmap_eq_map]
_ = s.attach.map fun x => f x.1 := by rw [pmap_eq_map_attach]
_ = t.map g := by rw [this, Multiset.map_map]; exact map_congr rfl fun x _ => h _ _
end Multiset
|
Data\Multiset\Pi.lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import Mathlib.Data.Multiset.Bind
/-!
# The cartesian product of multisets
## Main definitions
* `Multiset.pi`: Cartesian product of multisets indexed by a multiset.
-/
namespace Multiset
section Pi
open Function
namespace Pi
variable {α : Type*} [DecidableEq α] {δ : α → Sort*}
/-- Given `δ : α → Sort*`, `Pi.empty δ` is the trivial dependent function out of the empty
multiset. -/
def empty (δ : α → Sort*) : ∀ a ∈ (0 : Multiset α), δ a :=
nofun
variable (m : Multiset α) (a : α)
/-- Given `δ : α → Sort*`, a multiset `m` and a term `a`, as well as a term `b : δ a` and a
function `f` such that `f a' : δ a'` for all `a'` in `m`, `Pi.cons m a b f` is a function `g` such
that `g a'' : δ a''` for all `a''` in `a ::ₘ m`. -/
def cons (b : δ a) (f : ∀ a ∈ m, δ a) : ∀ a' ∈ a ::ₘ m, δ a' :=
fun a' ha' => if h : a' = a then Eq.ndrec b h.symm else f a' <| (mem_cons.1 ha').resolve_left h
variable {m a}
theorem cons_same {b : δ a} {f : ∀ a ∈ m, δ a} (h : a ∈ a ::ₘ m) :
cons m a b f a h = b :=
dif_pos rfl
theorem cons_ne {a a' : α} {b : δ a} {f : ∀ a ∈ m, δ a} (h' : a' ∈ a ::ₘ m)
(h : a' ≠ a) : Pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) :=
dif_neg h
theorem cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : Multiset α} {f : ∀ a ∈ m, δ a}
(h : a ≠ a') : HEq (Pi.cons (a' ::ₘ m) a b (Pi.cons m a' b' f))
(Pi.cons (a ::ₘ m) a' b' (Pi.cons m a b f)) := by
apply hfunext rfl
simp only [heq_iff_eq]
rintro a'' _ rfl
refine hfunext (by rw [Multiset.cons_swap]) fun ha₁ ha₂ _ => ?_
rcases ne_or_eq a'' a with (h₁ | rfl)
on_goal 1 => rcases eq_or_ne a'' a' with (rfl | h₂)
all_goals simp [*, Pi.cons_same, Pi.cons_ne]
@[simp, nolint simpNF] -- Porting note: false positive, this lemma can prove itself
theorem cons_eta {m : Multiset α} {a : α} (f : ∀ a' ∈ a ::ₘ m, δ a') :
(cons m a (f _ (mem_cons_self _ _)) fun a' ha' => f a' (mem_cons_of_mem ha')) = f := by
ext a' h'
by_cases h : a' = a
· subst h
rw [Pi.cons_same]
· rw [Pi.cons_ne _ h]
theorem cons_map (b : δ a) (f : ∀ a' ∈ m, δ a')
{δ' : α → Sort*} (φ : ∀ ⦃a'⦄, δ a' → δ' a') :
Pi.cons _ _ (φ b) (fun a' ha' ↦ φ (f a' ha')) = (fun a' ha' ↦ φ ((cons _ _ b f) a' ha')) := by
ext a' ha'
refine (congrArg₂ _ ?_ rfl).trans (apply_dite (@φ _) (a' = a) _ _).symm
ext rfl
rfl
theorem forall_rel_cons_ext {r : ∀ ⦃a⦄, δ a → δ a → Prop} {b₁ b₂ : δ a} {f₁ f₂ : ∀ a' ∈ m, δ a'}
(hb : r b₁ b₂) (hf : ∀ (a : α) (ha : a ∈ m), r (f₁ a ha) (f₂ a ha)) :
∀ a ha, r (cons _ _ b₁ f₁ a ha) (cons _ _ b₂ f₂ a ha) := by
intro a ha
dsimp [cons]
split_ifs with H
· cases H
exact hb
· exact hf _ _
theorem cons_injective {a : α} {b : δ a} {s : Multiset α} (hs : a ∉ s) :
Function.Injective (Pi.cons s a b) := fun f₁ f₂ eq =>
funext fun a' =>
funext fun h' =>
have ne : a ≠ a' := fun h => hs <| h.symm ▸ h'
have : a' ∈ a ::ₘ s := mem_cons_of_mem h'
calc
f₁ a' h' = Pi.cons s a b f₁ a' this := by rw [Pi.cons_ne this ne.symm]
_ = Pi.cons s a b f₂ a' this := by rw [eq]
_ = f₂ a' h' := by rw [Pi.cons_ne this ne.symm]
end Pi
section
variable {α : Type*} [DecidableEq α] {β : α → Type*}
/-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/
def pi (m : Multiset α) (t : ∀ a, Multiset (β a)) : Multiset (∀ a ∈ m, β a) :=
m.recOn {Pi.empty β}
(fun a m (p : Multiset (∀ a ∈ m, β a)) => (t a).bind fun b => p.map <| Pi.cons m a b)
(by
intro a a' m n
by_cases eq : a = a'
· subst eq; rfl
· simp only [map_bind, map_map, comp_apply, bind_bind (t a') (t a)]
apply bind_hcongr
· rw [cons_swap a a']
intro b _
apply bind_hcongr
· rw [cons_swap a a']
intro b' _
apply map_hcongr
· rw [cons_swap a a']
intro f _
exact Pi.cons_swap eq)
@[simp]
theorem pi_zero (t : ∀ a, Multiset (β a)) : pi 0 t = {Pi.empty β} :=
rfl
@[simp]
theorem pi_cons (m : Multiset α) (t : ∀ a, Multiset (β a)) (a : α) :
pi (a ::ₘ m) t = (t a).bind fun b => (pi m t).map <| Pi.cons m a b :=
recOn_cons a m
theorem card_pi (m : Multiset α) (t : ∀ a, Multiset (β a)) :
card (pi m t) = prod (m.map fun a => card (t a)) :=
Multiset.induction_on m (by simp) (by simp (config := { contextual := true }) [mul_comm])
protected theorem Nodup.pi {s : Multiset α} {t : ∀ a, Multiset (β a)} :
Nodup s → (∀ a ∈ s, Nodup (t a)) → Nodup (pi s t) :=
Multiset.induction_on s (fun _ _ => nodup_singleton _)
(by
intro a s ih hs ht
have has : a ∉ s := by simp only [nodup_cons] at hs; exact hs.1
have hs : Nodup s := by simp only [nodup_cons] at hs; exact hs.2
simp only [pi_cons, nodup_bind]
refine
⟨fun b _ => ((ih hs) fun a' h' => ht a' <| mem_cons_of_mem h').map (Pi.cons_injective has),
?_⟩
refine (ht a <| mem_cons_self _ _).pairwise ?_
exact fun b₁ _ b₂ _ neb =>
disjoint_map_map.2 fun f _ g _ eq =>
have : Pi.cons s a b₁ f a (mem_cons_self _ _) = Pi.cons s a b₂ g a (mem_cons_self _ _) :=
by rw [eq]
neb <| show b₁ = b₂ by rwa [Pi.cons_same, Pi.cons_same] at this)
theorem mem_pi (m : Multiset α) (t : ∀ a, Multiset (β a)) :
∀ f : ∀ a ∈ m, β a, f ∈ pi m t ↔ ∀ (a) (h : a ∈ m), f a h ∈ t a := by
intro f
induction' m using Multiset.induction_on with a m ih
· have : f = Pi.empty β := funext (fun _ => funext fun h => (not_mem_zero _ h).elim)
simp only [this, pi_zero, mem_singleton, true_iff]
intro _ h; exact (not_mem_zero _ h).elim
simp_rw [pi_cons, mem_bind, mem_map, ih]
constructor
· rintro ⟨b, hb, f', hf', rfl⟩ a' ha'
by_cases h : a' = a
· subst h
rwa [Pi.cons_same]
· rw [Pi.cons_ne _ h]
apply hf'
· intro hf
refine ⟨_, hf a (mem_cons_self _ _), _, fun a ha => hf a (mem_cons_of_mem ha), ?_⟩
rw [Pi.cons_eta]
end
end Pi
end Multiset
|
Data\Multiset\Powerset.lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.List.Sublists
import Mathlib.Data.List.Zip
import Mathlib.Data.Multiset.Bind
/-!
# The powerset of a multiset
-/
namespace Multiset
open List
variable {α : Type*}
/-! ### powerset -/
-- Porting note (#11215): TODO: Write a more efficient version
/-- A helper function for the powerset of a multiset. Given a list `l`, returns a list
of sublists of `l` as multisets. -/
def powersetAux (l : List α) : List (Multiset α) :=
(sublists l).map (↑)
theorem powersetAux_eq_map_coe {l : List α} : powersetAux l = (sublists l).map (↑) :=
rfl
@[simp]
theorem mem_powersetAux {l : List α} {s} : s ∈ powersetAux l ↔ s ≤ ↑l :=
Quotient.inductionOn s <| by simp [powersetAux_eq_map_coe, Subperm, and_comm]
/-- Helper function for the powerset of a multiset. Given a list `l`, returns a list
of sublists of `l` (using `sublists'`), as multisets. -/
def powersetAux' (l : List α) : List (Multiset α) :=
(sublists' l).map (↑)
theorem powersetAux_perm_powersetAux' {l : List α} : powersetAux l ~ powersetAux' l := by
rw [powersetAux_eq_map_coe]; exact (sublists_perm_sublists' _).map _
@[simp]
theorem powersetAux'_nil : powersetAux' (@nil α) = [0] :=
rfl
@[simp]
theorem powersetAux'_cons (a : α) (l : List α) :
powersetAux' (a :: l) = powersetAux' l ++ List.map (cons a) (powersetAux' l) := by
simp [powersetAux']
theorem powerset_aux'_perm {l₁ l₂ : List α} (p : l₁ ~ l₂) : powersetAux' l₁ ~ powersetAux' l₂ := by
induction' p with a l₁ l₂ p IH a b l l₁ l₂ l₃ _ _ IH₁ IH₂
· simp
· simp only [powersetAux'_cons]
exact IH.append (IH.map _)
· simp only [powersetAux'_cons, map_append, List.map_map, append_assoc]
apply Perm.append_left
rw [← append_assoc, ← append_assoc,
(by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)]
exact perm_append_comm.append_right _
· exact IH₁.trans IH₂
theorem powersetAux_perm {l₁ l₂ : List α} (p : l₁ ~ l₂) : powersetAux l₁ ~ powersetAux l₂ :=
powersetAux_perm_powersetAux'.trans <|
(powerset_aux'_perm p).trans powersetAux_perm_powersetAux'.symm
--Porting note (#11083): slightly slower implementation due to `map ofList`
/-- The power set of a multiset. -/
def powerset (s : Multiset α) : Multiset (Multiset α) :=
Quot.liftOn s
(fun l => (powersetAux l : Multiset (Multiset α)))
(fun _ _ h => Quot.sound (powersetAux_perm h))
theorem powerset_coe (l : List α) : @powerset α l = ((sublists l).map (↑) : List (Multiset α)) :=
congr_arg ((↑) : List (Multiset α) → Multiset (Multiset α)) powersetAux_eq_map_coe
@[simp]
theorem powerset_coe' (l : List α) : @powerset α l = ((sublists' l).map (↑) : List (Multiset α)) :=
Quot.sound powersetAux_perm_powersetAux'
@[simp]
theorem powerset_zero : @powerset α 0 = {0} :=
rfl
@[simp]
theorem powerset_cons (a : α) (s) : powerset (a ::ₘ s) = powerset s + map (cons a) (powerset s) :=
Quotient.inductionOn s fun l => by simp [Function.comp_def]
@[simp]
theorem mem_powerset {s t : Multiset α} : s ∈ powerset t ↔ s ≤ t :=
Quotient.inductionOn₂ s t <| by simp [Subperm, and_comm]
theorem map_single_le_powerset (s : Multiset α) : s.map singleton ≤ powerset s :=
Quotient.inductionOn s fun l => by
simp only [powerset_coe, quot_mk_to_coe, coe_le, map_coe]
show l.map (((↑) : List α → Multiset α) ∘ pure) <+~ (sublists l).map (↑)
rw [← List.map_map]
exact ((map_pure_sublist_sublists _).map _).subperm
@[simp]
theorem card_powerset (s : Multiset α) : card (powerset s) = 2 ^ card s :=
Quotient.inductionOn s <| by simp
theorem revzip_powersetAux {l : List α} ⦃x⦄ (h : x ∈ revzip (powersetAux l)) : x.1 + x.2 = ↑l := by
rw [revzip, powersetAux_eq_map_coe, ← map_reverse, zip_map, ← revzip, List.mem_map] at h
simp only [Prod.map_apply, Prod.exists] at h
rcases h with ⟨l₁, l₂, h, rfl, rfl⟩
exact Quot.sound (revzip_sublists _ _ _ h)
theorem revzip_powersetAux' {l : List α} ⦃x⦄ (h : x ∈ revzip (powersetAux' l)) :
x.1 + x.2 = ↑l := by
rw [revzip, powersetAux', ← map_reverse, zip_map, ← revzip, List.mem_map] at h
simp only [Prod.map_apply, Prod.exists] at h
rcases h with ⟨l₁, l₂, h, rfl, rfl⟩
exact Quot.sound (revzip_sublists' _ _ _ h)
theorem revzip_powersetAux_lemma {α : Type*} [DecidableEq α] (l : List α) {l' : List (Multiset α)}
(H : ∀ ⦃x : _ × _⦄, x ∈ revzip l' → x.1 + x.2 = ↑l) :
revzip l' = l'.map fun x => (x, (l : Multiset α) - x) := by
have :
Forall₂ (fun (p : Multiset α × Multiset α) (s : Multiset α) => p = (s, ↑l - s)) (revzip l')
((revzip l').map Prod.fst) := by
rw [forall₂_map_right_iff, forall₂_same]
rintro ⟨s, t⟩ h
dsimp
rw [← H h, add_tsub_cancel_left]
rw [← forall₂_eq_eq_eq, forall₂_map_right_iff]
simpa using this
theorem revzip_powersetAux_perm_aux' {l : List α} :
revzip (powersetAux l) ~ revzip (powersetAux' l) := by
haveI := Classical.decEq α
rw [revzip_powersetAux_lemma l revzip_powersetAux, revzip_powersetAux_lemma l revzip_powersetAux']
exact powersetAux_perm_powersetAux'.map _
theorem revzip_powersetAux_perm {l₁ l₂ : List α} (p : l₁ ~ l₂) :
revzip (powersetAux l₁) ~ revzip (powersetAux l₂) := by
haveI := Classical.decEq α
simp only [fun l : List α => revzip_powersetAux_lemma l revzip_powersetAux, coe_eq_coe.2 p]
exact (powersetAux_perm p).map _
/-! ### powersetCard -/
/-- Helper function for `powersetCard`. Given a list `l`, `powersetCardAux n l` is the list
of sublists of length `n`, as multisets. -/
def powersetCardAux (n : ℕ) (l : List α) : List (Multiset α) :=
sublistsLenAux n l (↑) []
theorem powersetCardAux_eq_map_coe {n} {l : List α} :
powersetCardAux n l = (sublistsLen n l).map (↑) := by
rw [powersetCardAux, sublistsLenAux_eq, append_nil]
@[simp]
theorem mem_powersetCardAux {n} {l : List α} {s} : s ∈ powersetCardAux n l ↔ s ≤ ↑l ∧ card s = n :=
Quotient.inductionOn s <| by
simp only [quot_mk_to_coe, powersetCardAux_eq_map_coe, List.mem_map, mem_sublistsLen,
coe_eq_coe, coe_le, Subperm, exists_prop, coe_card]
exact fun l₁ =>
⟨fun ⟨l₂, ⟨s, e⟩, p⟩ => ⟨⟨_, p, s⟩, p.symm.length_eq.trans e⟩,
fun ⟨⟨l₂, p, s⟩, e⟩ => ⟨_, ⟨s, p.length_eq.trans e⟩, p⟩⟩
@[simp]
theorem powersetCardAux_zero (l : List α) : powersetCardAux 0 l = [0] := by
simp [powersetCardAux_eq_map_coe]
@[simp]
theorem powersetCardAux_nil (n : ℕ) : powersetCardAux (n + 1) (@nil α) = [] :=
rfl
@[simp]
theorem powersetCardAux_cons (n : ℕ) (a : α) (l : List α) :
powersetCardAux (n + 1) (a :: l) =
powersetCardAux (n + 1) l ++ List.map (cons a) (powersetCardAux n l) := by
simp [powersetCardAux_eq_map_coe]
theorem powersetCardAux_perm {n} {l₁ l₂ : List α} (p : l₁ ~ l₂) :
powersetCardAux n l₁ ~ powersetCardAux n l₂ := by
induction' n with n IHn generalizing l₁ l₂
· simp
induction' p with a l₁ l₂ p IH a b l l₁ l₂ l₃ _ _ IH₁ IH₂
· rfl
· simp only [powersetCardAux_cons]
exact IH.append ((IHn p).map _)
· simp only [powersetCardAux_cons, append_assoc]
apply Perm.append_left
cases n
· simp [Perm.swap]
simp only [powersetCardAux_cons, map_append, List.map_map]
rw [← append_assoc, ← append_assoc,
(by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)]
exact perm_append_comm.append_right _
· exact IH₁.trans IH₂
/-- `powersetCard n s` is the multiset of all submultisets of `s` of length `n`. -/
def powersetCard (n : ℕ) (s : Multiset α) : Multiset (Multiset α) :=
Quot.liftOn s (fun l => (powersetCardAux n l : Multiset (Multiset α))) fun _ _ h =>
Quot.sound (powersetCardAux_perm h)
theorem powersetCard_coe' (n) (l : List α) : @powersetCard α n l = powersetCardAux n l :=
rfl
theorem powersetCard_coe (n) (l : List α) :
@powersetCard α n l = ((sublistsLen n l).map (↑) : List (Multiset α)) :=
congr_arg ((↑) : List (Multiset α) → Multiset (Multiset α)) powersetCardAux_eq_map_coe
@[simp]
theorem powersetCard_zero_left (s : Multiset α) : powersetCard 0 s = {0} :=
Quotient.inductionOn s fun l => by simp [powersetCard_coe']
theorem powersetCard_zero_right (n : ℕ) : @powersetCard α (n + 1) 0 = 0 :=
rfl
@[simp]
theorem powersetCard_cons (n : ℕ) (a : α) (s) :
powersetCard (n + 1) (a ::ₘ s) = powersetCard (n + 1) s + map (cons a) (powersetCard n s) :=
Quotient.inductionOn s fun l => by simp [powersetCard_coe']
theorem powersetCard_one (s : Multiset α) : powersetCard 1 s = s.map singleton :=
Quotient.inductionOn s fun l ↦ by
simp [powersetCard_coe, sublistsLen_one, map_reverse, Function.comp]
@[simp]
theorem mem_powersetCard {n : ℕ} {s t : Multiset α} : s ∈ powersetCard n t ↔ s ≤ t ∧ card s = n :=
Quotient.inductionOn t fun l => by simp [powersetCard_coe']
@[simp]
theorem card_powersetCard (n : ℕ) (s : Multiset α) :
card (powersetCard n s) = Nat.choose (card s) n :=
Quotient.inductionOn s <| by simp [powersetCard_coe]
theorem powersetCard_le_powerset (n : ℕ) (s : Multiset α) : powersetCard n s ≤ powerset s :=
Quotient.inductionOn s fun l => by
simp only [quot_mk_to_coe, powersetCard_coe, powerset_coe', coe_le]
exact ((sublistsLen_sublist_sublists' _ _).map _).subperm
theorem powersetCard_mono (n : ℕ) {s t : Multiset α} (h : s ≤ t) :
powersetCard n s ≤ powersetCard n t :=
leInductionOn h fun {l₁ l₂} h => by
simp only [powersetCard_coe, coe_le]
exact ((sublistsLen_sublist_of_sublist _ h).map _).subperm
@[simp]
theorem powersetCard_eq_empty {α : Type*} (n : ℕ) {s : Multiset α} (h : card s < n) :
powersetCard n s = 0 :=
card_eq_zero.mp (Nat.choose_eq_zero_of_lt h ▸ card_powersetCard _ _)
@[simp]
theorem powersetCard_card_add (s : Multiset α) {i : ℕ} (hi : 0 < i) :
s.powersetCard (card s + i) = 0 :=
powersetCard_eq_empty _ (Nat.lt_add_of_pos_right hi)
theorem powersetCard_map {β : Type*} (f : α → β) (n : ℕ) (s : Multiset α) :
powersetCard n (s.map f) = (powersetCard n s).map (map f) := by
induction' s using Multiset.induction with t s ih generalizing n
· cases n <;> simp [powersetCard_zero_left, powersetCard_zero_right]
· cases n <;> simp [ih, map_comp_cons]
theorem pairwise_disjoint_powersetCard (s : Multiset α) :
_root_.Pairwise fun i j => Multiset.Disjoint (s.powersetCard i) (s.powersetCard j) :=
fun _ _ h _ hi hj =>
h (Eq.trans (Multiset.mem_powersetCard.mp hi).right.symm (Multiset.mem_powersetCard.mp hj).right)
theorem bind_powerset_len {α : Type*} (S : Multiset α) :
(bind (Multiset.range (card S + 1)) fun k => S.powersetCard k) = S.powerset := by
induction S using Quotient.inductionOn
simp_rw [quot_mk_to_coe, powerset_coe', powersetCard_coe, ← coe_range, coe_bind, ← List.map_bind,
coe_card]
exact coe_eq_coe.mpr ((List.range_bind_sublistsLen_perm _).map _)
@[simp]
theorem nodup_powerset {s : Multiset α} : Nodup (powerset s) ↔ Nodup s :=
⟨fun h => (nodup_of_le (map_single_le_powerset _) h).of_map _,
Quotient.inductionOn s fun l h => by
simp only [quot_mk_to_coe, powerset_coe', coe_nodup]
refine (nodup_sublists'.2 h).map_on ?_
exact fun x sx y sy e =>
(h.perm_iff_eq_of_sublist (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (Quotient.exact e)⟩
alias ⟨Nodup.ofPowerset, Nodup.powerset⟩ := nodup_powerset
protected theorem Nodup.powersetCard {n : ℕ} {s : Multiset α} (h : Nodup s) :
Nodup (powersetCard n s) :=
nodup_of_le (powersetCard_le_powerset _ _) (nodup_powerset.2 h)
end Multiset
|
Data\Multiset\Range.lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Data.Multiset.Basic
/-! # `Multiset.range n` gives `{0, 1, ..., n-1}` as a multiset. -/
open List Nat
namespace Multiset
-- range
/-- `range n` is the multiset lifted from the list `range n`,
that is, the set `{0, 1, ..., n-1}`. -/
def range (n : ℕ) : Multiset ℕ :=
List.range n
theorem coe_range (n : ℕ) : ↑(List.range n) = range n :=
rfl
@[simp]
theorem range_zero : range 0 = 0 :=
rfl
@[simp]
theorem range_succ (n : ℕ) : range (succ n) = n ::ₘ range n := by
rw [range, List.range_succ, ← coe_add, add_comm]; rfl
@[simp]
theorem card_range (n : ℕ) : card (range n) = n :=
length_range _
theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n :=
List.range_subset
@[simp]
theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n :=
List.mem_range
-- Porting note (#10618): removing @[simp], `simp` can prove it
theorem not_mem_range_self {n : ℕ} : n ∉ range n :=
List.not_mem_range_self
theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) :=
List.self_mem_range_succ n
theorem range_add (a b : ℕ) : range (a + b) = range a + (range b).map (a + ·) :=
congr_arg ((↑) : List ℕ → Multiset ℕ) (List.range_add _ _)
theorem range_disjoint_map_add (a : ℕ) (m : Multiset ℕ) :
(range a).Disjoint (m.map (a + ·)) := by
intro x hxa hxb
rw [range, mem_coe, List.mem_range] at hxa
obtain ⟨c, _, rfl⟩ := mem_map.1 hxb
exact (Nat.le_add_right _ _).not_lt hxa
theorem range_add_eq_union (a b : ℕ) : range (a + b) = range a ∪ (range b).map (a + ·) := by
rw [range_add, add_eq_union_iff_disjoint]
apply range_disjoint_map_add
end Multiset
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.