(*  Title:      HOL/Zorn.thy
    Author:     Jacques D. Fleuriot
    Author:     Tobias Nipkow, TUM
    Author:     Christian Sternagel, JAIST

Zorn's Lemma (ported from Larry Paulson's Zorn.thy in ZF).
The well-ordering theorem.
*)

section {* Zorn's Lemma *}

theory Zorn
imports Order_Relation Hilbert_Choice
begin

subsection {* Zorn's Lemma for the Subset Relation *}

subsubsection {* Results that do not require an order *}

text {*Let @{text P} be a binary predicate on the set @{text A}.*}
locale pred_on =
  fixes A :: "'a set"
    and P :: "'a \<Rightarrow> 'a \<Rightarrow> bool" (infix "\<sqsubset>" 50)
begin

abbreviation Peq :: "'a \<Rightarrow> 'a \<Rightarrow> bool" (infix "\<sqsubseteq>" 50) where
  "x \<sqsubseteq> y \<equiv> P\<^sup>=\<^sup>= x y"

text {*A chain is a totally ordered subset of @{term A}.*}
definition chain :: "'a set \<Rightarrow> bool" where
  "chain C \<longleftrightarrow> C \<subseteq> A \<and> (\<forall>x\<in>C. \<forall>y\<in>C. x \<sqsubseteq> y \<or> y \<sqsubseteq> x)"

text {*We call a chain that is a proper superset of some set @{term X},
but not necessarily a chain itself, a superchain of @{term X}.*}
abbreviation superchain :: "'a set \<Rightarrow> 'a set \<Rightarrow> bool" (infix "<c" 50) where
  "X <c C \<equiv> chain C \<and> X \<subset> C"

text {*A maximal chain is a chain that does not have a superchain.*}
definition maxchain :: "'a set \<Rightarrow> bool" where
  "maxchain C \<longleftrightarrow> chain C \<and> \<not> (\<exists>S. C <c S)"

text {*We define the successor of a set to be an arbitrary
superchain, if such exists, or the set itself, otherwise.*}
definition suc :: "'a set \<Rightarrow> 'a set" where
  "suc C = (if \<not> chain C \<or> maxchain C then C else (SOME D. C <c D))"

lemma chainI [Pure.intro?]:
  "\<lbrakk>C \<subseteq> A; \<And>x y. \<lbrakk>x \<in> C; y \<in> C\<rbrakk> \<Longrightarrow> x \<sqsubseteq> y \<or> y \<sqsubseteq> x\<rbrakk> \<Longrightarrow> chain C"
  unfolding chain_def by blast

lemma chain_total:
  "chain C \<Longrightarrow> x \<in> C \<Longrightarrow> y \<in> C \<Longrightarrow> x \<sqsubseteq> y \<or> y \<sqsubseteq> x"
  by (simp add: chain_def)

lemma not_chain_suc [simp]: "\<not> chain X \<Longrightarrow> suc X = X"
  by (simp add: suc_def)

lemma maxchain_suc [simp]: "maxchain X \<Longrightarrow> suc X = X"
  by (simp add: suc_def)

lemma suc_subset: "X \<subseteq> suc X"
  by (auto simp: suc_def maxchain_def intro: someI2)

lemma chain_empty [simp]: "chain {}"
  by (auto simp: chain_def)

lemma not_maxchain_Some:
  "chain C \<Longrightarrow> \<not> maxchain C \<Longrightarrow> C <c (SOME D. C <c D)"
  by (rule someI_ex) (auto simp: maxchain_def)

lemma suc_not_equals:
  "chain C \<Longrightarrow> \<not> maxchain C \<Longrightarrow> suc C \<noteq> C"
  using not_maxchain_Some by (auto simp: suc_def)

lemma subset_suc:
  assumes "X \<subseteq> Y" shows "X \<subseteq> suc Y"
  using assms by (rule subset_trans) (rule suc_subset)

text {*We build a set @{term \<C>} that is closed under applications
of @{term suc} and contains the union of all its subsets.*}
inductive_set suc_Union_closed ("\<C>") where
  suc: "X \<in> \<C> \<Longrightarrow> suc X \<in> \<C>" |
  Union [unfolded Pow_iff]: "X \<in> Pow \<C> \<Longrightarrow> \<Union>X \<in> \<C>"

text {*Since the empty set as well as the set itself is a subset of
every set, @{term \<C>} contains at least @{term "{} \<in> \<C>"} and
@{term "\<Union>\<C> \<in> \<C>"}.*}
lemma
  suc_Union_closed_empty: "{} \<in> \<C>" and
  suc_Union_closed_Union: "\<Union>\<C> \<in> \<C>"
  using Union [of "{}"] and Union [of "\<C>"] by simp+
text {*Thus closure under @{term suc} will hit a maximal chain
eventually, as is shown below.*}

lemma suc_Union_closed_induct [consumes 1, case_names suc Union,
  induct pred: suc_Union_closed]:
  assumes "X \<in> \<C>"
    and "\<And>X. \<lbrakk>X \<in> \<C>; Q X\<rbrakk> \<Longrightarrow> Q (suc X)"
    and "\<And>X. \<lbrakk>X \<subseteq> \<C>; \<forall>x\<in>X. Q x\<rbrakk> \<Longrightarrow> Q (\<Union>X)"
  shows "Q X"
  using assms by (induct) blast+

lemma suc_Union_closed_cases [consumes 1, case_names suc Union,
  cases pred: suc_Union_closed]:
  assumes "X \<in> \<C>"
    and "\<And>Y. \<lbrakk>X = suc Y; Y \<in> \<C>\<rbrakk> \<Longrightarrow> Q"
    and "\<And>Y. \<lbrakk>X = \<Union>Y; Y \<subseteq> \<C>\<rbrakk> \<Longrightarrow> Q"
  shows "Q"
  using assms by (cases) simp+

text {*On chains, @{term suc} yields a chain.*}
lemma chain_suc:
  assumes "chain X" shows "chain (suc X)"
  using assms
  by (cases "\<not> chain X \<or> maxchain X")
     (force simp: suc_def dest: not_maxchain_Some)+

lemma chain_sucD:
  assumes "chain X" shows "suc X \<subseteq> A \<and> chain (suc X)"
proof -
  from `chain X` have *: "chain (suc X)" by (rule chain_suc)
  then have "suc X \<subseteq> A" unfolding chain_def by blast
  with * show ?thesis by blast
qed

lemma suc_Union_closed_total':
  assumes "X \<in> \<C>" and "Y \<in> \<C>"
    and *: "\<And>Z. Z \<in> \<C> \<Longrightarrow> Z \<subseteq> Y \<Longrightarrow> Z = Y \<or> suc Z \<subseteq> Y"
  shows "X \<subseteq> Y \<or> suc Y \<subseteq> X"
  using `X \<in> \<C>`
proof (induct)
  case (suc X)
  with * show ?case by (blast del: subsetI intro: subset_suc)
qed blast

lemma suc_Union_closed_subsetD:
  assumes "Y \<subseteq> X" and "X \<in> \<C>" and "Y \<in> \<C>"
  shows "X = Y \<or> suc Y \<subseteq> X"
  using assms(2-, 1)
proof (induct arbitrary: Y)
  case (suc X)
  note * = `\<And>Y. \<lbrakk>Y \<in> \<C>; Y \<subseteq> X\<rbrakk> \<Longrightarrow> X = Y \<or> suc Y \<subseteq> X`
  with suc_Union_closed_total' [OF `Y \<in> \<C>` `X \<in> \<C>`]
    have "Y \<subseteq> X \<or> suc X \<subseteq> Y" by blast
  then show ?case
  proof
    assume "Y \<subseteq> X"
    with * and `Y \<in> \<C>` have "X = Y \<or> suc Y \<subseteq> X" by blast
    then show ?thesis
    proof
      assume "X = Y" then show ?thesis by simp
    next
      assume "suc Y \<subseteq> X"
      then have "suc Y \<subseteq> suc X" by (rule subset_suc)
      then show ?thesis by simp
    qed
  next
    assume "suc X \<subseteq> Y"
    with `Y \<subseteq> suc X` show ?thesis by blast
  qed
next
  case (Union X)
  show ?case
  proof (rule ccontr)
    assume "\<not> ?thesis"
    with `Y \<subseteq> \<Union>X` obtain x y z
    where "\<not> suc Y \<subseteq> \<Union>X"
      and "x \<in> X" and "y \<in> x" and "y \<notin> Y"
      and "z \<in> suc Y" and "\<forall>x\<in>X. z \<notin> x" by blast
    with `X \<subseteq> \<C>` have "x \<in> \<C>" by blast
    from Union and `x \<in> X`
      have *: "\<And>y. \<lbrakk>y \<in> \<C>; y \<subseteq> x\<rbrakk> \<Longrightarrow> x = y \<or> suc y \<subseteq> x" by blast
    with suc_Union_closed_total' [OF `Y \<in> \<C>` `x \<in> \<C>`]
      have "Y \<subseteq> x \<or> suc x \<subseteq> Y" by blast
    then show False
    proof
      assume "Y \<subseteq> x"
      with * [OF `Y \<in> \<C>`] have "x = Y \<or> suc Y \<subseteq> x" by blast
      then show False
      proof
        assume "x = Y" with `y \<in> x` and `y \<notin> Y` show False by blast
      next
        assume "suc Y \<subseteq> x"
        with `x \<in> X` have "suc Y \<subseteq> \<Union>X" by blast
        with `\<not> suc Y \<subseteq> \<Union>X` show False by contradiction
      qed
    next
      assume "suc x \<subseteq> Y"
      moreover from suc_subset and `y \<in> x` have "y \<in> suc x" by blast
      ultimately show False using `y \<notin> Y` by blast
    qed
  qed
qed

text {*The elements of @{term \<C>} are totally ordered by the subset relation.*}
lemma suc_Union_closed_total:
  assumes "X \<in> \<C>" and "Y \<in> \<C>"
  shows "X \<subseteq> Y \<or> Y \<subseteq> X"
proof (cases "\<forall>Z\<in>\<C>. Z \<subseteq> Y \<longrightarrow> Z = Y \<or> suc Z \<subseteq> Y")
  case True
  with suc_Union_closed_total' [OF assms]
    have "X \<subseteq> Y \<or> suc Y \<subseteq> X" by blast
  then show ?thesis using suc_subset [of Y] by blast
next
  case False
  then obtain Z
    where "Z \<in> \<C>" and "Z \<subseteq> Y" and "Z \<noteq> Y" and "\<not> suc Z \<subseteq> Y" by blast
  with suc_Union_closed_subsetD and `Y \<in> \<C>` show ?thesis by blast
qed

text {*Once we hit a fixed point w.r.t. @{term suc}, all other elements
of @{term \<C>} are subsets of this fixed point.*}
lemma suc_Union_closed_suc:
  assumes "X \<in> \<C>" and "Y \<in> \<C>" and "suc Y = Y"
  shows "X \<subseteq> Y"
using `X \<in> \<C>`
proof (induct)
  case (suc X)
  with `Y \<in> \<C>` and suc_Union_closed_subsetD
    have "X = Y \<or> suc X \<subseteq> Y" by blast
  then show ?case by (auto simp: `suc Y = Y`)
qed blast

lemma eq_suc_Union:
  assumes "X \<in> \<C>"
  shows "suc X = X \<longleftrightarrow> X = \<Union>\<C>"
proof
  assume "suc X = X"
  with suc_Union_closed_suc [OF suc_Union_closed_Union `X \<in> \<C>`]
    have "\<Union>\<C> \<subseteq> X" .
  with `X \<in> \<C>` show "X = \<Union>\<C>" by blast
next
  from `X \<in> \<C>` have "suc X \<in> \<C>" by (rule suc)
  then have "suc X \<subseteq> \<Union>\<C>" by blast
  moreover assume "X = \<Union>\<C>"
  ultimately have "suc X \<subseteq> X" by simp
  moreover have "X \<subseteq> suc X" by (rule suc_subset)
  ultimately show "suc X = X" ..
qed

lemma suc_in_carrier:
  assumes "X \<subseteq> A"
  shows "suc X \<subseteq> A"
  using assms
  by (cases "\<not> chain X \<or> maxchain X")
     (auto dest: chain_sucD)

lemma suc_Union_closed_in_carrier:
  assumes "X \<in> \<C>"
  shows "X \<subseteq> A"
  using assms
  by (induct) (auto dest: suc_in_carrier)

text {*All elements of @{term \<C>} are chains.*}
lemma suc_Union_closed_chain:
  assumes "X \<in> \<C>"
  shows "chain X"
using assms
proof (induct)
  case (suc X) then show ?case using not_maxchain_Some by (simp add: suc_def)
next
  case (Union X)
  then have "\<Union>X \<subseteq> A" by (auto dest: suc_Union_closed_in_carrier)
  moreover have "\<forall>x\<in>\<Union>X. \<forall>y\<in>\<Union>X. x \<sqsubseteq> y \<or> y \<sqsubseteq> x"
  proof (intro ballI)
    fix x y
    assume "x \<in> \<Union>X" and "y \<in> \<Union>X"
    then obtain u v where "x \<in> u" and "u \<in> X" and "y \<in> v" and "v \<in> X" by blast
    with Union have "u \<in> \<C>" and "v \<in> \<C>" and "chain u" and "chain v" by blast+
    with suc_Union_closed_total have "u \<subseteq> v \<or> v \<subseteq> u" by blast
    then show "x \<sqsubseteq> y \<or> y \<sqsubseteq> x"
    proof
      assume "u \<subseteq> v"
      from `chain v` show ?thesis
      proof (rule chain_total)
        show "y \<in> v" by fact
        show "x \<in> v" using `u \<subseteq> v` and `x \<in> u` by blast
      qed
    next
      assume "v \<subseteq> u"
      from `chain u` show ?thesis
      proof (rule chain_total)
        show "x \<in> u" by fact
        show "y \<in> u" using `v \<subseteq> u` and `y \<in> v` by blast
      qed
    qed
  qed
  ultimately show ?case unfolding chain_def ..
qed

subsubsection {* Hausdorff's Maximum Principle *}

text {*There exists a maximal totally ordered subset of @{term A}. (Note that we do not
require @{term A} to be partially ordered.)*}

theorem Hausdorff: "\<exists>C. maxchain C"
proof -
  let ?M = "\<Union>\<C>"
  have "maxchain ?M"
  proof (rule ccontr)
    assume "\<not> maxchain ?M"
    then have "suc ?M \<noteq> ?M"
      using suc_not_equals and
      suc_Union_closed_chain [OF suc_Union_closed_Union] by simp
    moreover have "suc ?M = ?M"
      using eq_suc_Union [OF suc_Union_closed_Union] by simp
    ultimately show False by contradiction
  qed
  then show ?thesis by blast
qed

text {*Make notation @{term \<C>} available again.*}
no_notation suc_Union_closed ("\<C>")

lemma chain_extend:
  "chain C \<Longrightarrow> z \<in> A \<Longrightarrow> \<forall>x\<in>C. x \<sqsubseteq> z \<Longrightarrow> chain ({z} \<union> C)"
  unfolding chain_def by blast

lemma maxchain_imp_chain:
  "maxchain C \<Longrightarrow> chain C"
  by (simp add: maxchain_def)

end

text {*Hide constant @{const pred_on.suc_Union_closed}, which was just needed
for the proof of Hausforff's maximum principle.*}
hide_const pred_on.suc_Union_closed

lemma chain_mono:
  assumes "\<And>x y. \<lbrakk>x \<in> A; y \<in> A; P x y\<rbrakk> \<Longrightarrow> Q x y"
    and "pred_on.chain A P C"
  shows "pred_on.chain A Q C"
  using assms unfolding pred_on.chain_def by blast

subsubsection {* Results for the proper subset relation *}

interpretation subset: pred_on "A" "op \<subset>" for A .

lemma subset_maxchain_max:
  assumes "subset.maxchain A C" and "X \<in> A" and "\<Union>C \<subseteq> X"
  shows "\<Union>C = X"
proof (rule ccontr)
  let ?C = "{X} \<union> C"
  from `subset.maxchain A C` have "subset.chain A C"
    and *: "\<And>S. subset.chain A S \<Longrightarrow> \<not> C \<subset> S"
    by (auto simp: subset.maxchain_def)
  moreover have "\<forall>x\<in>C. x \<subseteq> X" using `\<Union>C \<subseteq> X` by auto
  ultimately have "subset.chain A ?C"
    using subset.chain_extend [of A C X] and `X \<in> A` by auto
  moreover assume **: "\<Union>C \<noteq> X"
  moreover from ** have "C \<subset> ?C" using `\<Union>C \<subseteq> X` by auto
  ultimately show False using * by blast
qed

subsubsection {* Zorn's lemma *}

text {*If every chain has an upper bound, then there is a maximal set.*}
lemma subset_Zorn:
  assumes "\<And>C. subset.chain A C \<Longrightarrow> \<exists>U\<in>A. \<forall>X\<in>C. X \<subseteq> U"
  shows "\<exists>M\<in>A. \<forall>X\<in>A. M \<subseteq> X \<longrightarrow> X = M"
proof -
  from subset.Hausdorff [of A] obtain M where "subset.maxchain A M" ..
  then have "subset.chain A M" by (rule subset.maxchain_imp_chain)
  with assms obtain Y where "Y \<in> A" and "\<forall>X\<in>M. X \<subseteq> Y" by blast
  moreover have "\<forall>X\<in>A. Y \<subseteq> X \<longrightarrow> Y = X"
  proof (intro ballI impI)
    fix X
    assume "X \<in> A" and "Y \<subseteq> X"
    show "Y = X"
    proof (rule ccontr)
      assume "Y \<noteq> X"
      with `Y \<subseteq> X` have "\<not> X \<subseteq> Y" by blast
      from subset.chain_extend [OF `subset.chain A M` `X \<in> A`] and `\<forall>X\<in>M. X \<subseteq> Y`
        have "subset.chain A ({X} \<union> M)" using `Y \<subseteq> X` by auto
      moreover have "M \<subset> {X} \<union> M" using `\<forall>X\<in>M. X \<subseteq> Y` and `\<not> X \<subseteq> Y` by auto
      ultimately show False
        using `subset.maxchain A M` by (auto simp: subset.maxchain_def)
    qed
  qed
  ultimately show ?thesis by blast
qed

text{*Alternative version of Zorn's lemma for the subset relation.*}
lemma subset_Zorn':
  assumes "\<And>C. subset.chain A C \<Longrightarrow> \<Union>C \<in> A"
  shows "\<exists>M\<in>A. \<forall>X\<in>A. M \<subseteq> X \<longrightarrow> X = M"
proof -
  from subset.Hausdorff [of A] obtain M where "subset.maxchain A M" ..
  then have "subset.chain A M" by (rule subset.maxchain_imp_chain)
  with assms have "\<Union>M \<in> A" .
  moreover have "\<forall>Z\<in>A. \<Union>M \<subseteq> Z \<longrightarrow> \<Union>M = Z"
  proof (intro ballI impI)
    fix Z
    assume "Z \<in> A" and "\<Union>M \<subseteq> Z"
    with subset_maxchain_max [OF `subset.maxchain A M`]
      show "\<Union>M = Z" .
  qed
  ultimately show ?thesis by blast
qed

subsection {* Zorn's Lemma for Partial Orders *}

text {*Relate old to new definitions.*}

(* Define globally? In Set.thy? *)
definition chain_subset :: "'a set set \<Rightarrow> bool" ("chain\<^sub>\<subseteq>") where
  "chain\<^sub>\<subseteq> C \<longleftrightarrow> (\<forall>A\<in>C. \<forall>B\<in>C. A \<subseteq> B \<or> B \<subseteq> A)"

definition chains :: "'a set set \<Rightarrow> 'a set set set" where
  "chains A = {C. C \<subseteq> A \<and> chain\<^sub>\<subseteq> C}"

(* Define globally? In Relation.thy? *)
definition Chains :: "('a \<times> 'a) set \<Rightarrow> 'a set set" where
  "Chains r = {C. \<forall>a\<in>C. \<forall>b\<in>C. (a, b) \<in> r \<or> (b, a) \<in> r}"

lemma chains_extend:
  "[| c \<in> chains S; z \<in> S; \<forall>x \<in> c. x \<subseteq> (z:: 'a set) |] ==> {z} Un c \<in> chains S"
  by (unfold chains_def chain_subset_def) blast

lemma mono_Chains: "r \<subseteq> s \<Longrightarrow> Chains r \<subseteq> Chains s"
  unfolding Chains_def by blast

lemma chain_subset_alt_def: "chain\<^sub>\<subseteq> C = subset.chain UNIV C"
  unfolding chain_subset_def subset.chain_def by fast

lemma chains_alt_def: "chains A = {C. subset.chain A C}"
  by (simp add: chains_def chain_subset_alt_def subset.chain_def)

lemma Chains_subset:
  "Chains r \<subseteq> {C. pred_on.chain UNIV (\<lambda>x y. (x, y) \<in> r) C}"
  by (force simp add: Chains_def pred_on.chain_def)

lemma Chains_subset':
  assumes "refl r"
  shows "{C. pred_on.chain UNIV (\<lambda>x y. (x, y) \<in> r) C} \<subseteq> Chains r"
  using assms
  by (auto simp add: Chains_def pred_on.chain_def refl_on_def)

lemma Chains_alt_def:
  assumes "refl r"
  shows "Chains r = {C. pred_on.chain UNIV (\<lambda>x y. (x, y) \<in> r) C}"
  using assms Chains_subset Chains_subset' by blast

lemma Zorn_Lemma:
  "\<forall>C\<in>chains A. \<Union>C \<in> A \<Longrightarrow> \<exists>M\<in>A. \<forall>X\<in>A. M \<subseteq> X \<longrightarrow> X = M"
  using subset_Zorn' [of A] by (force simp: chains_alt_def)

lemma Zorn_Lemma2:
  "\<forall>C\<in>chains A. \<exists>U\<in>A. \<forall>X\<in>C. X \<subseteq> U \<Longrightarrow> \<exists>M\<in>A. \<forall>X\<in>A. M \<subseteq> X \<longrightarrow> X = M"
  using subset_Zorn [of A] by (auto simp: chains_alt_def)

text{*Various other lemmas*}

lemma chainsD: "[| c \<in> chains S; x \<in> c; y \<in> c |] ==> x \<subseteq> y | y \<subseteq> x"
by (unfold chains_def chain_subset_def) blast

lemma chainsD2: "!!(c :: 'a set set). c \<in> chains S ==> c \<subseteq> S"
by (unfold chains_def) blast

lemma Zorns_po_lemma:
  assumes po: "Partial_order r"
    and u: "\<forall>C\<in>Chains r. \<exists>u\<in>Field r. \<forall>a\<in>C. (a, u) \<in> r"
  shows "\<exists>m\<in>Field r. \<forall>a\<in>Field r. (m, a) \<in> r \<longrightarrow> a = m"
proof -
  have "Preorder r" using po by (simp add: partial_order_on_def)
--{* Mirror r in the set of subsets below (wrt r) elements of A*}
  let ?B = "%x. r\<inverse> `` {x}" let ?S = "?B ` Field r"
  {
    fix C assume 1: "C \<subseteq> ?S" and 2: "\<forall>A\<in>C. \<forall>B\<in>C. A \<subseteq> B \<or> B \<subseteq> A"
    let ?A = "{x\<in>Field r. \<exists>M\<in>C. M = ?B x}"
    have "C = ?B ` ?A" using 1 by (auto simp: image_def)
    have "?A \<in> Chains r"
    proof (simp add: Chains_def, intro allI impI, elim conjE)
      fix a b
      assume "a \<in> Field r" and "?B a \<in> C" and "b \<in> Field r" and "?B b \<in> C"
      hence "?B a \<subseteq> ?B b \<or> ?B b \<subseteq> ?B a" using 2 by auto
      thus "(a, b) \<in> r \<or> (b, a) \<in> r"
        using `Preorder r` and `a \<in> Field r` and `b \<in> Field r`
        by (simp add:subset_Image1_Image1_iff)
    qed
    then obtain u where uA: "u \<in> Field r" "\<forall>a\<in>?A. (a, u) \<in> r" using u by auto
    have "\<forall>A\<in>C. A \<subseteq> r\<inverse> `` {u}" (is "?P u")
    proof auto
      fix a B assume aB: "B \<in> C" "a \<in> B"
      with 1 obtain x where "x \<in> Field r" and "B = r\<inverse> `` {x}" by auto
      thus "(a, u) \<in> r" using uA and aB and `Preorder r`
        unfolding preorder_on_def refl_on_def by simp (fast dest: transD)
    qed
    then have "\<exists>u\<in>Field r. ?P u" using `u \<in> Field r` by blast
  }
  then have "\<forall>C\<in>chains ?S. \<exists>U\<in>?S. \<forall>A\<in>C. A \<subseteq> U"
    by (auto simp: chains_def chain_subset_def)
  from Zorn_Lemma2 [OF this]
  obtain m B where "m \<in> Field r" and "B = r\<inverse> `` {m}"
    and "\<forall>x\<in>Field r. B \<subseteq> r\<inverse> `` {x} \<longrightarrow> r\<inverse> `` {x} = B"
    by auto
  hence "\<forall>a\<in>Field r. (m, a) \<in> r \<longrightarrow> a = m"
    using po and `Preorder r` and `m \<in> Field r`
    by (auto simp: subset_Image1_Image1_iff Partial_order_eq_Image1_Image1_iff)
  thus ?thesis using `m \<in> Field r` by blast
qed

subsection {* The Well Ordering Theorem *}

(* The initial segment of a relation appears generally useful.
   Move to Relation.thy?
   Definition correct/most general?
   Naming?
*)
definition init_seg_of :: "(('a \<times> 'a) set \<times> ('a \<times> 'a) set) set" where
  "init_seg_of = {(r, s). r \<subseteq> s \<and> (\<forall>a b c. (a, b) \<in> s \<and> (b, c) \<in> r \<longrightarrow> (a, b) \<in> r)}"

abbreviation
  initialSegmentOf :: "('a \<times> 'a) set \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> bool" (infix "initial'_segment'_of" 55)
where
  "r initial_segment_of s \<equiv> (r, s) \<in> init_seg_of"

lemma refl_on_init_seg_of [simp]: "r initial_segment_of r"
  by (simp add: init_seg_of_def)

lemma trans_init_seg_of:
  "r initial_segment_of s \<Longrightarrow> s initial_segment_of t \<Longrightarrow> r initial_segment_of t"
  by (simp (no_asm_use) add: init_seg_of_def) blast

lemma antisym_init_seg_of:
  "r initial_segment_of s \<Longrightarrow> s initial_segment_of r \<Longrightarrow> r = s"
  unfolding init_seg_of_def by safe

lemma Chains_init_seg_of_Union:
  "R \<in> Chains init_seg_of \<Longrightarrow> r\<in>R \<Longrightarrow> r initial_segment_of \<Union>R"
  by (auto simp: init_seg_of_def Ball_def Chains_def) blast

lemma chain_subset_trans_Union:
  assumes "chain\<^sub>\<subseteq> R" "\<forall>r\<in>R. trans r"
  shows "trans (\<Union>R)"
proof (intro transI, elim UnionE)
  fix  S1 S2 :: "'a rel" and x y z :: 'a
  assume "S1 \<in> R" "S2 \<in> R"
  with assms(1) have "S1 \<subseteq> S2 \<or> S2 \<subseteq> S1" unfolding chain_subset_def by blast
  moreover assume "(x, y) \<in> S1" "(y, z) \<in> S2"
  ultimately have "((x, y) \<in> S1 \<and> (y, z) \<in> S1) \<or> ((x, y) \<in> S2 \<and> (y, z) \<in> S2)" by blast
  with `S1 \<in> R` `S2 \<in> R` assms(2) show "(x, z) \<in> \<Union>R" by (auto elim: transE)
qed

lemma chain_subset_antisym_Union:
  assumes "chain\<^sub>\<subseteq> R" "\<forall>r\<in>R. antisym r"
  shows "antisym (\<Union>R)"
proof (intro antisymI, elim UnionE)
  fix  S1 S2 :: "'a rel" and x y :: 'a
  assume "S1 \<in> R" "S2 \<in> R"
  with assms(1) have "S1 \<subseteq> S2 \<or> S2 \<subseteq> S1" unfolding chain_subset_def by blast
  moreover assume "(x, y) \<in> S1" "(y, x) \<in> S2"
  ultimately have "((x, y) \<in> S1 \<and> (y, x) \<in> S1) \<or> ((x, y) \<in> S2 \<and> (y, x) \<in> S2)" by blast
  with `S1 \<in> R` `S2 \<in> R` assms(2) show "x = y" unfolding antisym_def by auto
qed

lemma chain_subset_Total_Union:
  assumes "chain\<^sub>\<subseteq> R" and "\<forall>r\<in>R. Total r"
  shows "Total (\<Union>R)"
proof (simp add: total_on_def Ball_def, auto del: disjCI)
  fix r s a b assume A: "r \<in> R" "s \<in> R" "a \<in> Field r" "b \<in> Field s" "a \<noteq> b"
  from `chain\<^sub>\<subseteq> R` and `r \<in> R` and `s \<in> R` have "r \<subseteq> s \<or> s \<subseteq> r"
    by (auto simp add: chain_subset_def)
  thus "(\<exists>r\<in>R. (a, b) \<in> r) \<or> (\<exists>r\<in>R. (b, a) \<in> r)"
  proof
    assume "r \<subseteq> s" hence "(a, b) \<in> s \<or> (b, a) \<in> s" using assms(2) A mono_Field[of r s]
      by (auto simp add: total_on_def)
    thus ?thesis using `s \<in> R` by blast
  next
    assume "s \<subseteq> r" hence "(a, b) \<in> r \<or> (b, a) \<in> r" using assms(2) A mono_Field[of s r]
      by (fastforce simp add: total_on_def)
    thus ?thesis using `r \<in> R` by blast
  qed
qed

lemma wf_Union_wf_init_segs:
  assumes "R \<in> Chains init_seg_of" and "\<forall>r\<in>R. wf r"
  shows "wf (\<Union>R)"
proof(simp add: wf_iff_no_infinite_down_chain, rule ccontr, auto)
  fix f assume 1: "\<forall>i. \<exists>r\<in>R. (f (Suc i), f i) \<in> r"
  then obtain r where "r \<in> R" and "(f (Suc 0), f 0) \<in> r" by auto
  { fix i have "(f (Suc i), f i) \<in> r"
    proof (induct i)
      case 0 show ?case by fact
    next
      case (Suc i)
      then obtain s where s: "s \<in> R" "(f (Suc (Suc i)), f(Suc i)) \<in> s"
        using 1 by auto
      then have "s initial_segment_of r \<or> r initial_segment_of s"
        using assms(1) `r \<in> R` by (simp add: Chains_def)
      with Suc s show ?case by (simp add: init_seg_of_def) blast
    qed
  }
  thus False using assms(2) and `r \<in> R`
    by (simp add: wf_iff_no_infinite_down_chain) blast
qed

lemma initial_segment_of_Diff:
  "p initial_segment_of q \<Longrightarrow> p - s initial_segment_of q - s"
  unfolding init_seg_of_def by blast

lemma Chains_inits_DiffI:
  "R \<in> Chains init_seg_of \<Longrightarrow> {r - s |r. r \<in> R} \<in> Chains init_seg_of"
  unfolding Chains_def by (blast intro: initial_segment_of_Diff)

theorem well_ordering: "\<exists>r::'a rel. Well_order r \<and> Field r = UNIV"
proof -
-- {*The initial segment relation on well-orders: *}
  let ?WO = "{r::'a rel. Well_order r}"
  def I \<equiv> "init_seg_of \<inter> ?WO \<times> ?WO"
  have I_init: "I \<subseteq> init_seg_of" by (auto simp: I_def)
  hence subch: "\<And>R. R \<in> Chains I \<Longrightarrow> chain\<^sub>\<subseteq> R"
    unfolding init_seg_of_def chain_subset_def Chains_def by blast
  have Chains_wo: "\<And>R r. R \<in> Chains I \<Longrightarrow> r \<in> R \<Longrightarrow> Well_order r"
    by (simp add: Chains_def I_def) blast
  have FI: "Field I = ?WO" by (auto simp add: I_def init_seg_of_def Field_def)
  hence 0: "Partial_order I"
    by (auto simp: partial_order_on_def preorder_on_def antisym_def antisym_init_seg_of refl_on_def
      trans_def I_def elim!: trans_init_seg_of)
-- {*I-chains have upper bounds in ?WO wrt I: their Union*}
  { fix R assume "R \<in> Chains I"
    hence Ris: "R \<in> Chains init_seg_of" using mono_Chains [OF I_init] by blast
    have subch: "chain\<^sub>\<subseteq> R" using `R : Chains I` I_init
      by (auto simp: init_seg_of_def chain_subset_def Chains_def)
    have "\<forall>r\<in>R. Refl r" and "\<forall>r\<in>R. trans r" and "\<forall>r\<in>R. antisym r"
      and "\<forall>r\<in>R. Total r" and "\<forall>r\<in>R. wf (r - Id)"
      using Chains_wo [OF `R \<in> Chains I`] by (simp_all add: order_on_defs)
    have "Refl (\<Union>R)" using `\<forall>r\<in>R. Refl r` unfolding refl_on_def by fastforce
    moreover have "trans (\<Union>R)"
      by (rule chain_subset_trans_Union [OF subch `\<forall>r\<in>R. trans r`])
    moreover have "antisym (\<Union>R)"
      by (rule chain_subset_antisym_Union [OF subch `\<forall>r\<in>R. antisym r`])
    moreover have "Total (\<Union>R)"
      by (rule chain_subset_Total_Union [OF subch `\<forall>r\<in>R. Total r`])
    moreover have "wf ((\<Union>R) - Id)"
    proof -
      have "(\<Union>R) - Id = \<Union>{r - Id | r. r \<in> R}" by blast
      with `\<forall>r\<in>R. wf (r - Id)` and wf_Union_wf_init_segs [OF Chains_inits_DiffI [OF Ris]]
      show ?thesis by fastforce
    qed
    ultimately have "Well_order (\<Union>R)" by(simp add:order_on_defs)
    moreover have "\<forall>r \<in> R. r initial_segment_of \<Union>R" using Ris
      by(simp add: Chains_init_seg_of_Union)
    ultimately have "\<Union>R \<in> ?WO \<and> (\<forall>r\<in>R. (r, \<Union>R) \<in> I)"
      using mono_Chains [OF I_init] Chains_wo[of R] and `R \<in> Chains I`
      unfolding I_def by blast
  }
  hence 1: "\<forall>R \<in> Chains I. \<exists>u\<in>Field I. \<forall>r\<in>R. (r, u) \<in> I" by (subst FI) blast
--{*Zorn's Lemma yields a maximal well-order m:*}
  then obtain m::"'a rel" where "Well_order m" and
    max: "\<forall>r. Well_order r \<and> (m, r) \<in> I \<longrightarrow> r = m"
    using Zorns_po_lemma[OF 0 1] unfolding FI by fastforce
--{*Now show by contradiction that m covers the whole type:*}
  { fix x::'a assume "x \<notin> Field m"
--{*We assume that x is not covered and extend m at the top with x*}
    have "m \<noteq> {}"
    proof
      assume "m = {}"
      moreover have "Well_order {(x, x)}"
        by (simp add: order_on_defs refl_on_def trans_def antisym_def total_on_def Field_def)
      ultimately show False using max
        by (auto simp: I_def init_seg_of_def simp del: Field_insert)
    qed
    hence "Field m \<noteq> {}" by(auto simp:Field_def)
    moreover have "wf (m - Id)" using `Well_order m`
      by (simp add: well_order_on_def)
--{*The extension of m by x:*}
    let ?s = "{(a, x) | a. a \<in> Field m}"
    let ?m = "insert (x, x) m \<union> ?s"
    have Fm: "Field ?m = insert x (Field m)"
      by (auto simp: Field_def)
    have "Refl m" and "trans m" and "antisym m" and "Total m" and "wf (m - Id)"
      using `Well_order m` by (simp_all add: order_on_defs)
--{*We show that the extension is a well-order*}
    have "Refl ?m" using `Refl m` Fm unfolding refl_on_def by blast
    moreover have "trans ?m" using `trans m` and `x \<notin> Field m`
      unfolding trans_def Field_def by blast
    moreover have "antisym ?m" using `antisym m` and `x \<notin> Field m`
      unfolding antisym_def Field_def by blast
    moreover have "Total ?m" using `Total m` and Fm by (auto simp: total_on_def)
    moreover have "wf (?m - Id)"
    proof -
      have "wf ?s" using `x \<notin> Field m` unfolding wf_eq_minimal Field_def
        by (auto simp: Bex_def)
      thus ?thesis using `wf (m - Id)` and `x \<notin> Field m`
        wf_subset [OF `wf ?s` Diff_subset]
        unfolding Un_Diff Field_def by (auto intro: wf_Un)
    qed
    ultimately have "Well_order ?m" by (simp add: order_on_defs)
--{*We show that the extension is above m*}
    moreover have "(m, ?m) \<in> I" using `Well_order ?m` and `Well_order m` and `x \<notin> Field m`
      by (fastforce simp: I_def init_seg_of_def Field_def)
    ultimately
--{*This contradicts maximality of m:*}
    have False using max and `x \<notin> Field m` unfolding Field_def by blast
  }
  hence "Field m = UNIV" by auto
  with `Well_order m` show ?thesis by blast
qed

corollary well_order_on: "\<exists>r::'a rel. well_order_on A r"
proof -
  obtain r::"'a rel" where wo: "Well_order r" and univ: "Field r = UNIV"
    using well_ordering [where 'a = "'a"] by blast
  let ?r = "{(x, y). x \<in> A \<and> y \<in> A \<and> (x, y) \<in> r}"
  have 1: "Field ?r = A" using wo univ
    by (fastforce simp: Field_def order_on_defs refl_on_def)
  have "Refl r" and "trans r" and "antisym r" and "Total r" and "wf (r - Id)"
    using `Well_order r` by (simp_all add: order_on_defs)
  have "Refl ?r" using `Refl r` by (auto simp: refl_on_def 1 univ)
  moreover have "trans ?r" using `trans r`
    unfolding trans_def by blast
  moreover have "antisym ?r" using `antisym r`
    unfolding antisym_def by blast
  moreover have "Total ?r" using `Total r` by (simp add:total_on_def 1 univ)
  moreover have "wf (?r - Id)" by (rule wf_subset [OF `wf (r - Id)`]) blast
  ultimately have "Well_order ?r" by (simp add: order_on_defs)
  with 1 show ?thesis by auto
qed

(* Move this to Hilbert Choice and wfrec to Wellfounded*)

lemma wfrec_def_adm: "f \<equiv> wfrec R F \<Longrightarrow> wf R \<Longrightarrow> adm_wf R F \<Longrightarrow> f = F f"
  using wfrec_fixpoint by simp

lemma dependent_wf_choice:
  fixes P :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> bool"
  assumes "wf R" and adm: "\<And>f g x r. (\<And>z. (z, x) \<in> R \<Longrightarrow> f z = g z) \<Longrightarrow> P f x r = P g x r"
  assumes P: "\<And>x f. (\<And>y. (y, x) \<in> R \<Longrightarrow> P f y (f y)) \<Longrightarrow> \<exists>r. P f x r"
  shows "\<exists>f. \<forall>x. P f x (f x)"
proof (intro exI allI)
  fix x
  def f \<equiv> "wfrec R (\<lambda>f x. SOME r. P f x r)"
  from `wf R` show "P f x (f x)"
  proof (induct x)
    fix x assume "\<And>y. (y, x) \<in> R \<Longrightarrow> P f y (f y)"
    show "P f x (f x)"
    proof (subst (2) wfrec_def_adm[OF f_def `wf R`])
      show "adm_wf R (\<lambda>f x. SOME r. P f x r)"
        by (auto simp add: adm_wf_def intro!: arg_cong[where f=Eps] ext adm)
      show "P f x (Eps (P f x))"
        using P by (rule someI_ex) fact
    qed
  qed
qed

lemma (in wellorder) dependent_wellorder_choice:
  assumes "\<And>r f g x. (\<And>y. y < x \<Longrightarrow> f y = g y) \<Longrightarrow> P f x r = P g x r"
  assumes P: "\<And>x f. (\<And>y. y < x \<Longrightarrow> P f y (f y)) \<Longrightarrow> \<exists>r. P f x r"
  shows "\<exists>f. \<forall>x. P f x (f x)"
  using wf by (rule dependent_wf_choice) (auto intro!: assms)

end


(*  Author:     Tobias Nipkow
    Copyright   2000 TUM
*)

section \<open>Fixed Length Lists\<close>

theory NList
imports Main
begin

definition nlists :: "nat \<Rightarrow> 'a set \<Rightarrow> 'a list set"
  where "nlists n A = {xs. size xs = n \<and> set xs \<subseteq> A}"

lemma nlistsI: "\<lbrakk> size xs = n; set xs \<subseteq> A \<rbrakk> \<Longrightarrow> xs \<in> nlists n A"
  by (simp add: nlists_def)

text \<open>These [simp] attributes are double-edged.
 Many proofs in Jinja rely on it but they can degrade performance.\<close>

lemma nlistsE_length [simp]: "xs \<in> nlists n A \<Longrightarrow> size xs = n"
  by (simp add: nlists_def)

lemma less_lengthI: "\<lbrakk> xs \<in> nlists n A; p < n \<rbrakk> \<Longrightarrow> p < size xs"
by (simp)

lemma nlistsE_set[simp]: "xs \<in> nlists n A \<Longrightarrow> set xs \<subseteq> A"
unfolding nlists_def by (simp)

lemma nlists_mono:
assumes "A \<subseteq> B" shows "nlists n A \<subseteq> nlists n B"
proof
  fix xs assume "xs \<in> nlists n A"
  then obtain size: "size xs = n" and inA: "set xs \<subseteq> A" by (simp)
  with assms have "set xs \<subseteq> B" by simp
  with size show "xs \<in> nlists n B" by(clarsimp intro!: nlistsI)
qed

lemma nlists_n_0 [simp]: "nlists 0 A = {[]}"
unfolding nlists_def by (auto)

lemma in_nlists_Suc_iff: "(xs \<in> nlists (Suc n) A) = (\<exists>y\<in>A. \<exists>ys \<in> nlists n A. xs = y#ys)"
unfolding nlists_def by (cases "xs") auto

lemma Cons_in_nlists_Suc [iff]: "(x#xs \<in> nlists (Suc n) A) \<longleftrightarrow> (x\<in>A \<and> xs \<in> nlists n A)"
unfolding nlists_def by (auto)

lemma nlists_not_empty: "A\<noteq>{} \<Longrightarrow> \<exists>xs. xs \<in> nlists n A"
by (induct "n") (auto simp: in_nlists_Suc_iff)

lemma nlistsE_nth_in: "\<lbrakk> xs \<in> nlists n A; i < n \<rbrakk> \<Longrightarrow> xs!i \<in> A"
unfolding nlists_def by (auto)

lemma nlists_Cons_Suc [elim!]:
  "l#xs \<in> nlists n A \<Longrightarrow> (\<And>n'. n = Suc n' \<Longrightarrow> l \<in> A \<Longrightarrow> xs \<in> nlists n' A \<Longrightarrow> P) \<Longrightarrow> P"
unfolding nlists_def by (auto)

lemma nlists_appendE [elim!]:
  "a@b \<in> nlists n A \<Longrightarrow> (\<And>n1 n2. n=n1+n2 \<Longrightarrow> a \<in> nlists n1 A \<Longrightarrow> b \<in> nlists n2 A \<Longrightarrow> P) \<Longrightarrow> P"
proof -
  have "\<And>n. a@b \<in> nlists n A \<Longrightarrow> \<exists>n1 n2. n=n1+n2 \<and> a \<in> nlists n1 A \<and> b \<in> nlists n2 A"
    (is "\<And>n. ?list a n \<Longrightarrow> \<exists>n1 n2. ?P a n n1 n2")
  proof (induct a)
    fix n assume "?list [] n"
    hence "?P [] n 0 n" by simp
    thus "\<exists>n1 n2. ?P [] n n1 n2" by fast
  next
    fix n l ls
    assume "?list (l#ls) n"
    then obtain n' where n: "n = Suc n'" "l \<in> A" and n': "ls@b \<in> nlists n' A" by fastforce
    assume "\<And>n. ls @ b \<in> nlists n A \<Longrightarrow> \<exists>n1 n2. n = n1 + n2 \<and> ls \<in> nlists n1 A \<and> b \<in> nlists n2 A"
    from this and n' have "\<exists>n1 n2. n' = n1 + n2 \<and> ls \<in> nlists n1 A \<and> b \<in> nlists n2 A" .
    then obtain n1 n2 where "n' = n1 + n2" "ls \<in> nlists n1 A" "b \<in> nlists n2 A" by fast
    with n have "?P (l#ls) n (n1+1) n2" by simp
    thus "\<exists>n1 n2. ?P (l#ls) n n1 n2" by fastforce
  qed
  moreover assume "a@b \<in> nlists n A" "\<And>n1 n2. n=n1+n2 \<Longrightarrow> a \<in> nlists n1 A \<Longrightarrow> b \<in> nlists n2 A \<Longrightarrow> P"
  ultimately show ?thesis by blast
qed

lemma nlists_update_in_list [simp, intro!]:
  "\<lbrakk> xs \<in> nlists n A; x\<in>A \<rbrakk> \<Longrightarrow> xs[i := x] \<in> nlists n A"
  by (metis length_list_update nlistsE_length nlistsE_set nlistsI set_update_subsetI)

lemma nlists_appendI [intro?]:
  "\<lbrakk> a \<in> nlists n A; b \<in> nlists m A \<rbrakk> \<Longrightarrow> a @ b \<in> nlists (n+m) A"
unfolding nlists_def by (auto)

lemma nlists_append:
  "xs @ ys \<in> nlists k A \<longleftrightarrow>
   k = length(xs @ ys) \<and> xs \<in> nlists (length xs) A \<and> ys \<in> nlists (length ys) A"
unfolding nlists_def by (auto)

lemma nlists_map [simp]: "(map f xs \<in> nlists (size xs) A) = (f ` set xs \<subseteq> A)"
unfolding nlists_def by (auto)

lemma nlists_replicateI [intro]: "x \<in> A \<Longrightarrow> replicate n x \<in> nlists n A"
 by (induct n) auto

lemma nlists_set[code]: "nlists n (set xs) = set (List.n_lists n xs)"
unfolding nlists_def by (rule sym, induct n) (auto simp: image_iff length_Suc_conv)

end


(*  Title:      HOL/Cardinals/Fun_More.thy
    Author:     Andrei Popescu, TU Muenchen
    Copyright   2012

More on injections, bijections and inverses.
*)

section \<open>More on Injections, Bijections and Inverses\<close>

theory Fun_More
imports Main
begin

subsection \<open>Purely functional properties\<close>

(* unused *)
(*1*)lemma notIn_Un_bij_betw2:
assumes NIN: "b \<notin> A" and NIN': "b' \<notin> A'" and
        BIJ: "bij_betw f A A'"
shows "bij_betw f (A \<union> {b}) (A' \<union> {b'}) = (f b = b')"
proof
  assume "f b = b'"
  thus "bij_betw f (A \<union> {b}) (A' \<union> {b'})"
  using assms notIn_Un_bij_betw[of b A f A'] by auto
next
  assume *: "bij_betw f (A \<union> {b}) (A' \<union> {b'})"
  hence "f b \<in> A' \<union> {b'}"
  unfolding bij_betw_def by auto
  moreover
  {assume "f b \<in> A'"
   then obtain b1 where 1: "b1 \<in> A" and 2: "f b1 = f b" using BIJ
   by (auto simp add: bij_betw_def)
   hence "b = b1" using *
   by (auto simp add: bij_betw_def inj_on_def)
   with 1 NIN have False by auto
  }
  ultimately show "f b = b'" by blast
qed

(* unused *)
(*1*)lemma bij_betw_diff_singl:
assumes BIJ: "bij_betw f A A'" and IN: "a \<in> A"
shows "bij_betw f (A - {a}) (A' - {f a})"
proof-
  let ?B = "A - {a}"   let ?B' = "A' - {f a}"
  have "f a \<in> A'" using IN BIJ unfolding bij_betw_def by blast
  hence "a \<notin> ?B \<and> f a \<notin> ?B' \<and> A = ?B \<union> {a} \<and> A' = ?B' \<union> {f a}"
  using IN by blast
  thus ?thesis using notIn_Un_bij_betw3[of a ?B f ?B'] BIJ by simp
qed

subsection \<open>Properties involving finite and infinite sets\<close>

(* unused *)
(*1*)lemma bij_betw_inv_into_RIGHT:
assumes BIJ: "bij_betw f A A'" and SUB: "B' \<le> A'"
shows "f `((inv_into A f)`B') = B'"
using assms
proof(auto simp add: bij_betw_inv_into_right)
  let ?f' = "(inv_into A f)"
  fix a' assume *: "a' \<in> B'"
  hence "a' \<in> A'" using SUB by auto
  hence "a' = f (?f' a')"
  using BIJ by (auto simp add: bij_betw_inv_into_right)
  thus "a' \<in> f ` (?f' ` B')" using * by blast
qed

(* unused *)
(*1*)lemma bij_betw_inv_into_RIGHT_LEFT:
assumes BIJ: "bij_betw f A A'" and SUB: "B' \<le> A'" and
        IM: "(inv_into A f) ` B' = B"
shows "f ` B = B'"
proof-
  have "f`((inv_into A f)` B') = B'"
  using assms bij_betw_inv_into_RIGHT[of f A A' B'] by auto
  thus ?thesis using IM by auto
qed

(* unused *)
(*2*)lemma bij_betw_inv_into_twice:
assumes "bij_betw f A A'"
shows "\<forall>a \<in> A. inv_into A' (inv_into A f) a = f a"
proof
  let ?f' = "inv_into A f"   let ?f'' = "inv_into A' ?f'"
  have 1: "bij_betw ?f' A' A" using assms
  by (auto simp add: bij_betw_inv_into)
  fix a assume *: "a \<in> A"
  then obtain a' where 2: "a' \<in> A'" and 3: "?f' a' = a"
  using 1 unfolding bij_betw_def by force
  hence "?f'' a = a'"
  using * 1 3 by (auto simp add: bij_betw_inv_into_left)
  moreover have "f a = a'" using assms 2 3
  by (auto simp add: bij_betw_inv_into_right)
  ultimately show "?f'' a = f a" by simp
qed

subsection \<open>Properties involving Hilbert choice\<close>

(*1*)lemma bij_betw_inv_into_LEFT:
assumes BIJ: "bij_betw f A A'" and SUB: "B \<le> A"
shows "(inv_into A f)`(f ` B) = B"
using assms unfolding bij_betw_def using inv_into_image_cancel by force

(*1*)lemma bij_betw_inv_into_LEFT_RIGHT:
assumes BIJ: "bij_betw f A A'" and SUB: "B \<le> A" and
        IM: "f ` B = B'"
shows "(inv_into A f) ` B' = B"
using assms bij_betw_inv_into_LEFT[of f A A' B] by fast

subsection \<open>Other facts\<close>

(*3*)lemma atLeastLessThan_injective:
assumes "{0 ..< m::nat} = {0 ..< n}"
shows "m = n"
proof-
  {assume "m < n"
   hence "m \<in> {0 ..< n}" by auto
   hence "{0 ..< m} < {0 ..< n}" by auto
   hence False using assms by blast
  }
  moreover
  {assume "n < m"
   hence "n \<in> {0 ..< m}" by auto
   hence "{0 ..< n} < {0 ..< m}" by auto
   hence False using assms by blast
  }
  ultimately show ?thesis by force
qed

(*2*)lemma atLeastLessThan_injective2:
"bij_betw f {0 ..< m::nat} {0 ..< n} \<Longrightarrow> m = n"
using finite_atLeastLessThan[of m] finite_atLeastLessThan[of n]
      card_atLeastLessThan[of m] card_atLeastLessThan[of n]
      bij_betw_iff_card[of "{0 ..< m}" "{0 ..< n}"] by auto

(*2*)lemma atLeastLessThan_less_eq:
"({0..<m} \<le> {0..<n}) = ((m::nat) \<le> n)"
unfolding ivl_subset by arith

(*2*)lemma atLeastLessThan_less_eq2:
assumes "inj_on f {0..<(m::nat)} \<and> f ` {0..<m} \<le> {0..<n}"
shows "m \<le> n"
using assms
using finite_atLeastLessThan[of m] finite_atLeastLessThan[of n]
      card_atLeastLessThan[of m] card_atLeastLessThan[of n]
      card_inj_on_le[of f "{0 ..< m}" "{0 ..< n}"] by fastforce

(* unused *)
(*2*)lemma atLeastLessThan_less_eq3:
"(\<exists>f. inj_on f {0..<(m::nat)} \<and> f ` {0..<m} \<le> {0..<n}) = (m \<le> n)"
using atLeastLessThan_less_eq2
proof(auto)
  assume "m \<le> n"
  hence "inj_on id {0..<m} \<and> id ` {0..<m} \<subseteq> {0..<n}" unfolding inj_on_def by force
  thus "\<exists>f. inj_on f {0..<m} \<and> f ` {0..<m} \<subseteq> {0..<n}" by blast
qed

(* unused *)
(*3*)lemma atLeastLessThan_less:
"({0..<m} < {0..<n}) = ((m::nat) < n)"
proof-
  have "({0..<m} < {0..<n}) = ({0..<m} \<le> {0..<n} \<and> {0..<m} ~= {0..<n})"
  using subset_iff_psubset_eq by blast
  also have "\<dots> = (m \<le> n \<and> m ~= n)"
  using atLeastLessThan_less_eq atLeastLessThan_injective by blast
  also have "\<dots> = (m < n)" by auto
  finally show ?thesis .
qed

end


theory boolean_algebra_infinitary
  imports boolean_algebra_functional
begin

subsection \<open>Encoding infinitary Boolean operations\<close>

(**Our aim is to encode complete Boolean algebras (of sets) which we can later be used to
interpret quantified formulas (somewhat in the spirit of Boolean-valued models for set theory).*)

(**We start by defining infinite meet (infimum) and infinite join (supremum) operations,*)
definition infimum:: "('w \<sigma>)\<sigma> \<Rightarrow> 'w \<sigma>" ("\<^bold>\<And>_")
  where "\<^bold>\<And>S \<equiv> \<lambda>w. \<forall>X. S X \<longrightarrow> X w"
definition supremum::"('w \<sigma>)\<sigma> \<Rightarrow> 'w \<sigma>" ("\<^bold>\<Or>_")
  where "\<^bold>\<Or>S \<equiv> \<lambda>w. \<exists>X. S X  \<and>  X w"

(*add infimum and supremum to definition set of algebra connectives*)
declare infimum_def[conn] supremum_def[conn]

(**Infimum and supremum satisfy an infinite variant of the De Morgan laws*)
lemma iDM_a: "\<^bold>\<midarrow>(\<^bold>\<And>S) \<approx> \<^bold>\<Or>(S\<^sup>-)" unfolding order conn conn2 by force
lemma iDM_b:" \<^bold>\<midarrow>(\<^bold>\<Or>S) \<approx> \<^bold>\<And>(S\<^sup>-)" unfolding order conn conn2 by force

(**We show that the our encoded Boolean algebras are lattice-complete.*)

(**The functions below return the set of upper-/lower-bounds of a set of sets S (wrt. domain D)*)
definition upper_bounds::"('w \<sigma>)\<sigma> \<Rightarrow> ('w \<sigma>)\<sigma>" ("ub")
  where "ub S \<equiv> \<lambda>U. \<forall>X. S X \<longrightarrow> X \<preceq> U"
definition upper_bounds_restr::"('w \<sigma>)\<sigma> \<Rightarrow> ('w \<sigma>)\<sigma> \<Rightarrow> ('w \<sigma>)\<sigma>" ("ub\<^sup>_")
  where "ub\<^sup>D S \<equiv> \<lambda>U. D U \<and> (\<forall>X. S X \<longrightarrow> X \<preceq> U)"
definition lower_bounds::"('w \<sigma>)\<sigma> \<Rightarrow> ('w \<sigma>)\<sigma>" ("lb")
  where "lb S \<equiv> \<lambda>L. \<forall>X. S X \<longrightarrow> L \<preceq> X"
definition lower_bounds_restr::"('w \<sigma>)\<sigma> \<Rightarrow> ('w \<sigma>)\<sigma> \<Rightarrow> ('w \<sigma>)\<sigma>" ("lb\<^sup>_")
  where "lb\<^sup>D S \<equiv> \<lambda>L. D L \<and> (\<forall>X. S X \<longrightarrow> L \<preceq> X)"

lemma ub_char: "ub S = (let D=\<^bold>\<top> in ub\<^sup>D S) " by (simp add: top_def upper_bounds_def upper_bounds_restr_def)
lemma lb_char: "lb S = (let D=\<^bold>\<top> in lb\<^sup>D S) " by (simp add: top_def lower_bounds_def lower_bounds_restr_def)

(**Similarly, the functions below return the set of least/greatest upper-/lower-bounds for S (wrt. D)*)
definition lub::"('w \<sigma>)\<sigma> \<Rightarrow> ('w \<sigma>)\<sigma>" ("lub")
  where "lub S \<equiv> \<lambda>U. ub S U \<and> (\<forall>X. ub S X \<longrightarrow> U \<preceq> X)"
definition lub_restr::"('w \<sigma>)\<sigma> \<Rightarrow> ('w \<sigma>)\<sigma> \<Rightarrow> ('w \<sigma>)\<sigma>" ("lub\<^sup>_")
  where "lub\<^sup>D S \<equiv> \<lambda>U. ub\<^sup>D S U \<and> (\<forall>X. ub\<^sup>D S X \<longrightarrow> U \<preceq> X)"
definition glb::"('w \<sigma>)\<sigma> \<Rightarrow> ('w \<sigma>)\<sigma>" ("glb")
  where "glb S \<equiv> \<lambda>L. lb S L \<and> (\<forall>X. lb S X \<longrightarrow> X \<preceq> L)"
definition glb_restr::"('w \<sigma>)\<sigma> \<Rightarrow> ('w \<sigma>)\<sigma> \<Rightarrow> ('w \<sigma>)\<sigma>" ("glb\<^sup>_")
  where "glb\<^sup>D S \<equiv> \<lambda>L. lb\<^sup>D S L \<and> (\<forall>X. lb\<^sup>D S X \<longrightarrow> X \<preceq> L)"

lemma lub_char: "lub S = (let D=\<^bold>\<top> in lub\<^sup>D S) " by (simp add: lub_def lub_restr_def ub_char)
lemma glb_char: "glb S = (let D=\<^bold>\<top> in glb\<^sup>D S) " by (simp add: glb_def glb_restr_def lb_char)

(**Note that the term \<^bold>\<top> below denotes the top element in the algebra of sets of sets (i.e. the powerset)*)
lemma sup_lub: "lub S \<^bold>\<Or>S" unfolding lub_def upper_bounds_def supremum_def subset_def by blast
lemma sup_exist_unique: "\<forall>S. \<exists>!X. lub S X" by (meson lub_def setequ_char setequ_ext sup_lub)
lemma inf_glb: "glb S \<^bold>\<And>S" unfolding glb_def lower_bounds_def infimum_def subset_def by blast
lemma inf_exist_unique: "\<forall>S. \<exists>!X. glb S X" by (meson glb_def inf_glb setequ_char setequ_ext)

lemma inf_empty: "isEmpty S \<Longrightarrow> \<^bold>\<And>S \<approx> \<^bold>\<top>" unfolding order conn by simp
lemma sup_empty: "isEmpty S \<Longrightarrow> \<^bold>\<Or>S \<approx> \<^bold>\<bottom>" unfolding order conn by simp

(**The property of being closed under arbitrary (resp. nonempty) supremum/infimum.*)
definition infimum_closed :: "('w \<sigma>)\<sigma> \<Rightarrow> bool"
  where "infimum_closed S  \<equiv> \<forall>D. D \<preceq> S \<longrightarrow> S(\<^bold>\<And>D)" (*observe that D can be empty*)
definition supremum_closed :: "('w \<sigma>)\<sigma> \<Rightarrow> bool"
  where "supremum_closed S \<equiv> \<forall>D. D \<preceq> S \<longrightarrow> S(\<^bold>\<Or>D)" (*observe that D can be empty*)
definition infimum_closed' :: "('w \<sigma>)\<sigma> \<Rightarrow> bool"
  where"infimum_closed' S  \<equiv> \<forall>D. nonEmpty D \<and> D \<preceq> S \<longrightarrow> S(\<^bold>\<And>D)"
definition supremum_closed' :: "('w \<sigma>)\<sigma> \<Rightarrow> bool"
  where "supremum_closed' S \<equiv> \<forall>D. nonEmpty D \<and> D \<preceq> S \<longrightarrow> S(\<^bold>\<Or>D)"

(**Note that arbitrary infimum- (resp. supremum-) closed sets include the top (resp. bottom) element.*)
lemma "infimum_closed S \<Longrightarrow> S \<^bold>\<top>" unfolding infimum_closed_def conn order by force
lemma "supremum_closed S \<Longrightarrow> S \<^bold>\<bottom>" unfolding supremum_closed_def conn order by force
(**However, the above does not hold for non-empty infimum- (resp. supremum-) closed sets.*)
lemma "infimum_closed' S \<Longrightarrow> S \<^bold>\<top>" nitpick oops
lemma "supremum_closed' S \<Longrightarrow> S \<^bold>\<bottom>" nitpick oops

(**We have in fact the following characterizations for the notions above:*)
lemma inf_closed_char: "infimum_closed S = (infimum_closed' S \<and> S \<^bold>\<top>)"
  unfolding infimum_closed'_def infimum_closed_def by (metis bottom_def infimum_closed_def infimum_def setequ_char setequ_ext subset_def top_def)
lemma sup_closed_char: "supremum_closed S = (supremum_closed' S \<and> S \<^bold>\<bottom>)"
  unfolding supremum_closed'_def supremum_closed_def by (metis (no_types, opaque_lifting) L14 L9 bottom_def setequ_ext subset_def supremum_def)

lemma inf_sup_closed_dc: "infimum_closed S = supremum_closed S\<^sup>-" by (smt (verit) BA_dn iDM_a iDM_b infimum_closed_def setequ_ext sdfun_dcompl_def subset_def supremum_closed_def)
lemma inf_sup_closed_dc': "infimum_closed' S = supremum_closed' S\<^sup>-" by (smt (verit) dualcompl_invol iDM_a infimum_closed'_def sdfun_dcompl_def setequ_ext subset_def supremum_closed'_def)

(**We check some further properties:*)
lemma fp_inf_sup_closed_dual: "infimum_closed (fp \<phi>) = supremum_closed (fp \<phi>\<^sup>d)"
  by (simp add: fp_dual inf_sup_closed_dc)
lemma fp_inf_sup_closed_dual': "infimum_closed' (fp \<phi>) = supremum_closed' (fp \<phi>\<^sup>d)"
  by (simp add: fp_dual inf_sup_closed_dc')

(**We verify that being infimum-closed' (resp. supremum-closed') entails being meet-closed (resp. join-closed).*)
lemma inf_meet_closed: "\<forall>S. infimum_closed' S \<longrightarrow> meet_closed S" proof -
  { fix S::"'w \<sigma> \<Rightarrow> bool"
    { assume inf_closed: "infimum_closed' S"
      hence "meet_closed S" proof -
        { fix X::"'w \<sigma>" and Y::"'w \<sigma>"
          let ?D="\<lambda>Z. Z=X \<or> Z=Y"
          { assume "S X \<and> S Y"
            hence "?D \<preceq> S" using subset_def by blast
            moreover have "nonEmpty ?D" by auto
            ultimately have "S(\<^bold>\<And>?D)" using inf_closed infimum_closed'_def by (smt (z3))
            hence "S(\<lambda>w. \<forall>Z. (Z=X \<or> Z=Y) \<longrightarrow> Z w)" unfolding infimum_def by simp
            moreover have "(\<lambda>w. \<forall>Z. (Z=X \<or> Z=Y) \<longrightarrow> Z w) = (\<lambda>w. X w \<and> Y w)" by auto
            ultimately have "S(\<lambda>w. X w \<and> Y w)" by simp
          } hence "(S X \<and> S Y) \<longrightarrow> S(X \<^bold>\<and> Y)" unfolding conn by (rule impI)
        } thus ?thesis unfolding meet_closed_def by simp  qed
    } hence "infimum_closed' S \<longrightarrow> meet_closed S" by simp
  } thus ?thesis by (rule allI)
qed
lemma sup_join_closed: "\<forall>P. supremum_closed' P \<longrightarrow> join_closed P" proof -
  { fix S::"'w \<sigma> \<Rightarrow> bool"
    { assume sup_closed: "supremum_closed' S"
      hence "join_closed S" proof -
        { fix X::"'w \<sigma>" and Y::"'w \<sigma>"
          let ?D="\<lambda>Z. Z=X \<or> Z=Y"
          { assume "S X \<and> S Y"
            hence "?D \<preceq> S" using subset_def by blast
            moreover have "nonEmpty ?D" by auto
            ultimately have "S(\<^bold>\<Or>?D)" using sup_closed supremum_closed'_def by (smt (z3))
            hence "S(\<lambda>w. \<exists>Z. (Z=X \<or> Z=Y) \<and> Z w)" unfolding supremum_def by simp
            moreover have "(\<lambda>w. \<exists>Z. (Z=X \<or> Z=Y) \<and> Z w) = (\<lambda>w. X w \<or> Y w)" by auto
            ultimately have "S(\<lambda>w. X w \<or> Y w)" by simp
          } hence "(S X \<and> S Y) \<longrightarrow> S(X \<^bold>\<or> Y)" unfolding conn by (rule impI)
        } thus ?thesis unfolding join_closed_def by simp qed
    } hence "supremum_closed' S \<longrightarrow> join_closed S" by simp
  } thus ?thesis by (rule allI)
qed

end


section {* Finite sets: extra functions and properties *}

theory FSet_extra
imports
  "~~/src/HOL/Library/FSet"
  "~~/src/HOL/Library/Countable_Set_Type"
begin

setup_lifting type_definition_fset

notation fempty ("\<lbrace>\<rbrace>")
notation fset ("\<langle>_\<rangle>\<^sub>f")
notation fminus (infixl "-\<^sub>f" 65)

syntax
  "_FinFset" :: "args => 'a fset"    ("\<lbrace>(_)\<rbrace>")

translations
  "\<lbrace>x, xs\<rbrace>" == "CONST finsert x \<lbrace>xs\<rbrace>"
  "\<lbrace>x\<rbrace>" == "CONST finsert x \<lbrace>\<rbrace>"

term "fBall"

syntax
  "_fBall" :: "pttrn => 'a fset => bool => bool" ("(3\<forall> _|\<in>|_./ _)" [0, 0, 10] 10)
  "_fBex"  :: "pttrn => 'a fset => bool => bool" ("(3\<exists> _|\<in>|_./ _)" [0, 0, 10] 10)

translations
  "\<forall> x|\<in>|A. P" == "CONST fBall A (%x. P)"
  "\<exists> x|\<in>|A. P" == "CONST fBex A (%x. P)"

definition FUnion :: "'a fset fset \<Rightarrow> 'a fset" ("\<Union>\<^sub>f_" [90] 90) where
"FUnion xs = Abs_fset (\<Union>x\<in>\<langle>xs\<rangle>\<^sub>f. \<langle>x\<rangle>\<^sub>f)"

definition FInter :: "'a fset fset \<Rightarrow> 'a fset" ("\<Inter>\<^sub>f_" [90] 90) where
"FInter xs = Abs_fset (\<Inter>x\<in>\<langle>xs\<rangle>\<^sub>f. \<langle>x\<rangle>\<^sub>f)"

text {* Finite power set *}

definition FinPow :: "'a fset \<Rightarrow> 'a fset fset" where
"FinPow xs = Abs_fset (Abs_fset ` Pow \<langle>xs\<rangle>\<^sub>f)"

text {* Set of all finite subsets of a set *}

definition Fow :: "'a set \<Rightarrow> 'a fset set" where
"Fow A = {x. \<langle>x\<rangle>\<^sub>f \<subseteq> A}"

declare Abs_fset_inverse [simp]

lemma fset_intro:
  "fset x = fset y \<Longrightarrow> x = y"
  by (simp add:fset_inject)

lemma fset_elim:
  "\<lbrakk> x = y; fset x = fset y \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P"
  by (auto)

lemma fmember_intro:
  "\<lbrakk> x \<in> fset(xs) \<rbrakk> \<Longrightarrow> x |\<in>| xs"
  by (metis fmember.rep_eq)

lemma fmember_elim:
  "\<lbrakk> x |\<in>| xs; x \<in> fset(xs) \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P"
  by (metis fmember.rep_eq)

lemma fnmember_intro [intro]:
  "\<lbrakk> x \<notin> fset(xs) \<rbrakk> \<Longrightarrow> x |\<notin>| xs"
  by (metis fmember.rep_eq)

lemma fnmember_elim [elim]:
  "\<lbrakk> x |\<notin>| xs; x \<notin> fset(xs) \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P"
  by (metis fmember.rep_eq)

lemma fsubset_intro [intro]:
  "\<langle>xs\<rangle>\<^sub>f \<subseteq> \<langle>ys\<rangle>\<^sub>f \<Longrightarrow> xs |\<subseteq>| ys"
  by (metis less_eq_fset.rep_eq)

lemma fsubset_elim [elim]:
  "\<lbrakk> xs |\<subseteq>| ys; \<langle>xs\<rangle>\<^sub>f \<subseteq> \<langle>ys\<rangle>\<^sub>f \<Longrightarrow> P \<rbrakk> \<Longrightarrow> P"
  by (metis less_eq_fset.rep_eq)

lemma fBall_intro [intro]:
  "Ball \<langle>A\<rangle>\<^sub>f P \<Longrightarrow> fBall A P"
  by (metis (poly_guards_query) fBallI fmember.rep_eq)

lemma fBall_elim [elim]:
  "\<lbrakk> fBall A P; Ball \<langle>A\<rangle>\<^sub>f P \<Longrightarrow> Q \<rbrakk> \<Longrightarrow> Q"
  by (metis fBallE fmember.rep_eq)

lift_definition finset :: "'a list \<Rightarrow> 'a fset" is set ..

context linorder
begin

lemma sorted_list_of_set_inj:
  "\<lbrakk> finite xs; finite ys; sorted_list_of_set xs = sorted_list_of_set ys \<rbrakk>
   \<Longrightarrow> xs = ys"
  apply (simp add:sorted_list_of_set_def)
  apply (induct xs rule:finite_induct)
  apply (induct ys rule:finite_induct)
  apply (simp_all)
  apply (metis finite.insertI insert_not_empty sorted_list_of_set_def sorted_list_of_set_empty sorted_list_of_set_eq_Nil_iff)
  apply (metis finite.insertI finite_list set_remdups set_sort sorted_list_of_set_def sorted_list_of_set_sort_remdups)
done

definition flist :: "'a fset \<Rightarrow> 'a list" where
"flist xs = sorted_list_of_set (fset xs)"

lemma flist_inj: "inj flist"
  apply (simp add:flist_def inj_on_def)
  apply (clarify)
  apply (subgoal_tac "fset x = fset y")
  apply (simp add:fset_inject)
  apply (rule sorted_list_of_set_inj, simp_all)
done

lemma flist_props [simp]:
  "sorted (flist xs)"
  "distinct (flist xs)"
  by (simp_all add:flist_def)

lemma flist_empty [simp]:
  "flist \<lbrace>\<rbrace> = []"
  by (simp add:flist_def)

lemma flist_inv [simp]: "finset (flist xs) = xs"
  by (simp add:finset_def flist_def fset_inverse)

lemma flist_set [simp]: "set (flist xs) = fset xs"
  by (simp add:finset_def flist_def fset_inverse)

lemma fset_inv [simp]: "\<lbrakk> sorted xs; distinct xs \<rbrakk> \<Longrightarrow> flist (finset xs) = xs"
  apply (simp add:finset_def flist_def fset_inverse)
  apply (metis finset.abs_eq finset.rep_eq local.sorted_list_of_set_sort_remdups local.sorted_sort_id remdups_id_iff_distinct)
done

lemma fcard_flist:
  "fcard xs = length (flist xs)"
  apply (simp add:fcard_def)
  apply (fold flist_set)
  apply (unfold distinct_card[OF flist_props(2)])
  apply (rule refl)
done

lemma flist_nth:
  "i < fcard vs \<Longrightarrow> flist vs ! i |\<in>| vs"
  apply (simp add: fmember_def flist_def fcard_def)
  apply (metis distinct_card finite_fset nth_mem sorted_list_of_set)
done

definition fmax :: "'a fset \<Rightarrow> 'a" where
"fmax xs = (if (xs = \<lbrace>\<rbrace>) then undefined else last (flist xs))"

end

definition flists :: "'a fset \<Rightarrow> 'a list set" where
"flists A = {xs. distinct xs \<and> finset xs = A}"

lemma flists_nonempty: "\<exists> xs. xs \<in> flists A"
  apply (simp add: flists_def)
  apply (metis Abs_fset_cases Abs_fset_inverse finite_distinct_list finite_fset finset.rep_eq)
done

lemma flists_elem_uniq: "\<lbrakk> x \<in> flists A; x \<in> flists B \<rbrakk> \<Longrightarrow> A = B"
  by (simp add: flists_def)

definition flist_arb :: "'a fset \<Rightarrow> 'a list" where
"flist_arb A = (SOME xs. xs \<in> flists A)"

lemma flist_arb_distinct [simp]: "distinct (flist_arb A)"
  by (metis (mono_tags) flist_arb_def flists_def flists_nonempty mem_Collect_eq someI_ex)

lemma flist_arb_inv [simp]: "finset (flist_arb A) = A"
  by (metis (mono_tags) flist_arb_def flists_def flists_nonempty mem_Collect_eq someI_ex)

lemma flist_arb_inj:
  "inj flist_arb"
  by (metis flist_arb_inv injI)

lemma flist_arb_lists: "flist_arb ` Fow A \<subseteq> lists A"
  apply (auto)
  using Fow_def finset.rep_eq apply fastforce
done

lemma countable_Fow:
  fixes A :: "'a set"
  assumes "countable A"
  shows "countable (Fow A)"
proof -
  from assms obtain to_nat_list :: "'a list \<Rightarrow> nat" where "inj_on to_nat_list (lists A)"
    by blast
  thus ?thesis
    apply (simp add: countable_def)
    apply (rule_tac x="to_nat_list \<circ> flist_arb" in exI)
    apply (rule comp_inj_on)
    apply (metis flist_arb_inv inj_on_def)
    apply (simp add: flist_arb_lists subset_inj_on)
  done
qed

definition flub :: "'a fset set \<Rightarrow> 'a fset \<Rightarrow> 'a fset" where
"flub A t = (if (\<forall> a\<in>A. a |\<subseteq>| t) then Abs_fset (\<Union>x\<in>A. \<langle>x\<rangle>\<^sub>f) else t)"

lemma finite_Union_subsets:
  "\<lbrakk> \<forall> a \<in> A. a \<subseteq> b; finite b \<rbrakk> \<Longrightarrow> finite (\<Union>A)"
  by (metis Sup_le_iff finite_subset)

lemma finite_UN_subsets:
  "\<lbrakk> \<forall> a \<in> A. B a \<subseteq> b; finite b \<rbrakk> \<Longrightarrow> finite (\<Union>a\<in>A. B a)"
  by (metis UN_subset_iff finite_subset)

lemma flub_rep_eq:
  "\<langle>flub A t\<rangle>\<^sub>f = (if (\<forall> a\<in>A. a |\<subseteq>| t) then (\<Union>x\<in>A. \<langle>x\<rangle>\<^sub>f) else \<langle>t\<rangle>\<^sub>f)"
  apply (subgoal_tac "(if (\<forall> a\<in>A. a |\<subseteq>| t) then (\<Union>x\<in>A. \<langle>x\<rangle>\<^sub>f) else \<langle>t\<rangle>\<^sub>f) \<in> {x. finite x}")
  apply (auto simp add:flub_def Abs_fset_inverse)
  apply (rule finite_UN_subsets[of _ _ "\<langle>t\<rangle>\<^sub>f"])
  apply (auto)
done

definition fglb :: "'a fset set \<Rightarrow> 'a fset \<Rightarrow> 'a fset" where
"fglb A t = (if (A = {}) then t else Abs_fset (\<Inter>x\<in>A. \<langle>x\<rangle>\<^sub>f))"

lemma fglb_rep_eq:
  "\<langle>fglb A t\<rangle>\<^sub>f = (if (A = {}) then \<langle>t\<rangle>\<^sub>f else (\<Inter>x\<in>A. \<langle>x\<rangle>\<^sub>f))"
  apply (subgoal_tac "(if (A = {}) then \<langle>t\<rangle>\<^sub>f else (\<Inter>x\<in>A. \<langle>x\<rangle>\<^sub>f)) \<in> {x. finite x}")
  apply (metis Abs_fset_inverse fglb_def)
  apply (auto)
  apply (metis finite_INT finite_fset)
done

lemma FinPow_rep_eq [simp]:
  "fset (FinPow xs) = {ys. ys |\<subseteq>| xs}"
  apply (subgoal_tac "finite (Abs_fset ` Pow \<langle>xs\<rangle>\<^sub>f)")
  apply (auto simp add:Abs_fset_inverse fmember_def FinPow_def)
  apply (subgoal_tac "finite xa")
  apply (auto simp add:Abs_fset_inverse)
  apply (metis finite_fset finite_subset)
  apply (metis (full_types) Pow_iff fset_inverse imageI less_eq_fset.rep_eq)
done

lemma FUnion_rep_eq [simp]:
  "\<langle>\<Union>\<^sub>f xs\<rangle>\<^sub>f = (\<Union>x\<in>\<langle>xs\<rangle>\<^sub>f. \<langle>x\<rangle>\<^sub>f)"
  by (simp add:FUnion_def Abs_fset_inverse)

lemma FInter_rep_eq [simp]:
  "xs \<noteq> \<lbrace>\<rbrace> \<Longrightarrow> \<langle>\<Inter>\<^sub>f xs\<rangle>\<^sub>f = (\<Inter>x\<in>\<langle>xs\<rangle>\<^sub>f. \<langle>x\<rangle>\<^sub>f)"
  apply (simp add:FInter_def)
  apply (subgoal_tac "finite (\<Inter>x\<in>\<langle>xs\<rangle>\<^sub>f. \<langle>x\<rangle>\<^sub>f)")
  apply (simp add:Abs_fset_inverse)
  apply (metis (poly_guards_query) bot_fset.rep_eq fglb_rep_eq finite_fset fset_inverse)
done

lemma FUnion_empty [simp]:
  "\<Union>\<^sub>f \<lbrace>\<rbrace> = \<lbrace>\<rbrace>"
  by (auto simp add:FUnion_def fmember_def Abs_fset_inverse)

lemma FinPow_member [simp]:
  "xs |\<in>| FinPow xs"
  by (auto simp add:fmember_def)

lemma FUnion_FinPow [simp]:
  "\<Union>\<^sub>f (FinPow x) = x"
  by (auto simp add:fmember_def less_eq_fset_def)

lemma Fow_mem [iff]: "x \<in> Fow A \<longleftrightarrow> \<langle>x\<rangle>\<^sub>f \<subseteq> A"
  by (auto simp add:Fow_def)

lemma Fow_UNIV [simp]: "Fow UNIV = UNIV"
  by (simp add:Fow_def)

lift_definition FMax :: "('a::linorder) fset \<Rightarrow> 'a" is "Max" .

end


theory Locations
imports "../IrisCore/OFEs"
begin

section \<open> Locations \<close>
text \<open> Based on \<^url>\<open>https://gitlab.mpi-sws.org/iris/iris/-/blob/master/iris_heap_lang/locations.v\<close> \<close>

datatype loc = Loc (loc_car: int)

instantiation loc :: ord begin
definition less_eq_loc :: "loc \<Rightarrow> loc \<Rightarrow> bool" where
  "less_eq_loc l1 l2 = ((loc_car l1) \<le> (loc_car l2))"
definition less_loc :: "loc \<Rightarrow> loc \<Rightarrow> bool" where
  "less_loc l1 l2 = ((loc_car l1) < (loc_car l2))"
instance ..
end

instantiation loc :: linorder begin
instance proof qed (auto simp: less_eq_loc_def less_loc_def loc.expand)
end

definition loc_add :: "loc \<Rightarrow> int \<Rightarrow> loc" (infixl "+\<^sub>\<iota>" 60) where
  "loc_add l off = Loc (loc_car l + off)"

lemma loc_add_assoc:  "l +\<^sub>\<iota> i +\<^sub>\<iota> j = l +\<^sub>\<iota> (i + j)"
  by (simp add: loc_add_def)

lemma loc_add_0: "l +\<^sub>\<iota> 0 = l"
  by (simp add: loc_add_def)

lemma loc_ranges: "{(l+\<^sub>\<iota>i) |i. i\<in>{0..<n}} = {l..<(l+\<^sub>\<iota>n)}"
  by (auto simp: less_eq_loc_def less_loc_def loc_add_def, smt (z3) loc.exhaust_sel)

lemma loc_set_lift: "ls = Loc ` (loc_car ` ls)"
  unfolding image_def by auto

lemma loc_set_lift': "loc_car ` {l..<u::loc} = {loc_car l..<loc_car u}"
  apply (auto simp: less_eq_loc_def less_loc_def)
  by (metis atLeastLessThan_iff image_eqI less_eq_loc_def linorder_not_le loc.sel)

lemma finite_atLeastLessThan_loc [iff]: "finite {l..<u::loc}"
apply (subst loc_set_lift[of "{l..<u::loc}"])
apply (rule finite_imageI)
unfolding loc_set_lift'
by (rule finite_atLeastLessThan_int)

definition fresh_locs :: "loc list \<Rightarrow> loc" where
  "fresh_locs ls = Loc (fold (\<lambda>k r. max (1+loc_car k) r) ls 1)"

locale fresh_loc_properties begin
lemma max_fold_mono:
  "l\<le>u \<Longrightarrow> fold (\<lambda>k r. max (1+loc_car k) r) ls l \<le> fold (\<lambda>k r. max (1+loc_car k) r) ls u"
  by (induction ls arbitrary: l u) auto

lemma fresh_loc_cons_mono: "loc_car (fresh_locs ls) \<le> loc_car (fresh_locs (l#ls))"
  by (simp add: fresh_locs_def max_fold_mono)

lemma fresh_locs_strict: "l \<in> set ls \<Longrightarrow> loc_car l < loc_car (fresh_locs ls)"
proof (induction ls)
case (Cons a ls)
  then show ?case proof (cases "l=a")
    case True
    have aux: "x < fold (\<lambda>k r. max (1+loc_car k) r) ls (max (1+x) 1)" for x
      by (induction ls; auto) (smt (verit, best) max_fold_mono)
    from True show ?thesis by (simp add: fresh_locs_def)(rule aux[of "loc_car a"])
  next
    case False
    with Cons fresh_loc_cons_mono order_less_le_trans show ?thesis by fastforce
  qed
qed (simp)
end

lemma fresh_locs_fresh:
  assumes "(0 \<le> i)"
  shows "fresh_locs ls +\<^sub>\<iota> i \<notin> (set ls)"
proof
  assume "fresh_locs ls +\<^sub>\<iota> i \<in> set ls"
  hence "loc_car (fresh_locs ls +\<^sub>\<iota> i) < loc_car (fresh_locs ls)"
    by (rule fresh_loc_properties.fresh_locs_strict)
  with assms show "False" by (simp add: loc_add_def)
qed

instantiation loc :: ofe begin
definition n_equiv_loc :: "nat \<Rightarrow> loc \<Rightarrow> loc \<Rightarrow> bool" where "n_equiv_loc _ \<equiv> (=)"
definition ofe_eq_loc :: "loc \<Rightarrow> loc \<Rightarrow> bool" where "ofe_eq_loc \<equiv> (=)"
instance by standard (auto simp: n_equiv_loc_def ofe_eq_loc_def)
end

instance loc :: discrete by standard (auto simp: n_equiv_loc_def ofe_eq_loc_def)
end


(* This Isabelle theory is produced using the TIP tool offered at the following website:
     https://github.com/tip-org/tools
   This file was originally provided as part of TIP benchmark at the following website:
     https://github.com/tip-org/benchmarks
   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly
   to make it compatible with Isabelle2017.
\:w
   Some proofs were added by Yutaka Nagashima.*)
  theory TIP_sort_nat_StoogeSortCount
  imports "../../Test_Base"
begin

datatype ('a, 'b) pair = pair2 "'a" "'b"

datatype 'a list = nil2 | cons2 "'a" "'a list"

datatype Nat = Z | S "Nat"

fun x :: "'a list => 'a list => 'a list" where
  "x (nil2) z = z"
| "x (cons2 z2 xs) z = cons2 z2 (x xs z)"

fun reverse :: "'a list => 'a list" where
  "reverse (nil2) = nil2"
| "reverse (cons2 z xs) = x (reverse xs) (cons2 z (nil2))"

fun plus :: "Nat => Nat => Nat" where
  "plus (Z) z = z"
| "plus (S z2) z = S (plus z2 z)"

fun minus :: "Nat => Nat => Nat" where
  "minus (Z) z = Z"
| "minus (S z2) (S y2) = minus z2 y2"

fun lt :: "Nat => Nat => bool" where
  "lt y (Z) = False"
| "lt (Z) (S z2) = True"
| "lt (S n) (S z2) = lt n z2"

fun length :: "'a list => Nat" where
  "length (nil2) = Z"
| "length (cons2 z l) = plus (S Z) (length l)"

fun le :: "Nat => Nat => bool" where
  "le (Z) z = True"
| "le (S z2) (Z) = False"
| "le (S z2) (S x2) = le z2 x2"

fun sort2 :: "Nat => Nat => Nat list" where
  "sort2 y z =
   (if le y z then cons2 y (cons2 z (nil2)) else
      cons2 z (cons2 y (nil2)))"

fun take :: "Nat => 'a list => 'a list" where
  "take y z =
   (if le y Z then nil2 else
      (case z of
         nil2 => nil2
         | cons2 z2 xs => (case y of S x2 => cons2 z2 (take x2 xs))))"

(*fun did not finish the proof*)
function idiv :: "Nat => Nat => Nat" where
  "idiv y z = (if lt y z then Z else S (idiv (minus y z) z))"
  by pat_completeness auto

fun drop :: "Nat => 'a list => 'a list" where
  "drop y z =
   (if le y Z then z else
      (case z of
         nil2 => nil2
         | cons2 z2 xs1 => (case y of S x2 => drop x2 xs1)))"

fun splitAt :: "Nat => 'a list =>
              (('a list), ('a list)) pair" where
  "splitAt y z = pair2 (take y z) (drop y z)"

function stooge1sort2 :: "Nat list => Nat list"
  and stoogesort :: "Nat list => Nat list"
  and stooge1sort1 :: "Nat list => Nat list" where
  "stooge1sort2 y =
   (case splitAt (idiv (length y) (S (S (S Z)))) (reverse y) of
      pair2 ys2 zs2 => x (stoogesort zs2) (reverse ys2))"
| "stoogesort (nil2) = nil2"
| "stoogesort (cons2 z (nil2)) = cons2 z (nil2)"
| "stoogesort (cons2 z (cons2 y2 (nil2))) = sort2 z y2"
| "stoogesort (cons2 z (cons2 y2 (cons2 x3 x4))) =
     stooge1sort2
       (stooge1sort1 (stooge1sort2 (cons2 z (cons2 y2 (cons2 x3 x4)))))"
| "stooge1sort1 y =
     (case splitAt (idiv (length y) (S (S (S Z)))) y of
        pair2 ys2 zs1 => x ys2 (stoogesort zs1))"
  by pat_completeness auto

fun count :: "'a => 'a list => Nat" where
  "count y (nil2) = Z"
| "count y (cons2 z2 ys) =
     (if (y = z2) then plus (S Z) (count y ys) else count y ys)"

theorem property0 :
  "((count y (stoogesort xs)) = (count y xs))"
  oops

end


(*  Author: Tobias Nipkow, Alex Krauss  *)

header "Regular sets"

theory Regular_Set
imports Main
begin

type_synonym 'a lang = "'a list set"

definition conc :: "'a lang \<Rightarrow> 'a lang \<Rightarrow> 'a lang" (infixr "@@" 75) where
"A @@ B = {xs@ys | xs ys. xs:A & ys:B}"

text {* checks the code preprocessor for set comprehensions *}
export_code conc checking SML

overloading lang_pow == "compow :: nat \<Rightarrow> 'a lang \<Rightarrow> 'a lang"
begin
  primrec lang_pow :: "nat \<Rightarrow> 'a lang \<Rightarrow> 'a lang" where
  "lang_pow 0 A = {[]}" |
  "lang_pow (Suc n) A = A @@ (lang_pow n A)"
end

text {* for code generation *}

definition lang_pow :: "nat \<Rightarrow> 'a lang \<Rightarrow> 'a lang" where
  lang_pow_code_def [code_abbrev]: "lang_pow = compow"

hide_const (open) lang_pow

definition star :: "'a lang \<Rightarrow> 'a lang" where
"star A = (\<Union>n. A ^^ n)"

subsection{* @{term "op @@"} *}

lemma concI[simp,intro]: "u : A \<Longrightarrow> v : B \<Longrightarrow> u@v : A @@ B"
by (auto simp add: conc_def)

lemma concE[elim]:
assumes "w \<in> A @@ B"
obtains u v where "u \<in> A" "v \<in> B" "w = u@v"
using assms by (auto simp: conc_def)

lemma conc_mono: "A \<subseteq> C \<Longrightarrow> B \<subseteq> D \<Longrightarrow> A @@ B \<subseteq> C @@ D"
by (auto simp: conc_def)

lemma conc_empty[simp]: shows "{} @@ A = {}" and "A @@ {} = {}"
by auto

lemma conc_epsilon[simp]: shows "{[]} @@ A = A" and "A @@ {[]} = A"
by (simp_all add:conc_def)

lemma conc_assoc: "(A @@ B) @@ C = A @@ (B @@ C)"
by (auto elim!: concE) (simp only: append_assoc[symmetric] concI)

lemma conc_Un_distrib:
shows "A @@ (B \<union> C) = A @@ B \<union> A @@ C"
and   "(A \<union> B) @@ C = A @@ C \<union> B @@ C"
by auto

lemma conc_UNION_distrib:
shows "A @@ UNION I M = UNION I (%i. A @@ M i)"
and   "UNION I M @@ A = UNION I (%i. M i @@ A)"
by auto

lemma conc_subset_lists: "A \<subseteq> lists S \<Longrightarrow> B \<subseteq> lists S \<Longrightarrow> A @@ B \<subseteq> lists S"
by(fastforce simp: conc_def in_lists_conv_set)

lemma Nil_in_conc[simp]: "[] \<in> A @@ B \<longleftrightarrow> [] \<in> A \<and> [] \<in> B"
by (metis append_is_Nil_conv concE concI)

lemma concI_if_Nil1: "[] \<in> A \<Longrightarrow> xs : B \<Longrightarrow> xs \<in> A @@ B"
by (metis append_Nil concI)

lemma conc_Diff_if_Nil1: "[] \<in> A \<Longrightarrow> A @@ B = (A - {[]}) @@ B \<union> B"
by (fastforce elim: concI_if_Nil1)

lemma concI_if_Nil2: "[] \<in> B \<Longrightarrow> xs : A \<Longrightarrow> xs \<in> A @@ B"
by (metis append_Nil2 concI)

lemma conc_Diff_if_Nil2: "[] \<in> B \<Longrightarrow> A @@ B = A @@ (B - {[]}) \<union> A"
by (fastforce elim: concI_if_Nil2)

lemma singleton_in_conc:
  "[x] : A @@ B \<longleftrightarrow> [x] : A \<and> [] : B \<or> [] : A \<and> [x] : B"
by (fastforce simp: Cons_eq_append_conv append_eq_Cons_conv
       conc_Diff_if_Nil1 conc_Diff_if_Nil2)

subsection{* @{term "A ^^ n"} *}

lemma lang_pow_add: "A ^^ (n + m) = A ^^ n @@ A ^^ m"
by (induct n) (auto simp: conc_assoc)

lemma lang_pow_empty: "{} ^^ n = (if n = 0 then {[]} else {})"
by (induct n) auto

lemma lang_pow_empty_Suc[simp]: "({}::'a lang) ^^ Suc n = {}"
by (simp add: lang_pow_empty)

lemma length_lang_pow_ub:
  "ALL w : A. length w \<le> k \<Longrightarrow> w : A^^n \<Longrightarrow> length w \<le> k*n"
by(induct n arbitrary: w) (fastforce simp: conc_def)+

lemma length_lang_pow_lb:
  "ALL w : A. length w \<ge> k \<Longrightarrow> w : A^^n \<Longrightarrow> length w \<ge> k*n"
by(induct n arbitrary: w) (fastforce simp: conc_def)+

lemma lang_pow_subset_lists: "A \<subseteq> lists S \<Longrightarrow> A ^^ n \<subseteq> lists S"
by(induction n)(auto simp: conc_subset_lists[OF assms])

subsection{* @{const star} *}

lemma star_subset_lists: "A \<subseteq> lists S \<Longrightarrow> star A \<subseteq> lists S"
unfolding star_def by(blast dest: lang_pow_subset_lists)

lemma star_if_lang_pow[simp]: "w : A ^^ n \<Longrightarrow> w : star A"
by (auto simp: star_def)

lemma Nil_in_star[iff]: "[] : star A"
proof (rule star_if_lang_pow)
  show "[] : A ^^ 0" by simp
qed

lemma star_if_lang[simp]: assumes "w : A" shows "w : star A"
proof (rule star_if_lang_pow)
  show "w : A ^^ 1" using `w : A` by simp
qed

lemma append_in_starI[simp]:
assumes "u : star A" and "v : star A" shows "u@v : star A"
proof -
  from `u : star A` obtain m where "u : A ^^ m" by (auto simp: star_def)
  moreover
  from `v : star A` obtain n where "v : A ^^ n" by (auto simp: star_def)
  ultimately have "u@v : A ^^ (m+n)" by (simp add: lang_pow_add)
  thus ?thesis by simp
qed

lemma conc_star_star: "star A @@ star A = star A"
by (auto simp: conc_def)

lemma conc_star_comm:
  shows "A @@ star A = star A @@ A"
unfolding star_def conc_pow_comm conc_UNION_distrib
by simp

lemma star_induct[consumes 1, case_names Nil append, induct set: star]:
assumes "w : star A"
  and "P []"
  and step: "!!u v. u : A \<Longrightarrow> v : star A \<Longrightarrow> P v \<Longrightarrow> P (u@v)"
shows "P w"
proof -
  { fix n have "w : A ^^ n \<Longrightarrow> P w"
    by (induct n arbitrary: w) (auto intro: `P []` step star_if_lang_pow) }
  with `w : star A` show "P w" by (auto simp: star_def)
qed

lemma star_empty[simp]: "star {} = {[]}"
by (auto elim: star_induct)

lemma star_epsilon[simp]: "star {[]} = {[]}"
by (auto elim: star_induct)

lemma star_idemp[simp]: "star (star A) = star A"
by (auto elim: star_induct)

lemma star_unfold_left: "star A = A @@ star A \<union> {[]}" (is "?L = ?R")
proof
  show "?L \<subseteq> ?R" by (rule, erule star_induct) auto
qed auto

lemma concat_in_star: "set ws \<subseteq> A \<Longrightarrow> concat ws : star A"
by (induct ws) simp_all

lemma in_star_iff_concat:
  "w : star A = (EX ws. set ws \<subseteq> A & w = concat ws)"
  (is "_ = (EX ws. ?R w ws)")
proof
  assume "w : star A" thus "EX ws. ?R w ws"
  proof induct
    case Nil have "?R [] []" by simp
    thus ?case ..
  next
    case (append u v)
    moreover
    then obtain ws where "set ws \<subseteq> A \<and> v = concat ws" by blast
    ultimately have "?R (u@v) (u#ws)" by auto
    thus ?case ..
  qed
next
  assume "EX us. ?R w us" thus "w : star A"
  by (auto simp: concat_in_star)
qed

lemma star_conv_concat: "star A = {concat ws|ws. set ws \<subseteq> A}"
by (fastforce simp: in_star_iff_concat)

lemma star_insert_eps[simp]: "star (insert [] A) = star(A)"
proof-
  { fix us
    have "set us \<subseteq> insert [] A \<Longrightarrow> EX vs. concat us = concat vs \<and> set vs \<subseteq> A"
      (is "?P \<Longrightarrow> EX vs. ?Q vs")
    proof
      let ?vs = "filter (%u. u \<noteq> []) us"
      show "?P \<Longrightarrow> ?Q ?vs" by (induct us) auto
    qed
  } thus ?thesis by (auto simp: star_conv_concat)
qed

lemma star_unfold_left_Nil: "star A = (A - {[]}) @@ (star A) \<union> {[]}"
by (metis insert_Diff_single star_insert_eps star_unfold_left)

lemma star_Diff_Nil_fold: "(A - {[]}) @@ star A = star A - {[]}"
proof -
  have "[] \<notin> (A - {[]}) @@ star A" by simp
  thus ?thesis using star_unfold_left_Nil by blast
qed

lemma star_decom:
  assumes a: "x \<in> star A" "x \<noteq> []"
  shows "\<exists>a b. x = a @ b \<and> a \<noteq> [] \<and> a \<in> A \<and> b \<in> star A"
using a by (induct rule: star_induct) (blast)+

subsection {* Left-Quotients of languages *}

definition Deriv :: "'a \<Rightarrow> 'a lang \<Rightarrow> 'a lang"
where "Deriv x A = { xs. x#xs \<in> A }"

definition Derivs :: "'a list \<Rightarrow> 'a lang \<Rightarrow> 'a lang"
where "Derivs xs A = { ys. xs @ ys \<in> A }"

abbreviation
  Derivss :: "'a list \<Rightarrow> 'a lang set \<Rightarrow> 'a lang"
where
  "Derivss s As \<equiv> \<Union> (Derivs s ` As)"

lemma Deriv_empty[simp]:   "Deriv a {} = {}"
  and Deriv_epsilon[simp]: "Deriv a {[]} = {}"
  and Deriv_char[simp]:    "Deriv a {[b]} = (if a = b then {[]} else {})"
  and Deriv_union[simp]:   "Deriv a (A \<union> B) = Deriv a A \<union> Deriv a B"
  and Deriv_inter[simp]:   "Deriv a (A \<inter> B) = Deriv a A \<inter> Deriv a B"
  and Deriv_compl[simp]:   "Deriv a (-A) = - Deriv a A"
  and Deriv_Union[simp]:   "Deriv a (Union M) = Union(Deriv a ` M)"
  and Deriv_UN[simp]:      "Deriv a (UN x:I. S x) = (UN x:I. Deriv a (S x))"
by (auto simp: Deriv_def)

lemma Der_conc [simp]: "Deriv c (A @@ B) = (Deriv c A) @@ B \<union> (if [] \<in> A then Deriv c B else {})"
unfolding Deriv_def conc_def
by (auto simp add: Cons_eq_append_conv)

lemma Deriv_star [simp]: "Deriv c (star A) = (Deriv c A) @@ star A"
proof -
  have incl: "[] \<in> A \<Longrightarrow> Deriv c (star A) \<subseteq> (Deriv c A) @@ star A"
    unfolding Deriv_def conc_def
    apply(auto simp add: Cons_eq_append_conv)
    apply(drule star_decom)
    apply(auto simp add: Cons_eq_append_conv)
    done

  have "Deriv c (star A) = Deriv c (A @@ star A \<union> {[]})"
    by (simp only: star_unfold_left[symmetric])
  also have "... = Deriv c (A @@ star A)"
    by (simp only: Deriv_union) (simp)
  also have "... =  (Deriv c A) @@ (star A) \<union> (if [] \<in> A then Deriv c (star A) else {})"
    by simp
   also have "... =  (Deriv c A) @@ star A"
    using incl by auto
  finally show "Deriv c (star A) = (Deriv c A) @@ star A" .
qed

lemma Deriv_diff[simp]: "Deriv c (A - B) = Deriv c A - Deriv c B"
by(auto simp add: Deriv_def)

lemma Deriv_lists[simp]: "c : S \<Longrightarrow> Deriv c (lists S) = lists S"
by(auto simp add: Deriv_def)

lemma Derivs_simps [simp]:
  shows "Derivs [] A = A"
  and   "Derivs (c # s) A = Derivs s (Deriv c A)"
  and   "Derivs (s1 @ s2) A = Derivs s2 (Derivs s1 A)"
unfolding Derivs_def Deriv_def by auto

lemma in_fold_Deriv: "v \<in> fold Deriv w L \<longleftrightarrow> w @ v \<in> L"
  by (induct w arbitrary: L) (simp_all add: Deriv_def)

lemma Derivs_alt_def: "Derivs w L = fold Deriv w L"
  by (induct w arbitrary: L) simp_all

subsection {* Shuffle product *}

fun shuffle where
  "shuffle [] ys = {ys}"
| "shuffle xs [] = {xs}"
| "shuffle (x # xs) (y # ys) =
    {x # w | w . w \<in> shuffle xs (y # ys)} \<union>
    {y # w | w . w \<in> shuffle (x # xs) ys}"

lemma shuffle_empty2[simp]: "shuffle xs [] = {xs}"
  by (cases xs) auto

lemma Nil_in_shuffle[simp]: "[] \<in> shuffle xs ys \<longleftrightarrow> xs = [] \<and> ys = []"
  by (induct xs ys rule: shuffle.induct) auto

definition Shuffle (infixr "\<parallel>" 80) where
  "Shuffle A B = \<Union>{shuffle xs ys | xs ys. xs \<in> A \<and> ys \<in> B}"

lemma shuffleE:
  "zs \<in> shuffle xs ys \<Longrightarrow>
    (zs = xs \<Longrightarrow> ys = [] \<Longrightarrow> P) \<Longrightarrow>
    (zs = ys \<Longrightarrow> xs = [] \<Longrightarrow> P) \<Longrightarrow>
    (\<And>x xs' z zs'. xs = x # xs' \<Longrightarrow> zs = z # zs' \<Longrightarrow> x = z \<Longrightarrow> zs' \<in> shuffle xs' ys \<Longrightarrow> P) \<Longrightarrow>
    (\<And>y ys' z zs'. ys = y # ys' \<Longrightarrow> zs = z # zs' \<Longrightarrow> y = z \<Longrightarrow> zs' \<in> shuffle xs ys' \<Longrightarrow> P) \<Longrightarrow> P"
  by (induct xs ys rule: shuffle.induct) auto

lemma Cons_in_shuffle_iff:
  "z # zs \<in> shuffle xs ys \<longleftrightarrow>
    (xs \<noteq> [] \<and> hd xs = z \<and> zs \<in> shuffle (tl xs) ys \<or>
     ys \<noteq> [] \<and> hd ys = z \<and> zs \<in> shuffle xs (tl ys))"
  by (induct xs ys rule: shuffle.induct) auto

lemma Deriv_Shuffle[simp]:
  "Deriv a (A \<parallel> B) = Deriv a A \<parallel> B \<union> A \<parallel> Deriv a B"
  unfolding Shuffle_def Deriv_def by (fastforce simp: Cons_in_shuffle_iff neq_Nil_conv)

lemma shuffle_subset_lists:
  assumes "A \<subseteq> lists S" "B \<subseteq> lists S"
  shows "A \<parallel> B \<subseteq> lists S"
unfolding Shuffle_def proof safe
  fix x and zs xs ys :: "'a list"
  assume zs: "zs \<in> shuffle xs ys" "x \<in> set zs" and "xs \<in> A" "ys \<in> B"
  with assms have "xs \<in> lists S" "ys \<in> lists S" by auto
  with zs show "x \<in> S" by (induct xs ys arbitrary: zs rule: shuffle.induct) auto
qed

lemma Nil_in_Shuffle[simp]: "[] \<in> A \<parallel> B \<longleftrightarrow> [] \<in> A \<and> [] \<in> B"
  unfolding Shuffle_def by force

lemma shuffle_UNION_distrib:
shows "A \<parallel> UNION I M = UNION I (%i. A \<parallel> M i)"
and   "UNION I M \<parallel> A = UNION I (%i. M i \<parallel> A)"
unfolding Shuffle_def by fast+

lemma Shuffle_empty[simp]:
  "A \<parallel> {} = {}"
  "{} \<parallel> B = {}"
  unfolding Shuffle_def by auto

subsection {* Arden's Lemma *}

lemma arden_helper:
  assumes eq: "X = A @@ X \<union> B"
  shows "X = (A ^^ Suc n) @@ X \<union> (\<Union>m\<le>n. (A ^^ m) @@ B)"
proof (induct n)
  case 0
  show "X = (A ^^ Suc 0) @@ X \<union> (\<Union>m\<le>0. (A ^^ m) @@ B)"
    using eq by simp
next
  case (Suc n)
  have ih: "X = (A ^^ Suc n) @@ X \<union> (\<Union>m\<le>n. (A ^^ m) @@ B)" by fact
  also have "\<dots> = (A ^^ Suc n) @@ (A @@ X \<union> B) \<union> (\<Union>m\<le>n. (A ^^ m) @@ B)" using eq by simp
  also have "\<dots> = (A ^^ Suc (Suc n)) @@ X \<union> ((A ^^ Suc n) @@ B) \<union> (\<Union>m\<le>n. (A ^^ m) @@ B)"
    by (simp add: conc_Un_distrib conc_assoc[symmetric] conc_pow_comm)
  also have "\<dots> = (A ^^ Suc (Suc n)) @@ X \<union> (\<Union>m\<le>Suc n. (A ^^ m) @@ B)"
    by (auto simp add: le_Suc_eq)
  finally show "X = (A ^^ Suc (Suc n)) @@ X \<union> (\<Union>m\<le>Suc n. (A ^^ m) @@ B)" .
qed

lemma Arden:
  assumes "[] \<notin> A"
  shows "X = A @@ X \<union> B \<longleftrightarrow> X = star A @@ B"
proof
  assume eq: "X = A @@ X \<union> B"
  { fix w assume "w : X"
    let ?n = "size w"
    from `[] \<notin> A` have "ALL u : A. length u \<ge> 1"
      by (metis Suc_eq_plus1 add_leD2 le_0_eq length_0_conv not_less_eq_eq)
    hence "ALL u : A^^(?n+1). length u \<ge> ?n+1"
      by (metis length_lang_pow_lb nat_mult_1)
    hence "ALL u : A^^(?n+1)@@X. length u \<ge> ?n+1"
      by(auto simp only: conc_def length_append)
    hence "w \<notin> A^^(?n+1)@@X" by auto
    hence "w : star A @@ B" using `w : X` using arden_helper[OF eq, where n="?n"]
      by (auto simp add: star_def conc_UNION_distrib)
  } moreover
  { fix w assume "w : star A @@ B"
    hence "EX n. w : A^^n @@ B" by(auto simp: conc_def star_def)
    hence "w : X" using arden_helper[OF eq] by blast
  } ultimately show "X = star A @@ B" by blast
next
  assume eq: "X = star A @@ B"
  have "star A = A @@ star A \<union> {[]}"
    by (rule star_unfold_left)
  then have "star A @@ B = (A @@ star A \<union> {[]}) @@ B"
    by metis
  also have "\<dots> = (A @@ star A) @@ B \<union> B"
    unfolding conc_Un_distrib by simp
  also have "\<dots> = A @@ (star A @@ B) \<union> B"
    by (simp only: conc_assoc)
  finally show "X = A @@ X \<union> B"
    using eq by blast
qed

lemma reversed_arden_helper:
  assumes eq: "X = X @@ A \<union> B"
  shows "X = X @@ (A ^^ Suc n) \<union> (\<Union>m\<le>n. B @@ (A ^^ m))"
proof (induct n)
  case 0
  show "X = X @@ (A ^^ Suc 0) \<union> (\<Union>m\<le>0. B @@ (A ^^ m))"
    using eq by simp
next
  case (Suc n)
  have ih: "X = X @@ (A ^^ Suc n) \<union> (\<Union>m\<le>n. B @@ (A ^^ m))" by fact
  also have "\<dots> = (X @@ A \<union> B) @@ (A ^^ Suc n) \<union> (\<Union>m\<le>n. B @@ (A ^^ m))" using eq by simp
  also have "\<dots> = X @@ (A ^^ Suc (Suc n)) \<union> (B @@ (A ^^ Suc n)) \<union> (\<Union>m\<le>n. B @@ (A ^^ m))"
    by (simp add: conc_Un_distrib conc_assoc)
  also have "\<dots> = X @@ (A ^^ Suc (Suc n)) \<union> (\<Union>m\<le>Suc n. B @@ (A ^^ m))"
    by (auto simp add: le_Suc_eq)
  finally show "X = X @@ (A ^^ Suc (Suc n)) \<union> (\<Union>m\<le>Suc n. B @@ (A ^^ m))" .
qed

theorem reversed_Arden:
  assumes nemp: "[] \<notin> A"
  shows "X = X @@ A \<union> B \<longleftrightarrow> X = B @@ star A"
proof
 assume eq: "X = X @@ A \<union> B"
  { fix w assume "w : X"
    let ?n = "size w"
    from `[] \<notin> A` have "ALL u : A. length u \<ge> 1"
      by (metis Suc_eq_plus1 add_leD2 le_0_eq length_0_conv not_less_eq_eq)
    hence "ALL u : A^^(?n+1). length u \<ge> ?n+1"
      by (metis length_lang_pow_lb nat_mult_1)
    hence "ALL u : X @@ A^^(?n+1). length u \<ge> ?n+1"
      by(auto simp only: conc_def length_append)
    hence "w \<notin> X @@ A^^(?n+1)" by auto
    hence "w : B @@ star A" using `w : X` using reversed_arden_helper[OF eq, where n="?n"]
      by (auto simp add: star_def conc_UNION_distrib)
  } moreover
  { fix w assume "w : B @@ star A"
    hence "EX n. w : B @@ A^^n" by (auto simp: conc_def star_def)
    hence "w : X" using reversed_arden_helper[OF eq] by blast
  } ultimately show "X = B @@ star A" by blast
next
  assume eq: "X = B @@ star A"
  have "star A = {[]} \<union> star A @@ A"
    unfolding conc_star_comm[symmetric]
    by(metis Un_commute star_unfold_left)
  then have "B @@ star A = B @@ ({[]} \<union> star A @@ A)"
    by metis
  also have "\<dots> = B \<union> B @@ (star A @@ A)"
    unfolding conc_Un_distrib by simp
  also have "\<dots> = B \<union> (B @@ star A) @@ A"
    by (simp only: conc_assoc)
  finally show "X = X @@ A \<union> B"
    using eq by blast
qed

end