(*  Title:      HOL/HOLCF/Universal.thy
    Author:     Brian Huffman
*)

section {* A universal bifinite domain *}

theory Universal
imports Bifinite Completion "~~/src/HOL/Library/Nat_Bijection"
begin

subsection {* Basis for universal domain *}

subsubsection {* Basis datatype *}

type_synonym ubasis = nat

definition
  node :: "nat \<Rightarrow> ubasis \<Rightarrow> ubasis set \<Rightarrow> ubasis"
where
  "node i a S = Suc (prod_encode (i, prod_encode (a, set_encode S)))"

lemma node_not_0 [simp]: "node i a S \<noteq> 0"
unfolding node_def by simp

lemma node_gt_0 [simp]: "0 < node i a S"
unfolding node_def by simp

lemma node_inject [simp]:
  "\<lbrakk>finite S; finite T\<rbrakk>
    \<Longrightarrow> node i a S = node j b T \<longleftrightarrow> i = j \<and> a = b \<and> S = T"
unfolding node_def by (simp add: prod_encode_eq set_encode_eq)

lemma node_gt0: "i < node i a S"
unfolding node_def less_Suc_eq_le
by (rule le_prod_encode_1)

lemma node_gt1: "a < node i a S"
unfolding node_def less_Suc_eq_le
by (rule order_trans [OF le_prod_encode_1 le_prod_encode_2])

lemma nat_less_power2: "n < 2^n"
by (induct n) simp_all

lemma node_gt2: "\<lbrakk>finite S; b \<in> S\<rbrakk> \<Longrightarrow> b < node i a S"
unfolding node_def less_Suc_eq_le set_encode_def
apply (rule order_trans [OF _ le_prod_encode_2])
apply (rule order_trans [OF _ le_prod_encode_2])
apply (rule order_trans [where y="setsum (op ^ 2) {b}"])
apply (simp add: nat_less_power2 [THEN order_less_imp_le])
apply (erule setsum_mono2, simp, simp)
done

lemma eq_prod_encode_pairI:
  "\<lbrakk>fst (prod_decode x) = a; snd (prod_decode x) = b\<rbrakk> \<Longrightarrow> x = prod_encode (a, b)"
by (erule subst, erule subst, simp)

lemma node_cases:
  assumes 1: "x = 0 \<Longrightarrow> P"
  assumes 2: "\<And>i a S. \<lbrakk>finite S; x = node i a S\<rbrakk> \<Longrightarrow> P"
  shows "P"
 apply (cases x)
  apply (erule 1)
 apply (rule 2)
  apply (rule finite_set_decode)
 apply (simp add: node_def)
 apply (rule eq_prod_encode_pairI [OF refl])
 apply (rule eq_prod_encode_pairI [OF refl refl])
done

lemma node_induct:
  assumes 1: "P 0"
  assumes 2: "\<And>i a S. \<lbrakk>P a; finite S; \<forall>b\<in>S. P b\<rbrakk> \<Longrightarrow> P (node i a S)"
  shows "P x"
 apply (induct x rule: nat_less_induct)
 apply (case_tac n rule: node_cases)
  apply (simp add: 1)
 apply (simp add: 2 node_gt1 node_gt2)
done

subsubsection {* Basis ordering *}

inductive
  ubasis_le :: "nat \<Rightarrow> nat \<Rightarrow> bool"
where
  ubasis_le_refl: "ubasis_le a a"
| ubasis_le_trans:
    "\<lbrakk>ubasis_le a b; ubasis_le b c\<rbrakk> \<Longrightarrow> ubasis_le a c"
| ubasis_le_lower:
    "finite S \<Longrightarrow> ubasis_le a (node i a S)"
| ubasis_le_upper:
    "\<lbrakk>finite S; b \<in> S; ubasis_le a b\<rbrakk> \<Longrightarrow> ubasis_le (node i a S) b"

lemma ubasis_le_minimal: "ubasis_le 0 x"
apply (induct x rule: node_induct)
apply (rule ubasis_le_refl)
apply (erule ubasis_le_trans)
apply (erule ubasis_le_lower)
done

interpretation udom: preorder ubasis_le
apply default
apply (rule ubasis_le_refl)
apply (erule (1) ubasis_le_trans)
done

subsubsection {* Generic take function *}

function
  ubasis_until :: "(ubasis \<Rightarrow> bool) \<Rightarrow> ubasis \<Rightarrow> ubasis"
where
  "ubasis_until P 0 = 0"
| "finite S \<Longrightarrow> ubasis_until P (node i a S) =
    (if P (node i a S) then node i a S else ubasis_until P a)"
   apply clarify
   apply (rule_tac x=b in node_cases)
    apply simp
   apply simp
   apply fast
  apply simp
 apply simp
done

termination ubasis_until
apply (relation "measure snd")
apply (rule wf_measure)
apply (simp add: node_gt1)
done

lemma ubasis_until: "P 0 \<Longrightarrow> P (ubasis_until P x)"
by (induct x rule: node_induct) simp_all

lemma ubasis_until': "0 < ubasis_until P x \<Longrightarrow> P (ubasis_until P x)"
by (induct x rule: node_induct) auto

lemma ubasis_until_same: "P x \<Longrightarrow> ubasis_until P x = x"
by (induct x rule: node_induct) simp_all

lemma ubasis_until_idem:
  "P 0 \<Longrightarrow> ubasis_until P (ubasis_until P x) = ubasis_until P x"
by (rule ubasis_until_same [OF ubasis_until])

lemma ubasis_until_0:
  "\<forall>x. x \<noteq> 0 \<longrightarrow> \<not> P x \<Longrightarrow> ubasis_until P x = 0"
by (induct x rule: node_induct) simp_all

lemma ubasis_until_less: "ubasis_le (ubasis_until P x) x"
apply (induct x rule: node_induct)
apply (simp add: ubasis_le_refl)
apply (simp add: ubasis_le_refl)
apply (rule impI)
apply (erule ubasis_le_trans)
apply (erule ubasis_le_lower)
done

lemma ubasis_until_chain:
  assumes PQ: "\<And>x. P x \<Longrightarrow> Q x"
  shows "ubasis_le (ubasis_until P x) (ubasis_until Q x)"
apply (induct x rule: node_induct)
apply (simp add: ubasis_le_refl)
apply (simp add: ubasis_le_refl)
apply (simp add: PQ)
apply clarify
apply (rule ubasis_le_trans)
apply (rule ubasis_until_less)
apply (erule ubasis_le_lower)
done

lemma ubasis_until_mono:
  assumes "\<And>i a S b. \<lbrakk>finite S; P (node i a S); b \<in> S; ubasis_le a b\<rbrakk> \<Longrightarrow> P b"
  shows "ubasis_le a b \<Longrightarrow> ubasis_le (ubasis_until P a) (ubasis_until P b)"
proof (induct set: ubasis_le)
  case (ubasis_le_refl a) show ?case by (rule ubasis_le.ubasis_le_refl)
next
  case (ubasis_le_trans a b c) thus ?case by - (rule ubasis_le.ubasis_le_trans)
next
  case (ubasis_le_lower S a i) thus ?case
    apply (clarsimp simp add: ubasis_le_refl)
    apply (rule ubasis_le_trans [OF ubasis_until_less])
    apply (erule ubasis_le.ubasis_le_lower)
    done
next
  case (ubasis_le_upper S b a i) thus ?case
    apply clarsimp
    apply (subst ubasis_until_same)
     apply (erule (3) assms)
    apply (erule (2) ubasis_le.ubasis_le_upper)
    done
qed

lemma finite_range_ubasis_until:
  "finite {x. P x} \<Longrightarrow> finite (range (ubasis_until P))"
apply (rule finite_subset [where B="insert 0 {x. P x}"])
apply (clarsimp simp add: ubasis_until')
apply simp
done

subsection {* Defining the universal domain by ideal completion *}

typedef udom = "{S. udom.ideal S}"
by (rule udom.ex_ideal)

instantiation udom :: below
begin

definition
  "x \<sqsubseteq> y \<longleftrightarrow> Rep_udom x \<subseteq> Rep_udom y"

instance ..
end

instance udom :: po
using type_definition_udom below_udom_def
by (rule udom.typedef_ideal_po)

instance udom :: cpo
using type_definition_udom below_udom_def
by (rule udom.typedef_ideal_cpo)

definition
  udom_principal :: "nat \<Rightarrow> udom" where
  "udom_principal t = Abs_udom {u. ubasis_le u t}"

lemma ubasis_countable: "\<exists>f::ubasis \<Rightarrow> nat. inj f"
by (rule exI, rule inj_on_id)

interpretation udom:
  ideal_completion ubasis_le udom_principal Rep_udom
using type_definition_udom below_udom_def
using udom_principal_def ubasis_countable
by (rule udom.typedef_ideal_completion)

text {* Universal domain is pointed *}

lemma udom_minimal: "udom_principal 0 \<sqsubseteq> x"
apply (induct x rule: udom.principal_induct)
apply (simp, simp add: ubasis_le_minimal)
done

instance udom :: pcpo
by intro_classes (fast intro: udom_minimal)

lemma inst_udom_pcpo: "\<bottom> = udom_principal 0"
by (rule udom_minimal [THEN bottomI, symmetric])

subsection {* Compact bases of domains *}

typedef 'a compact_basis = "{x::'a::pcpo. compact x}"
by auto

lemma Rep_compact_basis' [simp]: "compact (Rep_compact_basis a)"
by (rule Rep_compact_basis [unfolded mem_Collect_eq])

lemma Abs_compact_basis_inverse' [simp]:
   "compact x \<Longrightarrow> Rep_compact_basis (Abs_compact_basis x) = x"
by (rule Abs_compact_basis_inverse [unfolded mem_Collect_eq])

instantiation compact_basis :: (pcpo) below
begin

definition
  compact_le_def:
    "(op \<sqsubseteq>) \<equiv> (\<lambda>x y. Rep_compact_basis x \<sqsubseteq> Rep_compact_basis y)"

instance ..
end

instance compact_basis :: (pcpo) po
using type_definition_compact_basis compact_le_def
by (rule typedef_po)

definition
  approximants :: "'a \<Rightarrow> 'a compact_basis set" where
  "approximants = (\<lambda>x. {a. Rep_compact_basis a \<sqsubseteq> x})"

definition
  compact_bot :: "'a::pcpo compact_basis" where
  "compact_bot = Abs_compact_basis \<bottom>"

lemma Rep_compact_bot [simp]: "Rep_compact_basis compact_bot = \<bottom>"
unfolding compact_bot_def by simp

lemma compact_bot_minimal [simp]: "compact_bot \<sqsubseteq> a"
unfolding compact_le_def Rep_compact_bot by simp

subsection {* Universality of \emph{udom} *}

text {* We use a locale to parameterize the construction over a chain
of approx functions on the type to be embedded. *}

locale bifinite_approx_chain =
  approx_chain approx for approx :: "nat \<Rightarrow> 'a::bifinite \<rightarrow> 'a"
begin

subsubsection {* Choosing a maximal element from a finite set *}

lemma finite_has_maximal:
  fixes A :: "'a compact_basis set"
  shows "\<lbrakk>finite A; A \<noteq> {}\<rbrakk> \<Longrightarrow> \<exists>x\<in>A. \<forall>y\<in>A. x \<sqsubseteq> y \<longrightarrow> x = y"
proof (induct rule: finite_ne_induct)
  case (singleton x)
    show ?case by simp
next
  case (insert a A)
  from `\<exists>x\<in>A. \<forall>y\<in>A. x \<sqsubseteq> y \<longrightarrow> x = y`
  obtain x where x: "x \<in> A"
           and x_eq: "\<And>y. \<lbrakk>y \<in> A; x \<sqsubseteq> y\<rbrakk> \<Longrightarrow> x = y" by fast
  show ?case
  proof (intro bexI ballI impI)
    fix y
    assume "y \<in> insert a A" and "(if x \<sqsubseteq> a then a else x) \<sqsubseteq> y"
    thus "(if x \<sqsubseteq> a then a else x) = y"
      apply auto
      apply (frule (1) below_trans)
      apply (frule (1) x_eq)
      apply (rule below_antisym, assumption)
      apply simp
      apply (erule (1) x_eq)
      done
  next
    show "(if x \<sqsubseteq> a then a else x) \<in> insert a A"
      by (simp add: x)
  qed
qed

definition
  choose :: "'a compact_basis set \<Rightarrow> 'a compact_basis"
where
  "choose A = (SOME x. x \<in> {x\<in>A. \<forall>y\<in>A. x \<sqsubseteq> y \<longrightarrow> x = y})"

lemma choose_lemma:
  "\<lbrakk>finite A; A \<noteq> {}\<rbrakk> \<Longrightarrow> choose A \<in> {x\<in>A. \<forall>y\<in>A. x \<sqsubseteq> y \<longrightarrow> x = y}"
unfolding choose_def
apply (rule someI_ex)
apply (frule (1) finite_has_maximal, fast)
done

lemma maximal_choose:
  "\<lbrakk>finite A; y \<in> A; choose A \<sqsubseteq> y\<rbrakk> \<Longrightarrow> choose A = y"
apply (cases "A = {}", simp)
apply (frule (1) choose_lemma, simp)
done

lemma choose_in: "\<lbrakk>finite A; A \<noteq> {}\<rbrakk> \<Longrightarrow> choose A \<in> A"
by (frule (1) choose_lemma, simp)

function
  choose_pos :: "'a compact_basis set \<Rightarrow> 'a compact_basis \<Rightarrow> nat"
where
  "choose_pos A x =
    (if finite A \<and> x \<in> A \<and> x \<noteq> choose A
      then Suc (choose_pos (A - {choose A}) x) else 0)"
by auto

termination choose_pos
apply (relation "measure (card \<circ> fst)", simp)
apply clarsimp
apply (rule card_Diff1_less)
apply assumption
apply (erule choose_in)
apply clarsimp
done

