# Theory Set_Interval

theory Set_Interval
imports Lattices_Big Divides
(*  Title:      HOL/Set_Interval.thy
Author:     Tobias Nipkow
Author:     Clemens Ballarin

lessThan, greaterThan, atLeast, atMost and two-sided intervals

Modern convention: Ixy stands for an interval where x and y
describe the lower and upper bound and x,y : {c,o,i}
where c = closed, o = open, i = infinite.
Examples: Ico = {_ ..< _} and Ici = {_ ..}
*)

section ‹Set intervals›

theory Set_Interval
imports Lattices_Big Divides Nat_Transfer
begin

context ord
begin

definition
lessThan    :: "'a => 'a set" ("(1{..<_})") where
"{..<u} == {x. x < u}"

definition
atMost      :: "'a => 'a set" ("(1{.._})") where
"{..u} == {x. x ≤ u}"

definition
greaterThan :: "'a => 'a set" ("(1{_<..})") where
"{l<..} == {x. l<x}"

definition
atLeast     :: "'a => 'a set" ("(1{_..})") where
"{l..} == {x. l≤x}"

definition
greaterThanLessThan :: "'a => 'a => 'a set"  ("(1{_<..<_})") where
"{l<..<u} == {l<..} Int {..<u}"

definition
atLeastLessThan :: "'a => 'a => 'a set"      ("(1{_..<_})") where
"{l..<u} == {l..} Int {..<u}"

definition
greaterThanAtMost :: "'a => 'a => 'a set"    ("(1{_<.._})") where
"{l<..u} == {l<..} Int {..u}"

definition
atLeastAtMost :: "'a => 'a => 'a set"        ("(1{_.._})") where
"{l..u} == {l..} Int {..u}"

end

text‹A note of warning when using @{term"{..<n}"} on type @{typ
nat}: it is equivalent to @{term"{0::nat..<n}"} but some lemmas involving
@{term"{m..<n}"} may not exist in @{term"{..<n}"}-form as well.›

syntax (ASCII)
"_UNION_le"   :: "'a => 'a => 'b set => 'b set"       ("(3UN _<=_./ _)" [0, 0, 10] 10)
"_UNION_less" :: "'a => 'a => 'b set => 'b set"       ("(3UN _<_./ _)" [0, 0, 10] 10)
"_INTER_le"   :: "'a => 'a => 'b set => 'b set"       ("(3INT _<=_./ _)" [0, 0, 10] 10)
"_INTER_less" :: "'a => 'a => 'b set => 'b set"       ("(3INT _<_./ _)" [0, 0, 10] 10)

syntax (latex output)
"_UNION_le"   :: "'a ⇒ 'a => 'b set => 'b set"       ("(3⋃(‹unbreakable›_ ≤ _)/ _)" [0, 0, 10] 10)
"_UNION_less" :: "'a ⇒ 'a => 'b set => 'b set"       ("(3⋃(‹unbreakable›_ < _)/ _)" [0, 0, 10] 10)
"_INTER_le"   :: "'a ⇒ 'a => 'b set => 'b set"       ("(3⋂(‹unbreakable›_ ≤ _)/ _)" [0, 0, 10] 10)
"_INTER_less" :: "'a ⇒ 'a => 'b set => 'b set"       ("(3⋂(‹unbreakable›_ < _)/ _)" [0, 0, 10] 10)

syntax
"_UNION_le"   :: "'a => 'a => 'b set => 'b set"       ("(3⋃_≤_./ _)" [0, 0, 10] 10)
"_UNION_less" :: "'a => 'a => 'b set => 'b set"       ("(3⋃_<_./ _)" [0, 0, 10] 10)
"_INTER_le"   :: "'a => 'a => 'b set => 'b set"       ("(3⋂_≤_./ _)" [0, 0, 10] 10)
"_INTER_less" :: "'a => 'a => 'b set => 'b set"       ("(3⋂_<_./ _)" [0, 0, 10] 10)

translations
"⋃i≤n. A"  "⋃i∈{..n}. A"
"⋃i<n. A"  "⋃i∈{..<n}. A"
"⋂i≤n. A"  "⋂i∈{..n}. A"
"⋂i<n. A"  "⋂i∈{..<n}. A"

subsection ‹Various equivalences›

lemma (in ord) lessThan_iff [iff]: "(i: lessThan k) = (i<k)"

lemma Compl_lessThan [simp]:
"!!k:: 'a::linorder. -lessThan k = atLeast k"
apply (auto simp add: lessThan_def atLeast_def)
done

lemma single_Diff_lessThan [simp]: "!!k:: 'a::order. {k} - lessThan k = {k}"
by auto

lemma (in ord) greaterThan_iff [iff]: "(i: greaterThan k) = (k<i)"

lemma Compl_greaterThan [simp]:
"!!k:: 'a::linorder. -greaterThan k = atMost k"
by (auto simp add: greaterThan_def atMost_def)

lemma Compl_atMost [simp]: "!!k:: 'a::linorder. -atMost k = greaterThan k"
apply (subst Compl_greaterThan [symmetric])
apply (rule double_complement)
done

lemma (in ord) atLeast_iff [iff]: "(i: atLeast k) = (k<=i)"

lemma Compl_atLeast [simp]:
"!!k:: 'a::linorder. -atLeast k = lessThan k"
by (auto simp add: lessThan_def atLeast_def)

lemma (in ord) atMost_iff [iff]: "(i: atMost k) = (i<=k)"

lemma atMost_Int_atLeast: "!!n:: 'a::order. atMost n Int atLeast n = {n}"
by (blast intro: order_antisym)

lemma (in linorder) lessThan_Int_lessThan: "{ a <..} ∩ { b <..} = { max a b <..}"
by auto

lemma (in linorder) greaterThan_Int_greaterThan: "{..< a} ∩ {..< b} = {..< min a b}"
by auto

subsection ‹Logical Equivalences for Set Inclusion and Equality›

lemma atLeast_empty_triv [simp]: "{{}..} = UNIV"
by auto

lemma atMost_UNIV_triv [simp]: "{..UNIV} = UNIV"
by auto

lemma atLeast_subset_iff [iff]:
"(atLeast x ⊆ atLeast y) = (y ≤ (x::'a::order))"
by (blast intro: order_trans)

lemma atLeast_eq_iff [iff]:
"(atLeast x = atLeast y) = (x = (y::'a::linorder))"
by (blast intro: order_antisym order_trans)

lemma greaterThan_subset_iff [iff]:
"(greaterThan x ⊆ greaterThan y) = (y ≤ (x::'a::linorder))"
apply (subst linorder_not_less [symmetric], blast)
done

lemma greaterThan_eq_iff [iff]:
"(greaterThan x = greaterThan y) = (x = (y::'a::linorder))"
apply (rule iffI)
apply (erule equalityE)
apply simp_all
done

lemma atMost_subset_iff [iff]: "(atMost x ⊆ atMost y) = (x ≤ (y::'a::order))"
by (blast intro: order_trans)

lemma atMost_eq_iff [iff]: "(atMost x = atMost y) = (x = (y::'a::linorder))"
by (blast intro: order_antisym order_trans)

lemma lessThan_subset_iff [iff]:
"(lessThan x ⊆ lessThan y) = (x ≤ (y::'a::linorder))"
apply (subst linorder_not_less [symmetric], blast)
done

lemma lessThan_eq_iff [iff]:
"(lessThan x = lessThan y) = (x = (y::'a::linorder))"
apply (rule iffI)
apply (erule equalityE)
apply simp_all
done

lemma lessThan_strict_subset_iff:
fixes m n :: "'a::linorder"
shows "{..<m} < {..<n} ⟷ m < n"
by (metis leD lessThan_subset_iff linorder_linear not_less_iff_gr_or_eq psubset_eq)

lemma (in linorder) Ici_subset_Ioi_iff: "{a ..} ⊆ {b <..} ⟷ b < a"
by auto

lemma (in linorder) Iic_subset_Iio_iff: "{.. a} ⊆ {..< b} ⟷ a < b"
by auto

lemma (in preorder) Ioi_le_Ico: "{a <..} ⊆ {a ..}"
by (auto intro: less_imp_le)

subsection ‹Two-sided intervals›

context ord
begin

lemma greaterThanLessThan_iff [simp]:
"(i : {l<..<u}) = (l < i & i < u)"

lemma atLeastLessThan_iff [simp]:
"(i : {l..<u}) = (l <= i & i < u)"

lemma greaterThanAtMost_iff [simp]:
"(i : {l<..u}) = (l < i & i <= u)"

lemma atLeastAtMost_iff [simp]:
"(i : {l..u}) = (l <= i & i <= u)"

text ‹The above four lemmas could be declared as iffs. Unfortunately this
breaks many proofs. Since it only helps blast, it is better to leave them
alone.›

lemma greaterThanLessThan_eq: "{ a <..< b} = { a <..} ∩ {..< b }"
by auto

end

subsubsection‹Emptyness, singletons, subset›

context order
begin

lemma atLeastatMost_empty[simp]:
"b < a ⟹ {a..b} = {}"
by(auto simp: atLeastAtMost_def atLeast_def atMost_def)

lemma atLeastatMost_empty_iff[simp]:
"{a..b} = {} ⟷ (~ a <= b)"
by auto (blast intro: order_trans)

lemma atLeastatMost_empty_iff2[simp]:
"{} = {a..b} ⟷ (~ a <= b)"
by auto (blast intro: order_trans)

lemma atLeastLessThan_empty[simp]:
"b <= a ⟹ {a..<b} = {}"
by(auto simp: atLeastLessThan_def)

lemma atLeastLessThan_empty_iff[simp]:
"{a..<b} = {} ⟷ (~ a < b)"
by auto (blast intro: le_less_trans)

lemma atLeastLessThan_empty_iff2[simp]:
"{} = {a..<b} ⟷ (~ a < b)"
by auto (blast intro: le_less_trans)

lemma greaterThanAtMost_empty[simp]: "l ≤ k ==> {k<..l} = {}"
by(auto simp:greaterThanAtMost_def greaterThan_def atMost_def)

lemma greaterThanAtMost_empty_iff[simp]: "{k<..l} = {} ⟷ ~ k < l"
by auto (blast intro: less_le_trans)

lemma greaterThanAtMost_empty_iff2[simp]: "{} = {k<..l} ⟷ ~ k < l"
by auto (blast intro: less_le_trans)

lemma greaterThanLessThan_empty[simp]:"l ≤ k ==> {k<..<l} = {}"
by(auto simp:greaterThanLessThan_def greaterThan_def lessThan_def)

lemma atLeastAtMost_singleton [simp]: "{a..a} = {a}"
by (auto simp add: atLeastAtMost_def atMost_def atLeast_def)

lemma atLeastAtMost_singleton': "a = b ⟹ {a .. b} = {a}" by simp

lemma atLeastatMost_subset_iff[simp]:
"{a..b} <= {c..d} ⟷ (~ a <= b) | c <= a & b <= d"
unfolding atLeastAtMost_def atLeast_def atMost_def
by (blast intro: order_trans)

lemma atLeastatMost_psubset_iff:
"{a..b} < {c..d} ⟷
((~ a <= b) | c <= a & b <= d & (c < a | b < d))  &  c <= d"
by(simp add: psubset_eq set_eq_iff less_le_not_le)(blast intro: order_trans)

lemma Icc_eq_Icc[simp]:
"{l..h} = {l'..h'} = (l=l' ∧ h=h' ∨ ¬ l≤h ∧ ¬ l'≤h')"

lemma atLeastAtMost_singleton_iff[simp]:
"{a .. b} = {c} ⟷ a = b ∧ b = c"
proof
assume "{a..b} = {c}"
hence *: "¬ (¬ a ≤ b)" unfolding atLeastatMost_empty_iff[symmetric] by simp
with ‹{a..b} = {c}› have "c ≤ a ∧ b ≤ c" by auto
with * show "a = b ∧ b = c" by auto
qed simp

lemma Icc_subset_Ici_iff[simp]:
"{l..h} ⊆ {l'..} = (~ l≤h ∨ l≥l')"
by(auto simp: subset_eq intro: order_trans)

