(*  Author:     Tobias Nipkow, Lawrence C Paulson and Markus Wenzel *)

section {* Set theory for higher-order logic *}

theory Set
imports Lattices
begin

subsection {* Sets as predicates *}

typedecl 'a set

axiomatization Collect :: "('a \<Rightarrow> bool) \<Rightarrow> 'a set" -- "comprehension"
  and member :: "'a \<Rightarrow> 'a set \<Rightarrow> bool" -- "membership"
where
  mem_Collect_eq [iff, code_unfold]: "member a (Collect P) = P a"
  and Collect_mem_eq [simp]: "Collect (\<lambda>x. member x A) = A"

notation
  member  ("op :") and
  member  ("(_/ : _)" [51, 51] 50)

abbreviation not_member where
  "not_member x A \<equiv> ~ (x : A)" -- "non-membership"

notation
  not_member  ("op ~:") and
  not_member  ("(_/ ~: _)" [51, 51] 50)

notation (xsymbols)
  member      ("op \<in>") and
  member      ("(_/ \<in> _)" [51, 51] 50) and
  not_member  ("op \<notin>") and
  not_member  ("(_/ \<notin> _)" [51, 51] 50)

notation (HTML output)
  member      ("op \<in>") and
  member      ("(_/ \<in> _)" [51, 51] 50) and
  not_member  ("op \<notin>") and
  not_member  ("(_/ \<notin> _)" [51, 51] 50)

text {* Set comprehensions *}

syntax
  "_Coll" :: "pttrn => bool => 'a set"    ("(1{_./ _})")
translations
  "{x. P}" == "CONST Collect (%x. P)"

syntax
  "_Collect" :: "pttrn => 'a set => bool => 'a set"    ("(1{_ :/ _./ _})")
syntax (xsymbols)
  "_Collect" :: "pttrn => 'a set => bool => 'a set"    ("(1{_ \<in>/ _./ _})")
translations
  "{p:A. P}" => "CONST Collect (%p. p:A & P)"

lemma CollectI: "P a \<Longrightarrow> a \<in> {x. P x}"
  by simp

lemma CollectD: "a \<in> {x. P x} \<Longrightarrow> P a"
  by simp

lemma Collect_cong: "(\<And>x. P x = Q x) ==> {x. P x} = {x. Q x}"
  by simp

text {*
Simproc for pulling @{text "x=t"} in @{text "{x. \<dots> & x=t & \<dots>}"}
to the front (and similarly for @{text "t=x"}):
*}

simproc_setup defined_Collect ("{x. P x & Q x}") = {*
  fn _ => Quantifier1.rearrange_Collect
    (fn _ =>
      resolve_tac @{thms Collect_cong} 1 THEN
      resolve_tac @{thms iffI} 1 THEN
      ALLGOALS
        (EVERY' [REPEAT_DETERM o eresolve_tac @{thms conjE},
          DEPTH_SOLVE_1 o ares_tac @{thms conjI}]))
*}

lemmas CollectE = CollectD [elim_format]

lemma set_eqI:
  assumes "\<And>x. x \<in> A \<longleftrightarrow> x \<in> B"
  shows "A = B"
proof -
  from assms have "{x. x \<in> A} = {x. x \<in> B}" by simp
  then show ?thesis by simp
qed

lemma set_eq_iff:
  "A = B \<longleftrightarrow> (\<forall>x. x \<in> A \<longleftrightarrow> x \<in> B)"
  by (auto intro:set_eqI)

text {* Lifting of predicate class instances *}

instantiation set :: (type) boolean_algebra
begin

definition less_eq_set where
  "A \<le> B \<longleftrightarrow> (\<lambda>x. member x A) \<le> (\<lambda>x. member x B)"

definition less_set where
  "A < B \<longleftrightarrow> (\<lambda>x. member x A) < (\<lambda>x. member x B)"

definition inf_set where
  "A \<sqinter> B = Collect ((\<lambda>x. member x A) \<sqinter> (\<lambda>x. member x B))"

definition sup_set where
  "A \<squnion> B = Collect ((\<lambda>x. member x A) \<squnion> (\<lambda>x. member x B))"

definition bot_set where
  "\<bottom> = Collect \<bottom>"

definition top_set where
  "\<top> = Collect \<top>"

definition uminus_set where
  "- A = Collect (- (\<lambda>x. member x A))"

definition minus_set where
  "A - B = Collect ((\<lambda>x. member x A) - (\<lambda>x. member x B))"

instance proof
qed (simp_all add: less_eq_set_def less_set_def inf_set_def sup_set_def
  bot_set_def top_set_def uminus_set_def minus_set_def
  less_le_not_le inf_compl_bot sup_compl_top sup_inf_distrib1 diff_eq
  set_eqI fun_eq_iff
  del: inf_apply sup_apply bot_apply top_apply minus_apply uminus_apply)

end

text {* Set enumerations *}

abbreviation empty :: "'a set" ("{}") where
  "{} \<equiv> bot"

definition insert :: "'a \<Rightarrow> 'a set \<Rightarrow> 'a set" where
  insert_compr: "insert a B = {x. x = a \<or> x \<in> B}"

syntax
  "_Finset" :: "args => 'a set"    ("{(_)}")
translations
  "{x, xs}" == "CONST insert x {xs}"
  "{x}" == "CONST insert x {}"

subsection {* Subsets and bounded quantifiers *}

abbreviation
  subset :: "'a set \<Rightarrow> 'a set \<Rightarrow> bool" where
  "subset \<equiv> less"

abbreviation
  subset_eq :: "'a set \<Rightarrow> 'a set \<Rightarrow> bool" where
  "subset_eq \<equiv> less_eq"

notation (output)
  subset  ("op <") and
  subset  ("(_/ < _)" [51, 51] 50) and
  subset_eq  ("op <=") and
  subset_eq  ("(_/ <= _)" [51, 51] 50)

notation (xsymbols)
  subset  ("op \<subset>") and
  subset  ("(_/ \<subset> _)" [51, 51] 50) and
  subset_eq  ("op \<subseteq>") and
  subset_eq  ("(_/ \<subseteq> _)" [51, 51] 50)

notation (HTML output)
  subset  ("op \<subset>") and
  subset  ("(_/ \<subset> _)" [51, 51] 50) and
  subset_eq  ("op \<subseteq>") and
  subset_eq  ("(_/ \<subseteq> _)" [51, 51] 50)

abbreviation (input)
  supset :: "'a set \<Rightarrow> 'a set \<Rightarrow> bool" where
  "supset \<equiv> greater"

abbreviation (input)
  supset_eq :: "'a set \<Rightarrow> 'a set \<Rightarrow> bool" where
  "supset_eq \<equiv> greater_eq"

notation (xsymbols)
  supset  ("op \<supset>") and
  supset  ("(_/ \<supset> _)" [51, 51] 50) and
  supset_eq  ("op \<supseteq>") and
  supset_eq  ("(_/ \<supseteq> _)" [51, 51] 50)

definition Ball :: "'a set \<Rightarrow> ('a \<Rightarrow> bool) \<Rightarrow> bool" where
  "Ball A P \<longleftrightarrow> (\<forall>x. x \<in> A \<longrightarrow> P x)"   -- "bounded universal quantifiers"

definition Bex :: "'a set \<Rightarrow> ('a \<Rightarrow> bool) \<Rightarrow> bool" where
  "Bex A P \<longleftrightarrow> (\<exists>x. x \<in> A \<and> P x)"   -- "bounded existential quantifiers"

syntax
  "_Ball"       :: "pttrn => 'a set => bool => bool"      ("(3ALL _:_./ _)" [0, 0, 10] 10)
  "_Bex"        :: "pttrn => 'a set => bool => bool"      ("(3EX _:_./ _)" [0, 0, 10] 10)
  "_Bex1"       :: "pttrn => 'a set => bool => bool"      ("(3EX! _:_./ _)" [0, 0, 10] 10)
  "_Bleast"     :: "id => 'a set => bool => 'a"           ("(3LEAST _:_./ _)" [0, 0, 10] 10)

syntax (HOL)
  "_Ball"       :: "pttrn => 'a set => bool => bool"      ("(3! _:_./ _)" [0, 0, 10] 10)
  "_Bex"        :: "pttrn => 'a set => bool => bool"      ("(3? _:_./ _)" [0, 0, 10] 10)
  "_Bex1"       :: "pttrn => 'a set => bool => bool"      ("(3?! _:_./ _)" [0, 0, 10] 10)

syntax (xsymbols)
  "_Ball"       :: "pttrn => 'a set => bool => bool"      ("(3\<forall>_\<in>_./ _)" [0, 0, 10] 10)
  "_Bex"        :: "pttrn => 'a set => bool => bool"      ("(3\<exists>_\<in>_./ _)" [0, 0, 10] 10)
  "_Bex1"       :: "pttrn => 'a set => bool => bool"      ("(3\<exists>!_\<in>_./ _)" [0, 0, 10] 10)
  "_Bleast"     :: "id => 'a set => bool => 'a"           ("(3LEAST_\<in>_./ _)" [0, 0, 10] 10)

syntax (HTML output)
  "_Ball"       :: "pttrn => 'a set => bool => bool"      ("(3\<forall>_\<in>_./ _)" [0, 0, 10] 10)
  "_Bex"        :: "pttrn => 'a set => bool => bool"      ("(3\<exists>_\<in>_./ _)" [0, 0, 10] 10)
  "_Bex1"       :: "pttrn => 'a set => bool => bool"      ("(3\<exists>!_\<in>_./ _)" [0, 0, 10] 10)

translations
  "ALL x:A. P" == "CONST Ball A (%x. P)"
  "EX x:A. P" == "CONST Bex A (%x. P)"
  "EX! x:A. P" => "EX! x. x:A & P"
  "LEAST x:A. P" => "LEAST x. x:A & P"

syntax (output)
  "_setlessAll" :: "[idt, 'a, bool] => bool"  ("(3ALL _<_./ _)"  [0, 0, 10] 10)
  "_setlessEx"  :: "[idt, 'a, bool] => bool"  ("(3EX _<_./ _)"  [0, 0, 10] 10)
  "_setleAll"   :: "[idt, 'a, bool] => bool"  ("(3ALL _<=_./ _)" [0, 0, 10] 10)
  "_setleEx"    :: "[idt, 'a, bool] => bool"  ("(3EX _<=_./ _)" [0, 0, 10] 10)
  "_setleEx1"   :: "[idt, 'a, bool] => bool"  ("(3EX! _<=_./ _)" [0, 0, 10] 10)

syntax (xsymbols)
  "_setlessAll" :: "[idt, 'a, bool] => bool"   ("(3\<forall>_\<subset>_./ _)"  [0, 0, 10] 10)
  "_setlessEx"  :: "[idt, 'a, bool] => bool"   ("(3\<exists>_\<subset>_./ _)"  [0, 0, 10] 10)
  "_setleAll"   :: "[idt, 'a, bool] => bool"   ("(3\<forall>_\<subseteq>_./ _)" [0, 0, 10] 10)
  "_setleEx"    :: "[idt, 'a, bool] => bool"   ("(3\<exists>_\<subseteq>_./ _)" [0, 0, 10] 10)
  "_setleEx1"   :: "[idt, 'a, bool] => bool"   ("(3\<exists>!_\<subseteq>_./ _)" [0, 0, 10] 10)

syntax (HOL output)
  "_setlessAll" :: "[idt, 'a, bool] => bool"   ("(3! _<_./ _)"  [0, 0, 10] 10)
  "_setlessEx"  :: "[idt, 'a, bool] => bool"   ("(3? _<_./ _)"  [0, 0, 10] 10)
  "_setleAll"   :: "[idt, 'a, bool] => bool"   ("(3! _<=_./ _)" [0, 0, 10] 10)
  "_setleEx"    :: "[idt, 'a, bool] => bool"   ("(3? _<=_./ _)" [0, 0, 10] 10)
  "_setleEx1"   :: "[idt, 'a, bool] => bool"   ("(3?! _<=_./ _)" [0, 0, 10] 10)

syntax (HTML output)
  "_setlessAll" :: "[idt, 'a, bool] => bool"   ("(3\<forall>_\<subset>_./ _)"  [0, 0, 10] 10)
  "_setlessEx"  :: "[idt, 'a, bool] => bool"   ("(3\<exists>_\<subset>_./ _)"  [0, 0, 10] 10)
  "_setleAll"   :: "[idt, 'a, bool] => bool"   ("(3\<forall>_\<subseteq>_./ _)" [0, 0, 10] 10)
  "_setleEx"    :: "[idt, 'a, bool] => bool"   ("(3\<exists>_\<subseteq>_./ _)" [0, 0, 10] 10)
  "_setleEx1"   :: "[idt, 'a, bool] => bool"   ("(3\<exists>!_\<subseteq>_./ _)" [0, 0, 10] 10)

translations
 "\<forall>A\<subset>B. P"   =>  "ALL A. A \<subset> B --> P"
 "\<exists>A\<subset>B. P"   =>  "EX A. A \<subset> B & P"
 "\<forall>A\<subseteq>B. P"   =>  "ALL A. A \<subseteq> B --> P"
 "\<exists>A\<subseteq>B. P"   =>  "EX A. A \<subseteq> B & P"
 "\<exists>!A\<subseteq>B. P"  =>  "EX! A. A \<subseteq> B & P"