declare choose_pos.simps [simp del]

lemma choose_pos_choose: "finite A \<Longrightarrow> choose_pos A (choose A) = 0"
by (simp add: choose_pos.simps)

lemma inj_on_choose_pos [OF refl]:
  "\<lbrakk>card A = n; finite A\<rbrakk> \<Longrightarrow> inj_on (choose_pos A) A"
 apply (induct n arbitrary: A)
  apply simp
 apply (case_tac "A = {}", simp)
 apply (frule (1) choose_in)
 apply (rule inj_onI)
 apply (drule_tac x="A - {choose A}" in meta_spec, simp)
 apply (simp add: choose_pos.simps)
 apply (simp split: split_if_asm)
 apply (erule (1) inj_onD, simp, simp)
done

lemma choose_pos_bounded [OF refl]:
  "\<lbrakk>card A = n; finite A; x \<in> A\<rbrakk> \<Longrightarrow> choose_pos A x < n"
apply (induct n arbitrary: A)
apply simp
 apply (case_tac "A = {}", simp)
 apply (frule (1) choose_in)
apply (subst choose_pos.simps)
apply simp
done

lemma choose_pos_lessD:
  "\<lbrakk>choose_pos A x < choose_pos A y; finite A; x \<in> A; y \<in> A\<rbrakk> \<Longrightarrow> x \<notsqsubseteq> y"
 apply (induct A x arbitrary: y rule: choose_pos.induct)
 apply simp
 apply (case_tac "x = choose A")
  apply simp
  apply (rule notI)
  apply (frule (2) maximal_choose)
  apply simp
 apply (case_tac "y = choose A")
  apply (simp add: choose_pos_choose)
 apply (drule_tac x=y in meta_spec)
 apply simp
 apply (erule meta_mp)
 apply (simp add: choose_pos.simps)
done

subsubsection {* Compact basis take function *}

primrec
  cb_take :: "nat \<Rightarrow> 'a compact_basis \<Rightarrow> 'a compact_basis" where
  "cb_take 0 = (\<lambda>x. compact_bot)"
| "cb_take (Suc n) = (\<lambda>a. Abs_compact_basis (approx n\<cdot>(Rep_compact_basis a)))"

declare cb_take.simps [simp del]

lemma cb_take_zero [simp]: "cb_take 0 a = compact_bot"
by (simp only: cb_take.simps)

lemma Rep_cb_take:
  "Rep_compact_basis (cb_take (Suc n) a) = approx n\<cdot>(Rep_compact_basis a)"
by (simp add: cb_take.simps(2))

lemmas approx_Rep_compact_basis = Rep_cb_take [symmetric]