lemma Icc_subset_Iic_iff[simp]:
"{l..h} ⊆ {..h'} = (~ l≤h ∨ h≤h')"
by(auto simp: subset_eq intro: order_trans)

lemma not_Ici_eq_empty[simp]: "{l..} ≠ {}"
by(auto simp: set_eq_iff)

lemma not_Iic_eq_empty[simp]: "{..h} ≠ {}"
by(auto simp: set_eq_iff)

lemmas not_empty_eq_Ici_eq_empty[simp] = not_Ici_eq_empty[symmetric]
lemmas not_empty_eq_Iic_eq_empty[simp] = not_Iic_eq_empty[symmetric]

end

context no_top
begin

(* also holds for no_bot but no_top should suffice *)
lemma not_UNIV_le_Icc[simp]: "¬ UNIV ⊆ {l..h}"
using gt_ex[of h] by(auto simp: subset_eq less_le_not_le)

lemma not_UNIV_le_Iic[simp]: "¬ UNIV ⊆ {..h}"
using gt_ex[of h] by(auto simp: subset_eq less_le_not_le)

lemma not_Ici_le_Icc[simp]: "¬ {l..} ⊆ {l'..h'}"
using gt_ex[of h']
by(auto simp: subset_eq less_le)(blast dest:antisym_conv intro: order_trans)

lemma not_Ici_le_Iic[simp]: "¬ {l..} ⊆ {..h'}"
using gt_ex[of h']
by(auto simp: subset_eq less_le)(blast dest:antisym_conv intro: order_trans)

end

context no_bot
begin

lemma not_UNIV_le_Ici[simp]: "¬ UNIV ⊆ {l..}"
using lt_ex[of l] by(auto simp: subset_eq less_le_not_le)

lemma not_Iic_le_Icc[simp]: "¬ {..h} ⊆ {l'..h'}"
using lt_ex[of l']
by(auto simp: subset_eq less_le)(blast dest:antisym_conv intro: order_trans)

lemma not_Iic_le_Ici[simp]: "¬ {..h} ⊆ {l'..}"
using lt_ex[of l']
by(auto simp: subset_eq less_le)(blast dest:antisym_conv intro: order_trans)

end

context no_top
begin

(* also holds for no_bot but no_top should suffice *)
lemma not_UNIV_eq_Icc[simp]: "¬ UNIV = {l'..h'}"
using gt_ex[of h'] by(auto simp: set_eq_iff  less_le_not_le)

lemmas not_Icc_eq_UNIV[simp] = not_UNIV_eq_Icc[symmetric]

lemma not_UNIV_eq_Iic[simp]: "¬ UNIV = {..h'}"
using gt_ex[of h'] by(auto simp: set_eq_iff  less_le_not_le)

lemmas not_Iic_eq_UNIV[simp] = not_UNIV_eq_Iic[symmetric]

lemma not_Icc_eq_Ici[simp]: "¬ {l..h} = {l'..}"
unfolding atLeastAtMost_def using not_Ici_le_Iic[of l'] by blast

lemmas not_Ici_eq_Icc[simp] = not_Icc_eq_Ici[symmetric]

(* also holds for no_bot but no_top should suffice *)
lemma not_Iic_eq_Ici[simp]: "¬ {..h} = {l'..}"
using not_Ici_le_Iic[of l' h] by blast

lemmas not_Ici_eq_Iic[simp] = not_Iic_eq_Ici[symmetric]

end

context no_bot
begin

lemma not_UNIV_eq_Ici[simp]: "¬ UNIV = {l'..}"
using lt_ex[of l'] by(auto simp: set_eq_iff  less_le_not_le)

lemmas not_Ici_eq_UNIV[simp] = not_UNIV_eq_Ici[symmetric]

lemma not_Icc_eq_Iic[simp]: "¬ {l..h} = {..h'}"
unfolding atLeastAtMost_def using not_Iic_le_Ici[of h'] by blast

lemmas not_Iic_eq_Icc[simp] = not_Icc_eq_Iic[symmetric]

end

context dense_linorder
begin

lemma greaterThanLessThan_empty_iff[simp]:
"{ a <..< b } = {} ⟷ b ≤ a"
using dense[of a b] by (cases "a < b") auto

lemma greaterThanLessThan_empty_iff2[simp]:
"{} = { a <..< b } ⟷ b ≤ a"
using dense[of a b] by (cases "a < b") auto

lemma atLeastLessThan_subseteq_atLeastAtMost_iff:
"{a ..< b} ⊆ { c .. d } ⟷ (a < b ⟶ c ≤ a ∧ b ≤ d)"
using dense[of "max a d" "b"]
by (force simp: subset_eq Ball_def not_less[symmetric])

lemma greaterThanAtMost_subseteq_atLeastAtMost_iff:
"{a <.. b} ⊆ { c .. d } ⟷ (a < b ⟶ c ≤ a ∧ b ≤ d)"
using dense[of "a" "min c b"]
by (force simp: subset_eq Ball_def not_less[symmetric])

lemma greaterThanLessThan_subseteq_atLeastAtMost_iff:
"{a <..< b} ⊆ { c .. d } ⟷ (a < b ⟶ c ≤ a ∧ b ≤ d)"
using dense[of "a" "min c b"] dense[of "max a d" "b"]
by (force simp: subset_eq Ball_def not_less[symmetric])

lemma atLeastAtMost_subseteq_atLeastLessThan_iff:
"{a .. b} ⊆ { c ..< d } ⟷ (a ≤ b ⟶ c ≤ a ∧ b < d)"
using dense[of "max a d" "b"]
by (force simp: subset_eq Ball_def not_less[symmetric])

lemma greaterThanLessThan_subseteq_greaterThanLessThan:
"{a <..< b} ⊆ {c <..< d} ⟷ (a < b ⟶ a ≥ c ∧ b ≤ d)"
using dense[of "a" "min c b"] dense[of "max a d" "b"]
by (force simp: subset_eq Ball_def not_less[symmetric])

lemma greaterThanAtMost_subseteq_atLeastLessThan_iff:
"{a <.. b} ⊆ { c ..< d } ⟷ (a < b ⟶ c ≤ a ∧ b < d)"
using dense[of "a" "min c b"]
by (force simp: subset_eq Ball_def not_less[symmetric])

lemma greaterThanLessThan_subseteq_atLeastLessThan_iff:
"{a <..< b} ⊆ { c ..< d } ⟷ (a < b ⟶ c ≤ a ∧ b ≤ d)"
using dense[of "a" "min c b"] dense[of "max a d" "b"]
by (force simp: subset_eq Ball_def not_less[symmetric])

lemma greaterThanLessThan_subseteq_greaterThanAtMost_iff:
"{a <..< b} ⊆ { c <.. d } ⟷ (a < b ⟶ c ≤ a ∧ b ≤ d)"
using dense[of "a" "min c b"] dense[of "max a d" "b"]
by (force simp: subset_eq Ball_def not_less[symmetric])

end

context no_top
begin

lemma greaterThan_non_empty[simp]: "{x <..} ≠ {}"
using gt_ex[of x] by auto

end

context no_bot
begin

lemma lessThan_non_empty[simp]: "{..< x} ≠ {}"
using lt_ex[of x] by auto

end

lemma (in linorder) atLeastLessThan_subset_iff:
"{a..<b} <= {c..<d} ⟹ b <= a | c<=a & b<=d"
apply (auto simp:subset_eq Ball_def)
apply(frule_tac x=a in spec)
apply(erule_tac x=d in allE)
done

lemma atLeastLessThan_inj:
fixes a b c d :: "'a::linorder"
assumes eq: "{a ..< b} = {c ..< d}" and "a < b" "c < d"
shows "a = c" "b = d"
using assms by (metis atLeastLessThan_subset_iff eq less_le_not_le linorder_antisym_conv2 subset_refl)+

lemma atLeastLessThan_eq_iff:
fixes a b c d :: "'a::linorder"
assumes "a < b" "c < d"
shows "{a ..< b} = {c ..< d} ⟷ a = c ∧ b = d"
using atLeastLessThan_inj assms by auto

lemma (in linorder) Ioc_inj: "{a <.. b} = {c <.. d} ⟷ (b ≤ a ∧ d ≤ c) ∨ a = c ∧ b = d"
by (metis eq_iff greaterThanAtMost_empty_iff2 greaterThanAtMost_iff le_cases not_le)

lemma (in order) Iio_Int_singleton: "{..<k} ∩ {x} = (if x < k then {x} else {})"
by auto

lemma (in linorder) Ioc_subset_iff: "{a<..b} ⊆ {c<..d} ⟷ (b ≤ a ∨ c ≤ a ∧ b ≤ d)"
by (auto simp: subset_eq Ball_def) (metis less_le not_less)

lemma (in order_bot) atLeast_eq_UNIV_iff: "{x..} = UNIV ⟷ x = bot"
by (auto simp: set_eq_iff intro: le_bot)

lemma (in order_top) atMost_eq_UNIV_iff: "{..x} = UNIV ⟷ x = top"
by (auto simp: set_eq_iff intro: top_le)

lemma (in bounded_lattice) atLeastAtMost_eq_UNIV_iff:
"{x..y} = UNIV ⟷ (x = bot ∧ y = top)"
by (auto simp: set_eq_iff intro: top_le le_bot)

lemma Iio_eq_empty_iff: "{..< n::'a::{linorder, order_bot}} = {} ⟷ n = bot"
by (auto simp: set_eq_iff not_less le_bot)

lemma Iio_eq_empty_iff_nat: "{..< n::nat} = {} ⟷ n = 0"

lemma mono_image_least:
assumes f_mono: "mono f" and f_img: "f  {m ..< n} = {m' ..< n'}" "m < n"
shows "f m = m'"
proof -
from f_img have "{m' ..< n'} ≠ {}"
by (metis atLeastLessThan_empty_iff image_is_empty)
with f_img have "m' ∈ f  {m ..< n}" by auto
then obtain k where "f k = m'" "m ≤ k" by auto
moreover have "m' ≤ f m" using f_img by auto
ultimately show "f m = m'"
using f_mono by (auto elim: monoE[where x=m and y=k])
qed

subsection ‹Infinite intervals›

context dense_linorder
begin

lemma infinite_Ioo:
assumes "a < b"
shows "¬ finite {a<..<b}"
proof
assume fin: "finite {a<..<b}"
moreover have ne: "{a<..<b} ≠ {}"
using ‹a < b› by auto
ultimately have "a < Max {a <..< b}" "Max {a <..< b} < b"
using Max_in[of "{a <..< b}"] by auto
then obtain x where "Max {a <..< b} < x" "x < b"
using dense[of "Max {a<..<b}" b] by auto
then have "x ∈ {a <..< b}"
using ‹a < Max {a <..< b}› by auto
then have "x ≤ Max {a <..< b}"
using fin by auto
with ‹Max {a <..< b} < x› show False by auto
qed

lemma infinite_Icc: "a < b ⟹ ¬ finite {a .. b}"
using greaterThanLessThan_subseteq_atLeastAtMost_iff[of a b a b] infinite_Ioo[of a b]
by (auto dest: finite_subset)

lemma infinite_Ico: "a < b ⟹ ¬ finite {a ..< b}"
using greaterThanLessThan_subseteq_atLeastLessThan_iff[of a b a b] infinite_Ioo[of a b]
by (auto dest: finite_subset)

lemma infinite_Ioc: "a < b ⟹ ¬ finite {a <.. b}"
using greaterThanLessThan_subseteq_greaterThanAtMost_iff[of a b a b] infinite_Ioo[of a b]
by (auto dest: finite_subset)

lemma infinite_Ioo_iff [simp]: "infinite {a<..<b} ⟷ a < b"
using not_less_iff_gr_or_eq by (fastforce simp: infinite_Ioo)

lemma infinite_Icc_iff [simp]: "infinite {a .. b} ⟷ a < b"
using not_less_iff_gr_or_eq by (fastforce simp: infinite_Icc)

lemma infinite_Ico_iff [simp]: "infinite {a..<b} ⟷ a < b"
using not_less_iff_gr_or_eq by (fastforce simp: infinite_Ico)

lemma infinite_Ioc_iff [simp]: "infinite {a<..b} ⟷ a < b"
using not_less_iff_gr_or_eq by (fastforce simp: infinite_Ioc)

end

lemma infinite_Iio: "¬ finite {..< a :: 'a :: {no_bot, linorder}}"
proof
assume "finite {..< a}"
then have *: "⋀x. x < a ⟹ Min {..< a} ≤ x"
by auto
obtain x where "x < a"
using lt_ex by auto

obtain y where "y < Min {..< a}"
using lt_ex by auto
also have "Min {..< a} ≤ x"
using ‹x < a› by fact
also note ‹x < a›
finally have "Min {..< a} ≤ y"
by fact
with ‹y < Min {..< a}› show False by auto
qed

lemma infinite_Iic: "¬ finite {.. a :: 'a :: {no_bot, linorder}}"
using infinite_Iio[of a] finite_subset[of "{..< a}" "{.. a}"]
by (auto simp: subset_eq less_imp_le)

lemma infinite_Ioi: "¬ finite {a :: 'a :: {no_top, linorder} <..}"
proof
assume "finite {a <..}"
then have *: "⋀x. a < x ⟹ x ≤ Max {a <..}"
by auto

obtain y where "Max {a <..} < y"
using gt_ex by auto

obtain x where x: "a < x"
using gt_ex by auto
also from x have "x ≤ Max {a <..}"
by fact
also note ‹Max {a <..} < y›
finally have "y ≤ Max { a <..}"
by fact
with ‹Max {a <..} < y› show False by auto
qed

lemma infinite_Ici: "¬ finite {a :: 'a :: {no_top, linorder} ..}"
using infinite_Ioi[of a] finite_subset[of "{a <..}" "{a ..}"]
by (auto simp: subset_eq less_imp_le)

subsubsection ‹Intersection›

context linorder
begin

lemma Int_atLeastAtMost[simp]: "{a..b} Int {c..d} = {max a c .. min b d}"
by auto

lemma Int_atLeastAtMostR1[simp]: "{..b} Int {c..d} = {c .. min b d}"
by auto

lemma Int_atLeastAtMostR2[simp]: "{a..} Int {c..d} = {max a c .. d}"
by auto

lemma Int_atLeastAtMostL1[simp]: "{a..b} Int {..d} = {a .. min b d}"
by auto

lemma Int_atLeastAtMostL2[simp]: "{a..b} Int {c..} = {max a c .. b}"
by auto

lemma Int_atLeastLessThan[simp]: "{a..<b} Int {c..<d} = {max a c ..< min b d}"
by auto

lemma Int_greaterThanAtMost[simp]: "{a<..b} Int {c<..d} = {max a c <.. min b d}"
by auto

lemma Int_greaterThanLessThan[simp]: "{a<..<b} Int {c<..<d} = {max a c <..< min b d}"
by auto

lemma Int_atMost[simp]: "{..a} ∩ {..b} = {.. min a b}"
by (auto simp: min_def)

lemma Ioc_disjoint: "{a<..b} ∩ {c<..d} = {} ⟷ b ≤ a ∨ d ≤ c ∨ b ≤ c ∨ d ≤ a"
by auto

end

context complete_lattice
begin

lemma
shows Sup_atLeast[simp]: "Sup {x ..} = top"
and Sup_greaterThanAtLeast[simp]: "x < top ⟹ Sup {x <..} = top"
and Sup_atMost[simp]: "Sup {.. y} = y"
and Sup_atLeastAtMost[simp]: "x ≤ y ⟹ Sup { x .. y} = y"
and Sup_greaterThanAtMost[simp]: "x < y ⟹ Sup { x <.. y} = y"
by (auto intro!: Sup_eqI)

lemma
shows Inf_atMost[simp]: "Inf {.. x} = bot"
and Inf_atMostLessThan[simp]: "top < x ⟹ Inf {..< x} = bot"
and Inf_atLeast[simp]: "Inf {x ..} = x"
and Inf_atLeastAtMost[simp]: "x ≤ y ⟹ Inf { x .. y} = x"
and Inf_atLeastLessThan[simp]: "x < y ⟹ Inf { x ..< y} = x"
by (auto intro!: Inf_eqI)

end

lemma
fixes x y :: "'a :: {complete_lattice, dense_linorder}"
shows Sup_lessThan[simp]: "Sup {..< y} = y"
and Sup_atLeastLessThan[simp]: "x < y ⟹ Sup { x ..< y} = y"
and Sup_greaterThanLessThan[simp]: "x < y ⟹ Sup { x <..< y} = y"
and Inf_greaterThan[simp]: "Inf {x <..} = x"
and Inf_greaterThanAtMost[simp]: "x < y ⟹ Inf { x <.. y} = x"
and Inf_greaterThanLessThan[simp]: "x < y ⟹ Inf { x <..< y} = x"
by (auto intro!: Inf_eqI Sup_eqI intro: dense_le dense_le_bounded dense_ge dense_ge_bounded)

subsection ‹Intervals of natural numbers›

subsubsection ‹The Constant @{term lessThan}›

lemma lessThan_0 [simp]: "lessThan (0::nat) = {}"

lemma lessThan_Suc: "lessThan (Suc k) = insert k (lessThan k)"
by (simp add: lessThan_def less_Suc_eq, blast)

text ‹The following proof is convenient in induction proofs where
new elements get indices at the beginning. So it is used to transform
@{term "{..<Suc n}"} to @{term "0::nat"} and @{term "{..< n}"}.›

lemma zero_notin_Suc_image: "0 ∉ Suc  A"
by auto

lemma lessThan_Suc_eq_insert_0: "{..<Suc n} = insert 0 (Suc  {..<n})"
by (auto simp: image_iff less_Suc_eq_0_disj)

lemma lessThan_Suc_atMost: "lessThan (Suc k) = atMost k"
by (simp add: lessThan_def atMost_def less_Suc_eq_le)

lemma Iic_Suc_eq_insert_0: "{.. Suc n} = insert 0 (Suc  {.. n})"
unfolding lessThan_Suc_atMost[symmetric] lessThan_Suc_eq_insert_0[of "Suc n"] ..

lemma UN_lessThan_UNIV: "(UN m::nat. lessThan m) = UNIV"
by blast

subsubsection ‹The Constant @{term greaterThan}›

lemma greaterThan_0: "greaterThan 0 = range Suc"
apply (blast dest: gr0_conv_Suc [THEN iffD1])
done

lemma greaterThan_Suc: "greaterThan (Suc k) = greaterThan k - {Suc k}"
apply (auto elim: linorder_neqE)
done

lemma INT_greaterThan_UNIV: "(INT m::nat. greaterThan m) = {}"
by blast

subsubsection ‹The Constant @{term atLeast}›

lemma atLeast_0 [simp]: "atLeast (0::nat) = UNIV"
by (unfold atLeast_def UNIV_def, simp)

lemma atLeast_Suc: "atLeast (Suc k) = atLeast k - {k}"
done

lemma atLeast_Suc_greaterThan: "atLeast (Suc k) = greaterThan k"
by (auto simp add: greaterThan_def atLeast_def less_Suc_eq_le)

lemma UN_atLeast_UNIV: "(UN m::nat. atLeast m) = UNIV"
by blast

subsubsection ‹The Constant @{term atMost}›

lemma atMost_0 [simp]: "atMost (0::nat) = {0}"

lemma atMost_Suc: "atMost (Suc k) = insert (Suc k) (atMost k)"
apply (simp add: less_Suc_eq order_le_less, blast)
done

lemma UN_atMost_UNIV: "(UN m::nat. atMost m) = UNIV"
by blast

subsubsection ‹The Constant @{term atLeastLessThan}›

text‹The orientation of the following 2 rules is tricky. The lhs is
defined in terms of the rhs.  Hence the chosen orientation makes sense
in this theory --- the reverse orientation complicates proofs (eg
nontermination). But outside, when the definition of the lhs is rarely
used, the opposite orientation seems preferable because it reduces a
specific concept to a more general one.›

lemma atLeast0LessThan [code_abbrev]: "{0::nat..<n} = {..<n}"

lemma atLeast0AtMost [code_abbrev]: "{0..n::nat} = {..n}"

lemma lessThan_atLeast0:
"{..<n} = {0::nat..<n}"

lemma atMost_atLeast0:
"{..n} = {0::nat..n}"

lemma atLeastLessThan0: "{m..<0::nat} = {}"

lemma atLeast0_lessThan_Suc:
"{0..<Suc n} = insert n {0..<n}"

lemma atLeast0_lessThan_Suc_eq_insert_0:
"{0..<Suc n} = insert 0 (Suc  {0..<n})"

subsubsection ‹The Constant @{term atLeastAtMost}›

lemma atLeast0_atMost_Suc:
"{0..Suc n} = insert (Suc n) {0..n}"

lemma atLeast0_atMost_Suc_eq_insert_0:
"{0..Suc n} = insert 0 (Suc  {0..n})"

subsubsection ‹Intervals of nats with @{term Suc}›

text‹Not a simprule because the RHS is too messy.›
lemma atLeastLessThanSuc:
"{m..<Suc n} = (if m ≤ n then insert n {m..<n} else {})"

lemma atLeastLessThan_singleton [simp]: "{m..<Suc m} = {m}"
(*
lemma atLeast_sum_LessThan [simp]: "{m + k..<k::nat} = {}"
by (induct k, simp_all add: atLeastLessThanSuc)

lemma atLeastSucLessThan [simp]: "{Suc n..<n} = {}"
*)
lemma atLeastLessThanSuc_atLeastAtMost: "{l..<Suc u} = {l..u}"
by (simp add: lessThan_Suc_atMost atLeastAtMost_def atLeastLessThan_def)

lemma atLeastSucAtMost_greaterThanAtMost: "{Suc l..u} = {l<..u}"
greaterThanAtMost_def)

lemma atLeastSucLessThan_greaterThanLessThan: "{Suc l..<u} = {l<..<u}"
greaterThanLessThan_def)

lemma atLeastAtMostSuc_conv: "m ≤ Suc n ⟹ {m..Suc n} = insert (Suc n) {m..n}"

lemma atLeastAtMost_insertL: "m ≤ n ⟹ insert m {Suc m..n} = {m ..n}"
by auto

text ‹The analogous result is useful on @{typ int}:›
(* here, because we don't have an own int section *)
lemma atLeastAtMostPlus1_int_conv:
"m <= 1+n ⟹ {m..1+n} = insert (1+n) {m..n::int}"
by (auto intro: set_eqI)

lemma atLeastLessThan_add_Un: "i ≤ j ⟹ {i..<j+k} = {i..<j} ∪ {j..<j+k::nat}"
apply (induct k)
done

subsubsection ‹Intervals and numerals›

lemma lessThan_nat_numeral:  ‹Evaluation for specific numerals›
"lessThan (numeral k :: nat) = insert (pred_numeral k) (lessThan (pred_numeral k))"

lemma atMost_nat_numeral:  ‹Evaluation for specific numerals›
"atMost (numeral k :: nat) = insert (numeral k) (atMost (pred_numeral k))"

lemma atLeastLessThan_nat_numeral:  ‹Evaluation for specific numerals›
"atLeastLessThan m (numeral k :: nat) =
(if m ≤ (pred_numeral k) then insert (pred_numeral k) (atLeastLessThan m (pred_numeral k))
else {})"

subsubsection ‹Image›

fixes k ::"'a::linordered_semidom"
shows "(λn. n+k)  {i..j} = {i+k..j+k}" (is "?A = ?B")
proof
show "?A ⊆ ?B" by auto
next
show "?B ⊆ ?A"
proof
fix n assume a: "n : ?B"
hence "n - k : {i..j}"
moreover have "n = (n - k) + k" using a
proof -
have "k + i ≤ n"
hence "k + (n - k) = n"
thus ?thesis
qed
ultimately show "n : ?A" by blast
qed
qed

lemma image_diff_atLeastAtMost [simp]:
fixes d::"'a::linordered_idom" shows "(op - d  {a..b}) = {d-b..d-a}"
apply auto
apply (rule_tac x="d-x" in rev_image_eqI, auto)
done

lemma image_mult_atLeastAtMost [simp]:
fixes d::"'a::linordered_field"
assumes "d>0" shows "(op * d  {a..b}) = {d*a..d*b}"
using assms
by (auto simp: field_simps mult_le_cancel_right intro: rev_image_eqI [where x="x/d" for x])

lemma image_affinity_atLeastAtMost:
fixes c :: "'a::linordered_field"
shows "((λx. m*x + c)  {a..b}) = (if {a..b}={} then {}
else if 0 ≤ m then {m*a + c .. m *b + c}
else {m*b + c .. m*a + c})"
apply (case_tac "m=0", auto simp: mult_le_cancel_left)
apply (rule_tac x="inverse m*(x-c)" in rev_image_eqI, auto simp: field_simps)
apply (rule_tac x="inverse m*(x-c)" in rev_image_eqI, auto simp: field_simps)
done

lemma image_affinity_atLeastAtMost_diff:
fixes c :: "'a::linordered_field"
shows "((λx. m*x - c)  {a..b}) = (if {a..b}={} then {}
else if 0 ≤ m then {m*a - c .. m*b - c}
else {m*b - c .. m*a - c})"
using image_affinity_atLeastAtMost [of m "-c" a b]
by simp

lemma image_affinity_atLeastAtMost_div:
fixes c :: "'a::linordered_field"
shows "((λx. x/m + c)  {a..b}) = (if {a..b}={} then {}
else if 0 ≤ m then {a/m + c .. b/m + c}
else {b/m + c .. a/m + c})"
using image_affinity_atLeastAtMost [of "inverse m" c a b]

lemma image_affinity_atLeastAtMost_div_diff:
fixes c :: "'a::linordered_field"
shows "((λx. x/m - c)  {a..b}) = (if {a..b}={} then {}
else if 0 ≤ m then {a/m - c .. b/m - c}
else {b/m - c .. a/m - c})"
using image_affinity_atLeastAtMost_diff [of "inverse m" c a b]

"(%n::nat. n+k)  {i..<j} = {i+k..<j+k}" (is "?A = ?B")
proof
show "?A ⊆ ?B" by auto
next
show "?B ⊆ ?A"
proof
fix n assume a: "n : ?B"
hence "n - k : {i..<j}" by auto
moreover have "n = (n - k) + k" using a by auto
ultimately show "n : ?A" by blast
qed
qed

corollary image_Suc_lessThan:
"Suc  {..<n} = {1..n}"
using image_add_atLeastLessThan [of 1 0 n]
by (auto simp add: lessThan_Suc_atMost atLeast0LessThan)

corollary image_Suc_atMost:
"Suc  {..n} = {1..Suc n}"
using image_add_atLeastLessThan [of 1 0 "Suc n"]
by (auto simp add: lessThan_Suc_atMost atLeast0LessThan)

corollary image_Suc_atLeastAtMost[simp]:
"Suc  {i..j} = {Suc i..Suc j}"
using image_add_atLeastAtMost[where k="Suc 0"] by simp

corollary image_Suc_atLeastLessThan[simp]:
"Suc  {i..<j} = {Suc i..<Suc j}"
using image_add_atLeastLessThan[where k="Suc 0"] by simp

lemma atLeast1_lessThan_eq_remove0:
"{Suc 0..<n} = {..<n} - {0}"
by auto

lemma atLeast1_atMost_eq_remove0:
"{Suc 0..n} = {..n} - {0}"
by auto

"(%x. x + (l::int))  {0..<u-l} = {l..<u}"
apply (rule_tac x = "x - l" in bexI)
apply auto
done

lemma image_minus_const_atLeastLessThan_nat:
fixes c :: nat
shows "(λi. i - c)  {x ..< y} =
(if c < y then {x - c ..< y - c} else if x < y then {0} else {})"
(is "_ = ?right")
proof safe
fix a assume a: "a ∈ ?right"
show "a ∈ (λi. i - c)  {x ..< y}"
proof cases
assume "c < y" with a show ?thesis
by (auto intro!: image_eqI[of _ _ "a + c"])
next
assume "¬ c < y" with a show ?thesis
by (auto intro!: image_eqI[of _ _ x] split: if_split_asm)
qed
qed auto

lemma image_int_atLeastLessThan: "int  {a..<b} = {int a..<int b}"
by (auto intro!: image_eqI [where x = "nat x" for x])

begin

lemma
fixes x :: 'a
shows image_uminus_greaterThan[simp]: "uminus  {x<..} = {..<-x}"
and image_uminus_atLeast[simp]: "uminus  {x..} = {..-x}"
proof safe
fix y assume "y < -x"
hence *:  "x < -y" using neg_less_iff_less[of "-y" x] by simp
have "- (-y) ∈ uminus  {x<..}"
by (rule imageI) (simp add: *)
thus "y ∈ uminus  {x<..}" by simp
next
fix y assume "y ≤ -x"
have "- (-y) ∈ uminus  {x..}"
by (rule imageI) (insert ‹y ≤ -x›[THEN le_imp_neg_le], simp)
thus "y ∈ uminus  {x..}" by simp
qed simp_all

lemma
fixes x :: 'a
shows image_uminus_lessThan[simp]: "uminus  {..<x} = {-x<..}"
and image_uminus_atMost[simp]: "uminus  {..x} = {-x..}"
proof -
have "uminus  {..<x} = uminus  uminus  {-x<..}"
and "uminus  {..x} = uminus  uminus  {-x..}" by simp_all
thus "uminus  {..<x} = {-x<..}" and "uminus  {..x} = {-x..}"
del: image_uminus_greaterThan image_uminus_atLeast)
qed

lemma
fixes x :: 'a
shows image_uminus_atLeastAtMost[simp]: "uminus  {x..y} = {-y..-x}"
and image_uminus_greaterThanAtMost[simp]: "uminus  {x<..y} = {-y..<-x}"
and image_uminus_atLeastLessThan[simp]: "uminus  {x..<y} = {-y<..-x}"
and image_uminus_greaterThanLessThan[simp]: "uminus  {x<..<y} = {-y<..<-x}"
by (simp_all add: atLeastAtMost_def greaterThanAtMost_def atLeastLessThan_def
greaterThanLessThan_def image_Int[OF inj_uminus] Int_commute)
end

subsubsection ‹Finiteness›

lemma finite_lessThan [iff]: fixes k :: nat shows "finite {..<k}"
by (induct k) (simp_all add: lessThan_Suc)

lemma finite_atMost [iff]: fixes k :: nat shows "finite {..k}"
by (induct k) (simp_all add: atMost_Suc)

lemma finite_greaterThanLessThan [iff]:
fixes l :: nat shows "finite {l<..<u}"

lemma finite_atLeastLessThan [iff]:
fixes l :: nat shows "finite {l..<u}"

lemma finite_greaterThanAtMost [iff]:
fixes l :: nat shows "finite {l<..u}"

lemma finite_atLeastAtMost [iff]:
fixes l :: nat shows "finite {l..u}"

text ‹A bounded set of natural numbers is finite.›
lemma bounded_nat_set_is_finite:
"(ALL i:N. i < (n::nat)) ==> finite N"
apply (rule finite_subset)
apply (rule_tac [2] finite_lessThan, auto)
done

text ‹A set of natural numbers is finite iff it is bounded.›
lemma finite_nat_set_iff_bounded:
"finite(N::nat set) = (EX m. ALL n:N. n<m)" (is "?F = ?B")
proof
assume f:?F  show ?B
using Max_ge[OF ‹?F›, simplified less_Suc_eq_le[symmetric]] by blast
next
assume ?B show ?F using ‹?B› by(blast intro:bounded_nat_set_is_finite)
qed

lemma finite_nat_set_iff_bounded_le:
"finite(N::nat set) = (EX m. ALL n:N. n<=m)"
apply(blast dest:less_imp_le_nat le_imp_less_Suc)
done

lemma finite_less_ub:
"!!f::nat=>nat. (!!n. n ≤ f n) ==> finite {n. f n ≤ u}"
by (rule_tac B="{..u}" in finite_subset, auto intro: order_trans)

lemma bounded_Max_nat:
fixes P :: "nat ⇒ bool"
assumes x: "P x" and M: "⋀x. P x ⟹ x ≤ M"
obtains m where "P m" "⋀x. P x ⟹ x ≤ m"
proof -
have "finite {x. P x}"
using M finite_nat_set_iff_bounded_le by auto
then have "Max {x. P x} ∈ {x. P x}"
using Max_in x by auto
then show ?thesis
by (simp add: ‹finite {x. P x}› that)
qed

text‹Any subset of an interval of natural numbers the size of the
subset is exactly that interval.›

lemma subset_card_intvl_is_intvl:
assumes "A ⊆ {k..<k + card A}"
shows "A = {k..<k + card A}"
proof (cases "finite A")
case True
from this and assms show ?thesis
proof (induct A rule: finite_linorder_max_induct)
case empty thus ?case by auto
next
case (insert b A)
hence *: "b ∉ A" by auto
with insert have "A <= {k..<k + card A}" and "b = k + card A"
by fastforce+
with insert * show ?case by auto
qed
next
case False
with assms show ?thesis by simp
qed

subsubsection ‹Proving Inclusions and Equalities between Unions›

lemma UN_le_eq_Un0:
"(⋃i≤n::nat. M i) = (⋃i∈{1..n}. M i) ∪ M 0" (is "?A = ?B")
proof
show "?A <= ?B"
proof
fix x assume "x : ?A"
then obtain i where i: "i≤n" "x : M i" by auto
show "x : ?B"
proof(cases i)
case 0 with i show ?thesis by simp
next
case (Suc j) with i show ?thesis by auto
qed
qed
next
show "?B <= ?A" by fastforce
qed

"(⋃i≤n::nat. M(i+k)) = (⋃i∈{k..n+k}. M i)" (is "?A = ?B")
proof
show "?A <= ?B" by fastforce
next
show "?B <= ?A"
proof
fix x assume "x : ?B"
then obtain i where i: "i : {k..n+k}" "x : M(i)" by auto
hence "i-k≤n & x : M((i-k)+k)" by auto
thus "x : ?A" by blast
qed
qed

lemma UN_UN_finite_eq: "(⋃n::nat. ⋃i∈{0..<n}. A i) = (⋃n. A n)"

lemma UN_finite_subset:
"(⋀n::nat. (⋃i∈{0..<n}. A i) ⊆ C) ⟹ (⋃n. A n) ⊆ C"
by (subst UN_UN_finite_eq [symmetric]) blast

lemma UN_finite2_subset:
assumes "⋀n::nat. (⋃i∈{0..<n}. A i) ⊆ (⋃i∈{0..<n + k}. B i)"
shows "(⋃n. A n) ⊆ (⋃n. B n)"
proof (rule UN_finite_subset, rule)
fix n and a
from assms have "(⋃i∈{0..<n}. A i) ⊆ (⋃i∈{0..<n + k}. B i)" .
moreover assume "a ∈ (⋃i∈{0..<n}. A i)"
ultimately have "a ∈ (⋃i∈{0..<n + k}. B i)" by blast
then show "a ∈ (⋃i. B i)" by (auto simp add: UN_UN_finite_eq)
qed

lemma UN_finite2_eq:
"(⋀n::nat. (⋃i∈{0..<n}. A i) = (⋃i∈{0..<n + k}. B i)) ⟹
(⋃n. A n) = (⋃n. B n)"
apply (rule subset_antisym)
apply (rule UN_finite2_subset, blast)
apply (rule UN_finite2_subset [where k=k])
done

subsubsection ‹Cardinality›

lemma card_lessThan [simp]: "card {..<u} = u"
by (induct u, simp_all add: lessThan_Suc)

lemma card_atMost [simp]: "card {..u} = Suc u"
by (simp add: lessThan_Suc_atMost [THEN sym])

lemma card_atLeastLessThan [simp]: "card {l..<u} = u - l"
proof -
have "{l..<u} = (%x. x + l)  {..<u-l}"
apply (auto simp add: image_def atLeastLessThan_def lessThan_def)
apply (rule_tac x = "x - l" in exI)
apply arith
done
then have "card {l..<u} = card {..<u-l}"
then show ?thesis
by simp
qed

lemma card_atLeastAtMost [simp]: "card {l..u} = Suc u - l"
by (subst atLeastLessThanSuc_atLeastAtMost [THEN sym], simp)

lemma card_greaterThanAtMost [simp]: "card {l<..u} = u - l"
by (subst atLeastSucAtMost_greaterThanAtMost [THEN sym], simp)

lemma card_greaterThanLessThan [simp]: "card {l<..<u} = u - Suc l"
by (subst atLeastSucLessThan_greaterThanLessThan [THEN sym], simp)

lemma subset_eq_atLeast0_lessThan_finite:
fixes n :: nat
assumes "N ⊆ {0..<n}"
shows "finite N"
using assms finite_atLeastLessThan by (rule finite_subset)

lemma subset_eq_atLeast0_atMost_finite:
fixes n :: nat
assumes "N ⊆ {0..n}"
shows "finite N"
using assms finite_atLeastAtMost by (rule finite_subset)

lemma ex_bij_betw_nat_finite:
"finite M ⟹ ∃h. bij_betw h {0..<card M} M"
apply(drule finite_imp_nat_seg_image_inj_on)
apply(auto simp:atLeast0LessThan[symmetric] lessThan_def[symmetric] card_image bij_betw_def)
done

lemma ex_bij_betw_finite_nat:
"finite M ⟹ ∃h. bij_betw h M {0..<card M}"
by (blast dest: ex_bij_betw_nat_finite bij_betw_inv)

lemma finite_same_card_bij:
"finite A ⟹ finite B ⟹ card A = card B ⟹ EX h. bij_betw h A B"
apply(drule ex_bij_betw_finite_nat)
apply(drule ex_bij_betw_nat_finite)
apply(auto intro!:bij_betw_trans)
done

lemma ex_bij_betw_nat_finite_1:
"finite M ⟹ ∃h. bij_betw h {1 .. card M} M"
by (rule finite_same_card_bij) auto

lemma bij_betw_iff_card:
assumes "finite A" "finite B"
shows "(∃f. bij_betw f A B) ⟷ (card A = card B)"
proof
assume "card A = card B"
moreover obtain f where "bij_betw f A {0 ..< card A}"
using assms ex_bij_betw_finite_nat by blast
moreover obtain g where "bij_betw g {0 ..< card B} B"
using assms ex_bij_betw_nat_finite by blast
ultimately have "bij_betw (g o f) A B"
by (auto simp: bij_betw_trans)
thus "(∃f. bij_betw f A B)" by blast
qed (auto simp: bij_betw_same_card)

lemma inj_on_iff_card_le:
assumes FIN: "finite A" and FIN': "finite B"
shows "(∃f. inj_on f A ∧ f  A ≤ B) = (card A ≤ card B)"
proof (safe intro!: card_inj_on_le)
assume *: "card A ≤ card B"
obtain f where 1: "inj_on f A" and 2: "f  A = {0 ..< card A}"
using FIN ex_bij_betw_finite_nat unfolding bij_betw_def by force
moreover obtain g where "inj_on g {0 ..< card B}" and 3: "g  {0 ..< card B} = B"
using FIN' ex_bij_betw_nat_finite unfolding bij_betw_def by force
ultimately have "inj_on g (f  A)" using subset_inj_on[of g _ "f  A"] * by force
hence "inj_on (g o f) A" using 1 comp_inj_on by blast
moreover
{have "{0 ..< card A} ≤ {0 ..< card B}" using * by force
with 2 have "f  A  ≤ {0 ..< card B}" by blast
hence "(g o f)  A ≤ B" unfolding comp_def using 3 by force
}
ultimately show "(∃f. inj_on f A ∧ f  A ≤ B)" by blast
qed (insert assms, auto)

lemma subset_eq_atLeast0_lessThan_card:
fixes n :: nat
assumes "N ⊆ {0..<n}"
shows "card N ≤ n"
proof -
from assms finite_lessThan have "card N ≤ card {0..<n}"
using card_mono by blast
then show ?thesis by simp
qed

subsection ‹Intervals of integers›

lemma atLeastLessThanPlusOne_atLeastAtMost_int: "{l..<u+1} = {l..(u::int)}"
by (auto simp add: atLeastAtMost_def atLeastLessThan_def)

lemma atLeastPlusOneAtMost_greaterThanAtMost_int: "{l+1..u} = {l<..(u::int)}"
by (auto simp add: atLeastAtMost_def greaterThanAtMost_def)

lemma atLeastPlusOneLessThan_greaterThanLessThan_int:
"{l+1..<u} = {l<..<u::int}"
by (auto simp add: atLeastLessThan_def greaterThanLessThan_def)

subsubsection ‹Finiteness›

lemma image_atLeastZeroLessThan_int: "0 ≤ u ==>
{(0::int)..<u} = int  {..<nat u}"
apply (unfold image_def lessThan_def)
apply auto
apply (rule_tac x = "nat x" in exI)
apply (auto simp add: zless_nat_eq_int_zless [THEN sym])
done

lemma finite_atLeastZeroLessThan_int: "finite {(0::int)..<u}"
apply (cases "0 ≤ u")
apply (subst image_atLeastZeroLessThan_int, assumption)
apply (rule finite_imageI)
apply auto
done

lemma finite_atLeastLessThan_int [iff]: "finite {l..<u::int}"
apply (subgoal_tac "(%x. x + l)  {0..<u-l} = {l..<u}")
apply (erule subst)
apply (rule finite_imageI)
apply (rule finite_atLeastZeroLessThan_int)
done

lemma finite_atLeastAtMost_int [iff]: "finite {l..(u::int)}"
by (subst atLeastLessThanPlusOne_atLeastAtMost_int [THEN sym], simp)

lemma finite_greaterThanAtMost_int [iff]: "finite {l<..(u::int)}"
by (subst atLeastPlusOneAtMost_greaterThanAtMost_int [THEN sym], simp)

lemma finite_greaterThanLessThan_int [iff]: "finite {l<..<u::int}"
by (subst atLeastPlusOneLessThan_greaterThanLessThan_int [THEN sym], simp)

subsubsection ‹Cardinality›

lemma card_atLeastZeroLessThan_int: "card {(0::int)..<u} = nat u"
apply (cases "0 ≤ u")
apply (subst image_atLeastZeroLessThan_int, assumption)
apply (subst card_image)
done

lemma card_atLeastLessThan_int [simp]: "card {l..<u} = nat (u - l)"
apply (subgoal_tac "card {l..<u} = card {0..<u-l}")
apply (erule ssubst, rule card_atLeastZeroLessThan_int)
apply (subgoal_tac "(%x. x + l)  {0..<u-l} = {l..<u}")
apply (erule subst)
apply (rule card_image)
done

lemma card_atLeastAtMost_int [simp]: "card {l..u} = nat (u - l + 1)"
apply (subst atLeastLessThanPlusOne_atLeastAtMost_int [THEN sym])
done

lemma card_greaterThanAtMost_int [simp]: "card {l<..u} = nat (u - l)"
by (subst atLeastPlusOneAtMost_greaterThanAtMost_int [THEN sym], simp)

lemma card_greaterThanLessThan_int [simp]: "card {l<..<u} = nat (u - (l + 1))"
by (subst atLeastPlusOneLessThan_greaterThanLessThan_int [THEN sym], simp)

lemma finite_M_bounded_by_nat: "finite {k. P k ∧ k < (i::nat)}"
proof -
have "{k. P k ∧ k < i} ⊆ {..<i}" by auto
with finite_lessThan[of "i"] show ?thesis by (simp add: finite_subset)
qed

lemma card_less:
assumes zero_in_M: "0 ∈ M"
shows "card {k ∈ M. k < Suc i} ≠ 0"
proof -
from zero_in_M have "{k ∈ M. k < Suc i} ≠ {}" by auto
with finite_M_bounded_by_nat show ?thesis by (auto simp add: card_eq_0_iff)
qed

lemma card_less_Suc2: "0 ∉ M ⟹ card {k. Suc k ∈ M ∧ k < i} = card {k ∈ M. k < Suc i}"
apply (rule card_bij_eq [of Suc _ _ "λx. x - Suc 0"])
apply auto
apply (rule inj_on_diff_nat)
apply auto
apply (case_tac x)
apply auto
apply (case_tac xa)
apply auto
apply (case_tac xa)
apply auto
done

lemma card_less_Suc:
assumes zero_in_M: "0 ∈ M"
shows "Suc (card {k. Suc k ∈ M ∧ k < i}) = card {k ∈ M. k < Suc i}"
proof -
from assms have a: "0 ∈ {k ∈ M. k < Suc i}" by simp
hence c: "{k ∈ M. k < Suc i} = insert 0 ({k ∈ M. k < Suc i} - {0})"
by (auto simp only: insert_Diff)
have b: "{k ∈ M. k < Suc i} - {0} = {k ∈ M - {0}. k < Suc i}"  by auto
from finite_M_bounded_by_nat[of "λx. x ∈ M" "Suc i"]
have "Suc (card {k. Suc k ∈ M ∧ k < i}) = card (insert 0 ({k ∈ M. k < Suc i} - {0}))"
apply (subst card_insert)
apply simp_all
apply (subst b)
apply (subst card_less_Suc2[symmetric])
apply simp_all
done
with c show ?thesis by simp
qed

subsection ‹Lemmas useful with the summation operator sum›

text ‹For examples, see Algebra/poly/UnivPoly2.thy›

subsubsection ‹Disjoint Unions›

text ‹Singletons and open intervals›

lemma ivl_disj_un_singleton:
"{l::'a::linorder} Un {l<..} = {l..}"
"{..<u} Un {u::'a::linorder} = {..u}"
"(l::'a::linorder) < u ==> {l} Un {l<..<u} = {l..<u}"
"(l::'a::linorder) < u ==> {l<..<u} Un {u} = {l<..u}"
"(l::'a::linorder) <= u ==> {l} Un {l<..u} = {l..u}"
"(l::'a::linorder) <= u ==> {l..<u} Un {u} = {l..u}"
by auto

text ‹One- and two-sided intervals›

lemma ivl_disj_un_one:
"(l::'a::linorder) < u ==> {..l} Un {l<..<u} = {..<u}"
"(l::'a::linorder) <= u ==> {..<l} Un {l..<u} = {..<u}"
"(l::'a::linorder) <= u ==> {..l} Un {l<..u} = {..u}"
"(l::'a::linorder) <= u ==> {..<l} Un {l..u} = {..u}"
"(l::'a::linorder) <= u ==> {l<..u} Un {u<..} = {l<..}"
"(l::'a::linorder) < u ==> {l<..<u} Un {u..} = {l<..}"
"(l::'a::linorder) <= u ==> {l..u} Un {u<..} = {l..}"
"(l::'a::linorder) <= u ==> {l..<u} Un {u..} = {l..}"
by auto

text ‹Two- and two-sided intervals›

lemma ivl_disj_un_two:
"[| (l::'a::linorder) < m; m <= u |] ==> {l<..<m} Un {m..<u} = {l<..<u}"
"[| (l::'a::linorder) <= m; m < u |] ==> {l<..m} Un {m<..<u} = {l<..<u}"
"[| (l::'a::linorder) <= m; m <= u |] ==> {l..<m} Un {m..<u} = {l..<u}"
"[| (l::'a::linorder) <= m; m < u |] ==> {l..m} Un {m<..<u} = {l..<u}"
"[| (l::'a::linorder) < m; m <= u |] ==> {l<..<m} Un {m..u} = {l<..u}"
"[| (l::'a::linorder) <= m; m <= u |] ==> {l<..m} Un {m<..u} = {l<..u}"
"[| (l::'a::linorder) <= m; m <= u |] ==> {l..<m} Un {m..u} = {l..u}"
"[| (l::'a::linorder) <= m; m <= u |] ==> {l..m} Un {m<..u} = {l..u}"
by auto

lemma ivl_disj_un_two_touch:
"[| (l::'a::linorder) < m; m < u |] ==> {l<..m} Un {m..<u} = {l<..<u}"
"[| (l::'a::linorder) <= m; m < u |] ==> {l..m} Un {m..<u} = {l..<u}"
"[| (l::'a::linorder) < m; m <= u |] ==> {l<..m} Un {m..u} = {l<..u}"
"[| (l::'a::linorder) <= m; m <= u |] ==> {l..m} Un {m..u} = {l..u}"
by auto

lemmas ivl_disj_un = ivl_disj_un_singleton ivl_disj_un_one ivl_disj_un_two ivl_disj_un_two_touch

subsubsection ‹Disjoint Intersections›

text ‹One- and two-sided intervals›

lemma ivl_disj_int_one:
"{..l::'a::order} Int {l<..<u} = {}"
"{..<l} Int {l..<u} = {}"
"{..l} Int {l<..u} = {}"
"{..<l} Int {l..u} = {}"
"{l<..u} Int {u<..} = {}"
"{l<..<u} Int {u..} = {}"
"{l..u} Int {u<..} = {}"
"{l..<u} Int {u..} = {}"
by auto

text ‹Two- and two-sided intervals›

lemma ivl_disj_int_two:
"{l::'a::order<..<m} Int {m..<u} = {}"
"{l<..m} Int {m<..<u} = {}"
"{l..<m} Int {m..<u} = {}"
"{l..m} Int {m<..<u} = {}"
"{l<..<m} Int {m..u} = {}"
"{l<..m} Int {m<..u} = {}"
"{l..<m} Int {m..u} = {}"
"{l..m} Int {m<..u} = {}"
by auto

lemmas ivl_disj_int = ivl_disj_int_one ivl_disj_int_two

subsubsection ‹Some Differences›

lemma ivl_diff[simp]:
"i ≤ n ⟹ {i..<m} - {i..<n} = {n..<(m::'a::linorder)}"
by(auto)

lemma (in linorder) lessThan_minus_lessThan [simp]:
"{..< n} - {..< m} = {m ..< n}"
by auto

lemma (in linorder) atLeastAtMost_diff_ends:
"{a..b} - {a, b} = {a<..<b}"
by auto

subsubsection ‹Some Subset Conditions›

lemma ivl_subset [simp]:
"({i..<j} ⊆ {m..<n}) = (j ≤ i | m ≤ i & j ≤ (n::'a::linorder))"
apply(auto simp:linorder_not_le)
apply(rule ccontr)
apply(insert linorder_le_less_linear[of i n])
apply(clarsimp simp:linorder_not_le)
apply(fastforce)
done

subsection ‹Generic big monoid operation over intervals›

"inj_on (plus k) N" for k :: nat
by rule simp

context comm_monoid_set
begin

lemma atLeast_lessThan_shift_bounds:
fixes m n k :: nat
shows "F g {m + k..<n + k} = F (g ∘ plus k) {m..<n}"
proof -
have "{m + k..<n + k} = plus k  {m..<n}"
also have "F g (plus k  {m..<n}) = F (g ∘ plus k) {m..<n}"
by (rule reindex) simp
finally show ?thesis .
qed

lemma atLeast_atMost_shift_bounds:
fixes m n k :: nat
shows "F g {m + k..n + k} = F (g ∘ plus k) {m..n}"
proof -
have "{m + k..n + k} = plus k  {m..n}"
also have "F g (plus k  {m..n}) = F (g ∘ plus k) {m..n}"
by (rule reindex) simp
finally show ?thesis .
qed

lemma atLeast_Suc_lessThan_Suc_shift:
"F g {Suc m..<Suc n} = F (g ∘ Suc) {m..<n}"
using atLeast_lessThan_shift_bounds [of _ _ 1] by simp

lemma atLeast_Suc_atMost_Suc_shift:
"F g {Suc m..Suc n} = F (g ∘ Suc) {m..n}"
using atLeast_atMost_shift_bounds [of _ _ 1] by simp

lemma atLeast0_lessThan_Suc:
"F g {0..<Suc n} = F g {0..<n} * g n"

lemma atLeast0_atMost_Suc:
"F g {0..Suc n} = F g {0..n} * g (Suc n)"

lemma atLeast0_lessThan_Suc_shift:
"F g {0..<Suc n} = g 0 * F (g ∘ Suc) {0..<n}"

lemma atLeast0_atMost_Suc_shift:
"F g {0..Suc n} = g 0 * F (g ∘ Suc) {0..n}"

lemma ivl_cong:
"a = c ⟹ b = d ⟹ (⋀x. c ≤ x ⟹ x < d ⟹ g x = h x)
⟹ F g {a..<b} = F h {c..<d}"
by (rule cong) simp_all

lemma atLeast_lessThan_shift_0:
fixes m n p :: nat
shows "F g {m..<n} = F (g ∘ plus m) {0..<n - m}"
using atLeast_lessThan_shift_bounds [of g 0 m "n - m"]
by (cases "m ≤ n") simp_all

lemma atLeast_atMost_shift_0:
fixes m n p :: nat
assumes "m ≤ n"
shows "F g {m..n} = F (g ∘ plus m) {0..n - m}"
using assms atLeast_atMost_shift_bounds [of g 0 m "n - m"] by simp

lemma atLeast_lessThan_concat:
fixes m n p :: nat
shows "m ≤ n ⟹ n ≤ p ⟹ F g {m..<n} * F g {n..<p} = F g {m..<p}"
by (simp add: union_disjoint [symmetric] ivl_disj_un)

lemma atLeast_lessThan_rev:
"F g {n..<m} = F (λi. g (m + n - Suc i)) {n..<m}"
by (rule reindex_bij_witness [where i="λi. m + n - Suc i" and j="λi. m + n - Suc i"], auto)

lemma atLeast_atMost_rev:
fixes n m :: nat
shows "F g {n..m} = F (λi. g (m + n - i)) {n..m}"
by (rule reindex_bij_witness [where i="λi. m + n - i" and j="λi. m + n - i"]) auto

lemma atLeast_lessThan_rev_at_least_Suc_atMost:
"F g {n..<m} = F (λi. g (m + n - i)) {Suc n..m}"
unfolding atLeast_lessThan_rev [of g n m]
by (cases m) (simp_all add: atLeast_Suc_atMost_Suc_shift atLeastLessThanSuc_atLeastAtMost)

end

subsection ‹Summation indexed over intervals›

syntax (ASCII)
"_from_to_sum" :: "idt ⇒ 'a ⇒ 'a ⇒ 'b ⇒ 'b"  ("(SUM _ = _.._./ _)" [0,0,0,10] 10)
"_from_upto_sum" :: "idt ⇒ 'a ⇒ 'a ⇒ 'b ⇒ 'b"  ("(SUM _ = _..<_./ _)" [0,0,0,10] 10)
"_upt_sum" :: "idt ⇒ 'a ⇒ 'b ⇒ 'b"  ("(SUM _<_./ _)" [0,0,10] 10)
"_upto_sum" :: "idt ⇒ 'a ⇒ 'b ⇒ 'b"  ("(SUM _<=_./ _)" [0,0,10] 10)

syntax (latex_sum output)
"_from_to_sum" :: "idt ⇒ 'a ⇒ 'a ⇒ 'b ⇒ 'b"
("(3\<^latex>‹$\\sum_{›_ = _\<^latex>‹}^{›_\<^latex>‹}$› _)" [0,0,0,10] 10)
"_from_upto_sum" :: "idt ⇒ 'a ⇒ 'a ⇒ 'b ⇒ 'b"
("(3\<^latex>‹$\\sum_{›_ = _\<^latex>‹}^{<›_\<^latex>‹}$› _)" [0,0,0,10] 10)
"_upt_sum" :: "idt ⇒ 'a ⇒ 'b ⇒ 'b"
("(3\<^latex>‹$\\sum_{›_ < _\<^latex>‹}$› _)" [0,0,10] 10)
"_upto_sum" :: "idt ⇒ 'a ⇒ 'b ⇒ 'b"
("(3\<^latex>‹$\\sum_{›_ ≤ _\<^latex>‹}$› _)" [0,0,10] 10)

syntax
"_from_to_sum" :: "idt ⇒ 'a ⇒ 'a ⇒ 'b ⇒ 'b"  ("(3∑_ = _.._./ _)" [0,0,0,10] 10)
"_from_upto_sum" :: "idt ⇒ 'a ⇒ 'a ⇒ 'b ⇒ 'b"  ("(3∑_ = _..<_./ _)" [0,0,0,10] 10)
"_upt_sum" :: "idt ⇒ 'a ⇒ 'b ⇒ 'b"  ("(3∑_<_./ _)" [0,0,10] 10)
"_upto_sum" :: "idt ⇒ 'a ⇒ 'b ⇒ 'b"  ("(3∑_≤_./ _)" [0,0,10] 10)

translations
"∑x=a..b. t" == "CONST sum (λx. t) {a..b}"
"∑x=a..<b. t" == "CONST sum (λx. t) {a..<b}"
"∑i≤n. t" == "CONST sum (λi. t) {..n}"
"∑i<n. t" == "CONST sum (λi. t) {..<n}"

text‹The above introduces some pretty alternative syntaxes for
summation over intervals:
\begin{center}
\begin{tabular}{lll}
Old & New & \LaTeX\\
@{term[source]"∑x∈{a..b}. e"} & @{term"∑x=a..b. e"} & @{term[mode=latex_sum]"∑x=a..b. e"}\\
@{term[source]"∑x∈{a..<b}. e"} & @{term"∑x=a..<b. e"} & @{term[mode=latex_sum]"∑x=a..<b. e"}\\
@{term[source]"∑x∈{..b}. e"} & @{term"∑x≤b. e"} & @{term[mode=latex_sum]"∑x≤b. e"}\\
@{term[source]"∑x∈{..<b}. e"} & @{term"∑x<b. e"} & @{term[mode=latex_sum]"∑x<b. e"}
\end{tabular}
\end{center}
The left column shows the term before introduction of the new syntax,
the middle column shows the new (default) syntax, and the right column
shows a special syntax. The latter is only meaningful for latex output
and has to be activated explicitly by setting the print mode to
‹latex_sum› (e.g.\ via ‹mode = latex_sum› in
antiquotations). It is not the default \LaTeX\ output because it only
works well with italic-style formulae, not tt-style.

Note that for uniformity on @{typ nat} it is better to use
@{term"∑x::nat=0..<n. e"} rather than ‹∑x<n. e›: ‹sum› may
not provide all lemmas available for @{term"{m..<n}"} also in the
special form for @{term"{..<n}"}.›

text‹This congruence rule should be used for sums over intervals as
the standard theorem @{text[source]sum.cong} does not work well
with the simplifier who adds the unsimplified premise @{term"x:B"} to
the context.›

lemmas sum_ivl_cong = sum.ivl_cong

(* FIXME why are the following simp rules but the corresponding eqns
on intervals are not? *)

lemma sum_atMost_Suc [simp]:
"(∑i ≤ Suc n. f i) = (∑i ≤ n. f i) + f (Suc n)"

lemma sum_lessThan_Suc [simp]:
"(∑i < Suc n. f i) = (∑i < n. f i) + f n"

lemma sum_cl_ivl_Suc [simp]:
"sum f {m..Suc n} = (if Suc n < m then 0 else sum f {m..n} + f(Suc n))"
by (auto simp: ac_simps atLeastAtMostSuc_conv)

lemma sum_op_ivl_Suc [simp]:
"sum f {m..<Suc n} = (if n < m then 0 else sum f {m..<n} + f(n))"
by (auto simp: ac_simps atLeastLessThanSuc)
(*
lemma sum_cl_ivl_add_one_nat: "(n::nat) <= m + 1 ==>
(∑i=n..m+1. f i) = (∑i=n..m. f i) + f(m + 1)"
by (auto simp:ac_simps atLeastAtMostSuc_conv)
*)

fixes n :: nat
assumes mn: "m <= n"
shows "(∑x∈{m..n}. P x) = P m + (∑x∈{m<..n}. P x)" (is "?lhs = ?rhs")
proof -
from mn
have "{m..n} = {m} ∪ {m<..n}"
by (auto intro: ivl_disj_un_singleton)
hence "?lhs = (∑x∈{m} ∪ {m<..n}. P x)"
also have "… = ?rhs" by simp
finally show ?thesis .
qed

"m ≤ n ⟹ sum f {m..n} = f m + sum f {Suc m..n}"

"m < n ⟹ sum f {m..<n} = f m + sum f {Suc m..<n}"
apply(insert sum_head_Suc[of m "n - Suc 0" f])
done

lemma sum_ub_add_nat: assumes "(m::nat) ≤ n + 1"
shows "sum f {m..n + p} = sum f {m..n} + sum f {n + 1..n + p}"
proof-
have "{m .. n+p} = {m..n} ∪ {n+1..n+p}" using ‹m ≤ n+1› by auto
thus ?thesis by (auto simp: ivl_disj_int sum.union_disjoint
atLeastSucAtMost_greaterThanAtMost)
qed

lemma sum_diff_nat_ivl:
fixes f :: "nat ⇒ 'a::ab_group_add"
shows "⟦ m ≤ n; n ≤ p ⟧ ⟹
sum f {m..<p} - sum f {m..<n} = sum f {n..<p}"
using sum_add_nat_ivl [of m n p f,symmetric]
done

lemma sum_natinterval_difff:
shows  "sum (λk. f k - f(k + 1)) {(m::nat) .. n} =
(if m <= n then f m - f(n + 1) else 0)"
by (induct n, auto simp add: algebra_simps not_le le_Suc_eq)

lemma sum_nat_group: "(∑m<n::nat. sum f {m * k ..< m*k + k}) = sum f {..< n * k}"
apply (subgoal_tac "k = 0 | 0 < k", auto)
apply (induct "n")
done

lemma sum_triangle_reindex:
fixes n :: nat
shows "(∑(i,j)∈{(i,j). i+j < n}. f i j) = (∑k<n. ∑i≤k. f i (k - i))"
apply (rule sum.reindex_bij_witness[where j="λ(i, j). (i+j, i)" and i="λ(k, i). (i, k - i)"])
apply auto
done

lemma sum_triangle_reindex_eq:
fixes n :: nat
shows "(∑(i,j)∈{(i,j). i+j ≤ n}. f i j) = (∑k≤n. ∑i≤k. f i (k - i))"
using sum_triangle_reindex [of f "Suc n"]
by (simp only: Nat.less_Suc_eq_le lessThan_Suc_atMost)

lemma nat_diff_sum_reindex: "(∑i<n. f (n - Suc i)) = (∑i<n. f i)"
by (rule sum.reindex_bij_witness[where i="λi. n - Suc i" and j="λi. n - Suc i"]) auto

subsubsection ‹Shifting bounds›

lemma sum_shift_bounds_nat_ivl:
"sum f {m+k..<n+k} = sum (%i. f(i + k)){m..<n::nat}"
by (induct "n", auto simp:atLeastLessThanSuc)

lemma sum_shift_bounds_cl_nat_ivl:
"sum f {m+k..n+k} = sum (%i. f(i + k)){m..n::nat}"
by (rule sum.reindex_bij_witness[where i="λi. i + k" and j="λi. i - k"]) auto

corollary sum_shift_bounds_cl_Suc_ivl:
"sum f {Suc m..Suc n} = sum (%i. f(Suc i)){m..n}"
by (simp add:sum_shift_bounds_cl_nat_ivl[where k="Suc 0", simplified])

corollary sum_shift_bounds_Suc_ivl:
"sum f {Suc m..<Suc n} = sum (%i. f(Suc i)){m..<n}"
by (simp add:sum_shift_bounds_nat_ivl[where k="Suc 0", simplified])

lemma sum_shift_lb_Suc0_0:
"f(0::nat) = (0::nat) ⟹ sum f {Suc 0..k} = sum f {0..k}"

lemma sum_shift_lb_Suc0_0_upt:
"f(0::nat) = 0 ⟹ sum f {Suc 0..<k} = sum f {0..<k}"
apply(cases k)apply simp
done

lemma sum_atMost_Suc_shift:
fixes f :: "nat ⇒ 'a::comm_monoid_add"
shows "(∑i≤Suc n. f i) = f 0 + (∑i≤n. f (Suc i))"
proof (induct n)
case 0 show ?case by simp
next
case (Suc n) note IH = this
have "(∑i≤Suc (Suc n). f i) = (∑i≤Suc n. f i) + f (Suc (Suc n))"
by (rule sum_atMost_Suc)
also have "(∑i≤Suc n. f i) = f 0 + (∑i≤n. f (Suc i))"
by (rule IH)
also have "f 0 + (∑i≤n. f (Suc i)) + f (Suc (Suc n)) =
f 0 + ((∑i≤n. f (Suc i)) + f (Suc (Suc n)))"
also have "(∑i≤n. f (Suc i)) + f (Suc (Suc n)) = (∑i≤Suc n. f (Suc i))"
by (rule sum_atMost_Suc [symmetric])
finally show ?case .
qed

lemma sum_lessThan_Suc_shift:
"(∑i<Suc n. f i) = f 0 + (∑i<n. f (Suc i))"

lemma sum_atMost_shift:
fixes f :: "nat ⇒ 'a::comm_monoid_add"
shows "(∑i≤n. f i) = f 0 + (∑i<n. f (Suc i))"
by (metis atLeast0AtMost atLeast0LessThan atLeastLessThanSuc_atLeastAtMost atLeastSucAtMost_greaterThanAtMost le0 sum_head sum_shift_bounds_Suc_ivl)

lemma sum_last_plus: fixes n::nat shows "m <= n ⟹ (∑i = m..n. f i) = f n + (∑i = m..<n. f i)"
by (cases n) (auto simp: atLeastLessThanSuc_atLeastAtMost add.commute)

lemma sum_Suc_diff:
fixes f :: "nat ⇒ 'a::ab_group_add"
assumes "m ≤ Suc n"
shows "(∑i = m..n. f(Suc i) - f i) = f (Suc n) - f m"
using assms by (induct n) (auto simp: le_Suc_eq)

lemma sum_Suc_diff':
fixes f :: "nat ⇒ 'a::ab_group_add"
assumes "m ≤ n"
shows "(∑i = m..<n. f (Suc i) - f i) = f n - f m"
using assms by (induct n) (auto simp: le_Suc_eq)

lemma nested_sum_swap:
"(∑i = 0..n. (∑j = 0..<i. a i j)) = (∑j = 0..<n. ∑i = Suc j..n. a i j)"
by (induction n) (auto simp: sum.distrib)

lemma nested_sum_swap':
"(∑i≤n. (∑j<i. a i j)) = (∑j<n. ∑i = Suc j..n. a i j)"
by (induction n) (auto simp: sum.distrib)

lemma sum_atLeast1_atMost_eq:
"sum f {Suc 0..n} = (∑k<n. f (Suc k))"
proof -
have "sum f {Suc 0..n} = sum f (Suc  {..<n})"
also have "… = (∑k<n. f (Suc k))"
finally show ?thesis .
qed

subsubsection ‹Telescoping›

lemma sum_telescope:
shows "sum (λi. f i - f (Suc i)) {.. i} = f 0 - f (Suc i)"
by (induct i) simp_all

lemma sum_telescope'':
assumes "m ≤ n"
shows   "(∑k∈{Suc m..n}. f k - f (k - 1)) = f n - (f m :: 'a :: ab_group_add)"
by (rule dec_induct[OF assms]) (simp_all add: algebra_simps)

lemma sum_lessThan_telescope:
"(∑n<m. f (Suc n) - f n :: 'a :: ab_group_add) = f m - f 0"
by (induction m) (simp_all add: algebra_simps)

lemma sum_lessThan_telescope':
"(∑n<m. f n - f (Suc n) :: 'a :: ab_group_add) = f 0 - f m"
by (induction m) (simp_all add: algebra_simps)

subsection ‹The formula for geometric sums›

lemma sum_power2: "(∑i=0..<k. (2::nat)^i) = 2^k-1"
by (induction k) (auto simp: mult_2)

lemma geometric_sum:
assumes "x ≠ 1"
shows "(∑i<n. x ^ i) = (x ^ n - 1) / (x - 1::'a::field)"
proof -
from assms obtain y where "y = x - 1" and "y ≠ 0" by simp_all
moreover have "(∑i<n. (y + 1) ^ i) = ((y + 1) ^ n - 1) / y"
by (induct n) (simp_all add: field_simps ‹y ≠ 0›)
ultimately show ?thesis by simp
qed

lemma diff_power_eq_sum:
fixes y :: "'a::{comm_ring,monoid_mult}"
shows
"x ^ (Suc n) - y ^ (Suc n) =
(x - y) * (∑p<Suc n. (x ^ p) * y ^ (n - p))"
proof (induct n)
case (Suc n)
have "x ^ Suc (Suc n) - y ^ Suc (Suc n) = x * (x * x^n) - y * (y * y ^ n)"
by simp
also have "... = y * (x ^ (Suc n) - y ^ (Suc n)) + (x - y) * (x * x^n)"
also have "... = y * ((x - y) * (∑p<Suc n. (x ^ p) * y ^ (n - p))) + (x - y) * (x * x^n)"
by (simp only: Suc)
also have "... = (x - y) * (y * (∑p<Suc n. (x ^ p) * y ^ (n - p))) + (x - y) * (x * x^n)"
by (simp only: mult.left_commute)
also have "... = (x - y) * (∑p<Suc (Suc n). x ^ p * y ^ (Suc n - p))"
by (simp add: field_simps Suc_diff_le sum_distrib_right sum_distrib_left)
finally show ?case .
qed simp

corollary power_diff_sumr2: ‹‹COMPLEX_POLYFUN› in HOL Light›
fixes x :: "'a::{comm_ring,monoid_mult}"
shows   "x^n - y^n = (x - y) * (∑i<n. y^(n - Suc i) * x^i)"
using diff_power_eq_sum[of x "n - 1" y]
by (cases "n = 0") (simp_all add: field_simps)

lemma power_diff_1_eq:
fixes x :: "'a::{comm_ring,monoid_mult}"
shows "n ≠ 0 ⟹ x^n - 1 = (x - 1) * (∑i<n. (x^i))"
using diff_power_eq_sum [of x _ 1]
by (cases n) auto

lemma one_diff_power_eq':
fixes x :: "'a::{comm_ring,monoid_mult}"
shows "n ≠ 0 ⟹ 1 - x^n = (1 - x) * (∑i<n. x^(n - Suc i))"
using diff_power_eq_sum [of 1 _ x]
by (cases n) auto

lemma one_diff_power_eq:
fixes x :: "'a::{comm_ring,monoid_mult}"
shows "n ≠ 0 ⟹ 1 - x^n = (1 - x) * (∑i<n. x^i)"
by (metis one_diff_power_eq' [of n x] nat_diff_sum_reindex)

lemma sum_gp_basic:
fixes x :: "'a::{comm_ring,monoid_mult}"
shows "(1 - x) * (∑i≤n. x^i) = 1 - x^Suc n"
by (simp only: one_diff_power_eq [of "Suc n" x] lessThan_Suc_atMost)

lemma sum_power_shift:
fixes x :: "'a::{comm_ring,monoid_mult}"
assumes "m ≤ n"
shows "(∑i=m..n. x^i) = x^m * (∑i≤n-m. x^i)"
proof -
have "(∑i=m..n. x^i) = x^m * (∑i=m..n. x^(i-m))"
also have "(∑i=m..n. x^(i-m)) = (∑i≤n-m. x^i)"
using ‹m ≤ n› by (intro sum.reindex_bij_witness[where j="λi. i - m" and i="λi. i + m"]) auto
finally show ?thesis .
qed

lemma sum_gp_multiplied:
fixes x :: "'a::{comm_ring,monoid_mult}"
assumes "m ≤ n"
shows "(1 - x) * (∑i=m..n. x^i) = x^m - x^Suc n"
proof -
have  "(1 - x) * (∑i=m..n. x^i) = x^m * (1 - x) * (∑i≤n-m. x^i)"
by (metis mult.assoc mult.commute assms sum_power_shift)
also have "... =x^m * (1 - x^Suc(n-m))"
by (metis mult.assoc sum_gp_basic)
also have "... = x^m - x^Suc n"
using assms
finally show ?thesis .
qed

lemma sum_gp:
fixes x :: "'a::{comm_ring,division_ring}"
shows   "(∑i=m..n. x^i) =
(if n < m then 0
else if x = 1 then of_nat((n + 1) - m)
else (x^m - x^Suc n) / (1 - x))"
using sum_gp_multiplied [of m n x] apply auto
by (metis eq_iff_diff_eq_0 mult.commute nonzero_divide_eq_eq)

subsection‹Geometric progressions›

lemma sum_gp0:
fixes x :: "'a::{comm_ring,division_ring}"
shows   "(∑i≤n. x^i) = (if x = 1 then of_nat(n + 1) else (1 - x^Suc n) / (1 - x))"
using sum_gp_basic[of x n]

fixes x :: "'a::{comm_ring,monoid_mult}"
shows "(∑i∈I. x^(m+i)) = x^m * (∑i∈I. x^i)"

lemma sum_gp_offset:
fixes x :: "'a::{comm_ring,division_ring}"
shows   "(∑i=m..m+n. x^i) =
(if x = 1 then of_nat n + 1 else x^m * (1 - x^Suc n) / (1 - x))"
using sum_gp [of x m "m+n"]

lemma sum_gp_strict:
fixes x :: "'a::{comm_ring,division_ring}"
shows "(∑i<n. x^i) = (if x = 1 then of_nat n else (1 - x^n) / (1 - x))"
by (induct n) (auto simp: algebra_simps divide_simps)

subsubsection ‹The formula for arithmetic sums›

lemma gauss_sum:
"(2::'a::comm_semiring_1)*(∑i∈{1..n}. of_nat i) = of_nat n*((of_nat n)+1)"
proof (induct n)
case 0
show ?case by simp
next
case (Suc n)
then show ?case
(* FIXME: make numeral cancellation simprocs work for semirings *)
qed

theorem arith_series_general:
"(2::'a::comm_semiring_1) * (∑i∈{..<n}. a + of_nat i * d) =
of_nat n * (a + (a + of_nat(n - 1)*d))"
proof cases
assume ngt1: "n > 1"
let ?I = "λi. of_nat i" and ?n = "of_nat n"
have
"(∑i∈{..<n}. a+?I i*d) =
((∑i∈{..<n}. a) + (∑i∈{..<n}. ?I i*d))"
by (rule sum.distrib)
also from ngt1 have "… = ?n*a + (∑i∈{..<n}. ?I i*d)" by simp
also from ngt1 have "… = (?n*a + d*(∑i∈{1..<n}. ?I i))"
unfolding One_nat_def
by (simp add: sum_distrib_left atLeast0LessThan[symmetric] sum_shift_lb_Suc0_0_upt ac_simps)
also have "2*… = 2*?n*a + d*2*(∑i∈{1..<n}. ?I i)"
also from ngt1 have "{1..<n} = {1..n - 1}"
by (cases n) (auto simp: atLeastLessThanSuc_atLeastAtMost)
also from ngt1
have "2*?n*a + d*2*(∑i∈{1..n - 1}. ?I i) = (2*?n*a + d*?I (n - 1)*?I n)"
by (simp only: mult.assoc gauss_sum [of "n - 1"], unfold One_nat_def)
finally show ?thesis
unfolding mult_2 by (simp add: algebra_simps)
next
assume "¬(n > 1)"
hence "n = 1 ∨ n = 0" by auto
thus ?thesis by (auto simp: mult_2)
qed

lemma arith_series_nat:
"(2::nat) * (∑i∈{..<n}. a+i*d) = n * (a + (a+(n - 1)*d))"
proof -
have
"2 * (∑i∈{..<n::nat}. a + of_nat(i)*d) =
of_nat(n) * (a + (a + of_nat(n - 1)*d))"
by (rule arith_series_general)
thus ?thesis
unfolding One_nat_def by auto
qed

lemma arith_series_int:
"2 * (∑i∈{..<n}. a + int i * d) = int n * (a + (a + int(n - 1)*d))"
by (fact arith_series_general) (* FIXME: duplicate *)

lemma sum_diff_distrib: "∀x. Q x ≤ P x  ⟹ (∑x<n. P x) - (∑x<n. Q x) = (∑x<n. P x - Q x :: nat)"
by (subst sum_subtractf_nat) auto

subsubsection ‹Division remainder›

lemma range_mod:
fixes n :: nat
assumes "n > 0"
shows "range (λm. m mod n) = {0..<n}" (is "?A = ?B")
proof (rule set_eqI)
fix m
show "m ∈ ?A ⟷ m ∈ ?B"
proof
assume "m ∈ ?A"
with assms show "m ∈ ?B"
by auto
next
assume "m ∈ ?B"
moreover have "m mod n ∈ ?A"
by (rule rangeI)
ultimately show "m ∈ ?A"
by simp
qed
qed

subsection ‹Products indexed over intervals›

syntax (ASCII)
"_from_to_prod" :: "idt ⇒ 'a ⇒ 'a ⇒ 'b ⇒ 'b"  ("(PROD _ = _.._./ _)" [0,0,0,10] 10)
"_from_upto_prod" :: "idt ⇒ 'a ⇒ 'a ⇒ 'b ⇒ 'b"  ("(PROD _ = _..<_./ _)" [0,0,0,10] 10)
"_upt_prod" :: "idt ⇒ 'a ⇒ 'b ⇒ 'b"  ("(PROD _<_./ _)" [0,0,10] 10)
"_upto_prod" :: "idt ⇒ 'a ⇒ 'b ⇒ 'b"  ("(PROD _<=_./ _)" [0,0,10] 10)

syntax (latex_prod output)
"_from_to_prod" :: "idt ⇒ 'a ⇒ 'a ⇒ 'b ⇒ 'b"
("(3\<^latex>‹$\\prod_{›_ = _\<^latex>‹}^{›_\<^latex>‹}$› _)" [0,0,0,10] 10)
"_from_upto_prod" :: "idt ⇒ 'a ⇒ 'a ⇒ 'b ⇒ 'b"
("(3\<^latex>‹$\\prod_{›_ = _\<^latex>‹}^{<›_\<^latex>‹}$› _)" [0,0,0,10] 10)
"_upt_prod" :: "idt ⇒ 'a ⇒ 'b ⇒ 'b"
("(3\<^latex>‹$\\prod_{›_ < _\<^latex>‹}$› _)" [0,0,10] 10)
"_upto_prod" :: "idt ⇒ 'a ⇒ 'b ⇒ 'b"
("(3\<^latex>‹$\\prod_{›_ ≤ _\<^latex>‹}$› _)" [0,0,10] 10)

syntax
"_from_to_prod" :: "idt ⇒ 'a ⇒ 'a ⇒ 'b ⇒ 'b"  ("(3∏_ = _.._./ _)" [0,0,0,10] 10)
"_from_upto_prod" :: "idt ⇒ 'a ⇒ 'a ⇒ 'b ⇒ 'b"  ("(3∏_ = _..<_./ _)" [0,0,0,10] 10)
"_upt_prod" :: "idt ⇒ 'a ⇒ 'b ⇒ 'b"  ("(3∏_<_./ _)" [0,0,10] 10)
"_upto_prod" :: "idt ⇒ 'a ⇒ 'b ⇒ 'b"  ("(3∏_≤_./ _)" [0,0,10] 10)

translations
"∏x=a..b. t"  "CONST prod (λx. t) {a..b}"
"∏x=a..<b. t"  "CONST prod (λx. t) {a..<b}"
"∏i≤n. t"  "CONST prod (λi. t) {..n}"
"∏i<n. t"  "CONST prod (λi. t) {..<n}"

lemma prod_int_plus_eq: "prod int {i..i+j} =  ∏{int i..int (i+j)}"
by (induct j) (auto simp add: atLeastAtMostSuc_conv atLeastAtMostPlus1_int_conv)

lemma prod_int_eq: "prod int {i..j} =  ∏{int i..int j}"
proof (cases "i ≤ j")
case True
then show ?thesis
next
case False
then show ?thesis
by auto
qed

subsubsection ‹Shifting bounds›

lemma prod_shift_bounds_nat_ivl:
"prod f {m+k..<n+k} = prod (%i. f(i + k)){m..<n::nat}"
by (induct "n", auto simp:atLeastLessThanSuc)

lemma prod_shift_bounds_cl_nat_ivl:
"prod f {m+k..n+k} = prod (%i. f(i + k)){m..n::nat}"
by (rule prod.reindex_bij_witness[where i="λi. i + k" and j="λi. i - k"]) auto

corollary prod_shift_bounds_cl_Suc_ivl:
"prod f {Suc m..Suc n} = prod (%i. f(Suc i)){m..n}"
by (simp add:prod_shift_bounds_cl_nat_ivl[where k="Suc 0", simplified])

corollary prod_shift_bounds_Suc_ivl:
"prod f {Suc m..<Suc n} = prod (%i. f(Suc i)){m..<n}"
by (simp add:prod_shift_bounds_nat_ivl[where k="Suc 0", simplified])

lemma prod_lessThan_Suc: "prod f {..<Suc n} = prod f {..<n} * f n"

lemma prod_lessThan_Suc_shift:"(∏i<Suc n. f i) = f 0 * (∏i<n. f (Suc i))"
by (induction n) (simp_all add: lessThan_Suc mult_ac)

lemma prod_atLeastLessThan_Suc: "a ≤ b ⟹ prod f {a..<Suc b} = prod f {a..<b} * f b"

lemma prod_nat_ivl_Suc':
assumes "m ≤ Suc n"
shows   "prod f {m..Suc n} = f (Suc n) * prod f {m..n}"
proof -
from assms have "{m..Suc n} = insert (Suc n) {m..n}" by auto
also have "prod f … = f (Suc n) * prod f {m..n}" by simp
finally show ?thesis .
qed

subsection ‹Efficient folding over intervals›

function fold_atLeastAtMost_nat where
[simp del]: "fold_atLeastAtMost_nat f a (b::nat) acc =
(if a > b then acc else fold_atLeastAtMost_nat f (a+1) b (f a acc))"
by pat_completeness auto
termination by (relation "measure (λ(_,a,b,_). Suc b - a)") auto

lemma fold_atLeastAtMost_nat:
assumes "comp_fun_commute f"
shows   "fold_atLeastAtMost_nat f a b acc = Finite_Set.fold f acc {a..b}"
using assms
proof (induction f a b acc rule: fold_atLeastAtMost_nat.induct, goal_cases)
case (1 f a b acc)
interpret comp_fun_commute f by fact
show ?case
proof (cases "a > b")
case True
thus ?thesis by (subst fold_atLeastAtMost_nat.simps) auto
next
case False
with 1 show ?thesis
by (subst fold_atLeastAtMost_nat.simps)
(auto simp: atLeastAtMost_insertL[symmetric] fold_fun_left_comm)
qed
qed

lemma sum_atLeastAtMost_code:
"sum f {a..b} = fold_atLeastAtMost_nat (λa acc. f a + acc) a b 0"
proof -
have "comp_fun_commute (λa. op + (f a))"
by unfold_locales (auto simp: o_def add_ac)
thus ?thesis
by (simp add: sum.eq_fold fold_atLeastAtMost_nat o_def)
qed

lemma prod_atLeastAtMost_code:
"prod f {a..b} = fold_atLeastAtMost_nat (λa acc. f a * acc) a b 1"
proof -
have "comp_fun_commute (λa. op * (f a))"
by unfold_locales (auto simp: o_def mult_ac)
thus ?thesis
by (simp add: prod.eq_fold fold_atLeastAtMost_nat o_def)
qed

(* TODO: Add support for more kinds of intervals here *)

subsection ‹Transfer setup›

lemma transfer_nat_int_set_functions:
"{..n} = nat  {0..int n}"
"{m..n} = nat  {int m..int n}"  (* need all variants of these! *)
apply (rule_tac x = "int x" in bexI)
apply auto
apply (rule_tac x = "int x" in bexI)
apply auto
done

lemma transfer_nat_int_set_function_closures:
"x >= 0 ⟹ nat_set {x..y}"

return: transfer_nat_int_set_functions
transfer_nat_int_set_function_closures
]

lemma transfer_int_nat_set_functions:
"is_nat m ⟹ is_nat n ⟹ {m..n} = int ` {nat m..nat n}"
by (simp only: is_nat_def transfer_nat_int_set_functions
transfer_nat_int_set_function_closures
transfer_nat_int_set_return_embed nat_0_le
cong: transfer_nat_int_set_cong)

lemma transfer_int_nat_set_function_closures:
"is_nat x ⟹ nat_set {x..y}"
by (simp only: transfer_nat_int_set_function_closures is_nat_def)