print_translation {*
  let
    val All_binder = Mixfix.binder_name @{const_syntax All};
    val Ex_binder = Mixfix.binder_name @{const_syntax Ex};
    val impl = @{const_syntax HOL.implies};
    val conj = @{const_syntax HOL.conj};
    val sbset = @{const_syntax subset};
    val sbset_eq = @{const_syntax subset_eq};

    val trans =
     [((All_binder, impl, sbset), @{syntax_const "_setlessAll"}),
      ((All_binder, impl, sbset_eq), @{syntax_const "_setleAll"}),
      ((Ex_binder, conj, sbset), @{syntax_const "_setlessEx"}),
      ((Ex_binder, conj, sbset_eq), @{syntax_const "_setleEx"})];

    fun mk v (v', T) c n P =
      if v = v' andalso not (Term.exists_subterm (fn Free (x, _) => x = v | _ => false) n)
      then Syntax.const c $ Syntax_Trans.mark_bound_body (v', T) $ n $ P
      else raise Match;

    fun tr' q = (q, fn _ =>
      (fn [Const (@{syntax_const "_bound"}, _) $ Free (v, Type (@{type_name set}, _)),
          Const (c, _) $
            (Const (d, _) $ (Const (@{syntax_const "_bound"}, _) $ Free (v', T)) $ n) $ P] =>
          (case AList.lookup (op =) trans (q, c, d) of
            NONE => raise Match
          | SOME l => mk v (v', T) l n P)
        | _ => raise Match));
  in
    [tr' All_binder, tr' Ex_binder]
  end
*}

text {*
  \medskip Translate between @{text "{e | x1...xn. P}"} and @{text
  "{u. EX x1..xn. u = e & P}"}; @{text "{y. EX x1..xn. y = e & P}"} is
  only translated if @{text "[0..n] subset bvs(e)"}.
*}

syntax
  "_Setcompr" :: "'a => idts => bool => 'a set"    ("(1{_ |/_./ _})")

parse_translation {*
  let
    val ex_tr = snd (Syntax_Trans.mk_binder_tr ("EX ", @{const_syntax Ex}));

    fun nvars (Const (@{syntax_const "_idts"}, _) $ _ $ idts) = nvars idts + 1
      | nvars _ = 1;

    fun setcompr_tr ctxt [e, idts, b] =
      let
        val eq = Syntax.const @{const_syntax HOL.eq} $ Bound (nvars idts) $ e;
        val P = Syntax.const @{const_syntax HOL.conj} $ eq $ b;
        val exP = ex_tr ctxt [idts, P];
      in Syntax.const @{const_syntax Collect} $ absdummy dummyT exP end;

  in [(@{syntax_const "_Setcompr"}, setcompr_tr)] end;
*}

print_translation {*
 [Syntax_Trans.preserve_binder_abs2_tr' @{const_syntax Ball} @{syntax_const "_Ball"},
  Syntax_Trans.preserve_binder_abs2_tr' @{const_syntax Bex} @{syntax_const "_Bex"}]
*} -- {* to avoid eta-contraction of body *}

print_translation {*
let
  val ex_tr' = snd (Syntax_Trans.mk_binder_tr' (@{const_syntax Ex}, "DUMMY"));

  fun setcompr_tr' ctxt [Abs (abs as (_, _, P))] =
    let
      fun check (Const (@{const_syntax Ex}, _) $ Abs (_, _, P), n) = check (P, n + 1)
        | check (Const (@{const_syntax HOL.conj}, _) $
              (Const (@{const_syntax HOL.eq}, _) $ Bound m $ e) $ P, n) =
            n > 0 andalso m = n andalso not (loose_bvar1 (P, n)) andalso
            subset (op =) (0 upto (n - 1), add_loose_bnos (e, 0, []))
        | check _ = false;

        fun tr' (_ $ abs) =
          let val _ $ idts $ (_ $ (_ $ _ $ e) $ Q) = ex_tr' ctxt [abs]
          in Syntax.const @{syntax_const "_Setcompr"} $ e $ idts $ Q end;
    in
      if check (P, 0) then tr' P
      else
        let
          val (x as _ $ Free(xN, _), t) = Syntax_Trans.atomic_abs_tr' abs;
          val M = Syntax.const @{syntax_const "_Coll"} $ x $ t;
        in
          case t of
            Const (@{const_syntax HOL.conj}, _) $
              (Const (@{const_syntax Set.member}, _) $
                (Const (@{syntax_const "_bound"}, _) $ Free (yN, _)) $ A) $ P =>
            if xN = yN then Syntax.const @{syntax_const "_Collect"} $ x $ A $ P else M
          | _ => M
        end
    end;
  in [(@{const_syntax Collect}, setcompr_tr')] end;
*}

simproc_setup defined_Bex ("EX x:A. P x & Q x") = {*
  fn _ => Quantifier1.rearrange_bex
    (fn ctxt =>
      unfold_tac ctxt @{thms Bex_def} THEN
      Quantifier1.prove_one_point_ex_tac)
*}

simproc_setup defined_All ("ALL x:A. P x --> Q x") = {*
  fn _ => Quantifier1.rearrange_ball
    (fn ctxt =>
      unfold_tac ctxt @{thms Ball_def} THEN
      Quantifier1.prove_one_point_all_tac)
*}

lemma ballI [intro!]: "(!!x. x:A ==> P x) ==> ALL x:A. P x"
  by (simp add: Ball_def)

lemmas strip = impI allI ballI

lemma bspec [dest?]: "ALL x:A. P x ==> x:A ==> P x"
  by (simp add: Ball_def)

text {*
  Gives better instantiation for bound:
*}

setup {*
  map_theory_claset (fn ctxt =>
    ctxt addbefore ("bspec", fn ctxt' => dresolve_tac @{thms bspec} THEN' assume_tac ctxt'))
*}

ML {*
structure Simpdata =
struct

open Simpdata;

val mksimps_pairs = [(@{const_name Ball}, @{thms bspec})] @ mksimps_pairs;

end;

open Simpdata;
*}

declaration {* fn _ =>
  Simplifier.map_ss (Simplifier.set_mksimps (mksimps mksimps_pairs))
*}

lemma ballE [elim]: "ALL x:A. P x ==> (P x ==> Q) ==> (x ~: A ==> Q) ==> Q"
  by (unfold Ball_def) blast

lemma bexI [intro]: "P x ==> x:A ==> EX x:A. P x"
  -- {* Normally the best argument order: @{prop "P x"} constrains the
    choice of @{prop "x:A"}. *}
  by (unfold Bex_def) blast

lemma rev_bexI [intro?]: "x:A ==> P x ==> EX x:A. P x"
  -- {* The best argument order when there is only one @{prop "x:A"}. *}
  by (unfold Bex_def) blast

lemma bexCI: "(ALL x:A. ~P x ==> P a) ==> a:A ==> EX x:A. P x"
  by (unfold Bex_def) blast

lemma bexE [elim!]: "EX x:A. P x ==> (!!x. x:A ==> P x ==> Q) ==> Q"
  by (unfold Bex_def) blast

lemma ball_triv [simp]: "(ALL x:A. P) = ((EX x. x:A) --> P)"
  -- {* Trival rewrite rule. *}
  by (simp add: Ball_def)

lemma bex_triv [simp]: "(EX x:A. P) = ((EX x. x:A) & P)"
  -- {* Dual form for existentials. *}
  by (simp add: Bex_def)

lemma bex_triv_one_point1 [simp]: "(EX x:A. x = a) = (a:A)"
  by blast

lemma bex_triv_one_point2 [simp]: "(EX x:A. a = x) = (a:A)"
  by blast

lemma bex_one_point1 [simp]: "(EX x:A. x = a & P x) = (a:A & P a)"
  by blast

lemma bex_one_point2 [simp]: "(EX x:A. a = x & P x) = (a:A & P a)"
  by blast

lemma ball_one_point1 [simp]: "(ALL x:A. x = a --> P x) = (a:A --> P a)"
  by blast

lemma ball_one_point2 [simp]: "(ALL x:A. a = x --> P x) = (a:A --> P a)"
  by blast

lemma ball_conj_distrib:
  "(\<forall>x\<in>A. P x \<and> Q x) \<longleftrightarrow> ((\<forall>x\<in>A. P x) \<and> (\<forall>x\<in>A. Q x))"
  by blast

lemma bex_disj_distrib:
  "(\<exists>x\<in>A. P x \<or> Q x) \<longleftrightarrow> ((\<exists>x\<in>A. P x) \<or> (\<exists>x\<in>A. Q x))"
  by blast

text {* Congruence rules *}

lemma ball_cong:
  "A = B ==> (!!x. x:B ==> P x = Q x) ==>
    (ALL x:A. P x) = (ALL x:B. Q x)"
  by (simp add: Ball_def)

lemma strong_ball_cong [cong]:
  "A = B ==> (!!x. x:B =simp=> P x = Q x) ==>
    (ALL x:A. P x) = (ALL x:B. Q x)"
  by (simp add: simp_implies_def Ball_def)

lemma bex_cong:
  "A = B ==> (!!x. x:B ==> P x = Q x) ==>
    (EX x:A. P x) = (EX x:B. Q x)"
  by (simp add: Bex_def cong: conj_cong)

lemma strong_bex_cong [cong]:
  "A = B ==> (!!x. x:B =simp=> P x = Q x) ==>
    (EX x:A. P x) = (EX x:B. Q x)"
  by (simp add: simp_implies_def Bex_def cong: conj_cong)

lemma bex1_def: "(\<exists>!x\<in>X. P x) \<longleftrightarrow> (\<exists>x\<in>X. P x) \<and> (\<forall>x\<in>X. \<forall>y\<in>X. P x \<longrightarrow> P y \<longrightarrow> x = y)"
  by auto

subsection {* Basic operations *}

subsubsection {* Subsets *}

lemma subsetI [intro!]: "(\<And>x. x \<in> A \<Longrightarrow> x \<in> B) \<Longrightarrow> A \<subseteq> B"
  by (simp add: less_eq_set_def le_fun_def)

text {*
  \medskip Map the type @{text "'a set => anything"} to just @{typ
  'a}; for overloading constants whose first argument has type @{typ
  "'a set"}.
*}

lemma subsetD [elim, intro?]: "A \<subseteq> B ==> c \<in> A ==> c \<in> B"
  by (simp add: less_eq_set_def le_fun_def)
  -- {* Rule in Modus Ponens style. *}

lemma rev_subsetD [intro?]: "c \<in> A ==> A \<subseteq> B ==> c \<in> B"
  -- {* The same, with reversed premises for use with @{text erule} --
      cf @{text rev_mp}. *}
  by (rule subsetD)

text {*
  \medskip Converts @{prop "A \<subseteq> B"} to @{prop "x \<in> A ==> x \<in> B"}.
*}

lemma subsetCE [elim]: "A \<subseteq> B ==> (c \<notin> A ==> P) ==> (c \<in> B ==> P) ==> P"
  -- {* Classical elimination rule. *}
  by (auto simp add: less_eq_set_def le_fun_def)

lemma subset_eq: "A \<le> B = (\<forall>x\<in>A. x \<in> B)" by blast

lemma contra_subsetD: "A \<subseteq> B ==> c \<notin> B ==> c \<notin> A"
  by blast

lemma subset_refl: "A \<subseteq> A"
  by (fact order_refl) (* already [iff] *)

lemma subset_trans: "A \<subseteq> B ==> B \<subseteq> C ==> A \<subseteq> C"
  by (fact order_trans)

lemma set_rev_mp: "x:A ==> A \<subseteq> B ==> x:B"
  by (rule subsetD)

lemma set_mp: "A \<subseteq> B ==> x:A ==> x:B"
  by (rule subsetD)

lemma subset_not_subset_eq [code]:
  "A \<subset> B \<longleftrightarrow> A \<subseteq> B \<and> \<not> B \<subseteq> A"
  by (fact less_le_not_le)

lemma eq_mem_trans: "a=b ==> b \<in> A ==> a \<in> A"
  by simp

lemmas basic_trans_rules [trans] =
  order_trans_rules set_rev_mp set_mp eq_mem_trans

subsubsection {* Equality *}

lemma subset_antisym [intro!]: "A \<subseteq> B ==> B \<subseteq> A ==> A = B"
  -- {* Anti-symmetry of the subset relation. *}
  by (iprover intro: set_eqI subsetD)

text {*
  \medskip Equality rules from ZF set theory -- are they appropriate
  here?
*}

lemma equalityD1: "A = B ==> A \<subseteq> B"
  by simp

lemma equalityD2: "A = B ==> B \<subseteq> A"
  by simp

text {*
  \medskip Be careful when adding this to the claset as @{text
  subset_empty} is in the simpset: @{prop "A = {}"} goes to @{prop "{}
  \<subseteq> A"} and @{prop "A \<subseteq> {}"} and then back to @{prop "A = {}"}!
*}

lemma equalityE: "A = B ==> (A \<subseteq> B ==> B \<subseteq> A ==> P) ==> P"
  by simp

lemma equalityCE [elim]:
    "A = B ==> (c \<in> A ==> c \<in> B ==> P) ==> (c \<notin> A ==> c \<notin> B ==> P) ==> P"
  by blast

lemma eqset_imp_iff: "A = B ==> (x : A) = (x : B)"
  by simp

lemma eqelem_imp_iff: "x = y ==> (x : A) = (y : A)"
  by simp

subsubsection {* The empty set *}

lemma empty_def:
  "{} = {x. False}"
  by (simp add: bot_set_def bot_fun_def)

lemma empty_iff [simp]: "(c : {}) = False"
  by (simp add: empty_def)

lemma emptyE [elim!]: "a : {} ==> P"
  by simp

lemma empty_subsetI [iff]: "{} \<subseteq> A"
    -- {* One effect is to delete the ASSUMPTION @{prop "{} <= A"} *}
  by blast

lemma equals0I: "(!!y. y \<in> A ==> False) ==> A = {}"
  by blast

lemma equals0D: "A = {} ==> a \<notin> A"
    -- {* Use for reasoning about disjointness: @{text "A Int B = {}"} *}
  by blast

lemma ball_empty [simp]: "Ball {} P = True"
  by (simp add: Ball_def)

lemma bex_empty [simp]: "Bex {} P = False"
  by (simp add: Bex_def)

subsubsection {* The universal set -- UNIV *}

abbreviation UNIV :: "'a set" where
  "UNIV \<equiv> top"

lemma UNIV_def:
  "UNIV = {x. True}"
  by (simp add: top_set_def top_fun_def)

lemma UNIV_I [simp]: "x : UNIV"
  by (simp add: UNIV_def)

declare UNIV_I [intro]  -- {* unsafe makes it less likely to cause problems *}

lemma UNIV_witness [intro?]: "EX x. x : UNIV"
  by simp

lemma subset_UNIV: "A \<subseteq> UNIV"
  by (fact top_greatest) (* already simp *)

text {*
  \medskip Eta-contracting these two rules (to remove @{text P})
  causes them to be ignored because of their interaction with
  congruence rules.
*}

lemma ball_UNIV [simp]: "Ball UNIV P = All P"
  by (simp add: Ball_def)

lemma bex_UNIV [simp]: "Bex UNIV P = Ex P"
  by (simp add: Bex_def)

lemma UNIV_eq_I: "(\<And>x. x \<in> A) \<Longrightarrow> UNIV = A"
  by auto

lemma UNIV_not_empty [iff]: "UNIV ~= {}"
  by (blast elim: equalityE)

lemma empty_not_UNIV[simp]: "{} \<noteq> UNIV"
by blast

subsubsection {* The Powerset operator -- Pow *}

definition Pow :: "'a set => 'a set set" where
  Pow_def: "Pow A = {B. B \<le> A}"

lemma Pow_iff [iff]: "(A \<in> Pow B) = (A \<subseteq> B)"
  by (simp add: Pow_def)

lemma PowI: "A \<subseteq> B ==> A \<in> Pow B"
  by (simp add: Pow_def)

lemma PowD: "A \<in> Pow B ==> A \<subseteq> B"
  by (simp add: Pow_def)

lemma Pow_bottom: "{} \<in> Pow B"
  by simp

lemma Pow_top: "A \<in> Pow A"
  by simp

lemma Pow_not_empty: "Pow A \<noteq> {}"
  using Pow_top by blast

subsubsection {* Set complement *}

lemma Compl_iff [simp]: "(c \<in> -A) = (c \<notin> A)"
  by (simp add: fun_Compl_def uminus_set_def)

lemma ComplI [intro!]: "(c \<in> A ==> False) ==> c \<in> -A"
  by (simp add: fun_Compl_def uminus_set_def) blast

text {*
  \medskip This form, with negated conclusion, works well with the
  Classical prover.  Negated assumptions behave like formulae on the
  right side of the notional turnstile ... *}

lemma ComplD [dest!]: "c : -A ==> c~:A"
  by simp

lemmas ComplE = ComplD [elim_format]

lemma Compl_eq: "- A = {x. ~ x : A}"
  by blast

subsubsection {* Binary intersection *}

abbreviation inter :: "'a set \<Rightarrow> 'a set \<Rightarrow> 'a set" (infixl "Int" 70) where
  "op Int \<equiv> inf"

notation (xsymbols)
  inter  (infixl "\<inter>" 70)

notation (HTML output)
  inter  (infixl "\<inter>" 70)

lemma Int_def:
  "A \<inter> B = {x. x \<in> A \<and> x \<in> B}"
  by (simp add: inf_set_def inf_fun_def)

lemma Int_iff [simp]: "(c : A Int B) = (c:A & c:B)"
  by (unfold Int_def) blast

lemma IntI [intro!]: "c:A ==> c:B ==> c : A Int B"
  by simp

lemma IntD1: "c : A Int B ==> c:A"
  by simp

lemma IntD2: "c : A Int B ==> c:B"
  by simp

lemma IntE [elim!]: "c : A Int B ==> (c:A ==> c:B ==> P) ==> P"
  by simp

lemma mono_Int: "mono f \<Longrightarrow> f (A \<inter> B) \<subseteq> f A \<inter> f B"
  by (fact mono_inf)

subsubsection {* Binary union *}

abbreviation union :: "'a set \<Rightarrow> 'a set \<Rightarrow> 'a set" (infixl "Un" 65) where
  "union \<equiv> sup"

notation (xsymbols)
  union  (infixl "\<union>" 65)

notation (HTML output)
  union  (infixl "\<union>" 65)

lemma Un_def:
  "A \<union> B = {x. x \<in> A \<or> x \<in> B}"
  by (simp add: sup_set_def sup_fun_def)

lemma Un_iff [simp]: "(c : A Un B) = (c:A | c:B)"
  by (unfold Un_def) blast

lemma UnI1 [elim?]: "c:A ==> c : A Un B"
  by simp

lemma UnI2 [elim?]: "c:B ==> c : A Un B"
  by simp

text {*
  \medskip Classical introduction rule: no commitment to @{prop A} vs
  @{prop B}.
*}

lemma UnCI [intro!]: "(c~:B ==> c:A) ==> c : A Un B"
  by auto

lemma UnE [elim!]: "c : A Un B ==> (c:A ==> P) ==> (c:B ==> P) ==> P"
  by (unfold Un_def) blast

lemma insert_def: "insert a B = {x. x = a} \<union> B"
  by (simp add: insert_compr Un_def)

lemma mono_Un: "mono f \<Longrightarrow> f A \<union> f B \<subseteq> f (A \<union> B)"
  by (fact mono_sup)

subsubsection {* Set difference *}

lemma Diff_iff [simp]: "(c : A - B) = (c:A & c~:B)"
  by (simp add: minus_set_def fun_diff_def)

lemma DiffI [intro!]: "c : A ==> c ~: B ==> c : A - B"
  by simp

lemma DiffD1: "c : A - B ==> c : A"
  by simp

lemma DiffD2: "c : A - B ==> c : B ==> P"
  by simp

lemma DiffE [elim!]: "c : A - B ==> (c:A ==> c~:B ==> P) ==> P"
  by simp

lemma set_diff_eq: "A - B = {x. x : A & ~ x : B}" by blast

lemma Compl_eq_Diff_UNIV: "-A = (UNIV - A)"
by blast

subsubsection {* Augmenting a set -- @{const insert} *}

lemma insert_iff [simp]: "(a : insert b A) = (a = b | a:A)"
  by (unfold insert_def) blast

lemma insertI1: "a : insert a B"
  by simp

lemma insertI2: "a : B ==> a : insert b B"
  by simp

lemma insertE [elim!]: "a : insert b A ==> (a = b ==> P) ==> (a:A ==> P) ==> P"
  by (unfold insert_def) blast

lemma insertCI [intro!]: "(a~:B ==> a = b) ==> a: insert b B"
  -- {* Classical introduction rule. *}
  by auto

lemma subset_insert_iff: "(A \<subseteq> insert x B) = (if x:A then A - {x} \<subseteq> B else A \<subseteq> B)"
  by auto

lemma set_insert:
  assumes "x \<in> A"
  obtains B where "A = insert x B" and "x \<notin> B"
proof
  from assms show "A = insert x (A - {x})" by blast
next
  show "x \<notin> A - {x}" by blast
qed

lemma insert_ident: "x ~: A ==> x ~: B ==> (insert x A = insert x B) = (A = B)"
by auto

lemma insert_eq_iff: assumes "a \<notin> A" "b \<notin> B"
shows "insert a A = insert b B \<longleftrightarrow>
  (if a=b then A=B else \<exists>C. A = insert b C \<and> b \<notin> C \<and> B = insert a C \<and> a \<notin> C)"
  (is "?L \<longleftrightarrow> ?R")
proof
  assume ?L
  show ?R
  proof cases
    assume "a=b" with assms `?L` show ?R by (simp add: insert_ident)
  next
    assume "a\<noteq>b"
    let ?C = "A - {b}"
    have "A = insert b ?C \<and> b \<notin> ?C \<and> B = insert a ?C \<and> a \<notin> ?C"
      using assms `?L` `a\<noteq>b` by auto
    thus ?R using `a\<noteq>b` by auto
  qed
next
  assume ?R thus ?L by (auto split: if_splits)
qed

subsubsection {* Singletons, using insert *}

lemma singletonI [intro!]: "a : {a}"
    -- {* Redundant? But unlike @{text insertCI}, it proves the subgoal immediately! *}
  by (rule insertI1)

lemma singletonD [dest!]: "b : {a} ==> b = a"
  by blast

lemmas singletonE = singletonD [elim_format]

lemma singleton_iff: "(b : {a}) = (b = a)"
  by blast

lemma singleton_inject [dest!]: "{a} = {b} ==> a = b"
  by blast

lemma singleton_insert_inj_eq [iff]:
     "({b} = insert a A) = (a = b & A \<subseteq> {b})"
  by blast

lemma singleton_insert_inj_eq' [iff]:
     "(insert a A = {b}) = (a = b & A \<subseteq> {b})"
  by blast

lemma subset_singletonD: "A \<subseteq> {x} ==> A = {} | A = {x}"
  by fast

lemma singleton_conv [simp]: "{x. x = a} = {a}"
  by blast

lemma singleton_conv2 [simp]: "{x. a = x} = {a}"
  by blast

lemma diff_single_insert: "A - {x} \<subseteq> B ==> A \<subseteq> insert x B"
  by blast

lemma doubleton_eq_iff: "({a,b} = {c,d}) = (a=c & b=d | a=d & b=c)"
  by (blast elim: equalityE)

lemma Un_singleton_iff:
  "(A \<union> B = {x}) = (A = {} \<and> B = {x} \<or> A = {x} \<and> B = {} \<or> A = {x} \<and> B = {x})"
by auto

lemma singleton_Un_iff:
  "({x} = A \<union> B) = (A = {} \<and> B = {x} \<or> A = {x} \<and> B = {} \<or> A = {x} \<and> B = {x})"
by auto

subsubsection {* Image of a set under a function *}

text {*
  Frequently @{term b} does not have the syntactic form of @{term "f x"}.
*}

definition image :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a set \<Rightarrow> 'b set" (infixr "`" 90)
where
  "f ` A = {y. \<exists>x\<in>A. y = f x}"

lemma image_eqI [simp, intro]:
  "b = f x \<Longrightarrow> x \<in> A \<Longrightarrow> b \<in> f ` A"
  by (unfold image_def) blast

lemma imageI:
  "x \<in> A \<Longrightarrow> f x \<in> f ` A"
  by (rule image_eqI) (rule refl)

lemma rev_image_eqI:
  "x \<in> A \<Longrightarrow> b = f x \<Longrightarrow> b \<in> f ` A"
  -- {* This version's more effective when we already have the
    required @{term x}. *}
  by (rule image_eqI)

lemma imageE [elim!]:
  assumes "b \<in> (\<lambda>x. f x) ` A" -- {* The eta-expansion gives variable-name preservation. *}
  obtains x where "b = f x" and "x \<in> A"
  using assms by (unfold image_def) blast

lemma Compr_image_eq:
  "{x \<in> f ` A. P x} = f ` {x \<in> A. P (f x)}"
  by auto

lemma image_Un:
  "f ` (A \<union> B) = f ` A \<union> f ` B"
  by blast

lemma image_iff:
  "z \<in> f ` A \<longleftrightarrow> (\<exists>x\<in>A. z = f x)"
  by blast

lemma image_subsetI:
  "(\<And>x. x \<in> A \<Longrightarrow> f x \<in> B) \<Longrightarrow> f ` A \<subseteq> B"
  -- {* Replaces the three steps @{text subsetI}, @{text imageE},
    @{text hypsubst}, but breaks too many existing proofs. *}
  by blast

lemma image_subset_iff:
  "f ` A \<subseteq> B \<longleftrightarrow> (\<forall>x\<in>A. f x \<in> B)"
  -- {* This rewrite rule would confuse users if made default. *}
  by blast

lemma subset_imageE:
  assumes "B \<subseteq> f ` A"
  obtains C where "C \<subseteq> A" and "B = f ` C"
proof -
  from assms have "B = f ` {a \<in> A. f a \<in> B}" by fast
  moreover have "{a \<in> A. f a \<in> B} \<subseteq> A" by blast
  ultimately show thesis by (blast intro: that)
qed

lemma subset_image_iff:
  "B \<subseteq> f ` A \<longleftrightarrow> (\<exists>AA\<subseteq>A. B = f ` AA)"
  by (blast elim: subset_imageE)

lemma image_ident [simp]:
  "(\<lambda>x. x) ` Y = Y"
  by blast

lemma image_empty [simp]:
  "f ` {} = {}"
  by blast

lemma image_insert [simp]:
  "f ` insert a B = insert (f a) (f ` B)"
  by blast

lemma image_constant:
  "x \<in> A \<Longrightarrow> (\<lambda>x. c) ` A = {c}"
  by auto

lemma image_constant_conv:
  "(\<lambda>x. c) ` A = (if A = {} then {} else {c})"
  by auto

lemma image_image:
  "f ` (g ` A) = (\<lambda>x. f (g x)) ` A"
  by blast

lemma insert_image [simp]:
  "x \<in> A ==> insert (f x) (f ` A) = f ` A"
  by blast

lemma image_is_empty [iff]:
  "f ` A = {} \<longleftrightarrow> A = {}"
  by blast

lemma empty_is_image [iff]:
  "{} = f ` A \<longleftrightarrow> A = {}"
  by blast

lemma image_Collect:
  "f ` {x. P x} = {f x | x. P x}"
  -- {* NOT suitable as a default simprule: the RHS isn't simpler than the LHS,
      with its implicit quantifier and conjunction.  Also image enjoys better
      equational properties than does the RHS. *}
  by blast

lemma if_image_distrib [simp]:
  "(\<lambda>x. if P x then f x else g x) ` S
    = (f ` (S \<inter> {x. P x})) \<union> (g ` (S \<inter> {x. \<not> P x}))"
  by auto

lemma image_cong:
  "M = N \<Longrightarrow> (\<And>x. x \<in> N \<Longrightarrow> f x = g x) \<Longrightarrow> f ` M = g ` N"
  by (simp add: image_def)

lemma image_Int_subset:
  "f ` (A \<inter> B) \<subseteq> f ` A \<inter> f ` B"
  by blast

lemma image_diff_subset:
  "f ` A - f ` B \<subseteq> f ` (A - B)"
  by blast

lemma ball_imageD:
  assumes "\<forall>x\<in>f ` A. P x"
  shows "\<forall>x\<in>A. P (f x)"
  using assms by simp

lemma bex_imageD:
  assumes "\<exists>x\<in>f ` A. P x"
  shows "\<exists>x\<in>A. P (f x)"
  using assms by auto

text {*
  \medskip Range of a function -- just a translation for image!
*}

abbreviation range :: "('a \<Rightarrow> 'b) \<Rightarrow> 'b set"
where -- "of function"
  "range f \<equiv> f ` UNIV"

lemma range_eqI:
  "b = f x \<Longrightarrow> b \<in> range f"
  by simp

lemma rangeI:
  "f x \<in> range f"
  by simp

lemma rangeE [elim?]:
  "b \<in> range (\<lambda>x. f x) \<Longrightarrow> (\<And>x. b = f x \<Longrightarrow> P) \<Longrightarrow> P"
  by (rule imageE)

lemma full_SetCompr_eq:
  "{u. \<exists>x. u = f x} = range f"
  by auto

lemma range_composition:
  "range (\<lambda>x. f (g x)) = f ` range g"
  by auto

subsubsection {* Some rules with @{text "if"} *}

text{* Elimination of @{text"{x. \<dots> & x=t & \<dots>}"}. *}

lemma Collect_conv_if: "{x. x=a & P x} = (if P a then {a} else {})"
  by auto

lemma Collect_conv_if2: "{x. a=x & P x} = (if P a then {a} else {})"
  by auto

text {*
  Rewrite rules for boolean case-splitting: faster than @{text
  "split_if [split]"}.
*}

lemma split_if_eq1: "((if Q then x else y) = b) = ((Q --> x = b) & (~ Q --> y = b))"
  by (rule split_if)

lemma split_if_eq2: "(a = (if Q then x else y)) = ((Q --> a = x) & (~ Q --> a = y))"
  by (rule split_if)

text {*
  Split ifs on either side of the membership relation.  Not for @{text
  "[simp]"} -- can cause goals to blow up!
*}

lemma split_if_mem1: "((if Q then x else y) : b) = ((Q --> x : b) & (~ Q --> y : b))"
  by (rule split_if)

lemma split_if_mem2: "(a : (if Q then x else y)) = ((Q --> a : x) & (~ Q --> a : y))"
  by (rule split_if [where P="%S. a : S"])

lemmas split_ifs = if_bool_eq_conj split_if_eq1 split_if_eq2 split_if_mem1 split_if_mem2

(*Would like to add these, but the existing code only searches for the
  outer-level constant, which in this case is just Set.member; we instead need
  to use term-nets to associate patterns with rules.  Also, if a rule fails to
  apply, then the formula should be kept.
  [("uminus", Compl_iff RS iffD1), ("minus", [Diff_iff RS iffD1]),
   ("Int", [IntD1,IntD2]),
   ("Collect", [CollectD]), ("Inter", [InterD]), ("INTER", [INT_D])]
 *)

subsection {* Further operations and lemmas *}

subsubsection {* The ``proper subset'' relation *}

lemma psubsetI [intro!]: "A \<subseteq> B ==> A \<noteq> B ==> A \<subset> B"
  by (unfold less_le) blast

lemma psubsetE [elim!]:
    "[|A \<subset> B;  [|A \<subseteq> B; ~ (B\<subseteq>A)|] ==> R|] ==> R"
  by (unfold less_le) blast

lemma psubset_insert_iff:
  "(A \<subset> insert x B) = (if x \<in> B then A \<subset> B else if x \<in> A then A - {x} \<subset> B else A \<subseteq> B)"
  by (auto simp add: less_le subset_insert_iff)

lemma psubset_eq: "(A \<subset> B) = (A \<subseteq> B & A \<noteq> B)"
  by (simp only: less_le)

lemma psubset_imp_subset: "A \<subset> B ==> A \<subseteq> B"
  by (simp add: psubset_eq)

lemma psubset_trans: "[| A \<subset> B; B \<subset> C |] ==> A \<subset> C"
apply (unfold less_le)
apply (auto dest: subset_antisym)
done

lemma psubsetD: "[| A \<subset> B; c \<in> A |] ==> c \<in> B"
apply (unfold less_le)
apply (auto dest: subsetD)
done

lemma psubset_subset_trans: "A \<subset> B ==> B \<subseteq> C ==> A \<subset> C"
  by (auto simp add: psubset_eq)

lemma subset_psubset_trans: "A \<subseteq> B ==> B \<subset> C ==> A \<subset> C"
  by (auto simp add: psubset_eq)

lemma psubset_imp_ex_mem: "A \<subset> B ==> \<exists>b. b \<in> (B - A)"
  by (unfold less_le) blast

lemma atomize_ball:
    "(!!x. x \<in> A ==> P x) == Trueprop (\<forall>x\<in>A. P x)"
  by (simp only: Ball_def atomize_all atomize_imp)

lemmas [symmetric, rulify] = atomize_ball
  and [symmetric, defn] = atomize_ball

lemma image_Pow_mono:
  assumes "f ` A \<subseteq> B"
  shows "image f ` Pow A \<subseteq> Pow B"
  using assms by blast

lemma image_Pow_surj:
  assumes "f ` A = B"
  shows "image f ` Pow A = Pow B"
  using assms by (blast elim: subset_imageE)

subsubsection {* Derived rules involving subsets. *}

text {* @{text insert}. *}

lemma subset_insertI: "B \<subseteq> insert a B"
  by (rule subsetI) (erule insertI2)

lemma subset_insertI2: "A \<subseteq> B \<Longrightarrow> A \<subseteq> insert b B"
  by blast

lemma subset_insert: "x \<notin> A ==> (A \<subseteq> insert x B) = (A \<subseteq> B)"
  by blast

text {* \medskip Finite Union -- the least upper bound of two sets. *}

lemma Un_upper1: "A \<subseteq> A \<union> B"
  by (fact sup_ge1)

lemma Un_upper2: "B \<subseteq> A \<union> B"
  by (fact sup_ge2)

lemma Un_least: "A \<subseteq> C ==> B \<subseteq> C ==> A \<union> B \<subseteq> C"
  by (fact sup_least)

text {* \medskip Finite Intersection -- the greatest lower bound of two sets. *}

lemma Int_lower1: "A \<inter> B \<subseteq> A"
  by (fact inf_le1)

lemma Int_lower2: "A \<inter> B \<subseteq> B"
  by (fact inf_le2)

lemma Int_greatest: "C \<subseteq> A ==> C \<subseteq> B ==> C \<subseteq> A \<inter> B"
  by (fact inf_greatest)

text {* \medskip Set difference. *}

lemma Diff_subset: "A - B \<subseteq> A"
  by blast

lemma Diff_subset_conv: "(A - B \<subseteq> C) = (A \<subseteq> B \<union> C)"
by blast

subsubsection {* Equalities involving union, intersection, inclusion, etc. *}

text {* @{text "{}"}. *}

lemma Collect_const [simp]: "{s. P} = (if P then UNIV else {})"
  -- {* supersedes @{text "Collect_False_empty"} *}
  by auto

lemma subset_empty [simp]: "(A \<subseteq> {}) = (A = {})"
  by (fact bot_unique)

lemma not_psubset_empty [iff]: "\<not> (A < {})"
  by (fact not_less_bot) (* FIXME: already simp *)

lemma Collect_empty_eq [simp]: "(Collect P = {}) = (\<forall>x. \<not> P x)"
by blast

lemma empty_Collect_eq [simp]: "({} = Collect P) = (\<forall>x. \<not> P x)"
by blast

lemma Collect_neg_eq: "{x. \<not> P x} = - {x. P x}"
  by blast

lemma Collect_disj_eq: "{x. P x | Q x} = {x. P x} \<union> {x. Q x}"
  by blast

lemma Collect_imp_eq: "{x. P x --> Q x} = -{x. P x} \<union> {x. Q x}"
  by blast

lemma Collect_conj_eq: "{x. P x & Q x} = {x. P x} \<inter> {x. Q x}"
  by blast

text {* \medskip @{text insert}. *}

lemma insert_is_Un: "insert a A = {a} Un A"
  -- {* NOT SUITABLE FOR REWRITING since @{text "{a} == insert a {}"} *}
  by blast

lemma insert_not_empty [simp]: "insert a A \<noteq> {}"
  by blast

lemmas empty_not_insert = insert_not_empty [symmetric]
declare empty_not_insert [simp]

lemma insert_absorb: "a \<in> A ==> insert a A = A"
  -- {* @{text "[simp]"} causes recursive calls when there are nested inserts *}
  -- {* with \emph{quadratic} running time *}
  by blast

lemma insert_absorb2 [simp]: "insert x (insert x A) = insert x A"
  by blast

lemma insert_commute: "insert x (insert y A) = insert y (insert x A)"
  by blast

lemma insert_subset [simp]: "(insert x A \<subseteq> B) = (x \<in> B & A \<subseteq> B)"
  by blast

lemma mk_disjoint_insert: "a \<in> A ==> \<exists>B. A = insert a B & a \<notin> B"
  -- {* use new @{text B} rather than @{text "A - {a}"} to avoid infinite unfolding *}
  apply (rule_tac x = "A - {a}" in exI, blast)
  done

lemma insert_Collect: "insert a (Collect P) = {u. u \<noteq> a --> P u}"
  by auto

lemma insert_inter_insert[simp]: "insert a A \<inter> insert a B = insert a (A \<inter> B)"
  by blast

lemma insert_disjoint [simp]:
 "(insert a A \<inter> B = {}) = (a \<notin> B \<and> A \<inter> B = {})"
 "({} = insert a A \<inter> B) = (a \<notin> B \<and> {} = A \<inter> B)"
  by auto

lemma disjoint_insert [simp]:
 "(B \<inter> insert a A = {}) = (a \<notin> B \<and> B \<inter> A = {})"
 "({} = A \<inter> insert b B) = (b \<notin> A \<and> {} = A \<inter> B)"
  by auto

text {* \medskip @{text Int} *}

lemma Int_absorb: "A \<inter> A = A"
  by (fact inf_idem) (* already simp *)

lemma Int_left_absorb: "A \<inter> (A \<inter> B) = A \<inter> B"
  by (fact inf_left_idem)

lemma Int_commute: "A \<inter> B = B \<inter> A"
  by (fact inf_commute)

lemma Int_left_commute: "A \<inter> (B \<inter> C) = B \<inter> (A \<inter> C)"
  by (fact inf_left_commute)

lemma Int_assoc: "(A \<inter> B) \<inter> C = A \<inter> (B \<inter> C)"
  by (fact inf_assoc)

lemmas Int_ac = Int_assoc Int_left_absorb Int_commute Int_left_commute
  -- {* Intersection is an AC-operator *}

lemma Int_absorb1: "B \<subseteq> A ==> A \<inter> B = B"
  by (fact inf_absorb2)

lemma Int_absorb2: "A \<subseteq> B ==> A \<inter> B = A"
  by (fact inf_absorb1)

lemma Int_empty_left: "{} \<inter> B = {}"
  by (fact inf_bot_left) (* already simp *)

lemma Int_empty_right: "A \<inter> {} = {}"
  by (fact inf_bot_right) (* already simp *)

lemma disjoint_eq_subset_Compl: "(A \<inter> B = {}) = (A \<subseteq> -B)"
  by blast

lemma disjoint_iff_not_equal: "(A \<inter> B = {}) = (\<forall>x\<in>A. \<forall>y\<in>B. x \<noteq> y)"
  by blast

lemma Int_UNIV_left: "UNIV \<inter> B = B"
  by (fact inf_top_left) (* already simp *)

lemma Int_UNIV_right: "A \<inter> UNIV = A"
  by (fact inf_top_right) (* already simp *)

lemma Int_Un_distrib: "A \<inter> (B \<union> C) = (A \<inter> B) \<union> (A \<inter> C)"
  by (fact inf_sup_distrib1)

lemma Int_Un_distrib2: "(B \<union> C) \<inter> A = (B \<inter> A) \<union> (C \<inter> A)"
  by (fact inf_sup_distrib2)

lemma Int_UNIV [simp]: "(A \<inter> B = UNIV) = (A = UNIV & B = UNIV)"
  by (fact inf_eq_top_iff) (* already simp *)

lemma Int_subset_iff [simp]: "(C \<subseteq> A \<inter> B) = (C \<subseteq> A & C \<subseteq> B)"
  by (fact le_inf_iff)

lemma Int_Collect: "(x \<in> A \<inter> {x. P x}) = (x \<in> A & P x)"
  by blast

text {* \medskip @{text Un}. *}

lemma Un_absorb: "A \<union> A = A"
  by (fact sup_idem) (* already simp *)

lemma Un_left_absorb: "A \<union> (A \<union> B) = A \<union> B"
  by (fact sup_left_idem)

lemma Un_commute: "A \<union> B = B \<union> A"
  by (fact sup_commute)

lemma Un_left_commute: "A \<union> (B \<union> C) = B \<union> (A \<union> C)"
  by (fact sup_left_commute)

lemma Un_assoc: "(A \<union> B) \<union> C = A \<union> (B \<union> C)"
  by (fact sup_assoc)

lemmas Un_ac = Un_assoc Un_left_absorb Un_commute Un_left_commute
  -- {* Union is an AC-operator *}

lemma Un_absorb1: "A \<subseteq> B ==> A \<union> B = B"
  by (fact sup_absorb2)

lemma Un_absorb2: "B \<subseteq> A ==> A \<union> B = A"
  by (fact sup_absorb1)

lemma Un_empty_left: "{} \<union> B = B"
  by (fact sup_bot_left) (* already simp *)

lemma Un_empty_right: "A \<union> {} = A"
  by (fact sup_bot_right) (* already simp *)

lemma Un_UNIV_left: "UNIV \<union> B = UNIV"
  by (fact sup_top_left) (* already simp *)

lemma Un_UNIV_right: "A \<union> UNIV = UNIV"
  by (fact sup_top_right) (* already simp *)

lemma Un_insert_left [simp]: "(insert a B) \<union> C = insert a (B \<union> C)"
  by blast

lemma Un_insert_right [simp]: "A \<union> (insert a B) = insert a (A \<union> B)"
  by blast

lemma Int_insert_left:
    "(insert a B) Int C = (if a \<in> C then insert a (B \<inter> C) else B \<inter> C)"
  by auto

lemma Int_insert_left_if0[simp]:
    "a \<notin> C \<Longrightarrow> (insert a B) Int C = B \<inter> C"
  by auto

lemma Int_insert_left_if1[simp]:
    "a \<in> C \<Longrightarrow> (insert a B) Int C = insert a (B Int C)"
  by auto

lemma Int_insert_right:
    "A \<inter> (insert a B) = (if a \<in> A then insert a (A \<inter> B) else A \<inter> B)"
  by auto

lemma Int_insert_right_if0[simp]:
    "a \<notin> A \<Longrightarrow> A Int (insert a B) = A Int B"
  by auto

lemma Int_insert_right_if1[simp]:
    "a \<in> A \<Longrightarrow> A Int (insert a B) = insert a (A Int B)"
  by auto

lemma Un_Int_distrib: "A \<union> (B \<inter> C) = (A \<union> B) \<inter> (A \<union> C)"
  by (fact sup_inf_distrib1)

lemma Un_Int_distrib2: "(B \<inter> C) \<union> A = (B \<union> A) \<inter> (C \<union> A)"
  by (fact sup_inf_distrib2)

lemma Un_Int_crazy:
    "(A \<inter> B) \<union> (B \<inter> C) \<union> (C \<inter> A) = (A \<union> B) \<inter> (B \<union> C) \<inter> (C \<union> A)"
  by blast

lemma subset_Un_eq: "(A \<subseteq> B) = (A \<union> B = B)"
  by (fact le_iff_sup)

lemma Un_empty [iff]: "(A \<union> B = {}) = (A = {} & B = {})"
  by (fact sup_eq_bot_iff) (* FIXME: already simp *)

lemma Un_subset_iff [simp]: "(A \<union> B \<subseteq> C) = (A \<subseteq> C & B \<subseteq> C)"
  by (fact le_sup_iff)

lemma Un_Diff_Int: "(A - B) \<union> (A \<inter> B) = A"
  by blast

lemma Diff_Int2: "A \<inter> C - B \<inter> C = A \<inter> C - B"
  by blast

text {* \medskip Set complement *}

lemma Compl_disjoint [simp]: "A \<inter> -A = {}"
  by (fact inf_compl_bot)

lemma Compl_disjoint2 [simp]: "-A \<inter> A = {}"
  by (fact compl_inf_bot)

lemma Compl_partition: "A \<union> -A = UNIV"
  by (fact sup_compl_top)

lemma Compl_partition2: "-A \<union> A = UNIV"
  by (fact compl_sup_top)

lemma double_complement: "- (-A) = (A::'a set)"
  by (fact double_compl) (* already simp *)

lemma Compl_Un: "-(A \<union> B) = (-A) \<inter> (-B)"
  by (fact compl_sup) (* already simp *)

lemma Compl_Int: "-(A \<inter> B) = (-A) \<union> (-B)"
  by (fact compl_inf) (* already simp *)

lemma subset_Compl_self_eq: "(A \<subseteq> -A) = (A = {})"
  by blast

lemma Un_Int_assoc_eq: "((A \<inter> B) \<union> C = A \<inter> (B \<union> C)) = (C \<subseteq> A)"
  -- {* Halmos, Naive Set Theory, page 16. *}
  by blast

lemma Compl_UNIV_eq: "-UNIV = {}"
  by (fact compl_top_eq) (* already simp *)

lemma Compl_empty_eq: "-{} = UNIV"
  by (fact compl_bot_eq) (* already simp *)

lemma Compl_subset_Compl_iff [iff]: "(-A \<subseteq> -B) = (B \<subseteq> A)"
  by (fact compl_le_compl_iff) (* FIXME: already simp *)

lemma Compl_eq_Compl_iff [iff]: "(-A = -B) = (A = (B::'a set))"
  by (fact compl_eq_compl_iff) (* FIXME: already simp *)

lemma Compl_insert: "- insert x A = (-A) - {x}"
  by blast

text {* \medskip Bounded quantifiers.

  The following are not added to the default simpset because
  (a) they duplicate the body and (b) there are no similar rules for @{text Int}. *}

lemma ball_Un: "(\<forall>x \<in> A \<union> B. P x) = ((\<forall>x\<in>A. P x) & (\<forall>x\<in>B. P x))"
  by blast

lemma bex_Un: "(\<exists>x \<in> A \<union> B. P x) = ((\<exists>x\<in>A. P x) | (\<exists>x\<in>B. P x))"
  by blast

text {* \medskip Set difference. *}

lemma Diff_eq: "A - B = A \<inter> (-B)"
  by blast

lemma Diff_eq_empty_iff [simp]: "(A - B = {}) = (A \<subseteq> B)"
  by blast

lemma Diff_cancel [simp]: "A - A = {}"
  by blast

lemma Diff_idemp [simp]: "(A - B) - B = A - (B::'a set)"
by blast

lemma Diff_triv: "A \<inter> B = {} ==> A - B = A"
  by (blast elim: equalityE)

lemma empty_Diff [simp]: "{} - A = {}"
  by blast

lemma Diff_empty [simp]: "A - {} = A"
  by blast

lemma Diff_UNIV [simp]: "A - UNIV = {}"
  by blast

lemma Diff_insert0 [simp]: "x \<notin> A ==> A - insert x B = A - B"
  by blast

lemma Diff_insert: "A - insert a B = A - B - {a}"
  -- {* NOT SUITABLE FOR REWRITING since @{text "{a} == insert a 0"} *}
  by blast

lemma Diff_insert2: "A - insert a B = A - {a} - B"
  -- {* NOT SUITABLE FOR REWRITING since @{text "{a} == insert a 0"} *}
  by blast

lemma insert_Diff_if: "insert x A - B = (if x \<in> B then A - B else insert x (A - B))"
  by auto

lemma insert_Diff1 [simp]: "x \<in> B ==> insert x A - B = A - B"
  by blast

lemma insert_Diff_single[simp]: "insert a (A - {a}) = insert a A"
by blast

lemma insert_Diff: "a \<in> A ==> insert a (A - {a}) = A"
  by blast

lemma Diff_insert_absorb: "x \<notin> A ==> (insert x A) - {x} = A"
  by auto

lemma Diff_disjoint [simp]: "A \<inter> (B - A) = {}"
  by blast

lemma Diff_partition: "A \<subseteq> B ==> A \<union> (B - A) = B"
  by blast

lemma double_diff: "A \<subseteq> B ==> B \<subseteq> C ==> B - (C - A) = A"
  by blast

lemma Un_Diff_cancel [simp]: "A \<union> (B - A) = A \<union> B"
  by blast

lemma Un_Diff_cancel2 [simp]: "(B - A) \<union> A = B \<union> A"
  by blast

lemma Diff_Un: "A - (B \<union> C) = (A - B) \<inter> (A - C)"
  by blast

lemma Diff_Int: "A - (B \<inter> C) = (A - B) \<union> (A - C)"
  by blast

lemma Un_Diff: "(A \<union> B) - C = (A - C) \<union> (B - C)"
  by blast

lemma Int_Diff: "(A \<inter> B) - C = A \<inter> (B - C)"
  by blast

lemma Diff_Int_distrib: "C \<inter> (A - B) = (C \<inter> A) - (C \<inter> B)"
  by blast

lemma Diff_Int_distrib2: "(A - B) \<inter> C = (A \<inter> C) - (B \<inter> C)"
  by blast

lemma Diff_Compl [simp]: "A - (- B) = A \<inter> B"
  by auto

lemma Compl_Diff_eq [simp]: "- (A - B) = -A \<union> B"
  by blast

text {* \medskip Quantification over type @{typ bool}. *}

lemma bool_induct: "P True \<Longrightarrow> P False \<Longrightarrow> P x"
  by (cases x) auto

lemma all_bool_eq: "(\<forall>b. P b) \<longleftrightarrow> P True \<and> P False"
  by (auto intro: bool_induct)

lemma bool_contrapos: "P x \<Longrightarrow> \<not> P False \<Longrightarrow> P True"
  by (cases x) auto

lemma ex_bool_eq: "(\<exists>b. P b) \<longleftrightarrow> P True \<or> P False"
  by (auto intro: bool_contrapos)

lemma UNIV_bool: "UNIV = {False, True}"
  by (auto intro: bool_induct)

text {* \medskip @{text Pow} *}

lemma Pow_empty [simp]: "Pow {} = {{}}"
  by (auto simp add: Pow_def)

lemma Pow_insert: "Pow (insert a A) = Pow A \<union> (insert a ` Pow A)"
  by (blast intro: image_eqI [where ?x = "u - {a}" for u])

lemma Pow_Compl: "Pow (- A) = {-B | B. A \<in> Pow B}"
  by (blast intro: exI [where ?x = "- u" for u])

lemma Pow_UNIV [simp]: "Pow UNIV = UNIV"
  by blast

lemma Un_Pow_subset: "Pow A \<union> Pow B \<subseteq> Pow (A \<union> B)"
  by blast

lemma Pow_Int_eq [simp]: "Pow (A \<inter> B) = Pow A \<inter> Pow B"
  by blast

text {* \medskip Miscellany. *}

lemma set_eq_subset: "(A = B) = (A \<subseteq> B & B \<subseteq> A)"
  by blast

lemma subset_iff: "(A \<subseteq> B) = (\<forall>t. t \<in> A --> t \<in> B)"
  by blast

lemma subset_iff_psubset_eq: "(A \<subseteq> B) = ((A \<subset> B) | (A = B))"
  by (unfold less_le) blast

lemma all_not_in_conv [simp]: "(\<forall>x. x \<notin> A) = (A = {})"
  by blast

lemma ex_in_conv: "(\<exists>x. x \<in> A) = (A \<noteq> {})"
  by blast

lemma ball_simps [simp, no_atp]:
  "\<And>A P Q. (\<forall>x\<in>A. P x \<or> Q) \<longleftrightarrow> ((\<forall>x\<in>A. P x) \<or> Q)"
  "\<And>A P Q. (\<forall>x\<in>A. P \<or> Q x) \<longleftrightarrow> (P \<or> (\<forall>x\<in>A. Q x))"
  "\<And>A P Q. (\<forall>x\<in>A. P \<longrightarrow> Q x) \<longleftrightarrow> (P \<longrightarrow> (\<forall>x\<in>A. Q x))"
  "\<And>A P Q. (\<forall>x\<in>A. P x \<longrightarrow> Q) \<longleftrightarrow> ((\<exists>x\<in>A. P x) \<longrightarrow> Q)"
  "\<And>P. (\<forall>x\<in>{}. P x) \<longleftrightarrow> True"
  "\<And>P. (\<forall>x\<in>UNIV. P x) \<longleftrightarrow> (\<forall>x. P x)"
  "\<And>a B P. (\<forall>x\<in>insert a B. P x) \<longleftrightarrow> (P a \<and> (\<forall>x\<in>B. P x))"
  "\<And>P Q. (\<forall>x\<in>Collect Q. P x) \<longleftrightarrow> (\<forall>x. Q x \<longrightarrow> P x)"
  "\<And>A P f. (\<forall>x\<in>f`A. P x) \<longleftrightarrow> (\<forall>x\<in>A. P (f x))"
  "\<And>A P. (\<not> (\<forall>x\<in>A. P x)) \<longleftrightarrow> (\<exists>x\<in>A. \<not> P x)"
  by auto

lemma bex_simps [simp, no_atp]:
  "\<And>A P Q. (\<exists>x\<in>A. P x \<and> Q) \<longleftrightarrow> ((\<exists>x\<in>A. P x) \<and> Q)"
  "\<And>A P Q. (\<exists>x\<in>A. P \<and> Q x) \<longleftrightarrow> (P \<and> (\<exists>x\<in>A. Q x))"
  "\<And>P. (\<exists>x\<in>{}. P x) \<longleftrightarrow> False"
  "\<And>P. (\<exists>x\<in>UNIV. P x) \<longleftrightarrow> (\<exists>x. P x)"
  "\<And>a B P. (\<exists>x\<in>insert a B. P x) \<longleftrightarrow> (P a | (\<exists>x\<in>B. P x))"
  "\<And>P Q. (\<exists>x\<in>Collect Q. P x) \<longleftrightarrow> (\<exists>x. Q x \<and> P x)"
  "\<And>A P f. (\<exists>x\<in>f`A. P x) \<longleftrightarrow> (\<exists>x\<in>A. P (f x))"
  "\<And>A P. (\<not>(\<exists>x\<in>A. P x)) \<longleftrightarrow> (\<forall>x\<in>A. \<not> P x)"
  by auto

subsubsection {* Monotonicity of various operations *}

lemma image_mono: "A \<subseteq> B ==> f`A \<subseteq> f`B"
  by blast

lemma Pow_mono: "A \<subseteq> B ==> Pow A \<subseteq> Pow B"
  by blast

lemma insert_mono: "C \<subseteq> D ==> insert a C \<subseteq> insert a D"
  by blast

lemma Un_mono: "A \<subseteq> C ==> B \<subseteq> D ==> A \<union> B \<subseteq> C \<union> D"
  by (fact sup_mono)

lemma Int_mono: "A \<subseteq> C ==> B \<subseteq> D ==> A \<inter> B \<subseteq> C \<inter> D"
  by (fact inf_mono)

lemma Diff_mono: "A \<subseteq> C ==> D \<subseteq> B ==> A - B \<subseteq> C - D"
  by blast

lemma Compl_anti_mono: "A \<subseteq> B ==> -B \<subseteq> -A"
  by (fact compl_mono)

text {* \medskip Monotonicity of implications. *}

lemma in_mono: "A \<subseteq> B ==> x \<in> A --> x \<in> B"
  apply (rule impI)
  apply (erule subsetD, assumption)
  done

lemma conj_mono: "P1 --> Q1 ==> P2 --> Q2 ==> (P1 & P2) --> (Q1 & Q2)"
  by iprover

lemma disj_mono: "P1 --> Q1 ==> P2 --> Q2 ==> (P1 | P2) --> (Q1 | Q2)"
  by iprover

lemma imp_mono: "Q1 --> P1 ==> P2 --> Q2 ==> (P1 --> P2) --> (Q1 --> Q2)"
  by iprover

lemma imp_refl: "P --> P" ..

lemma not_mono: "Q --> P ==> ~ P --> ~ Q"
  by iprover

lemma ex_mono: "(!!x. P x --> Q x) ==> (EX x. P x) --> (EX x. Q x)"
  by iprover

lemma all_mono: "(!!x. P x --> Q x) ==> (ALL x. P x) --> (ALL x. Q x)"
  by iprover

lemma Collect_mono: "(!!x. P x --> Q x) ==> Collect P \<subseteq> Collect Q"
  by blast

lemma Int_Collect_mono:
    "A \<subseteq> B ==> (!!x. x \<in> A ==> P x --> Q x) ==> A \<inter> Collect P \<subseteq> B \<inter> Collect Q"
  by blast

lemmas basic_monos =
  subset_refl imp_refl disj_mono conj_mono
  ex_mono Collect_mono in_mono

lemma eq_to_mono: "a = b ==> c = d ==> b --> d ==> a --> c"
  by iprover

subsubsection {* Inverse image of a function *}

definition vimage :: "('a => 'b) => 'b set => 'a set" (infixr "-`" 90) where
  "f -` B == {x. f x : B}"

lemma vimage_eq [simp]: "(a : f -` B) = (f a : B)"
  by (unfold vimage_def) blast

lemma vimage_singleton_eq: "(a : f -` {b}) = (f a = b)"
  by simp

lemma vimageI [intro]: "f a = b ==> b:B ==> a : f -` B"
  by (unfold vimage_def) blast

lemma vimageI2: "f a : A ==> a : f -` A"
  by (unfold vimage_def) fast

lemma vimageE [elim!]: "a: f -` B ==> (!!x. f a = x ==> x:B ==> P) ==> P"
  by (unfold vimage_def) blast

lemma vimageD: "a : f -` A ==> f a : A"
  by (unfold vimage_def) fast

lemma vimage_empty [simp]: "f -` {} = {}"
  by blast

lemma vimage_Compl: "f -` (-A) = -(f -` A)"
  by blast

lemma vimage_Un [simp]: "f -` (A Un B) = (f -` A) Un (f -` B)"
  by blast

lemma vimage_Int [simp]: "f -` (A Int B) = (f -` A) Int (f -` B)"
  by fast

lemma vimage_Collect_eq [simp]: "f -` Collect P = {y. P (f y)}"
  by blast

lemma vimage_Collect: "(!!x. P (f x) = Q x) ==> f -` (Collect P) = Collect Q"
  by blast

lemma vimage_insert: "f-`(insert a B) = (f-`{a}) Un (f-`B)"
  -- {* NOT suitable for rewriting because of the recurrence of @{term "{a}"}. *}
  by blast

lemma vimage_Diff: "f -` (A - B) = (f -` A) - (f -` B)"
  by blast

lemma vimage_UNIV [simp]: "f -` UNIV = UNIV"
  by blast

lemma vimage_mono: "A \<subseteq> B ==> f -` A \<subseteq> f -` B"
  -- {* monotonicity *}
  by blast

lemma vimage_image_eq: "f -` (f ` A) = {y. EX x:A. f x = f y}"
by (blast intro: sym)

lemma image_vimage_subset: "f ` (f -` A) <= A"
by blast

lemma image_vimage_eq [simp]: "f ` (f -` A) = A Int range f"
by blast

lemma image_subset_iff_subset_vimage: "f ` A \<subseteq> B \<longleftrightarrow> A \<subseteq> f -` B"
  by blast

lemma vimage_const [simp]: "((\<lambda>x. c) -` A) = (if c \<in> A then UNIV else {})"
  by auto

lemma vimage_if [simp]: "((\<lambda>x. if x \<in> B then c else d) -` A) =
   (if c \<in> A then (if d \<in> A then UNIV else B)
    else if d \<in> A then -B else {})"
  by (auto simp add: vimage_def)

lemma vimage_inter_cong:
  "(\<And> w. w \<in> S \<Longrightarrow> f w = g w) \<Longrightarrow> f -` y \<inter> S = g -` y \<inter> S"
  by auto

lemma vimage_ident [simp]: "(%x. x) -` Y = Y"
  by blast

subsubsection {* Getting the Contents of a Singleton Set *}

definition the_elem :: "'a set \<Rightarrow> 'a" where
  "the_elem X = (THE x. X = {x})"

lemma the_elem_eq [simp]: "the_elem {x} = x"
  by (simp add: the_elem_def)

lemma the_elem_image_unique:
  assumes "A \<noteq> {}"
  assumes *: "\<And>y. y \<in> A \<Longrightarrow> f y = f x"
  shows "the_elem (f ` A) = f x"
unfolding the_elem_def proof (rule the1_equality)
  from `A \<noteq> {}` obtain y where "y \<in> A" by auto
  with * have "f x = f y" by simp
  with `y \<in> A` have "f x \<in> f ` A" by blast
  with * show "f ` A = {f x}" by auto
  then show "\<exists>!x. f ` A = {x}" by auto
qed

subsubsection {* Least value operator *}

lemma Least_mono:
  "mono (f::'a::order => 'b::order) ==> EX x:S. ALL y:S. x <= y
    ==> (LEAST y. y : f ` S) = f (LEAST x. x : S)"
    -- {* Courtesy of Stephan Merz *}
  apply clarify
  apply (erule_tac P = "%x. x : S" in LeastI2_order, fast)
  apply (rule LeastI2_order)
  apply (auto elim: monoD intro!: order_antisym)
  done

subsubsection {* Monad operation *}

definition bind :: "'a set \<Rightarrow> ('a \<Rightarrow> 'b set) \<Rightarrow> 'b set" where
  "bind A f = {x. \<exists>B \<in> f`A. x \<in> B}"

hide_const (open) bind

lemma bind_bind:
  fixes A :: "'a set"
  shows "Set.bind (Set.bind A B) C = Set.bind A (\<lambda>x. Set.bind (B x) C)"
  by (auto simp add: bind_def)

lemma empty_bind [simp]:
  "Set.bind {} f = {}"
  by (simp add: bind_def)

lemma nonempty_bind_const:
  "A \<noteq> {} \<Longrightarrow> Set.bind A (\<lambda>_. B) = B"
  by (auto simp add: bind_def)

lemma bind_const: "Set.bind A (\<lambda>_. B) = (if A = {} then {} else B)"
  by (auto simp add: bind_def)

subsubsection {* Operations for execution *}

definition is_empty :: "'a set \<Rightarrow> bool" where
  [code_abbrev]: "is_empty A \<longleftrightarrow> A = {}"

hide_const (open) is_empty

definition remove :: "'a \<Rightarrow> 'a set \<Rightarrow> 'a set" where
  [code_abbrev]: "remove x A = A - {x}"

hide_const (open) remove

lemma member_remove [simp]:
  "x \<in> Set.remove y A \<longleftrightarrow> x \<in> A \<and> x \<noteq> y"
  by (simp add: remove_def)

definition filter :: "('a \<Rightarrow> bool) \<Rightarrow> 'a set \<Rightarrow> 'a set" where
  [code_abbrev]: "filter P A = {a \<in> A. P a}"

hide_const (open) filter

lemma member_filter [simp]:
  "x \<in> Set.filter P A \<longleftrightarrow> x \<in> A \<and> P x"
  by (simp add: filter_def)

instantiation set :: (equal) equal
begin

definition
  "HOL.equal A B \<longleftrightarrow> A \<subseteq> B \<and> B \<subseteq> A"

instance proof
qed (auto simp add: equal_set_def)

end

text {* Misc *}

hide_const (open) member not_member

lemmas equalityI = subset_antisym

ML {*
val Ball_def = @{thm Ball_def}
val Bex_def = @{thm Bex_def}
val CollectD = @{thm CollectD}
val CollectE = @{thm CollectE}
val CollectI = @{thm CollectI}
val Collect_conj_eq = @{thm Collect_conj_eq}
val Collect_mem_eq = @{thm Collect_mem_eq}
val IntD1 = @{thm IntD1}
val IntD2 = @{thm IntD2}
val IntE = @{thm IntE}
val IntI = @{thm IntI}
val Int_Collect = @{thm Int_Collect}
val UNIV_I = @{thm UNIV_I}
val UNIV_witness = @{thm UNIV_witness}
val UnE = @{thm UnE}
val UnI1 = @{thm UnI1}
val UnI2 = @{thm UnI2}
val ballE = @{thm ballE}
val ballI = @{thm ballI}
val bexCI = @{thm bexCI}
val bexE = @{thm bexE}
val bexI = @{thm bexI}
val bex_triv = @{thm bex_triv}
val bspec = @{thm bspec}
val contra_subsetD = @{thm contra_subsetD}
val equalityCE = @{thm equalityCE}
val equalityD1 = @{thm equalityD1}
val equalityD2 = @{thm equalityD2}
val equalityE = @{thm equalityE}
val equalityI = @{thm equalityI}
val imageE = @{thm imageE}
val imageI = @{thm imageI}
val image_Un = @{thm image_Un}
val image_insert = @{thm image_insert}
val insert_commute = @{thm insert_commute}
val insert_iff = @{thm insert_iff}
val mem_Collect_eq = @{thm mem_Collect_eq}
val rangeE = @{thm rangeE}
val rangeI = @{thm rangeI}
val range_eqI = @{thm range_eqI}
val subsetCE = @{thm subsetCE}
val subsetD = @{thm subsetD}
val subsetI = @{thm subsetI}
val subset_refl = @{thm subset_refl}
val subset_trans = @{thm subset_trans}
val vimageD = @{thm vimageD}
val vimageE = @{thm vimageE}
val vimageI = @{thm vimageI}
val vimageI2 = @{thm vimageI2}
val vimage_Collect = @{thm vimage_Collect}
val vimage_Int = @{thm vimage_Int}
val vimage_Un = @{thm vimage_Un}
*}

end


(*  Title:      Open Induction
    Author:     Mizuhito Ogawa
                Christian Sternagel <c-sterna@jaist.ac.jp>
    Maintainer: Christian Sternagel
    License:    LGPL
*)

header {* Open Induction *}

theory Open_Induction
imports
  Main
  "../Well_Quasi_Orders/Restricted_Predicates"
begin

subsection {* (Greatest) Lower Bounds and Chains *}

text {*A set @{term B} has the \emph{lower bound} @{term x} w.r.t.\ to the order
@{term_type "P :: 'a => 'a => bool"} iff @{term x} is less than or equal to every element
of @{term B}.*}
definition lb where
  "lb P B x \<equiv> \<forall>y\<in>B. P x y"

text {*A set @{term B} has the \emph{greatest lower bound} @{term x} (w.r.t.\ @{term P})
iff @{term x} is a lower bound \emph{and} less than or equal to every other lower bound
of @{term B}.*}
definition glb where
  "glb P B x \<equiv> lb P B x \<and> (\<forall>y. lb P B y \<longrightarrow> P y x)"

text {*A subset @{term C} of @{term A} is a \emph{chain} on @{term A} (w.r.t.\ @{term P})
iff for all pairs of elements of @{term C}, one is less than or equal to the other one.*}
definition chain_on where
  "chain_on P C A \<equiv> C \<subseteq> A \<and> (\<forall>x\<in>C. \<forall>y\<in>C. P x y \<or> P y x)"

text {*A chain @{term M} on @{term A} (w.r.t.\ @{term P}) is a \emph{maximal chain} iff
there is no chain on @{term A} that is a superset of @{term M}.*}
definition max_chain_on where
  "max_chain_on P M A \<equiv> chain_on P M A \<and> (\<forall>C. chain_on P C A \<and> M \<subseteq> C \<longrightarrow> M = C)"

lemma chain_onI [Pure.intro!]:
  "C \<subseteq> A \<Longrightarrow> (\<And>x y. \<lbrakk>x \<in> C; y \<in> C\<rbrakk> \<Longrightarrow> P x y \<or> P y x) \<Longrightarrow> chain_on P C A"
  unfolding chain_on_def by blast

lemma chain_on_subset:
  "A \<subseteq> B \<Longrightarrow> chain_on P C A \<Longrightarrow> chain_on P C B"
  unfolding chain_on_def by force

lemma chain_on_imp_subset:
  "chain_on P C A \<Longrightarrow> C \<subseteq> A" by (simp add: chain_on_def)

lemma chain_on_Union:
  assumes "C \<in> chains {C. chain_on P C A}" (is "C \<in> chains ?A")
  shows "chain_on P (\<Union>C) A"
proof
  from assms have "C \<subseteq> ?A" and
    *[rule_format]: "\<forall>x\<in>C. \<forall>y\<in>C. x \<subseteq> y \<or> y \<subseteq> x"
    by (auto simp: chains_def chain_subset_def)
  then show "\<Union>C \<subseteq> A" unfolding chain_on_def by blast
  fix x y assume "x \<in> \<Union>C" and "y \<in> \<Union>C"
  then obtain X Y
    where "X \<in> C" and "Y \<in> C" and "x \<in> X" and "y \<in> Y" by auto
  with `C \<subseteq> ?A` have "X \<subseteq> A" and "Y \<subseteq> A"
    and "chain_on P X A" and "chain_on P Y A" unfolding chain_on_def by auto
  with `x \<in> X` and `y \<in> Y` show "P x y \<or> P y x"
    using * [OF `X \<in> C` `Y \<in> C`]
    unfolding chain_on_def by blast
qed

lemma chain_on_glb:
  assumes "qo_on P A"
  shows "chain_on P C A \<Longrightarrow> C \<noteq> {} \<Longrightarrow> glb P C x \<Longrightarrow> x \<in> A \<Longrightarrow> y \<in> A \<Longrightarrow> P y x \<Longrightarrow> chain_on P ({y} \<union> C) A"
  using qo_on_imp_reflp_on [OF assms, unfolded reflp_on_def, rule_format, of y]
    and qo_on_imp_transp_on [OF assms, unfolded transp_on_def]
  unfolding chain_on_def glb_def lb_def by blast

subsection {* Open Properties *}

definition open_on where
  "open_on P Q A \<equiv>
    \<forall>C. chain_on P C A \<and> C \<noteq> {} \<and> (\<exists>x\<in>A. glb P C x \<and> Q x) \<longrightarrow> (\<exists>y\<in>C. Q y)"

lemma open_on_glb:
  "\<lbrakk>chain_on P C A; C \<noteq> {}; open_on P Q A; \<forall>x\<in>C. \<not> Q x; x \<in> A; glb P C x\<rbrakk> \<Longrightarrow> \<not> Q x"
  by (auto simp: open_on_def)

lemma max_chain_on_exists:
  "\<exists>M. max_chain_on P M A"
proof -
  let ?S = "{C. chain_on P C A}"
  have "\<And>C. C \<in> chains ?S \<Longrightarrow> \<Union>C \<in> ?S"
    using chain_on_Union and chain_on_imp_subset by blast
  with Zorn_Lemma [of ?S]
    obtain M where "M \<in> ?S" and *: "\<forall>z\<in>?S. M \<subseteq> z \<longrightarrow> z = M" by blast
  then have "M \<subseteq> A" and "chain_on P M A" by (auto dest: chain_on_imp_subset)
  moreover {
    fix C assume "chain_on P C A" and "M \<subseteq> C"
    with * have "M = C"
      using chain_on_imp_subset [OF `chain_on P C A`]
      by blast }
  ultimately show "?thesis" by (auto simp: max_chain_on_def)
qed

subsection {* Downward Completeness *}

text {*An order @{term P} is \emph{downward-complete} on @{term A} iff every non-empty
chain on @{term A} has a greatest lower bound in @{term A}.*}
definition dc_on where
  "dc_on P A \<equiv> \<forall>C. chain_on P C A \<and> C \<noteq> {} \<longrightarrow> (\<exists>x\<in>A. glb P C x)"

subsection {* The Open Induction Schema *}

lemma open_induct_on [consumes 4]:
  assumes "qo_on P A" and "dc_on P A" and "open_on P Q A"
    and "x \<in> A"
    and ind: "\<And>x. \<lbrakk>x \<in> A; \<And>y. \<lbrakk>y \<in> A; strict P y x\<rbrakk> \<Longrightarrow> Q y\<rbrakk> \<Longrightarrow> Q x"
  shows "Q x"
proof (rule ccontr)
  note refl =
    qo_on_imp_reflp_on [OF `qo_on P A`, unfolded reflp_on_def, rule_format]
  assume "\<not> Q x"
  let ?A = "{x\<in>A. \<not> Q x}"
  from max_chain_on_exists [of P ?A] obtain M where
    chain: "chain_on P M ?A" and
    max: "\<And>C. chain_on P C ?A \<Longrightarrow> M \<subseteq> C \<Longrightarrow> M = C" by (auto simp: max_chain_on_def)
  from chain have "M \<subseteq> ?A" by (auto simp: chain_on_imp_subset)
  show False
  proof (cases "M = {}")
    assume "M = {}"
    moreover have "chain_on P {x} ?A"
      using refl and `x \<in> A` and `\<not> Q x` by (simp add: chain_on_def)
    ultimately show False using max by blast
  next
    assume "M \<noteq> {}"
    have "?A \<subseteq> A" by blast
    with chain have "chain_on P M A"
      using chain_on_subset by blast
    moreover with `dc_on P A` and `M \<noteq> {}` obtain m where
      "m \<in> A" and "glb P M m"
      unfolding dc_on_def by auto
    ultimately have "\<not> Q m" and "m \<in> ?A"
      using open_on_glb [OF _ `M \<noteq> {}` `open_on P Q A` _ _ `glb P M m`]
      and `M \<subseteq> ?A` by auto
    from ind [OF `m \<in> A`] and `\<not> Q m` obtain y where
      "y \<in> A" and "strict P y m" and "\<not> Q y" by blast
    then have "P y m" and "y \<in> ?A" by simp+
    from qo_on_subset [OF `?A \<subseteq> A` `qo_on P A`] have "qo_on P ?A" .
    from chain_on_glb [OF this chain, of m y]
     and `M \<noteq> {}` and `glb P M m` and `m \<in> ?A` and `y \<in> ?A` and `P y m`
      have "chain_on P ({y} \<union> M) ?A" by blast
    show False
    proof (cases "y \<in> M")
      assume "y \<in> M"
      with `glb P M m` and `strict P y m`
        show False by (simp add: glb_def lb_def)
    next
      assume "y \<notin> M"
      with max [OF `chain_on P ({y} \<union> M) ?A`] show False by blast
    qed
  qed
qed

subsection {* Universal Open Induction Schemas *}

text {*Open induction on quasi-orders (i.e., @{class preorder}).*}
lemma (in preorder) dc_open_induct [consumes 2]:
  assumes "dc_on (op \<le>) UNIV"
    and "open_on (op \<le>) Q UNIV"
    and "\<And>x. (\<And>y. y < x \<Longrightarrow> Q y) \<Longrightarrow> Q x"
  shows "Q x"
proof -
  have "qo_on (op \<le>) UNIV"
    unfolding qo_on_UNIV_conv
    unfolding less_le_not_le [symmetric] ..
  moreover have "dc_on (op \<le>) UNIV" by fact
  ultimately show "Q x"
    using assms and open_induct_on [of "op \<le>" UNIV Q]
    unfolding less_le_not_le by blast
qed

subsection {* Type Class of Downward Complete Orders *}

class dcorder = preorder +
  assumes dc: "\<lbrakk>chain_on (op \<le>) C UNIV; C \<noteq> {}\<rbrakk> \<Longrightarrow> (\<exists>x. glb (op \<le>) C x)"
begin

lemma dc_on_UNIV: "dc_on (op \<le>) UNIV"
  using dc unfolding dc_on_def by blast

text {*Open induction on downward-complete orders.*}
lemmas open_induct [consumes 1] = dc_open_induct [OF dc_on_UNIV]

end

end


(*  Title:      HOL/Datatype_Examples/Lambda_Term.thy
    Author:     Dmitriy Traytel, TU Muenchen
    Author:     Andrei Popescu, TU Muenchen
    Copyright   2012

Lambda-terms.
*)

section \<open>Lambda-Terms\<close>

theory Lambda_Term
imports "~~/src/HOL/Library/FSet"
begin

section \<open>Datatype definition\<close>

datatype 'a trm =
  Var 'a |
  App "'a trm" "'a trm" |
  Lam 'a "'a trm" |
  Lt "('a \<times> 'a trm) fset" "'a trm"

subsection \<open>Example: The set of all variables varsOf and free variables fvarsOf of a term\<close>

primrec varsOf :: "'a trm \<Rightarrow> 'a set" where
  "varsOf (Var a) = {a}"
| "varsOf (App f x) = varsOf f \<union> varsOf x"
| "varsOf (Lam x b) = {x} \<union> varsOf b"
| "varsOf (Lt F t) = varsOf t \<union> (\<Union>{{x} \<union> X | x X. (x,X) |\<in>| fimage (map_prod id varsOf) F})"

primrec fvarsOf :: "'a trm \<Rightarrow> 'a set" where
  "fvarsOf (Var x) = {x}"
| "fvarsOf (App t1 t2) = fvarsOf t1 \<union> fvarsOf t2"
| "fvarsOf (Lam x t) = fvarsOf t - {x}"
| "fvarsOf (Lt xts t) = fvarsOf t - {x | x X. (x,X) |\<in>| fimage (map_prod id varsOf) xts} \<union>
    (\<Union>{X | x X. (x,X) |\<in>| fimage (map_prod id varsOf) xts})"

lemma diff_Un_incl_triv: "\<lbrakk>A \<subseteq> D; C \<subseteq> E\<rbrakk> \<Longrightarrow> A - B \<union> C \<subseteq> D \<union> E" by blast

lemma in_fimage_map_prod_fset_iff[simp]:
  "(x, y) |\<in>| fimage (map_prod f g) xts \<longleftrightarrow> (\<exists> t1 t2. (t1, t2) |\<in>| xts \<and> x = f t1 \<and> y = g t2)"
  by force

lemma fvarsOf_varsOf: "fvarsOf t \<subseteq> varsOf t"
proof induct
  case (Lt xts t) thus ?case unfolding fvarsOf.simps varsOf.simps by (elim diff_Un_incl_triv) auto
qed auto

end


header {* Deciding Regular Expression Equivalence *}

theory Equivalence_Checking
imports
  NDerivative
  "~~/src/HOL/Library/While_Combinator"
begin

subsection {* Bisimulation between languages and regular expressions *}

coinductive bisimilar :: "'a lang \<Rightarrow> 'a lang \<Rightarrow> bool" where
"([] \<in> K \<longleftrightarrow> [] \<in> L)
 \<Longrightarrow> (\<And>x. bisimilar (Deriv x K) (Deriv x L))
 \<Longrightarrow> bisimilar K L"

lemma equal_if_bisimilar:
assumes "bisimilar K L" shows "K = L"
proof (rule set_eqI)
  fix w
  from `bisimilar K L` show "w \<in> K \<longleftrightarrow> w \<in> L"
  proof (induct w arbitrary: K L)
    case Nil thus ?case by (auto elim: bisimilar.cases)
  next
    case (Cons a w K L)
    from `bisimilar K L` have "bisimilar (Deriv a K) (Deriv a L)"
      by (auto elim: bisimilar.cases)
    then have "w \<in> Deriv a K \<longleftrightarrow> w \<in> Deriv a L" by (rule Cons(1))
    thus ?case by (auto simp: Deriv_def)
  qed
qed

lemma language_coinduct:
fixes R (infixl "\<sim>" 50)
assumes "K \<sim> L"
assumes "\<And>K L. K \<sim> L \<Longrightarrow> ([] \<in> K \<longleftrightarrow> [] \<in> L)"
assumes "\<And>K L x. K \<sim> L \<Longrightarrow> Deriv x K \<sim> Deriv x L"
shows "K = L"
apply (rule equal_if_bisimilar)
apply (rule bisimilar.coinduct[of R, OF `K \<sim> L`])
apply (auto simp: assms)
done

type_synonym 'a rexp_pair = "'a rexp * 'a rexp"
type_synonym 'a rexp_pairs = "'a rexp_pair list"

definition is_bisimulation ::  "'a::order list \<Rightarrow> 'a rexp_pair set \<Rightarrow> bool"
where
"is_bisimulation as R =
  (\<forall>(r,s)\<in> R. (atoms r \<union> atoms s \<subseteq> set as) \<and> (nullable r \<longleftrightarrow> nullable s) \<and>
    (\<forall>a\<in>set as. (nderiv a r, nderiv a s) \<in> R))"

lemma bisim_lang_eq:
assumes bisim: "is_bisimulation as ps"
assumes "(r, s) \<in> ps"
shows "lang r = lang s"
proof -
  def ps' \<equiv> "insert (Zero, Zero) ps"
  from bisim have bisim': "is_bisimulation as ps'"
    by (auto simp: ps'_def is_bisimulation_def)
  let ?R = "\<lambda>K L. (\<exists>(r,s)\<in>ps'. K = lang r \<and> L = lang s)"
  show ?thesis
  proof (rule language_coinduct[where R="?R"])
    from `(r, s) \<in> ps`
    have "(r, s) \<in> ps'" by (auto simp: ps'_def)
    thus "?R (lang r) (lang s)" by auto
  next
    fix K L assume "?R K L"
    then obtain r s where rs: "(r, s) \<in> ps'"
      and KL: "K = lang r" "L = lang s" by auto
    with bisim' have "nullable r \<longleftrightarrow> nullable s"
      by (auto simp: is_bisimulation_def)
    thus "[] \<in> K \<longleftrightarrow> [] \<in> L" by (auto simp: nullable_iff KL)
    fix a
    show "?R (Deriv a K) (Deriv a L)"
    proof cases
      assume "a \<in> set as"
      with rs bisim'
      have "(nderiv a r, nderiv a s) \<in> ps'"
        by (auto simp: is_bisimulation_def)
      thus ?thesis by (force simp: KL lang_nderiv)
    next
      assume "a \<notin> set as"
      with bisim' rs
      have "a \<notin> atoms r" "a \<notin> atoms s" by (auto simp: is_bisimulation_def)
      then have "nderiv a r = Zero" "nderiv a s = Zero"
        by (auto intro: deriv_no_occurrence)
      then have "Deriv a K = lang Zero"
        "Deriv a L = lang Zero"
        unfolding KL lang_nderiv[symmetric] by auto
      thus ?thesis by (auto simp: ps'_def)
    qed
  qed
qed

subsection {* Closure computation *}

definition closure ::
  "'a::order list \<Rightarrow> 'a rexp_pair \<Rightarrow> ('a rexp_pairs * 'a rexp_pair set) option"
where
"closure as = rtrancl_while (%(r,s). nullable r = nullable s)
  (%(r,s). map (\<lambda>a. (nderiv a r, nderiv a s)) as)"

definition pre_bisim :: "'a::order list \<Rightarrow> 'a rexp \<Rightarrow> 'a rexp \<Rightarrow>
 'a rexp_pairs * 'a rexp_pair set \<Rightarrow> bool"
where
"pre_bisim as r s = (\<lambda>(ws,R).
 (r,s) \<in> R \<and> set ws \<subseteq> R \<and>
 (\<forall>(r,s)\<in> R. atoms r \<union> atoms s \<subseteq> set as) \<and>
 (\<forall>(r,s)\<in> R - set ws. (nullable r \<longleftrightarrow> nullable s) \<and>
   (\<forall>a\<in>set as. (nderiv a r, nderiv a s) \<in> R)))"

subsection {* Bisimulation-free proof of closure computation *}

text{* The equivalence check can be viewed as the product construction
of two automata. The state space is the reflexive transitive closure of
the pair of next-state functions, i.e. derivatives. *}

lemma rtrancl_nderiv_nderivs: defines "nderivs == foldl (%r a. nderiv a r)"
shows "{((r,s),(nderiv a r,nderiv a s))| r s a. a : A}^* =
       {((r,s),(nderivs r w,nderivs s w))| r s w. w : lists A}" (is "?L = ?R")
proof-
  note [simp] = nderivs_def
  { fix r s r' s'
    have "((r,s),(r',s')) : ?L \<Longrightarrow> ((r,s),(r',s')) : ?R"
    proof(induction rule: converse_rtrancl_induct2)
      case refl show ?case by (force intro!: foldl.simps(1)[symmetric])
    next
      case step thus ?case by(force intro!: foldl.simps(2)[symmetric])
    qed
  } moreover
  { fix r s r' s'
    { fix w have "\<forall>x\<in>set w. x \<in> A \<Longrightarrow> ((r, s), nderivs r w, nderivs s w) :?L"
      proof(induction w rule: rev_induct)
        case Nil show ?case by simp
      next
        case snoc thus ?case by (auto elim!: rtrancl_into_rtrancl)
      qed
    }
    hence "((r,s),(r',s')) : ?R \<Longrightarrow> ((r,s),(r',s')) : ?L" by auto
  } ultimately show ?thesis by (auto simp: in_lists_conv_set) blast
qed

lemma nullable_nderivs:
  "nullable (foldl (%r a. nderiv a r) r w) = (w : lang r)"
by (induct w arbitrary: r) (simp_all add: nullable_iff lang_nderiv Deriv_def)

theorem closure_sound_complete:
assumes result: "closure as (r,s) = Some(ws,R)"
and atoms: "set as = atoms r \<union> atoms s"
shows "ws = [] \<longleftrightarrow> lang r = lang s"
proof -
  have leq: "(lang r = lang s) =
  (\<forall>(r',s') \<in> {((r0,s0),(nderiv a r0,nderiv a s0))| r0 s0 a. a : set as}^* `` {(r,s)}.
    nullable r' = nullable s')"
    by(simp add: atoms rtrancl_nderiv_nderivs Ball_def lang_eq_ext imp_ex nullable_nderivs
         del:Un_iff)
  have "{(x,y). y \<in> set ((\<lambda>(p,q). map (\<lambda>a. (nderiv a p, nderiv a q)) as) x)} =
    {((r,s), nderiv a r, nderiv a s) |r s a. a \<in> set as}"
    by auto
  with atoms rtrancl_while_Some[OF result[unfolded closure_def]]
  show ?thesis by (auto simp add: leq Ball_def split: if_splits)
qed

subsection {* The overall procedure *}

primrec add_atoms :: "'a rexp \<Rightarrow> 'a list \<Rightarrow> 'a list"
where
  "add_atoms Zero = id"
| "add_atoms One = id"
| "add_atoms (Atom a) = List.insert a"
| "add_atoms (Plus r s) = add_atoms s o add_atoms r"
| "add_atoms (Times r s) = add_atoms s o add_atoms r"
| "add_atoms (Star r) = add_atoms r"

lemma set_add_atoms: "set (add_atoms r as) = atoms r \<union> set as"
by (induct r arbitrary: as) auto

definition check_eqv :: "nat rexp \<Rightarrow> nat rexp \<Rightarrow> bool" where
"check_eqv r s =
  (let nr = norm r; ns = norm s; as = add_atoms nr (add_atoms ns [])
   in case closure as (nr, ns) of
     Some([],_) \<Rightarrow> True | _ \<Rightarrow> False)"

text{* Test: *}
lemma "check_eqv (Plus One (Times (Atom 0) (Star(Atom 0)))) (Star(Atom 0))"
by eval

end


(* Property from Case-Analysis for Rippling and Inductive Proof,
   Moa Johansson, Lucas Dixon and Alan Bundy, ITP 2010.
   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.*)
  theory TIP_prop_53
  imports "../../Test_Base"
begin

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

datatype Nat = Z | S "Nat"

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

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

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

fun insort :: "Nat => Nat list => Nat list" where
  "insort y (nil2) = cons2 y (nil2)"
| "insort y (cons2 z2 xs) =
     (if t2 y z2 then cons2 y (cons2 z2 xs) else cons2 z2 (insort y xs))"

fun sort :: "Nat list => Nat list" where
  "sort (nil2) = nil2"
| "sort (cons2 z xs) = insort z (sort xs)"

theorem property0 :
  "((count n xs) = (count n (sort xs)))"
  oops

end


theory Height
  imports "Lambda"
begin

text {*
  A small problem suggested by D. Wang. It shows how
  the height of a lambda-terms behaves under substitution.
*}

lemma height_ge_one:
  shows "1 \<le> (height e)"
by (induct e rule: lam.induct)
   (simp_all)

theorem height_subst:
  shows "height (e[x::=e']) \<le> height e - 1 + height e'"
proof (nominal_induct e avoiding: x e' rule: lam.strong_induct)
  case (Var y)
  have "1 \<le> height e'" using height_ge_one by simp
  then show "height (Var y[x::=e']) \<le> height (Var y) - 1 + height e'" by simp
next
  case (Lam y e1)
  have ih: "height (e1[x::=e']) \<le> height e1 - 1 + height e'" by fact
  moreover
  have vc: "atom y \<sharp> x" "atom y \<sharp> e'" by fact+ (* usual variable convention *)
  ultimately show "height ((Lam [y].e1)[x::=e']) \<le> height (Lam [y].e1) - 1 + height e'" by simp
next
  case (App e1 e2)
  have ih1: "height (e1[x::=e']) \<le> (height e1) - 1 + height e'"
  and  ih2: "height (e2[x::=e']) \<le> (height e2) - 1 + height e'" by fact+
  then show "height ((App e1 e2)[x::=e']) \<le> height (App e1 e2) - 1 + height e'" by simp
qed

end


(*  Title:      HOL/Word/Misc_Auxiliary.thy
    Author:     Jeremy Dawson, NICTA
*)

section \<open>Generic auxiliary\<close>

theory Misc_Auxiliary
  imports Main
begin

subsection \<open>Arithmetic lemmas\<close>

lemma int_mod_lem: "0 < n \<Longrightarrow> 0 \<le> b \<and> b < n \<longleftrightarrow> b mod n = b"
  for b n :: int
  apply safe
    apply (erule (1) mod_pos_pos_trivial)
   apply (erule_tac [!] subst)
   apply auto
  done

lemma int_mod_ge: "a < n \<Longrightarrow> 0 < n \<Longrightarrow> a \<le> a mod n"
  for a n :: int
  by (metis dual_order.trans le_cases mod_pos_pos_trivial pos_mod_conj)

lemma int_mod_ge': "b < 0 \<Longrightarrow> 0 < n \<Longrightarrow> b + n \<le> b mod n"
  for b n :: int
  by (metis add_less_same_cancel2 int_mod_ge mod_add_self2)

lemma int_mod_le': "0 \<le> b - n \<Longrightarrow> b mod n \<le> b - n"
  for b n :: int
  by (metis minus_mod_self2 zmod_le_nonneg_dividend)

lemma emep1: "even n \<Longrightarrow> even d \<Longrightarrow> 0 \<le> d \<Longrightarrow> (n + 1) mod d = (n mod d) + 1"
  for n d :: int
  by (auto simp add: pos_zmod_mult_2 add.commute dvd_def)

lemma m1mod2k: "- 1 mod 2 ^ n = (2 ^ n - 1 :: int)"
  by (rule zmod_minus1) simp

lemma sub_inc_One: "Num.sub (Num.inc n) num.One = numeral n"
  by (metis add_diff_cancel add_neg_numeral_special(3) add_uminus_conv_diff numeral_inc)

lemma inc_BitM: "Num.inc (Num.BitM n) = num.Bit0 n"
  by (simp add: BitM_plus_one[symmetric] add_One)

subsection \<open>Lemmas on list operations\<close>

lemma butlast_power: "(butlast ^^ n) bl = take (length bl - n) bl"
  by (induct n) (auto simp: butlast_take)

lemma nth_rev: "n < length xs \<Longrightarrow> rev xs ! n = xs ! (length xs - 1 - n)"
  using rev_nth by simp

lemma nth_rev_alt: "n < length ys \<Longrightarrow> ys ! n = rev ys ! (length ys - Suc n)"
  by (simp add: nth_rev)

lemma hd_butlast: "length xs > 1 \<Longrightarrow> hd (butlast xs) = hd xs"
  by (cases xs) auto

subsection \<open>Implicit augmentation of list prefixes\<close>

primrec takefill :: "'a \<Rightarrow> nat \<Rightarrow> 'a list \<Rightarrow> 'a list"
where
    Z: "takefill fill 0 xs = []"
  | Suc: "takefill fill (Suc n) xs =
      (case xs of
        [] \<Rightarrow> fill # takefill fill n xs
      | y # ys \<Rightarrow> y # takefill fill n ys)"

lemma nth_takefill: "m < n \<Longrightarrow> takefill fill n l ! m = (if m < length l then l ! m else fill)"
  apply (induct n arbitrary: m l)
   apply clarsimp
  apply clarsimp
  apply (case_tac m)
   apply (simp split: list.split)
  apply (simp split: list.split)
  done

lemma takefill_alt: "takefill fill n l = take n l @ replicate (n - length l) fill"
  by (induct n arbitrary: l) (auto split: list.split)

lemma takefill_replicate [simp]: "takefill fill n (replicate m fill) = replicate n fill"
  by (simp add: takefill_alt replicate_add [symmetric])

lemma takefill_le': "n = m + k \<Longrightarrow> takefill x m (takefill x n l) = takefill x m l"
  by (induct m arbitrary: l n) (auto split: list.split)

lemma length_takefill [simp]: "length (takefill fill n l) = n"
  by (simp add: takefill_alt)

lemma take_takefill': "n = k + m \<Longrightarrow> take k (takefill fill n w) = takefill fill k w"
  by (induct k arbitrary: w n) (auto split: list.split)

lemma drop_takefill: "drop k (takefill fill (m + k) w) = takefill fill m (drop k w)"
  by (induct k arbitrary: w) (auto split: list.split)

lemma takefill_le [simp]: "m \<le> n \<Longrightarrow> takefill x m (takefill x n l) = takefill x m l"
  by (auto simp: le_iff_add takefill_le')

lemma take_takefill [simp]: "m \<le> n \<Longrightarrow> take m (takefill fill n w) = takefill fill m w"
  by (auto simp: le_iff_add take_takefill')

lemma takefill_append: "takefill fill (m + length xs) (xs @ w) = xs @ (takefill fill m w)"
  by (induct xs) auto

lemma takefill_same': "l = length xs \<Longrightarrow> takefill fill l xs = xs"
  by (induct xs arbitrary: l) auto

lemmas takefill_same [simp] = takefill_same' [OF refl]

lemma tf_rev:
  "n + k = m + length bl \<Longrightarrow> takefill x m (rev (takefill y n bl)) =
    rev (takefill y m (rev (takefill x k (rev bl))))"
  apply (rule nth_equalityI)
   apply (auto simp add: nth_takefill nth_rev)
  apply (rule_tac f = "\<lambda>n. bl ! n" in arg_cong)
  apply arith
  done

lemma takefill_minus: "0 < n \<Longrightarrow> takefill fill (Suc (n - 1)) w = takefill fill n w"
  by auto

lemmas takefill_Suc_cases =
  list.cases [THEN takefill.Suc [THEN trans]]

lemmas takefill_Suc_Nil = takefill_Suc_cases (1)
lemmas takefill_Suc_Cons = takefill_Suc_cases (2)

lemmas takefill_minus_simps = takefill_Suc_cases [THEN [2]
  takefill_minus [symmetric, THEN trans]]

lemma takefill_numeral_Nil [simp]:
  "takefill fill (numeral k) [] = fill # takefill fill (pred_numeral k) []"
  by (simp add: numeral_eq_Suc)

lemma takefill_numeral_Cons [simp]:
  "takefill fill (numeral k) (x # xs) = x # takefill fill (pred_numeral k) xs"
  by (simp add: numeral_eq_Suc)

subsection \<open>Auxiliary: Range projection\<close>

definition bl_of_nth :: "nat \<Rightarrow> (nat \<Rightarrow> 'a) \<Rightarrow> 'a list"
  where "bl_of_nth n f = map f (rev [0..<n])"

lemma bl_of_nth_simps [simp, code]:
  "bl_of_nth 0 f = []"
  "bl_of_nth (Suc n) f = f n # bl_of_nth n f"
  by (simp_all add: bl_of_nth_def)

lemma length_bl_of_nth [simp]: "length (bl_of_nth n f) = n"
  by (simp add: bl_of_nth_def)

lemma nth_bl_of_nth [simp]: "m < n \<Longrightarrow> rev (bl_of_nth n f) ! m = f m"
  by (simp add: bl_of_nth_def rev_map)

lemma bl_of_nth_inj: "(\<And>k. k < n \<Longrightarrow> f k = g k) \<Longrightarrow> bl_of_nth n f = bl_of_nth n g"
  by (simp add: bl_of_nth_def)

lemma bl_of_nth_nth_le: "n \<le> length xs \<Longrightarrow> bl_of_nth n (nth (rev xs)) = drop (length xs - n) xs"
  apply (induct n arbitrary: xs)
   apply clarsimp
  apply clarsimp
  apply (rule trans [OF _ hd_Cons_tl])
   apply (frule Suc_le_lessD)
   apply (simp add: nth_rev trans [OF drop_Suc drop_tl, symmetric])
   apply (subst hd_drop_conv_nth)
    apply force
   apply simp_all
  apply (rule_tac f = "\<lambda>n. drop n xs" in arg_cong)
  apply simp
  done

lemma bl_of_nth_nth [simp]: "bl_of_nth (length xs) ((!) (rev xs)) = xs"
  by (simp add: bl_of_nth_nth_le)

end


(* Property from Case-Analysis for Rippling and Inductive Proof,
   Moa Johansson, Lucas Dixon and Alan Bundy, ITP 2010.
   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.
   Some proofs were added by Yutaka Nagashima.*)
theory TIP_prop_27
  imports "../../Test_Base"
begin

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

datatype Nat = Z | S "Nat"

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

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

fun elem :: "Nat => Nat list => bool" where
  "elem z (nil2) = False"
| "elem z (cons2 z2 xs) = (if x z z2 then True else elem z xs)"

theorem property0 :
  "((elem z ys) ==> (elem z (y xs ys)))"(*This problem is very similar to TIP_prop_26.thy*)
  find_proof DInd
  apply (induct arbitrary: ys rule: TIP_prop_27.elem.induct)
   apply auto
  done

end


header{* Simplification Lemmas for Lattices *}

(*
    Author: Viorel Preoteasa
*)

theory Lattice_Prop
imports Main
begin

text{*
This theory introduces some simplification lemmas
for semilattices and lattices
*}

notation
   inf (infixl "\<sqinter>" 70) and
   sup (infixl "\<squnion>" 65)

context semilattice_inf begin

lemma [simp]: "x \<sqinter> y \<sqinter> z \<le> y"
  by (rule_tac y = "x \<sqinter> y" in order_trans, rule inf_le1, simp)

lemma [simp]: "x \<sqinter> (y \<sqinter> z) \<le> y"
  by (rule_tac y = "y \<sqinter> z" in order_trans, rule inf_le2, simp)

lemma [simp]: "x \<sqinter> (y \<sqinter> z) \<le> z"
  by (rule_tac y = "y \<sqinter> z" in order_trans, rule inf_le2, simp)
end

context semilattice_sup begin

lemma [simp]: "x \<le> x \<squnion> y \<squnion> z"
  by (rule_tac y = "x \<squnion> y" in order_trans, simp_all)

lemma [simp]: "y \<le> x \<squnion> y \<squnion> z"
  by (rule_tac y = "x \<squnion> y" in order_trans, simp_all)

lemma [simp]: "y \<le> x \<squnion> (y \<squnion> z)"
  by (rule_tac y = "y \<squnion> z" in order_trans, simp_all)

lemma [simp]: "z \<le> x \<squnion> (y \<squnion> z)"
  by (rule_tac y = "y \<squnion> z" in order_trans, simp_all)
end

context lattice begin

lemma [simp]: "x \<sqinter> y \<le> x \<squnion> z"
  by (rule_tac y = x in order_trans, simp_all)

lemma [simp]: "y \<sqinter> x \<le> x \<squnion> z"
  by (rule_tac y = x in order_trans, simp_all)

lemma [simp]: "x \<sqinter> y \<le> z \<squnion> x"
  by (rule_tac y = x in order_trans, simp_all)

lemma [simp]: "y \<sqinter> x \<le> z \<squnion> x"
  by (rule_tac y = x in order_trans, simp_all)

end

end


theory Exercises
imports Main
begin

(* we are given these definitions *)

datatype 'a list = Nil | Cons 'a "'a list"

fun app :: "'a list => 'a list => 'a list" where
"app Nil ys = ys" |
"app (Cons x xs) ys = Cons x (app xs ys)"

fun rev :: "'a list => 'a list" where
"rev Nil = Nil" |
"rev (Cons x xs) = app (rev xs) (Cons x Nil)"

value "rev(Cons True (Cons False Nil))"

(* exercise 2.1 - expression evaluation *)

value "1 + (2::nat)"

value "1 + (2::int)"

value "1 - (2::nat)" (* evaluates as 0 *)

value "1 - (2::int)"

(* exercise 2.2 - associativity of add *)

fun add :: "nat \<Rightarrow> nat \<Rightarrow> nat" where
"add 0 n = n" |
"add (Suc m) n = Suc(add m n)"

lemma add_assoc [simp]: "add (add xs ys) zs = add xs (add ys zs)"
  apply(induction xs)
  apply (auto)
  done

lemma add_ys_0 [simp]: "add ys 0 = ys"
  apply(induction ys)
   apply auto
  done

lemma suc_add [simp]: "Suc (add ys xs) = add ys (Suc xs)"
  apply(induction ys)
  apply(auto)
  done

lemma add_comm [simp]: "add xs ys = add ys xs"
  apply(induction xs)
  apply (auto)
  done

end


section \<open> Sequence Toolkit \<close>

theory Sequence_Toolkit
  imports Number_Toolkit
begin

subsection \<open> Conversion \<close>

text \<open> We define a number of coercions for mapping a list to finite function. \<close>

abbreviation rel_of_list :: "'a list \<Rightarrow> nat \<leftrightarrow> 'a" ("[_]\<^sub>s") where
"rel_of_list xs \<equiv> [list_pfun xs]\<^sub>\<Zpfun>"

abbreviation seq_nth ("_'(_')\<^sub>s" [999,0] 999) where
"seq_nth xs i \<equiv> xs ! (i - 1)"

declare [[coercion list_ffun]]
declare [[coercion list_pfun]]
declare [[coercion rel_of_list]]
declare [[coercion seq_nth]]

subsection \<open> Number range\<close>

lemma number_range: "{i..j} = {k :: \<int>. i \<le> k \<and> k \<le> j}"
  by (auto)

text \<open> The number range from $i$ to $j$ is the set of all integers greater than or equal to $i$,
  which are also less than or equal to $j$.\<close>

subsection \<open> Iteration \<close>

definition iter :: "\<int> \<Rightarrow> ('X \<leftrightarrow> 'X) \<Rightarrow> ('X \<leftrightarrow> 'X)" where
"iter n R = (if (n \<ge> 0) then R ^^ (nat n) else (R\<^sup>\<sim>) ^^ (nat n))"

lemma iter_eqs:
  "iter 0 r = Id"
  "n \<ge> 0 \<Longrightarrow> iter (n + 1) r = r \<^bold>; (iter n r)"
  "n < 0 \<Longrightarrow> iter (n + 1) r = iter n (r\<^sup>\<sim>)"
  by (simp_all add: iter_def, metis Suc_nat_eq_nat_zadd1 add.commute relpow.simps(2) relpow_commute)

subsection \<open> Number of members of a set \<close>

lemma size_rel_of_list:
  "#xs = length xs"
  by simp

subsection \<open> Minimum \<close>

text \<open> Implemented by the function @{const Min}. \<close>

subsection \<open> Maximum \<close>

text \<open> Implemented by the function @{const Max}. \<close>

subsection \<open> Finite sequences \<close>

definition "seq A = lists A"

lemma seq_iff [simp]: "xs \<in> seq A \<longleftrightarrow> set xs \<subseteq> A"
  by (simp add: in_lists_conv_set seq_def subset_code(1))

lemma seq_ffun_set: "range list_ffun = {f :: \<nat> \<Zffun> 'X. dom(f) = {1..#f}}"
  by (simp add: range_list_ffun, force)

subsection \<open> Non-empty finite sequences \<close>

definition "seq\<^sub>1 A = seq A - {[]}"

lemma seq\<^sub>1_iff [simp]: "xs \<in> seq\<^sub>1(A) \<longleftrightarrow> (xs \<in> seq A \<and> #xs > 0)"
  by (simp add: seq\<^sub>1_def)

subsection \<open> Injective sequences \<close>

definition "iseq A = seq A \<inter> Collect distinct"

lemma iseq_iff [simp]: "xs \<in> iseq(A) \<longleftrightarrow> (xs \<in> seq A \<and> distinct xs)"
  by (simp add: iseq_def)

subsection \<open> Bounded sequences \<close>

definition bseq :: "\<nat> \<Rightarrow> 'a set \<Rightarrow> 'a list set" ("bseq[_]") where
"bseq n A = blists n A"

(* Proof that this corresponds to the Z definition required *)

subsection \<open> Sequence brackets \<close>

text \<open> Provided by the HOL list notation @{term "[x, y, z]"}. \<close>

subsection \<open> Concatenation \<close>

text \<open> Provided by the HOL concatenation operator @{term "(@)"}. \<close>

subsection \<open> Reverse \<close>

text \<open> Provided by the HOL function @{const rev}. \<close>

subsection \<open> Head of a sequence \<close>

definition head :: "'a list \<Zpfun> 'a" where
"head = (\<lambda> xs :: 'a list | #xs > 0 \<bullet> hd xs)"

lemma dom_head: "dom head = {xs. #xs > 0}"
  by (simp add: head_def)

lemma head_app: "#xs > 0 \<Longrightarrow> head xs = hd xs"
  by (simp add: head_def)

lemma head_z_def: "xs \<in> seq\<^sub>1(A) \<Longrightarrow> head xs = xs 1"
  by (simp add: hd_conv_nth head_app seq\<^sub>1_def)

subsection \<open> Last of a sequence \<close>

hide_const (open) last

definition last :: "'a list \<Zpfun> 'a" where
"last = (\<lambda> xs :: 'a list | #xs > 0 \<bullet> List.last xs)"

lemma dom_last: "dom last = {xs. #xs > 0}"
  by (simp add: last_def)

lemma last_app: "#xs > 0 \<Longrightarrow> last xs = List.last xs"
  by (simp add: last_def)

lemma last_eq: "#s > 0 \<Longrightarrow> last s = s (#s)"
  by (simp add: last_app last_conv_nth)

subsection \<open> Tail of a sequence \<close>

definition tail :: "'a list \<Zpfun> 'a list" where
"tail = (\<lambda> xs :: 'a list | #xs > 0 \<bullet> tl xs)"

lemma dom_tail: "dom tail = {xs. #xs > 0}"
  by (simp add: tail_def)

lemma tail_app: "#xs > 0 \<Longrightarrow> tail xs = tl xs"
  by (simp add: tail_def)

subsection \<open> Domain \<close>

definition dom_seq :: "'a list \<Rightarrow> \<nat> set" where
[simp]: "dom_seq xs = {0..<#xs}"

adhoc_overloading dom dom_seq

subsection \<open> Range \<close>

definition ran_seq :: "'a list \<Rightarrow> 'a set" where
[simp]: "ran_seq xs = set xs"

adhoc_overloading ran ran_seq

subsection \<open> Filter \<close>

notation seq_filter (infix "\<restriction>" 80)

lemma seq_filter_Nil: "[] \<restriction> V = []" by simp

lemma seq_filter_append: "(s @ t) \<restriction> V = (s \<restriction> V) @ (t \<restriction> V)"
  by (simp add: seq_filter_append)

lemma seq_filter_subset_iff: "ran s \<subseteq> V \<longleftrightarrow> (s \<restriction> V = s)"
  by (auto simp add: seq_filter_def subsetD, meson filter_id_conv)

lemma seq_filter_empty: "s \<restriction> {} = []" by simp

lemma seq_filter_size: "#(s \<restriction> V) \<le> #s"
  by (simp add: seq_filter_def)

lemma seq_filter_twice: "(s \<restriction> V) \<restriction> W = s \<restriction> (V \<inter> W)" by simp

subsection \<open> Examples \<close>

lemma "([1,2,3] \<^bold>; (\<lambda> x \<bullet> x + 1)) 1 = 2"
  by (simp add: pfun_graph_comp[THEN sym] list_pfun_def pcomp_pabs)

end