lemma cb_take_covers: "\<exists>n. cb_take n x = x"
apply (subgoal_tac "\<exists>n. cb_take (Suc n) x = x", fast)
apply (simp add: Rep_compact_basis_inject [symmetric])
apply (simp add: Rep_cb_take)
apply (rule compact_eq_approx)
apply (rule Rep_compact_basis')
done

lemma cb_take_less: "cb_take n x \<sqsubseteq> x"
unfolding compact_le_def
by (cases n, simp, simp add: Rep_cb_take approx_below)

lemma cb_take_idem: "cb_take n (cb_take n x) = cb_take n x"
unfolding Rep_compact_basis_inject [symmetric]
by (cases n, simp, simp add: Rep_cb_take approx_idem)

lemma cb_take_mono: "x \<sqsubseteq> y \<Longrightarrow> cb_take n x \<sqsubseteq> cb_take n y"
unfolding compact_le_def
by (cases n, simp, simp add: Rep_cb_take monofun_cfun_arg)

lemma cb_take_chain_le: "m \<le> n \<Longrightarrow> cb_take m x \<sqsubseteq> cb_take n x"
unfolding compact_le_def
apply (cases m, simp, cases n, simp)
apply (simp add: Rep_cb_take, rule chain_mono, simp, simp)
done

lemma finite_range_cb_take: "finite (range (cb_take n))"
apply (cases n)
apply (subgoal_tac "range (cb_take 0) = {compact_bot}", simp, force)
apply (rule finite_imageD [where f="Rep_compact_basis"])
apply (rule finite_subset [where B="range (\<lambda>x. approx (n - 1)\<cdot>x)"])
apply (clarsimp simp add: Rep_cb_take)
apply (rule finite_range_approx)
apply (rule inj_onI, simp add: Rep_compact_basis_inject)
done

subsubsection {* Rank of basis elements *}

definition
  rank :: "'a compact_basis \<Rightarrow> nat"
where
  "rank x = (LEAST n. cb_take n x = x)"

lemma compact_approx_rank: "cb_take (rank x) x = x"
unfolding rank_def
apply (rule LeastI_ex)
apply (rule cb_take_covers)
done

lemma rank_leD: "rank x \<le> n \<Longrightarrow> cb_take n x = x"
apply (rule below_antisym [OF cb_take_less])
apply (subst compact_approx_rank [symmetric])
apply (erule cb_take_chain_le)
done

lemma rank_leI: "cb_take n x = x \<Longrightarrow> rank x \<le> n"
unfolding rank_def by (rule Least_le)

lemma rank_le_iff: "rank x \<le> n \<longleftrightarrow> cb_take n x = x"
by (rule iffI [OF rank_leD rank_leI])

lemma rank_compact_bot [simp]: "rank compact_bot = 0"
using rank_leI [of 0 compact_bot] by simp

lemma rank_eq_0_iff [simp]: "rank x = 0 \<longleftrightarrow> x = compact_bot"
using rank_le_iff [of x 0] by auto

definition
  rank_le :: "'a compact_basis \<Rightarrow> 'a compact_basis set"
where
  "rank_le x = {y. rank y \<le> rank x}"

definition
  rank_lt :: "'a compact_basis \<Rightarrow> 'a compact_basis set"
where
  "rank_lt x = {y. rank y < rank x}"

definition
  rank_eq :: "'a compact_basis \<Rightarrow> 'a compact_basis set"
where
  "rank_eq x = {y. rank y = rank x}"

lemma rank_eq_cong: "rank x = rank y \<Longrightarrow> rank_eq x = rank_eq y"
unfolding rank_eq_def by simp

lemma rank_lt_cong: "rank x = rank y \<Longrightarrow> rank_lt x = rank_lt y"
unfolding rank_lt_def by simp

lemma rank_eq_subset: "rank_eq x \<subseteq> rank_le x"
unfolding rank_eq_def rank_le_def by auto

lemma rank_lt_subset: "rank_lt x \<subseteq> rank_le x"
unfolding rank_lt_def rank_le_def by auto

lemma finite_rank_le: "finite (rank_le x)"
unfolding rank_le_def
apply (rule finite_subset [where B="range (cb_take (rank x))"])
apply clarify
apply (rule range_eqI)
apply (erule rank_leD [symmetric])
apply (rule finite_range_cb_take)
done

lemma finite_rank_eq: "finite (rank_eq x)"
by (rule finite_subset [OF rank_eq_subset finite_rank_le])

lemma finite_rank_lt: "finite (rank_lt x)"
by (rule finite_subset [OF rank_lt_subset finite_rank_le])

lemma rank_lt_Int_rank_eq: "rank_lt x \<inter> rank_eq x = {}"
unfolding rank_lt_def rank_eq_def rank_le_def by auto

lemma rank_lt_Un_rank_eq: "rank_lt x \<union> rank_eq x = rank_le x"
unfolding rank_lt_def rank_eq_def rank_le_def by auto

subsubsection {* Sequencing basis elements *}

definition
  place :: "'a compact_basis \<Rightarrow> nat"
where
  "place x = card (rank_lt x) + choose_pos (rank_eq x) x"

lemma place_bounded: "place x < card (rank_le x)"
unfolding place_def
 apply (rule ord_less_eq_trans)
  apply (rule add_strict_left_mono)
  apply (rule choose_pos_bounded)
   apply (rule finite_rank_eq)
  apply (simp add: rank_eq_def)
 apply (subst card_Un_disjoint [symmetric])
    apply (rule finite_rank_lt)
   apply (rule finite_rank_eq)
  apply (rule rank_lt_Int_rank_eq)
 apply (simp add: rank_lt_Un_rank_eq)
done

lemma place_ge: "card (rank_lt x) \<le> place x"
unfolding place_def by simp

lemma place_rank_mono:
  fixes x y :: "'a compact_basis"
  shows "rank x < rank y \<Longrightarrow> place x < place y"
apply (rule less_le_trans [OF place_bounded])
apply (rule order_trans [OF _ place_ge])
apply (rule card_mono)
apply (rule finite_rank_lt)
apply (simp add: rank_le_def rank_lt_def subset_eq)
done

lemma place_eqD: "place x = place y \<Longrightarrow> x = y"
 apply (rule linorder_cases [where x="rank x" and y="rank y"])
   apply (drule place_rank_mono, simp)
  apply (simp add: place_def)
  apply (rule inj_on_choose_pos [where A="rank_eq x", THEN inj_onD])
     apply (rule finite_rank_eq)
    apply (simp cong: rank_lt_cong rank_eq_cong)
   apply (simp add: rank_eq_def)
  apply (simp add: rank_eq_def)
 apply (drule place_rank_mono, simp)
done

lemma inj_place: "inj place"
by (rule inj_onI, erule place_eqD)

subsubsection {* Embedding and projection on basis elements *}

definition
  sub :: "'a compact_basis \<Rightarrow> 'a compact_basis"
where
  "sub x = (case rank x of 0 \<Rightarrow> compact_bot | Suc k \<Rightarrow> cb_take k x)"

lemma rank_sub_less: "x \<noteq> compact_bot \<Longrightarrow> rank (sub x) < rank x"
unfolding sub_def
apply (cases "rank x", simp)
apply (simp add: less_Suc_eq_le)
apply (rule rank_leI)
apply (rule cb_take_idem)
done

lemma place_sub_less: "x \<noteq> compact_bot \<Longrightarrow> place (sub x) < place x"
apply (rule place_rank_mono)
apply (erule rank_sub_less)
done

lemma sub_below: "sub x \<sqsubseteq> x"
unfolding sub_def by (cases "rank x", simp_all add: cb_take_less)

lemma rank_less_imp_below_sub: "\<lbrakk>x \<sqsubseteq> y; rank x < rank y\<rbrakk> \<Longrightarrow> x \<sqsubseteq> sub y"
unfolding sub_def
apply (cases "rank y", simp)
apply (simp add: less_Suc_eq_le)
apply (subgoal_tac "cb_take nat x \<sqsubseteq> cb_take nat y")
apply (simp add: rank_leD)
apply (erule cb_take_mono)
done

function
  basis_emb :: "'a compact_basis \<Rightarrow> ubasis"
where
  "basis_emb x = (if x = compact_bot then 0 else
    node (place x) (basis_emb (sub x))
      (basis_emb ` {y. place y < place x \<and> x \<sqsubseteq> y}))"
by auto

termination basis_emb
apply (relation "measure place", simp)
apply (simp add: place_sub_less)
apply simp
done

declare basis_emb.simps [simp del]

lemma basis_emb_compact_bot [simp]: "basis_emb compact_bot = 0"
by (simp add: basis_emb.simps)

lemma fin1: "finite {y. place y < place x \<and> x \<sqsubseteq> y}"
apply (subst Collect_conj_eq)
apply (rule finite_Int)
apply (rule disjI1)
apply (subgoal_tac "finite (place -` {n. n < place x})", simp)
apply (rule finite_vimageI [OF _ inj_place])
apply (simp add: lessThan_def [symmetric])
done

lemma fin2: "finite (basis_emb ` {y. place y < place x \<and> x \<sqsubseteq> y})"
by (rule finite_imageI [OF fin1])

lemma rank_place_mono:
  "\<lbrakk>place x < place y; x \<sqsubseteq> y\<rbrakk> \<Longrightarrow> rank x < rank y"
apply (rule linorder_cases, assumption)
apply (simp add: place_def cong: rank_lt_cong rank_eq_cong)
apply (drule choose_pos_lessD)
apply (rule finite_rank_eq)
apply (simp add: rank_eq_def)
apply (simp add: rank_eq_def)
apply simp
apply (drule place_rank_mono, simp)
done

lemma basis_emb_mono:
  "x \<sqsubseteq> y \<Longrightarrow> ubasis_le (basis_emb x) (basis_emb y)"
proof (induct "max (place x) (place y)" arbitrary: x y rule: less_induct)
  case less
  show ?case proof (rule linorder_cases)
    assume "place x < place y"
    then have "rank x < rank y"
      using `x \<sqsubseteq> y` by (rule rank_place_mono)
    with `place x < place y` show ?case
      apply (case_tac "y = compact_bot", simp)
      apply (simp add: basis_emb.simps [of y])
      apply (rule ubasis_le_trans [OF _ ubasis_le_lower [OF fin2]])
      apply (rule less)
       apply (simp add: less_max_iff_disj)
       apply (erule place_sub_less)
      apply (erule rank_less_imp_below_sub [OF `x \<sqsubseteq> y`])
      done
  next
    assume "place x = place y"
    hence "x = y" by (rule place_eqD)
    thus ?case by (simp add: ubasis_le_refl)
  next
    assume "place x > place y"
    with `x \<sqsubseteq> y` show ?case
      apply (case_tac "x = compact_bot", simp add: ubasis_le_minimal)
      apply (simp add: basis_emb.simps [of x])
      apply (rule ubasis_le_upper [OF fin2], simp)
      apply (rule less)
       apply (simp add: less_max_iff_disj)
       apply (erule place_sub_less)
      apply (erule rev_below_trans)
      apply (rule sub_below)
      done
  qed
qed

lemma inj_basis_emb: "inj basis_emb"
 apply (rule inj_onI)
 apply (case_tac "x = compact_bot")
  apply (case_tac [!] "y = compact_bot")
    apply simp
   apply (simp add: basis_emb.simps)
  apply (simp add: basis_emb.simps)
 apply (simp add: basis_emb.simps)
 apply (simp add: fin2 inj_eq [OF inj_place])
done

definition
  basis_prj :: "ubasis \<Rightarrow> 'a compact_basis"
where
  "basis_prj x = inv basis_emb
    (ubasis_until (\<lambda>x. x \<in> range (basis_emb :: 'a compact_basis \<Rightarrow> ubasis)) x)"

lemma basis_prj_basis_emb: "\<And>x. basis_prj (basis_emb x) = x"
unfolding basis_prj_def
 apply (subst ubasis_until_same)
  apply (rule rangeI)
 apply (rule inv_f_f)
 apply (rule inj_basis_emb)
done

lemma basis_prj_node:
  "\<lbrakk>finite S; node i a S \<notin> range (basis_emb :: 'a compact_basis \<Rightarrow> nat)\<rbrakk>
    \<Longrightarrow> basis_prj (node i a S) = (basis_prj a :: 'a compact_basis)"
unfolding basis_prj_def by simp

lemma basis_prj_0: "basis_prj 0 = compact_bot"
apply (subst basis_emb_compact_bot [symmetric])
apply (rule basis_prj_basis_emb)
done

lemma node_eq_basis_emb_iff:
  "finite S \<Longrightarrow> node i a S = basis_emb x \<longleftrightarrow>
    x \<noteq> compact_bot \<and> i = place x \<and> a = basis_emb (sub x) \<and>
        S = basis_emb ` {y. place y < place x \<and> x \<sqsubseteq> y}"
apply (cases "x = compact_bot", simp)
apply (simp add: basis_emb.simps [of x])
apply (simp add: fin2)
done

lemma basis_prj_mono: "ubasis_le a b \<Longrightarrow> basis_prj a \<sqsubseteq> basis_prj b"
proof (induct a b rule: ubasis_le.induct)
  case (ubasis_le_refl a) show ?case by (rule below_refl)
next
  case (ubasis_le_trans a b c) thus ?case by - (rule below_trans)
next
  case (ubasis_le_lower S a i) thus ?case
    apply (cases "node i a S \<in> range (basis_emb :: 'a compact_basis \<Rightarrow> nat)")
     apply (erule rangeE, rename_tac x)
     apply (simp add: basis_prj_basis_emb)
     apply (simp add: node_eq_basis_emb_iff)
     apply (simp add: basis_prj_basis_emb)
     apply (rule sub_below)
    apply (simp add: basis_prj_node)
    done
next
  case (ubasis_le_upper S b a i) thus ?case
    apply (cases "node i a S \<in> range (basis_emb :: 'a compact_basis \<Rightarrow> nat)")
     apply (erule rangeE, rename_tac x)
     apply (simp add: basis_prj_basis_emb)
     apply (clarsimp simp add: node_eq_basis_emb_iff)
     apply (simp add: basis_prj_basis_emb)
    apply (simp add: basis_prj_node)
    done
qed

lemma basis_emb_prj_less: "ubasis_le (basis_emb (basis_prj x)) x"
unfolding basis_prj_def
 apply (subst f_inv_into_f [where f=basis_emb])
  apply (rule ubasis_until)
  apply (rule range_eqI [where x=compact_bot])
  apply simp
 apply (rule ubasis_until_less)
done

lemma ideal_completion:
  "ideal_completion below Rep_compact_basis (approximants :: 'a \<Rightarrow> _)"
proof
  fix w :: "'a"
  show "below.ideal (approximants w)"
  proof (rule below.idealI)
    have "Abs_compact_basis (approx 0\<cdot>w) \<in> approximants w"
      by (simp add: approximants_def approx_below)
    thus "\<exists>x. x \<in> approximants w" ..
  next
    fix x y :: "'a compact_basis"
    assume x: "x \<in> approximants w" and y: "y \<in> approximants w"
    obtain i where i: "approx i\<cdot>(Rep_compact_basis x) = Rep_compact_basis x"
      using compact_eq_approx Rep_compact_basis' by fast
    obtain j where j: "approx j\<cdot>(Rep_compact_basis y) = Rep_compact_basis y"
      using compact_eq_approx Rep_compact_basis' by fast
    let ?z = "Abs_compact_basis (approx (max i j)\<cdot>w)"
    have "?z \<in> approximants w"
      by (simp add: approximants_def approx_below)
    moreover from x y have "x \<sqsubseteq> ?z \<and> y \<sqsubseteq> ?z"
      by (simp add: approximants_def compact_le_def)
         (metis i j monofun_cfun chain_mono chain_approx max.cobounded1 max.cobounded2)
    ultimately show "\<exists>z \<in> approximants w. x \<sqsubseteq> z \<and> y \<sqsubseteq> z" ..
  next
    fix x y :: "'a compact_basis"
    assume "x \<sqsubseteq> y" "y \<in> approximants w" thus "x \<in> approximants w"
      unfolding approximants_def compact_le_def
      by (auto elim: below_trans)
  qed
next
  fix Y :: "nat \<Rightarrow> 'a"
  assume "chain Y"
  thus "approximants (\<Squnion>i. Y i) = (\<Union>i. approximants (Y i))"
    unfolding approximants_def
    by (auto simp add: compact_below_lub_iff)
next
  fix a :: "'a compact_basis"
  show "approximants (Rep_compact_basis a) = {b. b \<sqsubseteq> a}"
    unfolding approximants_def compact_le_def ..
next
  fix x y :: "'a"
  assume "approximants x \<subseteq> approximants y"
  hence "\<forall>z. compact z \<longrightarrow> z \<sqsubseteq> x \<longrightarrow> z \<sqsubseteq> y"
    by (simp add: approximants_def subset_eq)
       (metis Abs_compact_basis_inverse')
  hence "(\<Squnion>i. approx i\<cdot>x) \<sqsubseteq> y"
    by (simp add: lub_below approx_below)
  thus "x \<sqsubseteq> y"
    by (simp add: lub_distribs)
next
  show "\<exists>f::'a compact_basis \<Rightarrow> nat. inj f"
    by (rule exI, rule inj_place)
qed

end

interpretation compact_basis!:
  ideal_completion below Rep_compact_basis
    "approximants :: 'a::bifinite \<Rightarrow> 'a compact_basis set"
proof -
  obtain a :: "nat \<Rightarrow> 'a \<rightarrow> 'a" where "approx_chain a"
    using bifinite ..
  hence "bifinite_approx_chain a"
    unfolding bifinite_approx_chain_def .
  thus "ideal_completion below Rep_compact_basis (approximants :: 'a \<Rightarrow> _)"
    by (rule bifinite_approx_chain.ideal_completion)
qed

subsubsection {* EP-pair from any bifinite domain into \emph{udom} *}

context bifinite_approx_chain begin

definition
  udom_emb :: "'a \<rightarrow> udom"
where
  "udom_emb = compact_basis.extension (\<lambda>x. udom_principal (basis_emb x))"

definition
  udom_prj :: "udom \<rightarrow> 'a"
where
  "udom_prj = udom.extension (\<lambda>x. Rep_compact_basis (basis_prj x))"

lemma udom_emb_principal:
  "udom_emb\<cdot>(Rep_compact_basis x) = udom_principal (basis_emb x)"
unfolding udom_emb_def
apply (rule compact_basis.extension_principal)
apply (rule udom.principal_mono)
apply (erule basis_emb_mono)
done

lemma udom_prj_principal:
  "udom_prj\<cdot>(udom_principal x) = Rep_compact_basis (basis_prj x)"
unfolding udom_prj_def
apply (rule udom.extension_principal)
apply (rule compact_basis.principal_mono)
apply (erule basis_prj_mono)
done

lemma ep_pair_udom: "ep_pair udom_emb udom_prj"
 apply default
  apply (rule compact_basis.principal_induct, simp)
  apply (simp add: udom_emb_principal udom_prj_principal)
  apply (simp add: basis_prj_basis_emb)
 apply (rule udom.principal_induct, simp)
 apply (simp add: udom_emb_principal udom_prj_principal)
 apply (rule basis_emb_prj_less)
done

end

abbreviation "udom_emb \<equiv> bifinite_approx_chain.udom_emb"
abbreviation "udom_prj \<equiv> bifinite_approx_chain.udom_prj"

lemmas ep_pair_udom =
  bifinite_approx_chain.ep_pair_udom [unfolded bifinite_approx_chain_def]

subsection {* Chain of approx functions for type \emph{udom} *}

definition
  udom_approx :: "nat \<Rightarrow> udom \<rightarrow> udom"
where
  "udom_approx i =
    udom.extension (\<lambda>x. udom_principal (ubasis_until (\<lambda>y. y \<le> i) x))"

lemma udom_approx_mono:
  "ubasis_le a b \<Longrightarrow>
    udom_principal (ubasis_until (\<lambda>y. y \<le> i) a) \<sqsubseteq>
    udom_principal (ubasis_until (\<lambda>y. y \<le> i) b)"
apply (rule udom.principal_mono)
apply (rule ubasis_until_mono)
apply (frule (2) order_less_le_trans [OF node_gt2])
apply (erule order_less_imp_le)
apply assumption
done

lemma adm_mem_finite: "\<lbrakk>cont f; finite S\<rbrakk> \<Longrightarrow> adm (\<lambda>x. f x \<in> S)"
by (erule adm_subst, induct set: finite, simp_all)

lemma udom_approx_principal:
  "udom_approx i\<cdot>(udom_principal x) =
    udom_principal (ubasis_until (\<lambda>y. y \<le> i) x)"
unfolding udom_approx_def
apply (rule udom.extension_principal)
apply (erule udom_approx_mono)
done

lemma finite_deflation_udom_approx: "finite_deflation (udom_approx i)"
proof
  fix x show "udom_approx i\<cdot>(udom_approx i\<cdot>x) = udom_approx i\<cdot>x"
    by (induct x rule: udom.principal_induct, simp)
       (simp add: udom_approx_principal ubasis_until_idem)
next
  fix x show "udom_approx i\<cdot>x \<sqsubseteq> x"
    by (induct x rule: udom.principal_induct, simp)
       (simp add: udom_approx_principal ubasis_until_less)
next
  have *: "finite (range (\<lambda>x. udom_principal (ubasis_until (\<lambda>y. y \<le> i) x)))"
    apply (subst range_composition [where f=udom_principal])
    apply (simp add: finite_range_ubasis_until)
    done
  show "finite {x. udom_approx i\<cdot>x = x}"
    apply (rule finite_range_imp_finite_fixes)
    apply (rule rev_finite_subset [OF *])
    apply (clarsimp, rename_tac x)
    apply (induct_tac x rule: udom.principal_induct)
    apply (simp add: adm_mem_finite *)
    apply (simp add: udom_approx_principal)
    done
qed

interpretation udom_approx: finite_deflation "udom_approx i"
by (rule finite_deflation_udom_approx)

lemma chain_udom_approx [simp]: "chain (\<lambda>i. udom_approx i)"
unfolding udom_approx_def
apply (rule chainI)
apply (rule udom.extension_mono)
apply (erule udom_approx_mono)
apply (erule udom_approx_mono)
apply (rule udom.principal_mono)
apply (rule ubasis_until_chain, simp)
done

lemma lub_udom_approx [simp]: "(\<Squnion>i. udom_approx i) = ID"
apply (rule cfun_eqI, simp add: contlub_cfun_fun)
apply (rule below_antisym)
apply (rule lub_below)
apply (simp)
apply (rule udom_approx.below)
apply (rule_tac x=x in udom.principal_induct)
apply (simp add: lub_distribs)
apply (rule_tac i=a in below_lub)
apply simp
apply (simp add: udom_approx_principal)
apply (simp add: ubasis_until_same ubasis_le_refl)
done

lemma udom_approx [simp]: "approx_chain udom_approx"
proof
  show "chain (\<lambda>i. udom_approx i)"
    by (rule chain_udom_approx)
  show "(\<Squnion>i. udom_approx i) = ID"
    by (rule lub_udom_approx)
qed

instance udom :: bifinite
  by default (fast intro: udom_approx)

hide_const (open) node

end


(*  Title:      HOL/ex/Groebner_Examples.thy
    Author:     Amine Chaieb, TU Muenchen
*)

section \<open>Groebner Basis Examples\<close>

theory Groebner_Examples
imports HOL.Groebner_Basis
begin

subsection \<open>Basic examples\<close>

lemma
  fixes x :: int
  shows "x ^ 3 = x ^ 3"
  apply (tactic \<open>ALLGOALS (CONVERSION
    (Conv.arg_conv (Conv.arg1_conv (Semiring_Normalizer.semiring_normalize_conv @{context}))))\<close>)
  by (rule refl)

lemma
  fixes x :: int
  shows "(x - (-2))^5 = x ^ 5 + (10 * x ^ 4 + (40 * x ^ 3 + (80 * x\<^sup>2 + (80 * x + 32))))"
  apply (tactic \<open>ALLGOALS (CONVERSION
    (Conv.arg_conv (Conv.arg1_conv (Semiring_Normalizer.semiring_normalize_conv @{context}))))\<close>)
  by (rule refl)

schematic_goal
  fixes x :: int
  shows "(x - (-2))^5  * (y - 78) ^ 8 = ?X"
  apply (tactic \<open>ALLGOALS (CONVERSION
    (Conv.arg_conv (Conv.arg1_conv (Semiring_Normalizer.semiring_normalize_conv @{context}))))\<close>)
  by (rule refl)

lemma "((-3) ^ (Suc (Suc (Suc 0)))) == (X::'a::{comm_ring_1})"
  apply (simp only: power_Suc power_0)
  apply (simp only: semiring_norm)
  oops

lemma "((x::int) + y)^3 - 1 = (x - z)^2 - 10 \<Longrightarrow> x = z + 3 \<Longrightarrow> x = - y"
  by algebra

lemma "(4::nat) + 4 = 3 + 5"
  by algebra

lemma "(4::int) + 0 = 4"
  apply algebra?
  by simp

lemma
  assumes "a * x\<^sup>2 + b * x + c = (0::int)" and "d * x\<^sup>2 + e * x + f = 0"
  shows "d\<^sup>2 * c\<^sup>2 - 2 * d * c * a * f + a\<^sup>2 * f\<^sup>2 - e * d * b * c - e * b * a * f +
    a * e\<^sup>2 * c + f * d * b\<^sup>2 = 0"
  using assms by algebra

lemma "(x::int)^3  - x^2  - 5*x - 3 = 0 \<longleftrightarrow> (x = 3 \<or> x = -1)"
  by algebra

theorem "x* (x\<^sup>2 - x  - 5) - 3 = (0::int) \<longleftrightarrow> (x = 3 \<or> x = -1)"
  by algebra

lemma
  fixes x::"'a::idom"
  shows "x\<^sup>2*y = x\<^sup>2 & x*y\<^sup>2 = y\<^sup>2 \<longleftrightarrow>  x = 1 & y = 1 | x = 0 & y = 0"
  by algebra

subsection \<open>Lemmas for Lagrange's theorem\<close>

definition
  sq :: "'a::times => 'a" where
  "sq x == x*x"

lemma
  fixes x1 :: "'a::{idom}"
  shows
  "(sq x1 + sq x2 + sq x3 + sq x4) * (sq y1 + sq y2 + sq y3 + sq y4) =
    sq (x1*y1 - x2*y2 - x3*y3 - x4*y4)  +
    sq (x1*y2 + x2*y1 + x3*y4 - x4*y3)  +
    sq (x1*y3 - x2*y4 + x3*y1 + x4*y2)  +
    sq (x1*y4 + x2*y3 - x3*y2 + x4*y1)"
  by (algebra add: sq_def)

lemma
  fixes p1 :: "'a::{idom}"
  shows
  "(sq p1 + sq q1 + sq r1 + sq s1 + sq t1 + sq u1 + sq v1 + sq w1) *
   (sq p2 + sq q2 + sq r2 + sq s2 + sq t2 + sq u2 + sq v2 + sq w2)
    = sq (p1*p2 - q1*q2 - r1*r2 - s1*s2 - t1*t2 - u1*u2 - v1*v2 - w1*w2) +
      sq (p1*q2 + q1*p2 + r1*s2 - s1*r2 + t1*u2 - u1*t2 - v1*w2 + w1*v2) +
      sq (p1*r2 - q1*s2 + r1*p2 + s1*q2 + t1*v2 + u1*w2 - v1*t2 - w1*u2) +
      sq (p1*s2 + q1*r2 - r1*q2 + s1*p2 + t1*w2 - u1*v2 + v1*u2 - w1*t2) +
      sq (p1*t2 - q1*u2 - r1*v2 - s1*w2 + t1*p2 + u1*q2 + v1*r2 + w1*s2) +
      sq (p1*u2 + q1*t2 - r1*w2 + s1*v2 - t1*q2 + u1*p2 - v1*s2 + w1*r2) +
      sq (p1*v2 + q1*w2 + r1*t2 - s1*u2 - t1*r2 + u1*s2 + v1*p2 - w1*q2) +
      sq (p1*w2 - q1*v2 + r1*u2 + s1*t2 - t1*s2 - u1*r2 + v1*q2 + w1*p2)"
  by (algebra add: sq_def)

subsection \<open>Colinearity is invariant by rotation\<close>

type_synonym point = "int \<times> int"

definition collinear ::"point \<Rightarrow> point \<Rightarrow> point \<Rightarrow> bool" where
  "collinear \<equiv> \<lambda>(Ax,Ay) (Bx,By) (Cx,Cy).
    ((Ax - Bx) * (By - Cy) = (Ay - By) * (Bx - Cx))"

lemma collinear_inv_rotation:
  assumes "collinear (Ax, Ay) (Bx, By) (Cx, Cy)" and "c\<^sup>2 + s\<^sup>2 = 1"
  shows "collinear (Ax * c - Ay * s, Ay * c + Ax * s)
    (Bx * c - By * s, By * c + Bx * s) (Cx * c - Cy * s, Cy * c + Cx * s)"
  using assms
  by (algebra add: collinear_def split_def fst_conv snd_conv)

lemma "EX (d::int). a*y - a*x = n*d \<Longrightarrow> EX u v. a*u + n*v = 1 \<Longrightarrow> EX e. y - x = n*e"
  by algebra

end


theory minus
imports Main
        "../data/Natu"
        "$HIPSTER_HOME/IsaHipster"
begin

fun minus :: "Nat => Nat => Nat" where
  "minus (Z) y = Z"
| "minus (S z) (Z) = S z"
| "minus (S z) (S x2) = minus z x2"

lemma lemma_a [thy_expl]: "minus x2 x2 = Z"
by (hipster_induct_schemes minus.simps)

lemma lemma_aa [thy_expl]: "minus x3 Z = x3"
by (hipster_induct_schemes minus.simps)

lemma lemma_ab [thy_expl]: "minus x2 (S x2) = Z"
by (hipster_induct_schemes)

lemma lemma_ac [thy_expl]: "minus (S x2) x2 = S Z"
by (hipster_induct_schemes)

lemma lemma_ad [thy_expl]: "minus (minus x3 y3) (minus y3 x3) = minus x3 y3"
by (hipster_induct_schemes minus.simps)

lemma lemma_ae [thy_expl]: "minus (minus x3 y3) (S Z) = minus x3 (S y3)"
by (hipster_induct_schemes minus.simps)

lemma lemma_af [thy_expl]: "minus (minus x4 y4) x4 = Z"
by (hipster_induct_schemes minus.simps)

end


(*  Title:      HOL/Library/Extended_Nat.thy
    Author:     David von Oheimb, TU Muenchen;  Florian Haftmann, TU Muenchen
    Contributions: David Trachtenherz, TU Muenchen
*)

section \<open>Extended natural numbers (i.e. with infinity)\<close>

theory Extended_Nat
imports MainRLT Countable Order_Continuity
begin

class infinity =
  fixes infinity :: "'a"  ("\<infinity>")

context
  fixes f :: "nat \<Rightarrow> 'a::{canonically_ordered_monoid_add, linorder_topology, complete_linorder}"
begin

lemma sums_SUP[simp, intro]: "f sums (SUP n. \<Sum>i<n. f i)"
  unfolding sums_def by (intro LIMSEQ_SUP monoI sum_mono2 zero_le) auto

lemma suminf_eq_SUP: "suminf f = (SUP n. \<Sum>i<n. f i)"
  using sums_SUP by (rule sums_unique[symmetric])

end

subsection \<open>Type definition\<close>

text \<open>
  We extend the standard natural numbers by a special value indicating
  infinity.
\<close>

typedef enat = "UNIV :: nat option set" ..

text \<open>TODO: introduce enat as coinductive datatype, enat is just \<^const>\<open>of_nat\<close>\<close>

definition enat :: "nat \<Rightarrow> enat" where
  "enat n = Abs_enat (Some n)"

instantiation enat :: infinity
begin

definition "\<infinity> = Abs_enat None"
instance ..

end

instance enat :: countable
proof
  show "\<exists>to_nat::enat \<Rightarrow> nat. inj to_nat"
    by (rule exI[of _ "to_nat \<circ> Rep_enat"]) (simp add: inj_on_def Rep_enat_inject)
qed

old_rep_datatype enat "\<infinity> :: enat"
proof -
  fix P i assume "\<And>j. P (enat j)" "P \<infinity>"
  then show "P i"
  proof induct
    case (Abs_enat y) then show ?case
      by (cases y rule: option.exhaust)
         (auto simp: enat_def infinity_enat_def)
  qed
qed (auto simp add: enat_def infinity_enat_def Abs_enat_inject)

declare [[coercion "enat::nat\<Rightarrow>enat"]]

lemmas enat2_cases = enat.exhaust[case_product enat.exhaust]
lemmas enat3_cases = enat.exhaust[case_product enat.exhaust enat.exhaust]

lemma not_infinity_eq [iff]: "(x \<noteq> \<infinity>) = (\<exists>i. x = enat i)"
  by (cases x) auto

lemma not_enat_eq [iff]: "(\<forall>y. x \<noteq> enat y) = (x = \<infinity>)"
  by (cases x) auto

lemma enat_ex_split: "(\<exists>c::enat. P c) \<longleftrightarrow> P \<infinity> \<or> (\<exists>c::nat. P c)"
  by (metis enat.exhaust)

primrec the_enat :: "enat \<Rightarrow> nat"
  where "the_enat (enat n) = n"

subsection \<open>Constructors and numbers\<close>

instantiation enat :: zero_neq_one
begin

definition
  "0 = enat 0"

definition
  "1 = enat 1"

instance
  proof qed (simp add: zero_enat_def one_enat_def)

end

definition eSuc :: "enat \<Rightarrow> enat" where
  "eSuc i = (case i of enat n \<Rightarrow> enat (Suc n) | \<infinity> \<Rightarrow> \<infinity>)"

lemma enat_0 [code_post]: "enat 0 = 0"
  by (simp add: zero_enat_def)

lemma enat_1 [code_post]: "enat 1 = 1"
  by (simp add: one_enat_def)

lemma enat_0_iff: "enat x = 0 \<longleftrightarrow> x = 0" "0 = enat x \<longleftrightarrow> x = 0"
  by (auto simp add: zero_enat_def)

lemma enat_1_iff: "enat x = 1 \<longleftrightarrow> x = 1" "1 = enat x \<longleftrightarrow> x = 1"
  by (auto simp add: one_enat_def)

lemma one_eSuc: "1 = eSuc 0"
  by (simp add: zero_enat_def one_enat_def eSuc_def)

lemma infinity_ne_i0 [simp]: "(\<infinity>::enat) \<noteq> 0"
  by (simp add: zero_enat_def)

lemma i0_ne_infinity [simp]: "0 \<noteq> (\<infinity>::enat)"
  by (simp add: zero_enat_def)

lemma zero_one_enat_neq:
  "\<not> 0 = (1::enat)"
  "\<not> 1 = (0::enat)"
  unfolding zero_enat_def one_enat_def by simp_all

lemma infinity_ne_i1 [simp]: "(\<infinity>::enat) \<noteq> 1"
  by (simp add: one_enat_def)

lemma i1_ne_infinity [simp]: "1 \<noteq> (\<infinity>::enat)"
  by (simp add: one_enat_def)

lemma eSuc_enat: "eSuc (enat n) = enat (Suc n)"
  by (simp add: eSuc_def)

lemma eSuc_infinity [simp]: "eSuc \<infinity> = \<infinity>"
  by (simp add: eSuc_def)

lemma eSuc_ne_0 [simp]: "eSuc n \<noteq> 0"
  by (simp add: eSuc_def zero_enat_def split: enat.splits)

lemma zero_ne_eSuc [simp]: "0 \<noteq> eSuc n"
  by (rule eSuc_ne_0 [symmetric])

lemma eSuc_inject [simp]: "eSuc m = eSuc n \<longleftrightarrow> m = n"
  by (simp add: eSuc_def split: enat.splits)

lemma eSuc_enat_iff: "eSuc x = enat y \<longleftrightarrow> (\<exists>n. y = Suc n \<and> x = enat n)"
  by (cases y) (auto simp: enat_0 eSuc_enat[symmetric])

lemma enat_eSuc_iff: "enat y = eSuc x \<longleftrightarrow> (\<exists>n. y = Suc n \<and> enat n = x)"
  by (cases y) (auto simp: enat_0 eSuc_enat[symmetric])

subsection \<open>Addition\<close>

instantiation enat :: comm_monoid_add
begin

definition [nitpick_simp]:
  "m + n = (case m of \<infinity> \<Rightarrow> \<infinity> | enat m \<Rightarrow> (case n of \<infinity> \<Rightarrow> \<infinity> | enat n \<Rightarrow> enat (m + n)))"

lemma plus_enat_simps [simp, code]:
  fixes q :: enat
  shows "enat m + enat n = enat (m + n)"
    and "\<infinity> + q = \<infinity>"
    and "q + \<infinity> = \<infinity>"
  by (simp_all add: plus_enat_def split: enat.splits)

instance
proof
  fix n m q :: enat
  show "n + m + q = n + (m + q)"
    by (cases n m q rule: enat3_cases) auto
  show "n + m = m + n"
    by (cases n m rule: enat2_cases) auto
  show "0 + n = n"
    by (cases n) (simp_all add: zero_enat_def)
qed

end

lemma eSuc_plus_1:
  "eSuc n = n + 1"
  by (cases n) (simp_all add: eSuc_enat one_enat_def)

lemma plus_1_eSuc:
  "1 + q = eSuc q"
  "q + 1 = eSuc q"
  by (simp_all add: eSuc_plus_1 ac_simps)

lemma iadd_Suc: "eSuc m + n = eSuc (m + n)"
  by (simp_all add: eSuc_plus_1 ac_simps)

lemma iadd_Suc_right: "m + eSuc n = eSuc (m + n)"
  by (simp only: add.commute[of m] iadd_Suc)

subsection \<open>Multiplication\<close>

instantiation enat :: "{comm_semiring_1, semiring_no_zero_divisors}"
begin

definition times_enat_def [nitpick_simp]:
  "m * n = (case m of \<infinity> \<Rightarrow> if n = 0 then 0 else \<infinity> | enat m \<Rightarrow>
    (case n of \<infinity> \<Rightarrow> if m = 0 then 0 else \<infinity> | enat n \<Rightarrow> enat (m * n)))"

lemma times_enat_simps [simp, code]:
  "enat m * enat n = enat (m * n)"
  "\<infinity> * \<infinity> = (\<infinity>::enat)"
  "\<infinity> * enat n = (if n = 0 then 0 else \<infinity>)"
  "enat m * \<infinity> = (if m = 0 then 0 else \<infinity>)"
  unfolding times_enat_def zero_enat_def
  by (simp_all split: enat.split)

instance
proof
  fix a b c :: enat
  show "(a * b) * c = a * (b * c)"
    unfolding times_enat_def zero_enat_def
    by (simp split: enat.split)
  show comm: "a * b = b * a"
    unfolding times_enat_def zero_enat_def
    by (simp split: enat.split)
  show "1 * a = a"
    unfolding times_enat_def zero_enat_def one_enat_def
    by (simp split: enat.split)
  show distr: "(a + b) * c = a * c + b * c"
    unfolding times_enat_def zero_enat_def
    by (simp split: enat.split add: distrib_right)
  show "0 * a = 0"
    unfolding times_enat_def zero_enat_def
    by (simp split: enat.split)
  show "a * 0 = 0"
    unfolding times_enat_def zero_enat_def
    by (simp split: enat.split)
  show "a * (b + c) = a * b + a * c"
    by (cases a b c rule: enat3_cases) (auto simp: times_enat_def zero_enat_def distrib_left)
  show "a \<noteq> 0 \<Longrightarrow> b \<noteq> 0 \<Longrightarrow> a * b \<noteq> 0"
    by (cases a b rule: enat2_cases) (auto simp: times_enat_def zero_enat_def)
qed

end

lemma mult_eSuc: "eSuc m * n = n + m * n"
  unfolding eSuc_plus_1 by (simp add: algebra_simps)

lemma mult_eSuc_right: "m * eSuc n = m + m * n"
  unfolding eSuc_plus_1 by (simp add: algebra_simps)

lemma of_nat_eq_enat: "of_nat n = enat n"
  apply (induct n)
  apply (simp add: enat_0)
  apply (simp add: plus_1_eSuc eSuc_enat)
  done

instance enat :: semiring_char_0
proof
  have "inj enat" by (rule injI) simp
  then show "inj (\<lambda>n. of_nat n :: enat)" by (simp add: of_nat_eq_enat)
qed

lemma imult_is_infinity: "((a::enat) * b = \<infinity>) = (a = \<infinity> \<and> b \<noteq> 0 \<or> b = \<infinity> \<and> a \<noteq> 0)"
  by (auto simp add: times_enat_def zero_enat_def split: enat.split)

subsection \<open>Numerals\<close>

lemma numeral_eq_enat:
  "numeral k = enat (numeral k)"
  using of_nat_eq_enat [of "numeral k"] by simp

lemma enat_numeral [code_abbrev]:
  "enat (numeral k) = numeral k"
  using numeral_eq_enat ..

lemma infinity_ne_numeral [simp]: "(\<infinity>::enat) \<noteq> numeral k"
  by (simp add: numeral_eq_enat)

lemma numeral_ne_infinity [simp]: "numeral k \<noteq> (\<infinity>::enat)"
  by (simp add: numeral_eq_enat)

lemma eSuc_numeral [simp]: "eSuc (numeral k) = numeral (k + Num.One)"
  by (simp only: eSuc_plus_1 numeral_plus_one)

subsection \<open>Subtraction\<close>

instantiation enat :: minus
begin

definition diff_enat_def:
"a - b = (case a of (enat x) \<Rightarrow> (case b of (enat y) \<Rightarrow> enat (x - y) | \<infinity> \<Rightarrow> 0)
          | \<infinity> \<Rightarrow> \<infinity>)"

instance ..

end

lemma idiff_enat_enat [simp, code]: "enat a - enat b = enat (a - b)"
  by (simp add: diff_enat_def)

lemma idiff_infinity [simp, code]: "\<infinity> - n = (\<infinity>::enat)"
  by (simp add: diff_enat_def)

lemma idiff_infinity_right [simp, code]: "enat a - \<infinity> = 0"
  by (simp add: diff_enat_def)

lemma idiff_0 [simp]: "(0::enat) - n = 0"
  by (cases n, simp_all add: zero_enat_def)

lemmas idiff_enat_0 [simp] = idiff_0 [unfolded zero_enat_def]

lemma idiff_0_right [simp]: "(n::enat) - 0 = n"
  by (cases n) (simp_all add: zero_enat_def)

lemmas idiff_enat_0_right [simp] = idiff_0_right [unfolded zero_enat_def]

lemma idiff_self [simp]: "n \<noteq> \<infinity> \<Longrightarrow> (n::enat) - n = 0"
  by (auto simp: zero_enat_def)

lemma eSuc_minus_eSuc [simp]: "eSuc n - eSuc m = n - m"
  by (simp add: eSuc_def split: enat.split)

lemma eSuc_minus_1 [simp]: "eSuc n - 1 = n"
  by (simp add: one_enat_def flip: eSuc_enat zero_enat_def)

(*lemmas idiff_self_eq_0_enat = idiff_self_eq_0[unfolded zero_enat_def]*)

subsection \<open>Ordering\<close>

instantiation enat :: linordered_ab_semigroup_add
begin

definition [nitpick_simp]:
  "m \<le> n = (case n of enat n1 \<Rightarrow> (case m of enat m1 \<Rightarrow> m1 \<le> n1 | \<infinity> \<Rightarrow> False)
    | \<infinity> \<Rightarrow> True)"

definition [nitpick_simp]:
  "m < n = (case m of enat m1 \<Rightarrow> (case n of enat n1 \<Rightarrow> m1 < n1 | \<infinity> \<Rightarrow> True)
    | \<infinity> \<Rightarrow> False)"

lemma enat_ord_simps [simp]:
  "enat m \<le> enat n \<longleftrightarrow> m \<le> n"
  "enat m < enat n \<longleftrightarrow> m < n"
  "q \<le> (\<infinity>::enat)"
  "q < (\<infinity>::enat) \<longleftrightarrow> q \<noteq> \<infinity>"
  "(\<infinity>::enat) \<le> q \<longleftrightarrow> q = \<infinity>"
  "(\<infinity>::enat) < q \<longleftrightarrow> False"
  by (simp_all add: less_eq_enat_def less_enat_def split: enat.splits)

lemma numeral_le_enat_iff[simp]:
  shows "numeral m \<le> enat n \<longleftrightarrow> numeral m \<le> n"
by (auto simp: numeral_eq_enat)

lemma numeral_less_enat_iff[simp]:
  shows "numeral m < enat n \<longleftrightarrow> numeral m < n"
by (auto simp: numeral_eq_enat)

lemma enat_ord_code [code]:
  "enat m \<le> enat n \<longleftrightarrow> m \<le> n"
  "enat m < enat n \<longleftrightarrow> m < n"
  "q \<le> (\<infinity>::enat) \<longleftrightarrow> True"
  "enat m < \<infinity> \<longleftrightarrow> True"
  "\<infinity> \<le> enat n \<longleftrightarrow> False"
  "(\<infinity>::enat) < q \<longleftrightarrow> False"
  by simp_all

instance
  by standard (auto simp add: less_eq_enat_def less_enat_def plus_enat_def split: enat.splits)

end

instance enat :: dioid
proof
  fix a b :: enat show "(a \<le> b) = (\<exists>c. b = a + c)"
    by (cases a b rule: enat2_cases) (auto simp: le_iff_add enat_ex_split)
qed

instance enat :: "{linordered_nonzero_semiring, strict_ordered_comm_monoid_add}"
proof
  fix a b c :: enat
  show "a \<le> b \<Longrightarrow> 0 \<le> c \<Longrightarrow>c * a \<le> c * b"
    unfolding times_enat_def less_eq_enat_def zero_enat_def
    by (simp split: enat.splits)
  show "a < b \<Longrightarrow> c < d \<Longrightarrow> a + c < b + d" for a b c d :: enat
    by (cases a b c d rule: enat2_cases[case_product enat2_cases]) auto
  show "a < b \<Longrightarrow> a + 1 < b + 1"
    by (metis add_right_mono eSuc_minus_1 eSuc_plus_1 less_le)
qed (simp add: zero_enat_def one_enat_def)

(* BH: These equations are already proven generally for any type in
class linordered_semidom. However, enat is not in that class because
it does not have the cancellation property. Would it be worthwhile to
a generalize linordered_semidom to a new class that includes enat? *)

lemma add_diff_assoc_enat: "z \<le> y \<Longrightarrow> x + (y - z) = x + y - (z::enat)"
by(cases x)(auto simp add: diff_enat_def split: enat.split)

lemma enat_ord_number [simp]:
  "(numeral m :: enat) \<le> numeral n \<longleftrightarrow> (numeral m :: nat) \<le> numeral n"
  "(numeral m :: enat) < numeral n \<longleftrightarrow> (numeral m :: nat) < numeral n"
  by (simp_all add: numeral_eq_enat)

lemma infinity_ileE [elim!]: "\<infinity> \<le> enat m \<Longrightarrow> R"
  by (simp add: zero_enat_def less_eq_enat_def split: enat.splits)

lemma infinity_ilessE [elim!]: "\<infinity> < enat m \<Longrightarrow> R"
  by simp

lemma eSuc_ile_mono [simp]: "eSuc n \<le> eSuc m \<longleftrightarrow> n \<le> m"
  by (simp add: eSuc_def less_eq_enat_def split: enat.splits)

lemma eSuc_mono [simp]: "eSuc n < eSuc m \<longleftrightarrow> n < m"
  by (simp add: eSuc_def less_enat_def split: enat.splits)

lemma ile_eSuc [simp]: "n \<le> eSuc n"
  by (simp add: eSuc_def less_eq_enat_def split: enat.splits)

lemma not_eSuc_ilei0 [simp]: "\<not> eSuc n \<le> 0"
  by (simp add: zero_enat_def eSuc_def less_eq_enat_def split: enat.splits)

lemma i0_iless_eSuc [simp]: "0 < eSuc n"
  by (simp add: zero_enat_def eSuc_def less_enat_def split: enat.splits)

lemma iless_eSuc0[simp]: "(n < eSuc 0) = (n = 0)"
  by (simp add: zero_enat_def eSuc_def less_enat_def split: enat.split)

lemma ileI1: "m < n \<Longrightarrow> eSuc m \<le> n"
  by (simp add: eSuc_def less_eq_enat_def less_enat_def split: enat.splits)

lemma Suc_ile_eq: "enat (Suc m) \<le> n \<longleftrightarrow> enat m < n"
  by (cases n) auto

lemma iless_Suc_eq [simp]: "enat m < eSuc n \<longleftrightarrow> enat m \<le> n"
  by (auto simp add: eSuc_def less_enat_def split: enat.splits)

lemma imult_infinity: "(0::enat) < n \<Longrightarrow> \<infinity> * n = \<infinity>"
  by (simp add: zero_enat_def less_enat_def split: enat.splits)

lemma imult_infinity_right: "(0::enat) < n \<Longrightarrow> n * \<infinity> = \<infinity>"
  by (simp add: zero_enat_def less_enat_def split: enat.splits)

lemma enat_0_less_mult_iff: "(0 < (m::enat) * n) = (0 < m \<and> 0 < n)"
  by (simp only: zero_less_iff_neq_zero mult_eq_0_iff, simp)

lemma mono_eSuc: "mono eSuc"
  by (simp add: mono_def)

lemma min_enat_simps [simp]:
  "min (enat m) (enat n) = enat (min m n)"
  "min q 0 = 0"
  "min 0 q = 0"
  "min q (\<infinity>::enat) = q"
  "min (\<infinity>::enat) q = q"
  by (auto simp add: min_def)

lemma max_enat_simps [simp]:
  "max (enat m) (enat n) = enat (max m n)"
  "max q 0 = q"
  "max 0 q = q"
  "max q \<infinity> = (\<infinity>::enat)"
  "max \<infinity> q = (\<infinity>::enat)"
  by (simp_all add: max_def)

lemma enat_ile: "n \<le> enat m \<Longrightarrow> \<exists>k. n = enat k"
  by (cases n) simp_all

lemma enat_iless: "n < enat m \<Longrightarrow> \<exists>k. n = enat k"
  by (cases n) simp_all

lemma iadd_le_enat_iff:
  "x + y \<le> enat n \<longleftrightarrow> (\<exists>y' x'. x = enat x' \<and> y = enat y' \<and> x' + y' \<le> n)"
by(cases x y rule: enat.exhaust[case_product enat.exhaust]) simp_all

lemma chain_incr: "\<forall>i. \<exists>j. Y i < Y j \<Longrightarrow> \<exists>j. enat k < Y j"
apply (induct_tac k)
 apply (simp (no_asm) only: enat_0)
 apply (fast intro: le_less_trans [OF zero_le])
apply (erule exE)
apply (drule spec)
apply (erule exE)
apply (drule ileI1)
apply (rule eSuc_enat [THEN subst])
apply (rule exI)
apply (erule (1) le_less_trans)
done

lemma eSuc_max: "eSuc (max x y) = max (eSuc x) (eSuc y)"
  by (simp add: eSuc_def split: enat.split)

lemma eSuc_Max:
  assumes "finite A" "A \<noteq> {}"
  shows "eSuc (Max A) = Max (eSuc ` A)"
using assms proof induction
  case (insert x A)
  thus ?case by(cases "A = {}")(simp_all add: eSuc_max)
qed simp

instantiation enat :: "{order_bot, order_top}"
begin

definition bot_enat :: enat where "bot_enat = 0"
definition top_enat :: enat where "top_enat = \<infinity>"

instance
  by standard (simp_all add: bot_enat_def top_enat_def)

end

lemma finite_enat_bounded:
  assumes le_fin: "\<And>y. y \<in> A \<Longrightarrow> y \<le> enat n"
  shows "finite A"
proof (rule finite_subset)
  show "finite (enat ` {..n})" by blast
  have "A \<subseteq> {..enat n}" using le_fin by fastforce
  also have "\<dots> \<subseteq> enat ` {..n}"
    apply (rule subsetI)
    subgoal for x by (cases x) auto
    done
  finally show "A \<subseteq> enat ` {..n}" .
qed

subsection \<open>Cancellation simprocs\<close>

lemma add_diff_cancel_enat[simp]: "x \<noteq> \<infinity> \<Longrightarrow> x + y - x = (y::enat)"
by (metis add.commute add.right_neutral add_diff_assoc_enat idiff_self order_refl)

lemma enat_add_left_cancel: "a + b = a + c \<longleftrightarrow> a = (\<infinity>::enat) \<or> b = c"
  unfolding plus_enat_def by (simp split: enat.split)

lemma enat_add_left_cancel_le: "a + b \<le> a + c \<longleftrightarrow> a = (\<infinity>::enat) \<or> b \<le> c"
  unfolding plus_enat_def by (simp split: enat.split)

lemma enat_add_left_cancel_less: "a + b < a + c \<longleftrightarrow> a \<noteq> (\<infinity>::enat) \<and> b < c"
  unfolding plus_enat_def by (simp split: enat.split)

lemma plus_eq_infty_iff_enat: "(m::enat) + n = \<infinity> \<longleftrightarrow> m=\<infinity> \<or> n=\<infinity>"
using enat_add_left_cancel by fastforce

ML \<open>
structure Cancel_Enat_Common =
struct
  (* copied from src/HOL/Tools/nat_numeral_simprocs.ML *)
  fun find_first_t _    _ []         = raise TERM("find_first_t", [])
    | find_first_t past u (t::terms) =
          if u aconv t then (rev past @ terms)
          else find_first_t (t::past) u terms

  fun dest_summing (Const (\<^const_name>\<open>Groups.plus\<close>, _) $ t $ u, ts) =
        dest_summing (t, dest_summing (u, ts))
    | dest_summing (t, ts) = t :: ts

  val mk_sum = Arith_Data.long_mk_sum
  fun dest_sum t = dest_summing (t, [])
  val find_first = find_first_t []
  val trans_tac = Numeral_Simprocs.trans_tac
  val norm_ss =
    simpset_of (put_simpset HOL_basic_ss \<^context>
      addsimps @{thms ac_simps add_0_left add_0_right})
  fun norm_tac ctxt = ALLGOALS (simp_tac (put_simpset norm_ss ctxt))
  fun simplify_meta_eq ctxt cancel_th th =
    Arith_Data.simplify_meta_eq [] ctxt
      ([th, cancel_th] MRS trans)
  fun mk_eq (a, b) = HOLogic.mk_Trueprop (HOLogic.mk_eq (a, b))
end

structure Eq_Enat_Cancel = ExtractCommonTermFun
(open Cancel_Enat_Common
  val mk_bal = HOLogic.mk_eq
  val dest_bal = HOLogic.dest_bin \<^const_name>\<open>HOL.eq\<close> \<^typ>\<open>enat\<close>
  fun simp_conv _ _ = SOME @{thm enat_add_left_cancel}
)

structure Le_Enat_Cancel = ExtractCommonTermFun
(open Cancel_Enat_Common
  val mk_bal = HOLogic.mk_binrel \<^const_name>\<open>Orderings.less_eq\<close>
  val dest_bal = HOLogic.dest_bin \<^const_name>\<open>Orderings.less_eq\<close> \<^typ>\<open>enat\<close>
  fun simp_conv _ _ = SOME @{thm enat_add_left_cancel_le}
)

structure Less_Enat_Cancel = ExtractCommonTermFun
(open Cancel_Enat_Common
  val mk_bal = HOLogic.mk_binrel \<^const_name>\<open>Orderings.less\<close>
  val dest_bal = HOLogic.dest_bin \<^const_name>\<open>Orderings.less\<close> \<^typ>\<open>enat\<close>
  fun simp_conv _ _ = SOME @{thm enat_add_left_cancel_less}
)
\<close>

simproc_setup enat_eq_cancel
  ("(l::enat) + m = n" | "(l::enat) = m + n") =
  \<open>fn phi => fn ctxt => fn ct => Eq_Enat_Cancel.proc ctxt (Thm.term_of ct)\<close>

simproc_setup enat_le_cancel
  ("(l::enat) + m \<le> n" | "(l::enat) \<le> m + n") =
  \<open>fn phi => fn ctxt => fn ct => Le_Enat_Cancel.proc ctxt (Thm.term_of ct)\<close>

simproc_setup enat_less_cancel
  ("(l::enat) + m < n" | "(l::enat) < m + n") =
  \<open>fn phi => fn ctxt => fn ct => Less_Enat_Cancel.proc ctxt (Thm.term_of ct)\<close>

text \<open>TODO: add regression tests for these simprocs\<close>

text \<open>TODO: add simprocs for combining and cancelling numerals\<close>

subsection \<open>Well-ordering\<close>

lemma less_enatE:
  "[| n < enat m; !!k. n = enat k ==> k < m ==> P |] ==> P"
by (induct n) auto

lemma less_infinityE:
  "[| n < \<infinity>; !!k. n = enat k ==> P |] ==> P"
by (induct n) auto

lemma enat_less_induct:
  assumes prem: "\<And>n. \<forall>m::enat. m < n \<longrightarrow> P m \<Longrightarrow> P n" shows "P n"
proof -
  have P_enat: "\<And>k. P (enat k)"
    apply (rule nat_less_induct)
    apply (rule prem, clarify)
    apply (erule less_enatE, simp)
    done
  show ?thesis
  proof (induct n)
    fix nat
    show "P (enat nat)" by (rule P_enat)
  next
    show "P \<infinity>"
      apply (rule prem, clarify)
      apply (erule less_infinityE)
      apply (simp add: P_enat)
      done
  qed
qed

instance enat :: wellorder
proof
  fix P and n
  assume hyp: "(\<And>n::enat. (\<And>m::enat. m < n \<Longrightarrow> P m) \<Longrightarrow> P n)"
  show "P n" by (blast intro: enat_less_induct hyp)
qed

subsection \<open>Complete Lattice\<close>

instantiation enat :: complete_lattice
begin

definition inf_enat :: "enat \<Rightarrow> enat \<Rightarrow> enat" where
  "inf_enat = min"

definition sup_enat :: "enat \<Rightarrow> enat \<Rightarrow> enat" where
  "sup_enat = max"

definition Inf_enat :: "enat set \<Rightarrow> enat" where
  "Inf_enat A = (if A = {} then \<infinity> else (LEAST x. x \<in> A))"

definition Sup_enat :: "enat set \<Rightarrow> enat" where
  "Sup_enat A = (if A = {} then 0 else if finite A then Max A else \<infinity>)"
instance
proof
  fix x :: "enat" and A :: "enat set"
  { assume "x \<in> A" then show "Inf A \<le> x"
      unfolding Inf_enat_def by (auto intro: Least_le) }
  { assume "\<And>y. y \<in> A \<Longrightarrow> x \<le> y" then show "x \<le> Inf A"
      unfolding Inf_enat_def
      by (cases "A = {}") (auto intro: LeastI2_ex) }
  { assume "x \<in> A" then show "x \<le> Sup A"
      unfolding Sup_enat_def by (cases "finite A") auto }
  { assume "\<And>y. y \<in> A \<Longrightarrow> y \<le> x" then show "Sup A \<le> x"
      unfolding Sup_enat_def using finite_enat_bounded by auto }
qed (simp_all add:
 inf_enat_def sup_enat_def bot_enat_def top_enat_def Inf_enat_def Sup_enat_def)
end

instance enat :: complete_linorder ..

lemma eSuc_Sup: "A \<noteq> {} \<Longrightarrow> eSuc (Sup A) = Sup (eSuc ` A)"
  by(auto simp add: Sup_enat_def eSuc_Max inj_on_def dest: finite_imageD)

lemma sup_continuous_eSuc: "sup_continuous f \<Longrightarrow> sup_continuous (\<lambda>x. eSuc (f x))"
  using eSuc_Sup [of "_ ` UNIV"] by (auto simp: sup_continuous_def image_comp)

subsection \<open>Traditional theorem names\<close>

lemmas enat_defs = zero_enat_def one_enat_def eSuc_def
  plus_enat_def less_eq_enat_def less_enat_def

lemma iadd_is_0: "(m + n = (0::enat)) = (m = 0 \<and> n = 0)"
  by (rule add_eq_0_iff_both_eq_0)

lemma i0_lb : "(0::enat) \<le> n"
  by (rule zero_le)

lemma ile0_eq: "n \<le> (0::enat) \<longleftrightarrow> n = 0"
  by (rule le_zero_eq)

lemma not_iless0: "\<not> n < (0::enat)"
  by (rule not_less_zero)

lemma i0_less[simp]: "(0::enat) < n \<longleftrightarrow> n \<noteq> 0"
  by (rule zero_less_iff_neq_zero)

lemma imult_is_0: "((m::enat) * n = 0) = (m = 0 \<or> n = 0)"
  by (rule mult_eq_0_iff)

end


(* Author: Johannes Hölzl <hoelzl@in.tum.de> *)

subsection \<open>Trace Space equal to Markov Chains\<close>

theory Trace_Space_Equals_Markov_Processes
  imports Discrete_Time_Markov_Chain
begin

text \<open>
  We can construct for each time-homogeneous discrete-time Markov chain a corresponding
  probability space using @{theory Markov_Models.Discrete_Time_Markov_Chain}. The constructed probability space
  has the same probabilities.
\<close>

locale Time_Homogeneous_Discrete_Markov_Process = M?: prob_space +
  fixes S :: "'s set" and X :: "nat \<Rightarrow> 'a \<Rightarrow> 's"
  assumes X [measurable]: "\<And>t. X t \<in> measurable M (count_space UNIV)"
  assumes S: "countable S" "\<And>n. AE x in M. X n x \<in> S"
  assumes MC: "\<And>n s s'.
    \<P>(\<omega> in M. \<forall>t\<le>n. X t \<omega> = s t ) \<noteq> 0 \<Longrightarrow>
    \<P>(\<omega> in M. X (Suc n) \<omega> = s' \<bar> \<forall>t\<le>n. X t \<omega> = s t ) =
    \<P>(\<omega> in M. X (Suc n) \<omega> = s' \<bar> X n \<omega> = s n )"
  assumes TH: "\<And>n m s t.
    \<P>(\<omega> in M. X n \<omega> = t) \<noteq> 0 \<Longrightarrow> \<P>(\<omega> in M. X m \<omega> = t) \<noteq> 0 \<Longrightarrow>
    \<P>(\<omega> in M. X (Suc n) \<omega> = s \<bar> X n \<omega> = t) = \<P>(\<omega> in M. X (Suc m) \<omega> = s \<bar> X m \<omega> = t)"
begin

context
begin

interpretation pmf_as_measure .

lift_definition I :: "'s pmf" is "distr M (count_space UNIV) (X 0)"
proof -
  let ?X = "distr M (count_space UNIV) (X 0)"
  interpret X: prob_space ?X
    by (auto simp: prob_space_distr)
  have "AE x in ?X. measure ?X {x} \<noteq> 0"
    using S by (subst X.AE_support_countable) (auto simp: AE_distr_iff intro!: exI[of _ S])
  then show "prob_space ?X \<and> sets ?X = UNIV \<and> (AE x in ?X. measure ?X {x} \<noteq> 0)"
    by (simp add: prob_space_distr AE_support_countable)
qed

lemma I_in_S:
  assumes "pmf I s \<noteq> 0" shows "s \<in> S"
proof -
  from \<open>pmf I s \<noteq> 0\<close> have "0 \<noteq> \<P>(x in M. X 0 x = s)"
    by transfer (auto simp: measure_distr vimage_def Int_def conj_commute)
  also have "\<P>(x in M. X 0 x = s) = \<P>(x in M. X 0 x = s \<and> s \<in> S)"
    using S(2)[of 0] by (intro M.finite_measure_eq_AE) auto
  finally show ?thesis
    by (cases "s \<in> S") auto
qed

lift_definition K :: "'s \<Rightarrow> 's pmf" is
  "\<lambda>s. with (\<lambda>n. \<P>(\<omega> in M. X n \<omega> = s) \<noteq> 0)
     (\<lambda>n. distr (uniform_measure M {\<omega>\<in>space M. X n \<omega> = s}) (count_space UNIV) (X (Suc n)))
     (uniform_measure (count_space UNIV) {s})"
proof (rule withI)
  fix s n assume *: "\<P>(\<omega> in M. X n \<omega> = s) \<noteq> 0"
  let ?D = "distr (uniform_measure M {\<omega>\<in>space M. X n \<omega> = s}) (count_space UNIV) (X (Suc n))"
  have D: "prob_space ?D"
    by (intro prob_space.prob_space_distr prob_space_uniform_measure)
       (auto simp: M.emeasure_eq_measure *)
  then interpret D: prob_space ?D .
  have sets_D: "sets ?D = UNIV"
    by simp
  moreover have "AE x in ?D. measure ?D {x} \<noteq> 0"
    unfolding D.AE_support_countable[OF sets_D]
  proof (intro exI[of _ S] conjI)
    show "countable S" by (rule S)
    show "AE x in ?D. x \<in> S"
      using * S(2)[of "Suc n"] by (auto simp add: AE_distr_iff AE_uniform_measure M.emeasure_eq_measure)
  qed
  ultimately show "prob_space ?D \<and> sets ?D = UNIV \<and> (AE x in ?D. measure ?D {x} \<noteq> 0)"
    using D by blast
qed (auto intro!: prob_space_uniform_measure AE_uniform_measureI)

lemma pmf_K:
  assumes n: "0 < \<P>(\<omega> in M. X n \<omega> = s)"
  shows "pmf (K s) t = \<P>(\<omega> in M. X (Suc n) \<omega> = t \<bar> X n \<omega> = s)"
proof (transfer fixing: n s t)
  let ?P = "\<lambda>n. \<P>(\<omega> in M. X n \<omega> = s) \<noteq> 0"
  let ?D = "\<lambda>n. distr (uniform_measure M {\<omega>\<in>space M. X n \<omega> = s}) (count_space UNIV) (X (Suc n))"
  let ?U = "uniform_measure (count_space UNIV) {s}"
  show "measure (with ?P ?D ?U) {t} = \<P>(\<omega> in M. X (Suc n) \<omega> = t \<bar> X n \<omega> = s)"
  proof (rule withI)
    fix n' assume "?P n'"
    moreover have "X (Suc n') -` {t} \<inter> space M = {x\<in>space M. X (Suc n') x = t}"
      by auto
    ultimately show "measure (?D n') {t} = \<P>(\<omega> in M. X (Suc n) \<omega> = t \<bar> X n \<omega> = s)"
      using n M.measure_uniform_measure_eq_cond_prob[of "\<lambda>x. X (Suc n') x = t" "\<lambda>x. X n' x = s"]
      by (auto simp: measure_distr M.emeasure_eq_measure simp del: measure_uniform_measure intro!: TH)
  qed (insert n, simp)
qed

lemma pmf_K2:
  "(\<And>n. \<P>(\<omega> in M. X n \<omega> = s) = 0) \<Longrightarrow> pmf (K s) t = indicator {t} s"
  apply (transfer fixing: s t)
  apply (rule withI)
  apply (auto split: split_indicator)
  done

end

sublocale K: MC_syntax K .

lemma bind_I_K_eq_M: "K.T' I = distr M K.S (\<lambda>\<omega>. to_stream (\<lambda>n. X n \<omega>))" (is "_ = ?D")
proof (rule stream_space_eq_sstart)
  note streams_sets[measurable]
  note measurable_abs_UNIV[measurable (raw)]
  note sstart_sets[measurable]

  { fix s assume "s \<in> S"
    from K.AE_T_enabled[of s] have "AE \<omega> in K.T s. \<omega> \<in> streams S"
    proof eventually_elim
      fix \<omega> assume "K.enabled s \<omega>" from this \<open>s\<in>S\<close> show "\<omega> \<in> streams S"
      proof (coinduction arbitrary: s \<omega>)
        case streams
        then have 1: "pmf (K s) (shd \<omega>) \<noteq> 0"
          by (simp add: K.enabled.simps[of s] set_pmf_iff)
        have "shd \<omega> \<in> S"
        proof cases
          assume "\<exists>n. 0 < \<P>(\<omega> in M. X n \<omega> = s)"
          then obtain n where "0 < \<P>(\<omega> in M. X n \<omega> = s)" by auto
          with 1 have 2: "\<P>(\<omega>' in M. X (Suc n) \<omega>' = shd \<omega> \<and> X n \<omega>' = s) \<noteq> 0"
            by (simp add: pmf_K cond_prob_def)
          show "shd \<omega> \<in> S"
          proof (rule ccontr)
            assume "shd \<omega> \<notin> S"
            with S(2)[of "Suc n"] have "\<P>(\<omega>' in M. X (Suc n) \<omega>' = shd \<omega> \<and> X n \<omega>' = s) = 0"
              by (intro M.prob_eq_0_AE) auto
            with 2 show False by contradiction
          qed
        next
          assume "\<not> (\<exists>n. 0 < \<P>(\<omega> in M. X n \<omega> = s))"
          then have "pmf (K s) (shd \<omega>) = indicator {shd \<omega>} s"
            by (intro pmf_K2) (auto simp: not_less measure_le_0_iff)
          with 1 \<open>s\<in>S\<close> show ?thesis
            by (auto split: split_indicator_asm)
        qed
        with streams show ?case
          by (cases \<omega>) (auto simp: K.enabled.simps[of s])
      qed
    qed }
  note AE_streams = this

  show "prob_space (K.T' I)"
    by (rule K.prob_space_T')
  show "prob_space ?D"
    by (rule M.prob_space_distr) simp

  show "AE x in K.T' I. x \<in> streams S"
    by (auto simp add: K.AE_T' set_pmf_iff I_in_S AE_distr_iff streams_Stream intro!: AE_streams)
  show "AE x in ?D. x \<in> streams S"
    by (simp add: AE_distr_iff to_stream_in_streams AE_all_countable S)
  show "sets (K.T' I) = sets (stream_space (count_space UNIV))"
    by (simp add: K.sets_T')
  show "sets ?D = sets (stream_space (count_space UNIV))"
    by simp

  fix xs' assume "xs' \<noteq> []" "xs' \<in> lists S"
  then obtain s xs where xs': "xs' = s # xs" and s: "s \<in> S" and xs: "xs \<in> lists S"
    by (auto simp: neq_Nil_conv del: in_listsD)

  have "emeasure (K.T' I) (sstart S xs') = (\<integral>\<^sup>+s. emeasure (K.T s) {\<omega>\<in>space K.S. s ## \<omega> \<in> sstart S xs'} \<partial>I)"
    by (rule K.emeasure_T') measurable
  also have "\<dots> = (\<integral>\<^sup>+s'. emeasure (K.T s) (sstart S xs) * indicator {s} s' \<partial>I)"
    by (intro arg_cong2[where f=emeasure] nn_integral_cong)
       (auto split: split_indicator simp: emeasure_distr vimage_def space_stream_space neq_Nil_conv xs')
  also have "\<dots> = pmf I s * emeasure (K.T s) (sstart S xs)"
    by (auto simp add: max_def emeasure_pmf_single intro: mult_ac)
  also have "emeasure (K.T s) (sstart S xs) = ennreal (\<Prod>i<length xs. pmf (K ((s#xs)!i)) (xs!i))"
    using xs s
  proof (induction arbitrary: s)
    case Nil then show ?case
      by (simp add: K.T.emeasure_eq_1_AE AE_streams)
  next
    case (Cons t xs)
    have "emeasure (K.T s) (sstart S (t # xs)) =
      emeasure (K.T s) {x\<in>space (K.T s). shd x = t \<and> stl x \<in> sstart S xs}"
      by (intro arg_cong2[where f=emeasure]) (auto simp: space_stream_space)
    also have "\<dots> = (\<integral>\<^sup>+t'. emeasure (K.T t') {x\<in>space K.S. t' = t \<and> x \<in> sstart S xs} \<partial>K s)"
      by (subst K.emeasure_Collect_T) auto
    also have "\<dots> = (\<integral>\<^sup>+t'. emeasure (K.T t) (sstart S xs) * indicator {t} t' \<partial>K s)"
      by (intro nn_integral_cong) (auto split: split_indicator simp: space_stream_space)
    also have "\<dots> = emeasure (K.T t) (sstart S xs) * pmf (K s) t"
      by (simp add: emeasure_pmf_single max_def)
    finally show ?case
      by (simp add: lessThan_Suc_eq_insert_0 zero_notin_Suc_image prod.reindex Cons
        prod_nonneg ennreal_mult[symmetric])
  qed
  also have "pmf I s * ennreal (\<Prod>i<length xs. pmf (K ((s#xs)!i)) (xs!i)) =
    \<P>(x in M. \<forall>i\<le>length xs. X i x = (s # xs) ! i)"
    using xs s
  proof (induction xs rule: rev_induct)
    case Nil
    have "pmf I s = prob {x \<in> space M. X 0 x = s}"
      by transfer (simp add: vimage_def Int_def measure_distr conj_commute)
    then show ?case
      by simp
  next
    case (snoc t xs)
    let ?l = "length xs" and ?lt = "length (xs @ [t])" and ?xs' = "s # xs @ [t]"
    have "ennreal (pmf I s) * (\<Prod>i<?lt. pmf (K ((?xs') ! i)) ((xs @ [t]) ! i)) =
      (ennreal (pmf I s) * (\<Prod>i<?l. pmf (K ((s # xs) ! i)) (xs ! i))) * pmf (K ((s # xs) ! ?l)) t"
      by (simp add: lessThan_Suc mult_ac nth_append append_Cons[symmetric] prod_nonneg ennreal_mult[symmetric]
               del: append_Cons)
    also have "\<dots> = \<P>(x in M. \<forall>i\<le>?l. X i x = (s # xs) ! i) * pmf (K ((s # xs) ! ?l)) t"
      using snoc by (simp add: ennreal_mult[symmetric])
    also have "\<dots> = \<P>(x in M. \<forall>i\<le>?lt. X i x = (?xs') ! i)"
    proof cases
      assume "\<P>(\<omega> in M. \<forall>i\<le>?l. X i \<omega> = (s # xs) ! i) = 0"
      moreover have "\<P>(x in M. \<forall>i\<le>?lt. X i x = (?xs') ! i) \<le> \<P>(\<omega> in M. \<forall>i\<le>?l. X i \<omega> = (s # xs) ! i)"
        by (intro M.finite_measure_mono) (auto simp: nth_append nth_Cons split: nat.split)
      moreover have "\<P>(x in M. \<forall>i\<le>?l. X i x = (s # xs) ! i) \<le> \<P>(\<omega> in M. \<forall>i\<le>?l. X i \<omega> = (s # xs) ! i)"
        by (intro M.finite_measure_mono) (auto simp: nth_append nth_Cons split: nat.split)
      ultimately show ?thesis
        by (simp add: measure_le_0_iff)
    next
      assume "\<P>(\<omega> in M. \<forall>i\<le>?l. X i \<omega> = (s # xs) ! i) \<noteq> 0"
      then have *: "0 < \<P>(\<omega> in M. \<forall>i\<le>?l. X i \<omega> = (s # xs) ! i)"
        unfolding less_le by simp
      moreover have "\<P>(\<omega> in M. \<forall>i\<le>?l. X i \<omega> = (s # xs) ! i) \<le> \<P>(\<omega> in M. X ?l \<omega> = (s # xs) ! ?l)"
        by (intro M.finite_measure_mono) (auto simp: nth_append nth_Cons split: nat.split)
      ultimately have "\<P>(\<omega> in M. X ?l \<omega> = (s # xs) ! ?l) \<noteq> 0"
        by auto
      then have "pmf (K ((s # xs) ! ?l)) t = \<P>(\<omega> in M. X ?lt \<omega> = ?xs' ! ?lt \<bar> X ?l \<omega> = (s # xs) ! ?l)"
        by (subst pmf_K) (auto simp: less_le)
      also have "\<dots> = \<P>(\<omega> in M. X ?lt \<omega> = ?xs' ! ?lt \<bar> \<forall>i\<le>?l. X i \<omega> = (s # xs) ! i)"
        using * MC[of ?l "\<lambda>i. (s # xs) ! i" "?xs' ! ?lt"] by simp
      also have "\<dots> = \<P>(\<omega> in M. \<forall>i\<le>?lt. X i \<omega> = ?xs' ! i) / \<P>(\<omega> in M. \<forall>i\<le>?l. X i \<omega> = (s # xs) ! i)"
        unfolding cond_prob_def
        by (intro arg_cong2[where f="(/)"] arg_cong2[where f=measure]) (auto simp: nth_Cons nth_append split: nat.splits)
      finally show ?thesis
        using * by simp
    qed
    finally show ?case .
  qed
  also have "\<dots> = emeasure ?D (sstart S xs')"
  proof -
    have "AE x in M. \<forall>i. X i x \<in> S"
      using S(2) by (simp add: AE_all_countable)
    then have "AE x in M. (\<forall>i\<le>length xs. X i x = (s # xs) ! i) = (to_stream (\<lambda>n. X n x) \<in> sstart S xs')"
    proof eventually_elim
      fix x assume "\<forall>i. X i x \<in> S"
      then have "to_stream (\<lambda>n. X n x) \<in> streams S"
        by (auto simp: streams_iff_snth to_stream_def)
      then show "(\<forall>i\<le>length xs. X i x = (s # xs) ! i) = (to_stream (\<lambda>n. X n x) \<in> sstart S xs')"
        by (simp add: sstart_eq xs' to_stream_def less_Suc_eq_le del: sstart.simps(1) in_sstart)
    qed
    then show ?thesis
      by (auto simp: emeasure_distr M.emeasure_eq_measure intro!: M.finite_measure_eq_AE)
  qed
  finally show "emeasure (K.T' I) (sstart S xs') = emeasure ?D (sstart S xs')" .
qed (rule S)

end

lemma (in MC_syntax) is_THDTMC:
  fixes I :: "'s pmf"
  defines "U \<equiv> (SIGMA s:UNIV. K s)\<^sup>* `` I"
  shows "Time_Homogeneous_Discrete_Markov_Process (T' I) U (\<lambda>n \<omega>. \<omega> !! n)"
proof -
  have [measurable]: "U \<in> sets (count_space UNIV)"
    by auto

  interpret prob_space "T' I"
    by (rule prob_space_T')

  { fix s t I
    have "\<And>t s. \<P>(\<omega> in T s. s = t) = indicator {t} s"
      using T.prob_space by (auto split: split_indicator)
    moreover then have "\<And>t t' s. \<P>(\<omega> in T s. shd \<omega> = t' \<and> s = t) = pmf (K t) t' * indicator {t} s"
      by (subst prob_T) (auto split: split_indicator simp: pmf.rep_eq)
    ultimately have "\<P>(\<omega> in T' I. shd (stl \<omega>) = t \<and> shd \<omega> = s) = \<P>(\<omega> in T' I. shd \<omega> = s) * pmf (K s) t"
      by (simp add: prob_T' pmf.rep_eq) }
  note start_eq = this

  { fix n s t assume "\<P>(\<omega> in T' I. \<omega> !! n = s) \<noteq> 0"
    moreover have "\<P>(\<omega> in T' I. \<omega> !! (Suc n) = t \<and> \<omega> !! n = s) = \<P>(\<omega> in T' I. \<omega> !! n = s) * pmf (K s) t"
    proof (induction n arbitrary: I)
      case (Suc n) then show ?case
        by (subst (1 2) prob_T') (simp_all del: space_T add: T_eq_T')
    qed (simp add: start_eq)
    ultimately have "\<P>(\<omega> in T' I. stl \<omega> !! n = t \<bar> \<omega> !! n = s) = pmf (K s) t"
      by (simp add: cond_prob_def field_simps) }
  note TH = this

  { fix n \<omega>' t assume "\<P>(\<omega> in T' I. \<forall>i\<le>n. \<omega> !! i = \<omega>' i) \<noteq> 0"
    moreover have "\<P>(\<omega> in T' I. \<omega> !! (Suc n) = t \<and> (\<forall>i\<le>n. \<omega> !! i = \<omega>' i)) =
      \<P>(\<omega> in T' I. \<forall>i\<le>n. \<omega> !! i = \<omega>' i) * pmf (K (\<omega>' n)) t"
    proof (induction n arbitrary: I \<omega>')
      case (Suc n)
      have *[simp]: "\<And>s P. measure (T' (K s)) {x. s = \<omega>' 0 \<and> P x} =
        measure (T' (K (\<omega>' 0))) {x. P x} * indicator {\<omega>' 0} s"
        by (auto split: split_indicator)
      from Suc[of _ "\<lambda>i. \<omega>' (Suc i)"] show ?case
        by (subst (1 2) prob_T')
           (simp_all add: T_eq_T' all_Suc_split[where P="\<lambda>i. i \<le> Suc n \<longrightarrow> Q i" for n Q] conj_commute conj_left_commute sets_eq_imp_space_eq[OF sets_T'])
    qed (simp add: start_eq)
    ultimately have "\<P>(\<omega> in T' I. stl \<omega> !! n = t \<bar> \<forall>i\<le>n. \<omega> !! i = \<omega>' i) = pmf (K (\<omega>' n)) t"
      by (simp add: cond_prob_def field_simps) }
  note MC = this

  { fix n \<omega>' assume "\<P>(\<omega> in T' I. \<forall>t\<le>n. \<omega> !! t = \<omega>' t) \<noteq> 0"
    moreover have "\<P>(\<omega> in T' I. \<forall>t\<le>n. \<omega> !! t = \<omega>' t) \<le> \<P>(\<omega> in T' I. \<omega> !! n = \<omega>' n)"
      by (auto intro!: finite_measure_mono_AE simp: sets_T' sets_eq_imp_space_eq[OF sets_T'])
    ultimately have "\<P>(\<omega> in T' I. \<omega> !! n = \<omega>' n) \<noteq> 0"
      by (auto simp: neq_iff not_less measure_le_0_iff) }
  note MC' = this

  show ?thesis
  proof
    show "countable U"
      unfolding U_def by (rule countable_reachable countable_Image countable_set_pmf)+
    show "\<And>t. (\<lambda>\<omega>. \<omega> !! t) \<in> measurable (T' I) (count_space UNIV)"
      by (subst measurable_cong_sets[OF sets_T' refl]) simp
  next
    fix n
    have "\<forall>x\<in>I. AE y in T x. (x ## y) !! n \<in> U"
      unfolding U_def
    proof (induction n arbitrary: I)
      case 0 then show ?case
        by auto
    next
      case (Suc n)
      { fix x assume "x \<in> I"
        have "AE y in T x. y !! n \<in> (SIGMA x:UNIV. K x)\<^sup>* `` K x"
          apply (subst AE_T_iff)
          apply (rule measurable_compose[OF measurable_snth], simp)
          apply (rule Suc)
          done
        moreover have "(SIGMA x:UNIV. K x)\<^sup>* `` K x \<subseteq> (SIGMA x:UNIV. K x)\<^sup>* `` I"
          using \<open>x \<in> I\<close> by (auto intro: converse_rtrancl_into_rtrancl)
        ultimately have "AE y in T x. y !! n \<in> (SIGMA x:UNIV. K x)\<^sup>* `` I"
          by (auto simp: subset_eq) }
      then show ?case
        by simp
    qed
    then show "AE x in T' I. x !! n \<in> U"
      by (simp add: AE_T')
  qed (simp_all add: TH MC MC')
qed

end


theory Induction_Demo
imports Main
begin

fun itrev :: "'a list \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"itrev [] ys = ys" |
"itrev (x#xs) ys = itrev xs (x#ys)"

lemma "itrev xs [] = rev xs"
apply(induction xs)
apply(auto)
done

subsection "Computation Induction"

fun sep :: "'a \<Rightarrow> 'a list \<Rightarrow> 'a list" where
"sep a [] = []" |
"sep a [x] = [x]" |
"sep a (x#y#zs) = x # a # sep a (y#zs)"

lemma "map f (sep a xs) = sep (f a) (map f xs)"
apply(induction a xs rule: sep.induct)
apply auto
done

end


(*  Title:      ZF/Finite.thy
    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
    Copyright   1994  University of Cambridge

prove:  b \<in> Fin(A) ==> inj(b,b) \<subseteq> surj(b,b)
*)

section\<open>Finite Powerset Operator and Finite Function Space\<close>

theory Finite imports Inductive_ZF Epsilon Nat_ZF begin

(*The natural numbers as a datatype*)
rep_datatype
  elimination    natE
  induction      nat_induct
  case_eqns      nat_case_0 nat_case_succ
  recursor_eqns  recursor_0 recursor_succ

consts
  Fin       :: "i=>i"
  FiniteFun :: "[i,i]=>i"         ("(_ -||>/ _)" [61, 60] 60)

inductive
  domains   "Fin(A)" \<subseteq> "Pow(A)"
  intros
    emptyI:  "0 \<in> Fin(A)"
    consI:   "[| a \<in> A;  b \<in> Fin(A) |] ==> cons(a,b) \<in> Fin(A)"
  type_intros  empty_subsetI cons_subsetI PowI
  type_elims   PowD [elim_format]

inductive
  domains   "FiniteFun(A,B)" \<subseteq> "Fin(A*B)"
  intros
    emptyI:  "0 \<in> A -||> B"
    consI:   "[| a \<in> A;  b \<in> B;  h \<in> A -||> B;  a \<notin> domain(h) |]
              ==> cons(<a,b>,h) \<in> A -||> B"
  type_intros Fin.intros

subsection \<open>Finite Powerset Operator\<close>

lemma Fin_mono: "A<=B ==> Fin(A) \<subseteq> Fin(B)"
apply (unfold Fin.defs)
apply (rule lfp_mono)
apply (rule Fin.bnd_mono)+
apply blast
done

(* @{term"A \<in> Fin(B) ==> A \<subseteq> B"} *)
lemmas FinD = Fin.dom_subset [THEN subsetD, THEN PowD]

(** Induction on finite sets **)

(*Discharging @{term"x\<notin>y"} entails extra work*)
lemma Fin_induct [case_names 0 cons, induct set: Fin]:
    "[| b \<in> Fin(A);
        P(0);
        !!x y. [| x \<in> A;  y \<in> Fin(A);  x\<notin>y;  P(y) |] ==> P(cons(x,y))
     |] ==> P(b)"
apply (erule Fin.induct, simp)
apply (case_tac "a \<in> b")
 apply (erule cons_absorb [THEN ssubst], assumption) (*backtracking!*)
apply simp
done

(** Simplification for Fin **)
declare Fin.intros [simp]

lemma Fin_0: "Fin(0) = {0}"
by (blast intro: Fin.emptyI dest: FinD)

(*The union of two finite sets is finite.*)
lemma Fin_UnI [simp]: "[| b \<in> Fin(A);  c \<in> Fin(A) |] ==> b \<union> c \<in> Fin(A)"
apply (erule Fin_induct)
apply (simp_all add: Un_cons)
done

(*The union of a set of finite sets is finite.*)
lemma Fin_UnionI: "C \<in> Fin(Fin(A)) ==> \<Union>(C) \<in> Fin(A)"
by (erule Fin_induct, simp_all)

(*Every subset of a finite set is finite.*)
lemma Fin_subset_lemma [rule_format]: "b \<in> Fin(A) ==> \<forall>z. z<=b \<longrightarrow> z \<in> Fin(A)"
apply (erule Fin_induct)
apply (simp add: subset_empty_iff)
apply (simp add: subset_cons_iff distrib_simps, safe)
apply (erule_tac b = z in cons_Diff [THEN subst], simp)
done

lemma Fin_subset: "[| c<=b;  b \<in> Fin(A) |] ==> c \<in> Fin(A)"
by (blast intro: Fin_subset_lemma)

lemma Fin_IntI1 [intro,simp]: "b \<in> Fin(A) ==> b \<inter> c \<in> Fin(A)"
by (blast intro: Fin_subset)

lemma Fin_IntI2 [intro,simp]: "c \<in> Fin(A) ==> b \<inter> c \<in> Fin(A)"
by (blast intro: Fin_subset)

lemma Fin_0_induct_lemma [rule_format]:
    "[| c \<in> Fin(A);  b \<in> Fin(A); P(b);
        !!x y. [| x \<in> A;  y \<in> Fin(A);  x \<in> y;  P(y) |] ==> P(y-{x})
     |] ==> c<=b \<longrightarrow> P(b-c)"
apply (erule Fin_induct, simp)
apply (subst Diff_cons)
apply (simp add: cons_subset_iff Diff_subset [THEN Fin_subset])
done

lemma Fin_0_induct:
    "[| b \<in> Fin(A);
        P(b);
        !!x y. [| x \<in> A;  y \<in> Fin(A);  x \<in> y;  P(y) |] ==> P(y-{x})
     |] ==> P(0)"
apply (rule Diff_cancel [THEN subst])
apply (blast intro: Fin_0_induct_lemma)
done

(*Functions from a finite ordinal*)
lemma nat_fun_subset_Fin: "n \<in> nat ==> n->A \<subseteq> Fin(nat*A)"
apply (induct_tac "n")
apply (simp add: subset_iff)
apply (simp add: succ_def mem_not_refl [THEN cons_fun_eq])
apply (fast intro!: Fin.consI)
done

subsection\<open>Finite Function Space\<close>

lemma FiniteFun_mono:
    "[| A<=C;  B<=D |] ==> A -||> B  \<subseteq>  C -||> D"
apply (unfold FiniteFun.defs)
apply (rule lfp_mono)
apply (rule FiniteFun.bnd_mono)+
apply (intro Fin_mono Sigma_mono basic_monos, assumption+)
done

lemma FiniteFun_mono1: "A<=B ==> A -||> A  \<subseteq>  B -||> B"
by (blast dest: FiniteFun_mono)

lemma FiniteFun_is_fun: "h \<in> A -||>B ==> h \<in> domain(h) -> B"
apply (erule FiniteFun.induct, simp)
apply (simp add: fun_extend3)
done

lemma FiniteFun_domain_Fin: "h \<in> A -||>B ==> domain(h) \<in> Fin(A)"
by (erule FiniteFun.induct, simp, simp)

lemmas FiniteFun_apply_type = FiniteFun_is_fun [THEN apply_type]

(*Every subset of a finite function is a finite function.*)
lemma FiniteFun_subset_lemma [rule_format]:
     "b \<in> A-||>B ==> \<forall>z. z<=b \<longrightarrow> z \<in> A-||>B"
apply (erule FiniteFun.induct)
apply (simp add: subset_empty_iff FiniteFun.intros)
apply (simp add: subset_cons_iff distrib_simps, safe)
apply (erule_tac b = z in cons_Diff [THEN subst])
apply (drule spec [THEN mp], assumption)
apply (fast intro!: FiniteFun.intros)
done

lemma FiniteFun_subset: "[| c<=b;  b \<in> A-||>B |] ==> c \<in> A-||>B"
by (blast intro: FiniteFun_subset_lemma)

(** Some further results by Sidi O. Ehmety **)

lemma fun_FiniteFunI [rule_format]: "A \<in> Fin(X) ==> \<forall>f. f \<in> A->B \<longrightarrow> f \<in> A-||>B"
apply (erule Fin.induct)
 apply (simp add: FiniteFun.intros, clarify)
apply (case_tac "a \<in> b")
 apply (simp add: cons_absorb)
apply (subgoal_tac "restrict (f,b) \<in> b -||> B")
 prefer 2 apply (blast intro: restrict_type2)
apply (subst fun_cons_restrict_eq, assumption)
apply (simp add: restrict_def lam_def)
apply (blast intro: apply_funtype FiniteFun.intros
                    FiniteFun_mono [THEN [2] rev_subsetD])
done

lemma lam_FiniteFun: "A \<in> Fin(X) ==> (\<lambda>x\<in>A. b(x)) \<in> A -||> {b(x). x \<in> A}"
by (blast intro: fun_FiniteFunI lam_funtype)

lemma FiniteFun_Collect_iff:
     "f \<in> FiniteFun(A, {y \<in> B. P(y)})
      \<longleftrightarrow> f \<in> FiniteFun(A,B) & (\<forall>x\<in>domain(f). P(f`x))"
apply auto
apply (blast intro: FiniteFun_mono [THEN [2] rev_subsetD])
apply (blast dest: Pair_mem_PiD FiniteFun_is_fun)
apply (rule_tac A1="domain(f)" in
       subset_refl [THEN [2] FiniteFun_mono, THEN subsetD])
 apply (fast dest: FiniteFun_domain_Fin Fin.dom_subset [THEN subsetD])
apply (rule fun_FiniteFunI)
apply (erule FiniteFun_domain_Fin)
apply (rule_tac B = "range (f) " in fun_weaken_type)
 apply (blast dest: FiniteFun_is_fun range_of_fun range_type apply_equality)+
done

subsection\<open>The Contents of a Singleton Set\<close>

definition
  contents :: "i=>i"  where
   "contents(X) == THE x. X = {x}"

lemma contents_eq [simp]: "contents ({x}) = x"
by (simp add: contents_def)

end