# Theory Multiset

Up to index of Isabelle/HOL/Binomial-Heaps

theory Multiset
imports DAList
`(*  Title:      HOL/Library/Multiset.thy    Author:     Tobias Nipkow, Markus Wenzel, Lawrence C Paulson, Norbert Voelker*)header {* (Finite) multisets *}theory Multisetimports Main DAList (* FIXME too specific dependency for a generic theory *)beginsubsection {* The type of multisets *}definition "multiset = {f :: 'a => nat. finite {x. f x > 0}}"typedef 'a multiset = "multiset :: ('a => nat) set"  morphisms count Abs_multiset  unfolding multiset_defproof  show "(λx. 0::nat) ∈ {f. finite {x. f x > 0}}" by simpqedsetup_lifting type_definition_multisetabbreviation Melem :: "'a => 'a multiset => bool"  ("(_/ :# _)" [50, 51] 50) where  "a :# M == 0 < count M a"notation (xsymbols)  Melem (infix "∈#" 50)lemma multiset_eq_iff:  "M = N <-> (∀a. count M a = count N a)"  by (simp only: count_inject [symmetric] fun_eq_iff)lemma multiset_eqI:  "(!!x. count A x = count B x) ==> A = B"  using multiset_eq_iff by autotext {* \medskip Preservation of the representing set @{term multiset}.*}lemma const0_in_multiset:  "(λa. 0) ∈ multiset"  by (simp add: multiset_def)lemma only1_in_multiset:  "(λb. if b = a then n else 0) ∈ multiset"  by (simp add: multiset_def)lemma union_preserves_multiset:  "M ∈ multiset ==> N ∈ multiset ==> (λa. M a + N a) ∈ multiset"  by (simp add: multiset_def)lemma diff_preserves_multiset:  assumes "M ∈ multiset"  shows "(λa. M a - N a) ∈ multiset"proof -  have "{x. N x < M x} ⊆ {x. 0 < M x}"    by auto  with assms show ?thesis    by (auto simp add: multiset_def intro: finite_subset)qedlemma filter_preserves_multiset:  assumes "M ∈ multiset"  shows "(λx. if P x then M x else 0) ∈ multiset"proof -  have "{x. (P x --> 0 < M x) ∧ P x} ⊆ {x. 0 < M x}"    by auto  with assms show ?thesis    by (auto simp add: multiset_def intro: finite_subset)qedlemmas in_multiset = const0_in_multiset only1_in_multiset  union_preserves_multiset diff_preserves_multiset filter_preserves_multisetsubsection {* Representing multisets *}text {* Multiset enumeration *}instantiation multiset :: (type) cancel_comm_monoid_addbeginlift_definition zero_multiset :: "'a multiset" is "λa. 0"by (rule const0_in_multiset)abbreviation Mempty :: "'a multiset" ("{#}") where  "Mempty ≡ 0"lift_definition plus_multiset :: "'a multiset => 'a multiset => 'a multiset" is "λM N. (λa. M a + N a)"by (rule union_preserves_multiset)instanceby default (transfer, simp add: fun_eq_iff)+endlift_definition single :: "'a => 'a multiset" is "λa b. if b = a then 1 else 0"by (rule only1_in_multiset)syntax  "_multiset" :: "args => 'a multiset"    ("{#(_)#}")translations  "{#x, xs#}" == "{#x#} + {#xs#}"  "{#x#}" == "CONST single x"lemma count_empty [simp]: "count {#} a = 0"  by (simp add: zero_multiset.rep_eq)lemma count_single [simp]: "count {#b#} a = (if b = a then 1 else 0)"  by (simp add: single.rep_eq)subsection {* Basic operations *}subsubsection {* Union *}lemma count_union [simp]: "count (M + N) a = count M a + count N a"  by (simp add: plus_multiset.rep_eq)subsubsection {* Difference *}instantiation multiset :: (type) comm_monoid_diffbeginlift_definition minus_multiset :: "'a multiset => 'a multiset => 'a multiset" is "λ M N. λa. M a - N a"by (rule diff_preserves_multiset) instanceby default (transfer, simp add: fun_eq_iff)+endlemma count_diff [simp]: "count (M - N) a = count M a - count N a"  by (simp add: minus_multiset.rep_eq)lemma diff_empty [simp]: "M - {#} = M ∧ {#} - M = {#}"by(simp add: multiset_eq_iff)lemma diff_cancel[simp]: "A - A = {#}"by (rule multiset_eqI) simplemma diff_union_cancelR [simp]: "M + N - N = (M::'a multiset)"by(simp add: multiset_eq_iff)lemma diff_union_cancelL [simp]: "N + M - N = (M::'a multiset)"by(simp add: multiset_eq_iff)lemma insert_DiffM:  "x ∈# M ==> {#x#} + (M - {#x#}) = M"  by (clarsimp simp: multiset_eq_iff)lemma insert_DiffM2 [simp]:  "x ∈# M ==> M - {#x#} + {#x#} = M"  by (clarsimp simp: multiset_eq_iff)lemma diff_right_commute:  "(M::'a multiset) - N - Q = M - Q - N"  by (auto simp add: multiset_eq_iff)lemma diff_add:  "(M::'a multiset) - (N + Q) = M - N - Q"by (simp add: multiset_eq_iff)lemma diff_union_swap:  "a ≠ b ==> M - {#a#} + {#b#} = M + {#b#} - {#a#}"  by (auto simp add: multiset_eq_iff)lemma diff_union_single_conv:  "a ∈# J ==> I + J - {#a#} = I + (J - {#a#})"  by (simp add: multiset_eq_iff)subsubsection {* Equality of multisets *}lemma single_not_empty [simp]: "{#a#} ≠ {#} ∧ {#} ≠ {#a#}"  by (simp add: multiset_eq_iff)lemma single_eq_single [simp]: "{#a#} = {#b#} <-> a = b"  by (auto simp add: multiset_eq_iff)lemma union_eq_empty [iff]: "M + N = {#} <-> M = {#} ∧ N = {#}"  by (auto simp add: multiset_eq_iff)lemma empty_eq_union [iff]: "{#} = M + N <-> M = {#} ∧ N = {#}"  by (auto simp add: multiset_eq_iff)lemma multi_self_add_other_not_self [simp]: "M = M + {#x#} <-> False"  by (auto simp add: multiset_eq_iff)lemma diff_single_trivial:  "¬ x ∈# M ==> M - {#x#} = M"  by (auto simp add: multiset_eq_iff)lemma diff_single_eq_union:  "x ∈# M ==> M - {#x#} = N <-> M = N + {#x#}"  by autolemma union_single_eq_diff:  "M + {#x#} = N ==> M = N - {#x#}"  by (auto dest: sym)lemma union_single_eq_member:  "M + {#x#} = N ==> x ∈# N"  by autolemma union_is_single:  "M + N = {#a#} <-> M = {#a#} ∧ N={#} ∨ M = {#} ∧ N = {#a#}" (is "?lhs = ?rhs")proof  assume ?rhs then show ?lhs by autonext  assume ?lhs then show ?rhs    by (simp add: multiset_eq_iff split:if_splits) (metis add_is_1)qedlemma single_is_union:  "{#a#} = M + N <-> {#a#} = M ∧ N = {#} ∨ M = {#} ∧ {#a#} = N"  by (auto simp add: eq_commute [of "{#a#}" "M + N"] union_is_single)lemma add_eq_conv_diff:  "M + {#a#} = N + {#b#} <-> M = N ∧ a = b ∨ M = N - {#a#} + {#b#} ∧ N = M - {#b#} + {#a#}"  (is "?lhs = ?rhs")(* shorter: by (simp add: multiset_eq_iff) fastforce *)proof  assume ?rhs then show ?lhs  by (auto simp add: add_assoc add_commute [of "{#b#}"])    (drule sym, simp add: add_assoc [symmetric])next  assume ?lhs  show ?rhs  proof (cases "a = b")    case True with `?lhs` show ?thesis by simp  next    case False    from `?lhs` have "a ∈# N + {#b#}" by (rule union_single_eq_member)    with False have "a ∈# N" by auto    moreover from `?lhs` have "M = N + {#b#} - {#a#}" by (rule union_single_eq_diff)    moreover note False    ultimately show ?thesis by (auto simp add: diff_right_commute [of _ "{#a#}"] diff_union_swap)  qedqedlemma insert_noteq_member:   assumes BC: "B + {#b#} = C + {#c#}"   and bnotc: "b ≠ c"  shows "c ∈# B"proof -  have "c ∈# C + {#c#}" by simp  have nc: "¬ c ∈# {#b#}" using bnotc by simp  then have "c ∈# B + {#b#}" using BC by simp  then show "c ∈# B" using nc by simpqedlemma add_eq_conv_ex:  "(M + {#a#} = N + {#b#}) =    (M = N ∧ a = b ∨ (∃K. M = K + {#b#} ∧ N = K + {#a#}))"  by (auto simp add: add_eq_conv_diff)subsubsection {* Pointwise ordering induced by count *}instantiation multiset :: (type) ordered_ab_semigroup_add_imp_lebeginlift_definition less_eq_multiset :: "'a multiset => 'a multiset => bool" is "λ A B. (∀a. A a ≤ B a)"by simplemmas mset_le_def = less_eq_multiset_defdefinition less_multiset :: "'a multiset => 'a multiset => bool" where  mset_less_def: "(A::'a multiset) < B <-> A ≤ B ∧ A ≠ B"instance  by default (auto simp add: mset_le_def mset_less_def multiset_eq_iff intro: order_trans antisym)endlemma mset_less_eqI:  "(!!x. count A x ≤ count B x) ==> A ≤ B"  by (simp add: mset_le_def)lemma mset_le_exists_conv:  "(A::'a multiset) ≤ B <-> (∃C. B = A + C)"apply (unfold mset_le_def, rule iffI, rule_tac x = "B - A" in exI)apply (auto intro: multiset_eq_iff [THEN iffD2])donelemma mset_le_mono_add_right_cancel [simp]:  "(A::'a multiset) + C ≤ B + C <-> A ≤ B"  by (fact add_le_cancel_right)lemma mset_le_mono_add_left_cancel [simp]:  "C + (A::'a multiset) ≤ C + B <-> A ≤ B"  by (fact add_le_cancel_left)lemma mset_le_mono_add:  "(A::'a multiset) ≤ B ==> C ≤ D ==> A + C ≤ B + D"  by (fact add_mono)lemma mset_le_add_left [simp]:  "(A::'a multiset) ≤ A + B"  unfolding mset_le_def by autolemma mset_le_add_right [simp]:  "B ≤ (A::'a multiset) + B"  unfolding mset_le_def by autolemma mset_le_single:  "a :# B ==> {#a#} ≤ B"  by (simp add: mset_le_def)lemma multiset_diff_union_assoc:  "C ≤ B ==> (A::'a multiset) + B - C = A + (B - C)"  by (simp add: multiset_eq_iff mset_le_def)lemma mset_le_multiset_union_diff_commute:  "B ≤ A ==> (A::'a multiset) - B + C = A + C - B"by (simp add: multiset_eq_iff mset_le_def)lemma diff_le_self[simp]: "(M::'a multiset) - N ≤ M"by(simp add: mset_le_def)lemma mset_lessD: "A < B ==> x ∈# A ==> x ∈# B"apply (clarsimp simp: mset_le_def mset_less_def)apply (erule_tac x=x in allE)apply autodonelemma mset_leD: "A ≤ B ==> x ∈# A ==> x ∈# B"apply (clarsimp simp: mset_le_def mset_less_def)apply (erule_tac x = x in allE)apply autodone  lemma mset_less_insertD: "(A + {#x#} < B) ==> (x ∈# B ∧ A < B)"apply (rule conjI) apply (simp add: mset_lessD)apply (clarsimp simp: mset_le_def mset_less_def)apply safe apply (erule_tac x = a in allE) apply (auto split: split_if_asm)donelemma mset_le_insertD: "(A + {#x#} ≤ B) ==> (x ∈# B ∧ A ≤ B)"apply (rule conjI) apply (simp add: mset_leD)apply (force simp: mset_le_def mset_less_def split: split_if_asm)donelemma mset_less_of_empty[simp]: "A < {#} <-> False"  by (auto simp add: mset_less_def mset_le_def multiset_eq_iff)lemma multi_psub_of_add_self[simp]: "A < A + {#x#}"  by (auto simp: mset_le_def mset_less_def)lemma multi_psub_self[simp]: "(A::'a multiset) < A = False"  by simplemma mset_less_add_bothsides:  "T + {#x#} < S + {#x#} ==> T < S"  by (fact add_less_imp_less_right)lemma mset_less_empty_nonempty:  "{#} < S <-> S ≠ {#}"  by (auto simp: mset_le_def mset_less_def)lemma mset_less_diff_self:  "c ∈# B ==> B - {#c#} < B"  by (auto simp: mset_le_def mset_less_def multiset_eq_iff)subsubsection {* Intersection *}instantiation multiset :: (type) semilattice_infbegindefinition inf_multiset :: "'a multiset => 'a multiset => 'a multiset" where  multiset_inter_def: "inf_multiset A B = A - (A - B)"instanceproof -  have aux: "!!m n q :: nat. m ≤ n ==> m ≤ q ==> m ≤ n - (n - q)" by arith  show "OFCLASS('a multiset, semilattice_inf_class)"    by default (auto simp add: multiset_inter_def mset_le_def aux)qedendabbreviation multiset_inter :: "'a multiset => 'a multiset => 'a multiset" (infixl "#∩" 70) where  "multiset_inter ≡ inf"lemma multiset_inter_count [simp]:  "count (A #∩ B) x = min (count A x) (count B x)"  by (simp add: multiset_inter_def)lemma multiset_inter_single: "a ≠ b ==> {#a#} #∩ {#b#} = {#}"  by (rule multiset_eqI) autolemma multiset_union_diff_commute:  assumes "B #∩ C = {#}"  shows "A + B - C = A - C + B"proof (rule multiset_eqI)  fix x  from assms have "min (count B x) (count C x) = 0"    by (auto simp add: multiset_eq_iff)  then have "count B x = 0 ∨ count C x = 0"    by auto  then show "count (A + B - C) x = count (A - C + B) x"    by autoqedsubsubsection {* Filter (with comprehension syntax) *}text {* Multiset comprehension *}lift_definition filter :: "('a => bool) => 'a multiset => 'a multiset" is "λP M. λx. if P x then M x else 0"by (rule filter_preserves_multiset)hide_const (open) filterlemma count_filter [simp]:  "count (Multiset.filter P M) a = (if P a then count M a else 0)"  by (simp add: filter.rep_eq)lemma filter_empty [simp]:  "Multiset.filter P {#} = {#}"  by (rule multiset_eqI) simplemma filter_single [simp]:  "Multiset.filter P {#x#} = (if P x then {#x#} else {#})"  by (rule multiset_eqI) simplemma filter_union [simp]:  "Multiset.filter P (M + N) = Multiset.filter P M + Multiset.filter P N"  by (rule multiset_eqI) simplemma filter_diff [simp]:  "Multiset.filter P (M - N) = Multiset.filter P M - Multiset.filter P N"  by (rule multiset_eqI) simplemma filter_inter [simp]:  "Multiset.filter P (M #∩ N) = Multiset.filter P M #∩ Multiset.filter P N"  by (rule multiset_eqI) simpsyntax  "_MCollect" :: "pttrn => 'a multiset => bool => 'a multiset"    ("(1{# _ :# _./ _#})")syntax (xsymbol)  "_MCollect" :: "pttrn => 'a multiset => bool => 'a multiset"    ("(1{# _ ∈# _./ _#})")translations  "{#x ∈# M. P#}" == "CONST Multiset.filter (λx. P) M"subsubsection {* Set of elements *}definition set_of :: "'a multiset => 'a set" where  "set_of M = {x. x :# M}"lemma set_of_empty [simp]: "set_of {#} = {}"by (simp add: set_of_def)lemma set_of_single [simp]: "set_of {#b#} = {b}"by (simp add: set_of_def)lemma set_of_union [simp]: "set_of (M + N) = set_of M ∪ set_of N"by (auto simp add: set_of_def)lemma set_of_eq_empty_iff [simp]: "(set_of M = {}) = (M = {#})"by (auto simp add: set_of_def multiset_eq_iff)lemma mem_set_of_iff [simp]: "(x ∈ set_of M) = (x :# M)"by (auto simp add: set_of_def)lemma set_of_filter [simp]: "set_of {# x:#M. P x #} = set_of M ∩ {x. P x}"by (auto simp add: set_of_def)lemma finite_set_of [iff]: "finite (set_of M)"  using count [of M] by (simp add: multiset_def set_of_def)lemma finite_Collect_mem [iff]: "finite {x. x :# M}"  unfolding set_of_def[symmetric] by simpsubsubsection {* Size *}instantiation multiset :: (type) sizebegindefinition size_def:  "size M = setsum (count M) (set_of M)"instance ..endlemma size_empty [simp]: "size {#} = 0"by (simp add: size_def)lemma size_single [simp]: "size {#b#} = 1"by (simp add: size_def)lemma setsum_count_Int:  "finite A ==> setsum (count N) (A ∩ set_of N) = setsum (count N) A"apply (induct rule: finite_induct) apply simpapply (simp add: Int_insert_left set_of_def)donelemma size_union [simp]: "size (M + N::'a multiset) = size M + size N"apply (unfold size_def)apply (subgoal_tac "count (M + N) = (λa. count M a + count N a)") prefer 2 apply (rule ext, simp)apply (simp (no_asm_simp) add: setsum_Un_nat setsum_addf setsum_count_Int)apply (subst Int_commute)apply (simp (no_asm_simp) add: setsum_count_Int)donelemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})"by (auto simp add: size_def multiset_eq_iff)lemma nonempty_has_size: "(S ≠ {#}) = (0 < size S)"by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)lemma size_eq_Suc_imp_elem: "size M = Suc n ==> ∃a. a :# M"apply (unfold size_def)apply (drule setsum_SucD)apply autodonelemma size_eq_Suc_imp_eq_union:  assumes "size M = Suc n"  shows "∃a N. M = N + {#a#}"proof -  from assms obtain a where "a ∈# M"    by (erule size_eq_Suc_imp_elem [THEN exE])  then have "M = M - {#a#} + {#a#}" by simp  then show ?thesis by blastqedsubsection {* Induction and case splits *}theorem multiset_induct [case_names empty add, induct type: multiset]:  assumes empty: "P {#}"  assumes add: "!!M x. P M ==> P (M + {#x#})"  shows "P M"proof (induct n ≡ "size M" arbitrary: M)  case 0 thus "P M" by (simp add: empty)next  case (Suc k)  obtain N x where "M = N + {#x#}"    using `Suc k = size M` [symmetric]    using size_eq_Suc_imp_eq_union by fast  with Suc add show "P M" by simpqedlemma multi_nonempty_split: "M ≠ {#} ==> ∃A a. M = A + {#a#}"by (induct M) autolemma multiset_cases [cases type, case_names empty add]:assumes em:  "M = {#} ==> P"assumes add: "!!N x. M = N + {#x#} ==> P"shows "P"using assms by (induct M) simp_alllemma multi_member_split: "x ∈# M ==> ∃A. M = A + {#x#}"by (rule_tac x="M - {#x#}" in exI, simp)lemma multi_drop_mem_not_eq: "c ∈# B ==> B - {#c#} ≠ B"by (cases "B = {#}") (auto dest: multi_member_split)lemma multiset_partition: "M = {# x:#M. P x #} + {# x:#M. ¬ P x #}"apply (subst multiset_eq_iff)apply autodonelemma mset_less_size: "(A::'a multiset) < B ==> size A < size B"proof (induct A arbitrary: B)  case (empty M)  then have "M ≠ {#}" by (simp add: mset_less_empty_nonempty)  then obtain M' x where "M = M' + {#x#}"     by (blast dest: multi_nonempty_split)  then show ?case by simpnext  case (add S x T)  have IH: "!!B. S < B ==> size S < size B" by fact  have SxsubT: "S + {#x#} < T" by fact  then have "x ∈# T" and "S < T" by (auto dest: mset_less_insertD)  then obtain T' where T: "T = T' + {#x#}"     by (blast dest: multi_member_split)  then have "S < T'" using SxsubT     by (blast intro: mset_less_add_bothsides)  then have "size S < size T'" using IH by simp  then show ?case using T by simpqedsubsubsection {* Strong induction and subset induction for multisets *}text {* Well-foundedness of proper subset operator: *}text {* proper multiset subset *}definition  mset_less_rel :: "('a multiset * 'a multiset) set" where  "mset_less_rel = {(A,B). A < B}"lemma multiset_add_sub_el_shuffle:   assumes "c ∈# B" and "b ≠ c"   shows "B - {#c#} + {#b#} = B + {#b#} - {#c#}"proof -  from `c ∈# B` obtain A where B: "B = A + {#c#}"     by (blast dest: multi_member_split)  have "A + {#b#} = A + {#b#} + {#c#} - {#c#}" by simp  then have "A + {#b#} = A + {#c#} + {#b#} - {#c#}"     by (simp add: add_ac)  then show ?thesis using B by simpqedlemma wf_mset_less_rel: "wf mset_less_rel"apply (unfold mset_less_rel_def)apply (rule wf_measure [THEN wf_subset, where f1=size])apply (clarsimp simp: measure_def inv_image_def mset_less_size)donetext {* The induction rules: *}lemma full_multiset_induct [case_names less]:assumes ih: "!!B. ∀(A::'a multiset). A < B --> P A ==> P B"shows "P B"apply (rule wf_mset_less_rel [THEN wf_induct])apply (rule ih, auto simp: mset_less_rel_def)donelemma multi_subset_induct [consumes 2, case_names empty add]:assumes "F ≤ A"  and empty: "P {#}"  and insert: "!!a F. a ∈# A ==> P F ==> P (F + {#a#})"shows "P F"proof -  from `F ≤ A`  show ?thesis  proof (induct F)    show "P {#}" by fact  next    fix x F    assume P: "F ≤ A ==> P F" and i: "F + {#x#} ≤ A"    show "P (F + {#x#})"    proof (rule insert)      from i show "x ∈# A" by (auto dest: mset_le_insertD)      from i have "F ≤ A" by (auto dest: mset_le_insertD)      with P show "P F" .    qed  qedqedsubsection {* The fold combinator *}definition fold :: "('a => 'b => 'b) => 'b => 'a multiset => 'b"where  "fold f s M = Finite_Set.fold (λx. f x ^^ count M x) s (set_of M)"lemma fold_mset_empty [simp]:  "fold f s {#} = s"  by (simp add: fold_def)context comp_fun_commutebeginlemma fold_mset_insert:  "fold f s (M + {#x#}) = f x (fold f s M)"proof -  interpret mset: comp_fun_commute "λy. f y ^^ count M y"    by (fact comp_fun_commute_funpow)  interpret mset_union: comp_fun_commute "λy. f y ^^ count (M + {#x#}) y"    by (fact comp_fun_commute_funpow)  show ?thesis  proof (cases "x ∈ set_of M")    case False    then have *: "count (M + {#x#}) x = 1" by simp    from False have "Finite_Set.fold (λy. f y ^^ count (M + {#x#}) y) s (set_of M) =      Finite_Set.fold (λy. f y ^^ count M y) s (set_of M)"      by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)    with False * show ?thesis      by (simp add: fold_def del: count_union)  next    case True    def N ≡ "set_of M - {x}"    from N_def True have *: "set_of M = insert x N" "x ∉ N" "finite N" by auto    then have "Finite_Set.fold (λy. f y ^^ count (M + {#x#}) y) s N =      Finite_Set.fold (λy. f y ^^ count M y) s N"      by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)    with * show ?thesis by (simp add: fold_def del: count_union) simp  qedqedcorollary fold_mset_single [simp]:  "fold f s {#x#} = f x s"proof -  have "fold f s ({#} + {#x#}) = f x s" by (simp only: fold_mset_insert) simp  then show ?thesis by simpqedlemma fold_mset_fun_comm:  "f x (fold f s M) = fold f (f x s) M"  by (induct M) (simp_all add: fold_mset_insert fun_left_comm)lemma fold_mset_union [simp]:  "fold f s (M + N) = fold f (fold f s M) N"proof (induct M)  case empty then show ?case by simpnext  case (add M x)  have "M + {#x#} + N = (M + N) + {#x#}"    by (simp add: add_ac)  with add show ?case by (simp add: fold_mset_insert fold_mset_fun_comm)qedlemma fold_mset_fusion:  assumes "comp_fun_commute g"  shows "(!!x y. h (g x y) = f x (h y)) ==> h (fold g w A) = fold f (h w) A" (is "PROP ?P")proof -  interpret comp_fun_commute g by (fact assms)  show "PROP ?P" by (induct A) autoqedendtext {*  A note on code generation: When defining some function containing a  subterm @{term "fold F"}, code generation is not automatic. When  interpreting locale @{text left_commutative} with @{text F}, the  would be code thms for @{const fold} become thms like  @{term "fold F z {#} = z"} where @{text F} is not a pattern but  contains defined symbols, i.e.\ is not a code thm. Hence a separate  constant with its own code thms needs to be introduced for @{text  F}. See the image operator below.*}subsection {* Image *}definition image_mset :: "('a => 'b) => 'a multiset => 'b multiset" where  "image_mset f = fold (plus o single o f) {#}"lemma comp_fun_commute_mset_image:  "comp_fun_commute (plus o single o f)"proofqed (simp add: add_ac fun_eq_iff)lemma image_mset_empty [simp]: "image_mset f {#} = {#}"  by (simp add: image_mset_def)lemma image_mset_single [simp]: "image_mset f {#x#} = {#f x#}"proof -  interpret comp_fun_commute "plus o single o f"    by (fact comp_fun_commute_mset_image)  show ?thesis by (simp add: image_mset_def)qedlemma image_mset_union [simp]:  "image_mset f (M + N) = image_mset f M + image_mset f N"proof -  interpret comp_fun_commute "plus o single o f"    by (fact comp_fun_commute_mset_image)  show ?thesis by (induct N) (simp_all add: image_mset_def add_ac)qedcorollary image_mset_insert:  "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"  by simplemma set_of_image_mset [simp]:  "set_of (image_mset f M) = image f (set_of M)"  by (induct M) simp_alllemma size_image_mset [simp]:  "size (image_mset f M) = size M"  by (induct M) simp_alllemma image_mset_is_empty_iff [simp]:  "image_mset f M = {#} <-> M = {#}"  by (cases M) autosyntax  "_comprehension1_mset" :: "'a => 'b => 'b multiset => 'a multiset"      ("({#_/. _ :# _#})")translations  "{#e. x:#M#}" == "CONST image_mset (%x. e) M"syntax  "_comprehension2_mset" :: "'a => 'b => 'b multiset => bool => 'a multiset"      ("({#_/ | _ :# _./ _#})")translations  "{#e | x:#M. P#}" => "{#e. x :# {# x:#M. P#}#}"text {*  This allows to write not just filters like @{term "{#x:#M. x<c#}"}  but also images like @{term "{#x+x. x:#M #}"} and @{term [source]  "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as  @{term "{#x+x|x:#M. x<c#}"}.*}enriched_type image_mset: image_msetproof -  fix f g show "image_mset f o image_mset g = image_mset (f o g)"  proof    fix A    show "(image_mset f o image_mset g) A = image_mset (f o g) A"      by (induct A) simp_all  qed  show "image_mset id = id"  proof    fix A    show "image_mset id A = id A"      by (induct A) simp_all  qedqeddeclare image_mset.identity [simp]subsection {* Alternative representations *}subsubsection {* Lists *}primrec multiset_of :: "'a list => 'a multiset" where  "multiset_of [] = {#}" |  "multiset_of (a # x) = multiset_of x + {# a #}"lemma in_multiset_in_set:  "x ∈# multiset_of xs <-> x ∈ set xs"  by (induct xs) simp_alllemma count_multiset_of:  "count (multiset_of xs) x = length (filter (λy. x = y) xs)"  by (induct xs) simp_alllemma multiset_of_zero_iff[simp]: "(multiset_of x = {#}) = (x = [])"by (induct x) autolemma multiset_of_zero_iff_right[simp]: "({#} = multiset_of x) = (x = [])"by (induct x) autolemma set_of_multiset_of[simp]: "set_of (multiset_of x) = set x"by (induct x) autolemma mem_set_multiset_eq: "x ∈ set xs = (x :# multiset_of xs)"by (induct xs) autolemma size_multiset_of [simp]: "size (multiset_of xs) = length xs"  by (induct xs) simp_alllemma multiset_of_append [simp]:  "multiset_of (xs @ ys) = multiset_of xs + multiset_of ys"  by (induct xs arbitrary: ys) (auto simp: add_ac)lemma multiset_of_filter:  "multiset_of (filter P xs) = {#x :# multiset_of xs. P x #}"  by (induct xs) simp_alllemma multiset_of_rev [simp]:  "multiset_of (rev xs) = multiset_of xs"  by (induct xs) simp_alllemma surj_multiset_of: "surj multiset_of"apply (unfold surj_def)apply (rule allI)apply (rule_tac M = y in multiset_induct) apply autoapply (rule_tac x = "x # xa" in exI)apply autodonelemma set_count_greater_0: "set x = {a. count (multiset_of x) a > 0}"by (induct x) autolemma distinct_count_atmost_1:  "distinct x = (! a. count (multiset_of x) a = (if a ∈ set x then 1 else 0))"apply (induct x, simp, rule iffI, simp_all)apply (rule conjI)apply (simp_all add: set_of_multiset_of [THEN sym] del: set_of_multiset_of)apply (erule_tac x = a in allE, simp, clarify)apply (erule_tac x = aa in allE, simp)donelemma multiset_of_eq_setD:  "multiset_of xs = multiset_of ys ==> set xs = set ys"by (rule) (auto simp add:multiset_eq_iff set_count_greater_0)lemma set_eq_iff_multiset_of_eq_distinct:  "distinct x ==> distinct y ==>    (set x = set y) = (multiset_of x = multiset_of y)"by (auto simp: multiset_eq_iff distinct_count_atmost_1)lemma set_eq_iff_multiset_of_remdups_eq:   "(set x = set y) = (multiset_of (remdups x) = multiset_of (remdups y))"apply (rule iffI)apply (simp add: set_eq_iff_multiset_of_eq_distinct[THEN iffD1])apply (drule distinct_remdups [THEN distinct_remdups      [THEN set_eq_iff_multiset_of_eq_distinct [THEN iffD2]]])apply simpdonelemma multiset_of_compl_union [simp]:  "multiset_of [x\<leftarrow>xs. P x] + multiset_of [x\<leftarrow>xs. ¬P x] = multiset_of xs"  by (induct xs) (auto simp: add_ac)lemma count_multiset_of_length_filter:  "count (multiset_of xs) x = length (filter (λy. x = y) xs)"  by (induct xs) autolemma nth_mem_multiset_of: "i < length ls ==> (ls ! i) :# multiset_of ls"apply (induct ls arbitrary: i) apply simpapply (case_tac i) apply autodonelemma multiset_of_remove1[simp]:  "multiset_of (remove1 a xs) = multiset_of xs - {#a#}"by (induct xs) (auto simp add: multiset_eq_iff)lemma multiset_of_eq_length:  assumes "multiset_of xs = multiset_of ys"  shows "length xs = length ys"  using assms by (metis size_multiset_of)lemma multiset_of_eq_length_filter:  assumes "multiset_of xs = multiset_of ys"  shows "length (filter (λx. z = x) xs) = length (filter (λy. z = y) ys)"  using assms by (metis count_multiset_of)lemma fold_multiset_equiv:  assumes f: "!!x y. x ∈ set xs ==> y ∈ set xs ==> f x o f y = f y o f x"    and equiv: "multiset_of xs = multiset_of ys"  shows "List.fold f xs = List.fold f ys"using f equiv [symmetric]proof (induct xs arbitrary: ys)  case Nil then show ?case by simpnext  case (Cons x xs)  then have *: "set ys = set (x # xs)" by (blast dest: multiset_of_eq_setD)  have "!!x y. x ∈ set ys ==> y ∈ set ys ==> f x o f y = f y o f x"     by (rule Cons.prems(1)) (simp_all add: *)  moreover from * have "x ∈ set ys" by simp  ultimately have "List.fold f ys = List.fold f (remove1 x ys) o f x" by (fact fold_remove1_split)  moreover from Cons.prems have "List.fold f xs = List.fold f (remove1 x ys)" by (auto intro: Cons.hyps)  ultimately show ?case by simpqedcontext linorderbeginlemma multiset_of_insort [simp]:  "multiset_of (insort_key k x xs) = {#x#} + multiset_of xs"  by (induct xs) (simp_all add: ac_simps) lemma multiset_of_sort [simp]:  "multiset_of (sort_key k xs) = multiset_of xs"  by (induct xs) (simp_all add: ac_simps)text {*  This lemma shows which properties suffice to show that a function  @{text "f"} with @{text "f xs = ys"} behaves like sort.*}lemma properties_for_sort_key:  assumes "multiset_of ys = multiset_of xs"  and "!!k. k ∈ set ys ==> filter (λx. f k = f x) ys = filter (λx. f k = f x) xs"  and "sorted (map f ys)"  shows "sort_key f xs = ys"using assmsproof (induct xs arbitrary: ys)  case Nil then show ?case by simpnext  case (Cons x xs)  from Cons.prems(2) have    "∀k ∈ set ys. filter (λx. f k = f x) (remove1 x ys) = filter (λx. f k = f x) xs"    by (simp add: filter_remove1)  with Cons.prems have "sort_key f xs = remove1 x ys"    by (auto intro!: Cons.hyps simp add: sorted_map_remove1)  moreover from Cons.prems have "x ∈ set ys"    by (auto simp add: mem_set_multiset_eq intro!: ccontr)  ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)qedlemma properties_for_sort:  assumes multiset: "multiset_of ys = multiset_of xs"  and "sorted ys"  shows "sort xs = ys"proof (rule properties_for_sort_key)  from multiset show "multiset_of ys = multiset_of xs" .  from `sorted ys` show "sorted (map (λx. x) ys)" by simp  from multiset have "!!k. length (filter (λy. k = y) ys) = length (filter (λx. k = x) xs)"    by (rule multiset_of_eq_length_filter)  then have "!!k. replicate (length (filter (λy. k = y) ys)) k = replicate (length (filter (λx. k = x) xs)) k"    by simp  then show "!!k. k ∈ set ys ==> filter (λy. k = y) ys = filter (λx. k = x) xs"    by (simp add: replicate_length_filter)qedlemma sort_key_by_quicksort:  "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))]    @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))]    @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs")proof (rule properties_for_sort_key)  show "multiset_of ?rhs = multiset_of ?lhs"    by (rule multiset_eqI) (auto simp add: multiset_of_filter)next  show "sorted (map f ?rhs)"    by (auto simp add: sorted_append intro: sorted_map_same)next  fix l  assume "l ∈ set ?rhs"  let ?pivot = "f (xs ! (length xs div 2))"  have *: "!!x. f l = f x <-> f x = f l" by auto  have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]"    unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)  with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp  have "!!x P. P (f x) ?pivot ∧ f l = f x <-> P (f l) ?pivot ∧ f l = f x" by auto  then have "!!P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot ∧ f l = f x] =    [x \<leftarrow> sort_key f xs. P (f l) ?pivot ∧ f l = f x]" by simp  note *** = this [of "op <"] this [of "op >"] this [of "op ="]  show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]"  proof (cases "f l" ?pivot rule: linorder_cases)    case less    then have "f l ≠ ?pivot" and "¬ f l > ?pivot" by auto    with less show ?thesis      by (simp add: filter_sort [symmetric] ** ***)  next    case equal then show ?thesis      by (simp add: * less_le)  next    case greater    then have "f l ≠ ?pivot" and "¬ f l < ?pivot" by auto    with greater show ?thesis      by (simp add: filter_sort [symmetric] ** ***)  qedqedlemma sort_by_quicksort:  "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)]    @ [x\<leftarrow>xs. x = xs ! (length xs div 2)]    @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs")  using sort_key_by_quicksort [of "λx. x", symmetric] by simptext {* A stable parametrized quicksort *}definition part :: "('b => 'a) => 'a => 'b list => 'b list × 'b list × 'b list" where  "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])"lemma part_code [code]:  "part f pivot [] = ([], [], [])"  "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in     if x' < pivot then (x # lts, eqs, gts)     else if x' > pivot then (lts, eqs, x # gts)     else (lts, x # eqs, gts))"  by (auto simp add: part_def Let_def split_def)lemma sort_key_by_quicksort_code [code]:  "sort_key f xs = (case xs of [] => []    | [x] => xs    | [x, y] => (if f x ≤ f y then xs else [y, x])    | _ => (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs       in sort_key f lts @ eqs @ sort_key f gts))"proof (cases xs)  case Nil then show ?thesis by simpnext  case (Cons _ ys) note hyps = Cons show ?thesis  proof (cases ys)    case Nil with hyps show ?thesis by simp  next    case (Cons _ zs) note hyps = hyps Cons show ?thesis    proof (cases zs)      case Nil with hyps show ?thesis by auto    next      case Cons       from sort_key_by_quicksort [of f xs]      have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs        in sort_key f lts @ eqs @ sort_key f gts)"      by (simp only: split_def Let_def part_def fst_conv snd_conv)      with hyps Cons show ?thesis by (simp only: list.cases)    qed  qedqedendhide_const (open) partlemma multiset_of_remdups_le: "multiset_of (remdups xs) ≤ multiset_of xs"  by (induct xs) (auto intro: order_trans)lemma multiset_of_update:  "i < length ls ==> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}"proof (induct ls arbitrary: i)  case Nil then show ?case by simpnext  case (Cons x xs)  show ?case  proof (cases i)    case 0 then show ?thesis by simp  next    case (Suc i')    with Cons show ?thesis      apply simp      apply (subst add_assoc)      apply (subst add_commute [of "{#v#}" "{#x#}"])      apply (subst add_assoc [symmetric])      apply simp      apply (rule mset_le_multiset_union_diff_commute)      apply (simp add: mset_le_single nth_mem_multiset_of)      done  qedqedlemma multiset_of_swap:  "i < length ls ==> j < length ls ==>    multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls"  by (cases "i = j") (simp_all add: multiset_of_update nth_mem_multiset_of)subsubsection {* Association lists -- including code generation *}text {* Preliminaries *}text {* Raw operations on lists *}definition join_raw :: "('key => 'val × 'val => 'val) => ('key × 'val) list => ('key × 'val) list => ('key × 'val) list"where  "join_raw f xs ys = foldr (λ(k, v). map_default k v (%v'. f k (v', v))) ys xs"lemma join_raw_Nil [simp]:  "join_raw f xs [] = xs"by (simp add: join_raw_def)lemma join_raw_Cons [simp]:  "join_raw f xs ((k, v) # ys) = map_default k v (%v'. f k (v', v)) (join_raw f xs ys)"by (simp add: join_raw_def)lemma map_of_join_raw:  assumes "distinct (map fst ys)"  shows "map_of (join_raw f xs ys) x = (case map_of xs x of None => map_of ys x | Some v =>    (case map_of ys x of None => Some v | Some v' => Some (f x (v, v'))))"using assmsapply (induct ys)apply (auto simp add: map_of_map_default split: option.split)apply (metis map_of_eq_None_iff option.simps(2) weak_map_of_SomeI)by (metis Some_eq_map_of_iff map_of_eq_None_iff option.simps(2))lemma distinct_join_raw:  assumes "distinct (map fst xs)"  shows "distinct (map fst (join_raw f xs ys))"using assmsproof (induct ys)  case (Cons y ys)  thus ?case by (cases y) (simp add: distinct_map_default)qed autodefinition  "subtract_entries_raw xs ys = foldr (%(k, v). AList.map_entry k (%v'. v' - v)) ys xs"lemma map_of_subtract_entries_raw:  assumes "distinct (map fst ys)"  shows "map_of (subtract_entries_raw xs ys) x = (case map_of xs x of None => None | Some v =>    (case map_of ys x of None => Some v | Some v' => Some (v - v')))"using assms unfolding subtract_entries_raw_defapply (induct ys)apply autoapply (simp split: option.split)apply (simp add: map_of_map_entry)apply (auto split: option.split)apply (metis map_of_eq_None_iff option.simps(3) option.simps(4))by (metis map_of_eq_None_iff option.simps(4) option.simps(5))lemma distinct_subtract_entries_raw:  assumes "distinct (map fst xs)"  shows "distinct (map fst (subtract_entries_raw xs ys))"using assmsunfolding subtract_entries_raw_def by (induct ys) (auto simp add: distinct_map_entry)text {* Operations on alists with distinct keys *}lift_definition join :: "('a => 'b × 'b => 'b) => ('a, 'b) alist => ('a, 'b) alist => ('a, 'b) alist" is join_rawby (simp add: distinct_join_raw)lift_definition subtract_entries :: "('a, ('b :: minus)) alist => ('a, 'b) alist => ('a, 'b) alist"is subtract_entries_raw by (simp add: distinct_subtract_entries_raw)text {* Implementing multisets by means of association lists *}definition count_of :: "('a × nat) list => 'a => nat" where  "count_of xs x = (case map_of xs x of None => 0 | Some n => n)"lemma count_of_multiset:  "count_of xs ∈ multiset"proof -  let ?A = "{x::'a. 0 < (case map_of xs x of None => 0::nat | Some (n::nat) => n)}"  have "?A ⊆ dom (map_of xs)"  proof    fix x    assume "x ∈ ?A"    then have "0 < (case map_of xs x of None => 0::nat | Some (n::nat) => n)" by simp    then have "map_of xs x ≠ None" by (cases "map_of xs x") auto    then show "x ∈ dom (map_of xs)" by auto  qed  with finite_dom_map_of [of xs] have "finite ?A"    by (auto intro: finite_subset)  then show ?thesis    by (simp add: count_of_def fun_eq_iff multiset_def)qedlemma count_simps [simp]:  "count_of [] = (λ_. 0)"  "count_of ((x, n) # xs) = (λy. if x = y then n else count_of xs y)"  by (simp_all add: count_of_def fun_eq_iff)lemma count_of_empty:  "x ∉ fst ` set xs ==> count_of xs x = 0"  by (induct xs) (simp_all add: count_of_def)lemma count_of_filter:  "count_of (List.filter (P o fst) xs) x = (if P x then count_of xs x else 0)"  by (induct xs) autolemma count_of_map_default [simp]:  "count_of (map_default x b (%x. x + b) xs) y = (if x = y then count_of xs x + b else count_of xs y)"unfolding count_of_def by (simp add: map_of_map_default split: option.split)lemma count_of_join_raw:  "distinct (map fst ys) ==> count_of xs x + count_of ys x = count_of (join_raw (%x (x, y). x + y) xs ys) x"unfolding count_of_def by (simp add: map_of_join_raw split: option.split)lemma count_of_subtract_entries_raw:  "distinct (map fst ys) ==> count_of xs x - count_of ys x = count_of (subtract_entries_raw xs ys) x"unfolding count_of_def by (simp add: map_of_subtract_entries_raw split: option.split)text {* Code equations for multiset operations *}definition Bag :: "('a, nat) alist => 'a multiset" where  "Bag xs = Abs_multiset (count_of (DAList.impl_of xs))"code_datatype Baglemma count_Bag [simp, code]:  "count (Bag xs) = count_of (DAList.impl_of xs)"  by (simp add: Bag_def count_of_multiset Abs_multiset_inverse)lemma Mempty_Bag [code]:  "{#} = Bag (DAList.empty)"  by (simp add: multiset_eq_iff alist.Alist_inverse DAList.empty_def)lemma single_Bag [code]:  "{#x#} = Bag (DAList.update x 1 DAList.empty)"  by (simp add: multiset_eq_iff alist.Alist_inverse update.rep_eq empty.rep_eq)lemma union_Bag [code]:  "Bag xs + Bag ys = Bag (join (λx (n1, n2). n1 + n2) xs ys)"by (rule multiset_eqI) (simp add: count_of_join_raw alist.Alist_inverse distinct_join_raw join_def)lemma minus_Bag [code]:  "Bag xs - Bag ys = Bag (subtract_entries xs ys)"by (rule multiset_eqI)  (simp add: count_of_subtract_entries_raw alist.Alist_inverse distinct_subtract_entries_raw subtract_entries_def)lemma filter_Bag [code]:  "Multiset.filter P (Bag xs) = Bag (DAList.filter (P o fst) xs)"by (rule multiset_eqI) (simp add: count_of_filter DAList.filter.rep_eq)lemma mset_less_eq_Bag [code]:  "Bag xs ≤ A <-> (∀(x, n) ∈ set (DAList.impl_of xs). count_of (DAList.impl_of xs) x ≤ count A x)"    (is "?lhs <-> ?rhs")proof  assume ?lhs then show ?rhs    by (auto simp add: mset_le_def)next  assume ?rhs  show ?lhs  proof (rule mset_less_eqI)    fix x    from `?rhs` have "count_of (DAList.impl_of xs) x ≤ count A x"      by (cases "x ∈ fst ` set (DAList.impl_of xs)") (auto simp add: count_of_empty)    then show "count (Bag xs) x ≤ count A x"      by (simp add: mset_le_def)  qedqedinstantiation multiset :: (equal) equalbegindefinition  [code]: "HOL.equal A B <-> (A::'a multiset) ≤ B ∧ B ≤ A"instance  by default (simp add: equal_multiset_def eq_iff)endtext {* Quickcheck generators *}definition (in term_syntax)  bagify :: "('a::typerep, nat) alist × (unit => Code_Evaluation.term)    => 'a multiset × (unit => Code_Evaluation.term)" where  [code_unfold]: "bagify xs = Code_Evaluation.valtermify Bag {·} xs"notation fcomp (infixl "o>" 60)notation scomp (infixl "o->" 60)instantiation multiset :: (random) randombegindefinition  "Quickcheck_Random.random i = Quickcheck_Random.random i o-> (λxs. Pair (bagify xs))"instance ..endno_notation fcomp (infixl "o>" 60)no_notation scomp (infixl "o->" 60)instantiation multiset :: (exhaustive) exhaustivebegindefinition exhaustive_multiset :: "('a multiset => (bool * term list) option) => natural => (bool * term list) option"where  "exhaustive_multiset f i = Quickcheck_Exhaustive.exhaustive (%xs. f (Bag xs)) i"instance ..endinstantiation multiset :: (full_exhaustive) full_exhaustivebegindefinition full_exhaustive_multiset :: "('a multiset * (unit => term) => (bool * term list) option) => natural => (bool * term list) option"where  "full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (%xs. f (bagify xs)) i"instance ..endhide_const (open) bagifysubsection {* The multiset order *}subsubsection {* Well-foundedness *}definition mult1 :: "('a × 'a) set => ('a multiset × 'a multiset) set" where  "mult1 r = {(N, M). ∃a M0 K. M = M0 + {#a#} ∧ N = M0 + K ∧      (∀b. b :# K --> (b, a) ∈ r)}"definition mult :: "('a × 'a) set => ('a multiset × 'a multiset) set" where  "mult r = (mult1 r)⇧+"lemma not_less_empty [iff]: "(M, {#}) ∉ mult1 r"by (simp add: mult1_def)lemma less_add: "(N, M0 + {#a#}) ∈ mult1 r ==>    (∃M. (M, M0) ∈ mult1 r ∧ N = M + {#a#}) ∨    (∃K. (∀b. b :# K --> (b, a) ∈ r) ∧ N = M0 + K)"  (is "_ ==> ?case1 (mult1 r) ∨ ?case2")proof (unfold mult1_def)  let ?r = "λK a. ∀b. b :# K --> (b, a) ∈ r"  let ?R = "λN M. ∃a M0 K. M = M0 + {#a#} ∧ N = M0 + K ∧ ?r K a"  let ?case1 = "?case1 {(N, M). ?R N M}"  assume "(N, M0 + {#a#}) ∈ {(N, M). ?R N M}"  then have "∃a' M0' K.      M0 + {#a#} = M0' + {#a'#} ∧ N = M0' + K ∧ ?r K a'" by simp  then show "?case1 ∨ ?case2"  proof (elim exE conjE)    fix a' M0' K    assume N: "N = M0' + K" and r: "?r K a'"    assume "M0 + {#a#} = M0' + {#a'#}"    then have "M0 = M0' ∧ a = a' ∨        (∃K'. M0 = K' + {#a'#} ∧ M0' = K' + {#a#})"      by (simp only: add_eq_conv_ex)    then show ?thesis    proof (elim disjE conjE exE)      assume "M0 = M0'" "a = a'"      with N r have "?r K a ∧ N = M0 + K" by simp      then have ?case2 .. then show ?thesis ..    next      fix K'      assume "M0' = K' + {#a#}"      with N have n: "N = K' + K + {#a#}" by (simp add: add_ac)      assume "M0 = K' + {#a'#}"      with r have "?R (K' + K) M0" by blast      with n have ?case1 by simp then show ?thesis ..    qed  qedqedlemma all_accessible: "wf r ==> ∀M. M ∈ acc (mult1 r)"proof  let ?R = "mult1 r"  let ?W = "acc ?R"  {    fix M M0 a    assume M0: "M0 ∈ ?W"      and wf_hyp: "!!b. (b, a) ∈ r ==> (∀M ∈ ?W. M + {#b#} ∈ ?W)"      and acc_hyp: "∀M. (M, M0) ∈ ?R --> M + {#a#} ∈ ?W"    have "M0 + {#a#} ∈ ?W"    proof (rule accI [of "M0 + {#a#}"])      fix N      assume "(N, M0 + {#a#}) ∈ ?R"      then have "((∃M. (M, M0) ∈ ?R ∧ N = M + {#a#}) ∨          (∃K. (∀b. b :# K --> (b, a) ∈ r) ∧ N = M0 + K))"        by (rule less_add)      then show "N ∈ ?W"      proof (elim exE disjE conjE)        fix M assume "(M, M0) ∈ ?R" and N: "N = M + {#a#}"        from acc_hyp have "(M, M0) ∈ ?R --> M + {#a#} ∈ ?W" ..        from this and `(M, M0) ∈ ?R` have "M + {#a#} ∈ ?W" ..        then show "N ∈ ?W" by (simp only: N)      next        fix K        assume N: "N = M0 + K"        assume "∀b. b :# K --> (b, a) ∈ r"        then have "M0 + K ∈ ?W"        proof (induct K)          case empty          from M0 show "M0 + {#} ∈ ?W" by simp        next          case (add K x)          from add.prems have "(x, a) ∈ r" by simp          with wf_hyp have "∀M ∈ ?W. M + {#x#} ∈ ?W" by blast          moreover from add have "M0 + K ∈ ?W" by simp          ultimately have "(M0 + K) + {#x#} ∈ ?W" ..          then show "M0 + (K + {#x#}) ∈ ?W" by (simp only: add_assoc)        qed        then show "N ∈ ?W" by (simp only: N)      qed    qed  } note tedious_reasoning = this  assume wf: "wf r"  fix M  show "M ∈ ?W"  proof (induct M)    show "{#} ∈ ?W"    proof (rule accI)      fix b assume "(b, {#}) ∈ ?R"      with not_less_empty show "b ∈ ?W" by contradiction    qed    fix M a assume "M ∈ ?W"    from wf have "∀M ∈ ?W. M + {#a#} ∈ ?W"    proof induct      fix a      assume r: "!!b. (b, a) ∈ r ==> (∀M ∈ ?W. M + {#b#} ∈ ?W)"      show "∀M ∈ ?W. M + {#a#} ∈ ?W"      proof        fix M assume "M ∈ ?W"        then show "M + {#a#} ∈ ?W"          by (rule acc_induct) (rule tedious_reasoning [OF _ r])      qed    qed    from this and `M ∈ ?W` show "M + {#a#} ∈ ?W" ..  qedqedtheorem wf_mult1: "wf r ==> wf (mult1 r)"by (rule acc_wfI) (rule all_accessible)theorem wf_mult: "wf r ==> wf (mult r)"unfolding mult_def by (rule wf_trancl) (rule wf_mult1)subsubsection {* Closure-free presentation *}text {* One direction. *}lemma mult_implies_one_step:  "trans r ==> (M, N) ∈ mult r ==>    ∃I J K. N = I + J ∧ M = I + K ∧ J ≠ {#} ∧    (∀k ∈ set_of K. ∃j ∈ set_of J. (k, j) ∈ r)"apply (unfold mult_def mult1_def set_of_def)apply (erule converse_trancl_induct, clarify) apply (rule_tac x = M0 in exI, simp, clarify)apply (case_tac "a :# K") apply (rule_tac x = I in exI) apply (simp (no_asm)) apply (rule_tac x = "(K - {#a#}) + Ka" in exI) apply (simp (no_asm_simp) add: add_assoc [symmetric]) apply (drule_tac f = "λM. M - {#a#}" in arg_cong) apply (simp add: diff_union_single_conv) apply (simp (no_asm_use) add: trans_def) apply blastapply (subgoal_tac "a :# I") apply (rule_tac x = "I - {#a#}" in exI) apply (rule_tac x = "J + {#a#}" in exI) apply (rule_tac x = "K + Ka" in exI) apply (rule conjI)  apply (simp add: multiset_eq_iff split: nat_diff_split) apply (rule conjI)  apply (drule_tac f = "λM. M - {#a#}" in arg_cong, simp)  apply (simp add: multiset_eq_iff split: nat_diff_split) apply (simp (no_asm_use) add: trans_def) apply blastapply (subgoal_tac "a :# (M0 + {#a#})") apply simpapply (simp (no_asm))donelemma one_step_implies_mult_aux:  "trans r ==>    ∀I J K. (size J = n ∧ J ≠ {#} ∧ (∀k ∈ set_of K. ∃j ∈ set_of J. (k, j) ∈ r))      --> (I + K, I + J) ∈ mult r"apply (induct_tac n, auto)apply (frule size_eq_Suc_imp_eq_union, clarify)apply (rename_tac "J'", simp)apply (erule notE, auto)apply (case_tac "J' = {#}") apply (simp add: mult_def) apply (rule r_into_trancl) apply (simp add: mult1_def set_of_def, blast)txt {* Now we know @{term "J' ≠ {#}"}. *}apply (cut_tac M = K and P = "λx. (x, a) ∈ r" in multiset_partition)apply (erule_tac P = "∀k ∈ set_of K. ?P k" in rev_mp)apply (erule ssubst)apply (simp add: Ball_def, auto)apply (subgoal_tac  "((I + {# x :# K. (x, a) ∈ r #}) + {# x :# K. (x, a) ∉ r #},    (I + {# x :# K. (x, a) ∈ r #}) + J') ∈ mult r") prefer 2 apply forceapply (simp (no_asm_use) add: add_assoc [symmetric] mult_def)apply (erule trancl_trans)apply (rule r_into_trancl)apply (simp add: mult1_def set_of_def)apply (rule_tac x = a in exI)apply (rule_tac x = "I + J'" in exI)apply (simp add: add_ac)donelemma one_step_implies_mult:  "trans r ==> J ≠ {#} ==> ∀k ∈ set_of K. ∃j ∈ set_of J. (k, j) ∈ r    ==> (I + K, I + J) ∈ mult r"using one_step_implies_mult_aux by blastsubsubsection {* Partial-order properties *}definition less_multiset :: "'a::order multiset => 'a multiset => bool" (infix "<#" 50) where  "M' <# M <-> (M', M) ∈ mult {(x', x). x' < x}"definition le_multiset :: "'a::order multiset => 'a multiset => bool" (infix "<=#" 50) where  "M' <=# M <-> M' <# M ∨ M' = M"notation (xsymbols) less_multiset (infix "⊂#" 50)notation (xsymbols) le_multiset (infix "⊆#" 50)interpretation multiset_order: order le_multiset less_multisetproof -  have irrefl: "!!M :: 'a multiset. ¬ M ⊂# M"  proof    fix M :: "'a multiset"    assume "M ⊂# M"    then have MM: "(M, M) ∈ mult {(x, y). x < y}" by (simp add: less_multiset_def)    have "trans {(x'::'a, x). x' < x}"      by (rule transI) simp    moreover note MM    ultimately have "∃I J K. M = I + J ∧ M = I + K      ∧ J ≠ {#} ∧ (∀k∈set_of K. ∃j∈set_of J. (k, j) ∈ {(x, y). x < y})"      by (rule mult_implies_one_step)    then obtain I J K where "M = I + J" and "M = I + K"      and "J ≠ {#}" and "(∀k∈set_of K. ∃j∈set_of J. (k, j) ∈ {(x, y). x < y})" by blast    then have aux1: "K ≠ {#}" and aux2: "∀k∈set_of K. ∃j∈set_of K. k < j" by auto    have "finite (set_of K)" by simp    moreover note aux2    ultimately have "set_of K = {}"      by (induct rule: finite_induct) (auto intro: order_less_trans)    with aux1 show False by simp  qed  have trans: "!!K M N :: 'a multiset. K ⊂# M ==> M ⊂# N ==> K ⊂# N"    unfolding less_multiset_def mult_def by (blast intro: trancl_trans)  show "class.order (le_multiset :: 'a multiset => _) less_multiset"    by default (auto simp add: le_multiset_def irrefl dest: trans)qedlemma mult_less_irrefl [elim!]: "M ⊂# (M::'a::order multiset) ==> R"  by simpsubsubsection {* Monotonicity of multiset union *}lemma mult1_union: "(B, D) ∈ mult1 r ==> (C + B, C + D) ∈ mult1 r"apply (unfold mult1_def)apply autoapply (rule_tac x = a in exI)apply (rule_tac x = "C + M0" in exI)apply (simp add: add_assoc)donelemma union_less_mono2: "B ⊂# D ==> C + B ⊂# C + (D::'a::order multiset)"apply (unfold less_multiset_def mult_def)apply (erule trancl_induct) apply (blast intro: mult1_union)apply (blast intro: mult1_union trancl_trans)donelemma union_less_mono1: "B ⊂# D ==> B + C ⊂# D + (C::'a::order multiset)"apply (subst add_commute [of B C])apply (subst add_commute [of D C])apply (erule union_less_mono2)donelemma union_less_mono:  "A ⊂# C ==> B ⊂# D ==> A + B ⊂# C + (D::'a::order multiset)"  by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)interpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multisetproofqed (auto simp add: le_multiset_def intro: union_less_mono2)subsection {* Termination proofs with multiset orders *}lemma multi_member_skip: "x ∈# XS ==> x ∈# {# y #} + XS"  and multi_member_this: "x ∈# {# x #} + XS"  and multi_member_last: "x ∈# {# x #}"  by autodefinition "ms_strict = mult pair_less"definition "ms_weak = ms_strict ∪ Id"lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_defby (auto intro: wf_mult1 wf_trancl simp: mult_def)lemma smsI:  "(set_of A, set_of B) ∈ max_strict ==> (Z + A, Z + B) ∈ ms_strict"  unfolding ms_strict_defby (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)lemma wmsI:  "(set_of A, set_of B) ∈ max_strict ∨ A = {#} ∧ B = {#}  ==> (Z + A, Z + B) ∈ ms_weak"unfolding ms_weak_def ms_strict_defby (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)inductive pw_leqwhere  pw_leq_empty: "pw_leq {#} {#}"| pw_leq_step:  "[|(x,y) ∈ pair_leq; pw_leq X Y |] ==> pw_leq ({#x#} + X) ({#y#} + Y)"lemma pw_leq_lstep:  "(x, y) ∈ pair_leq ==> pw_leq {#x#} {#y#}"by (drule pw_leq_step) (rule pw_leq_empty, simp)lemma pw_leq_split:  assumes "pw_leq X Y"  shows "∃A B Z. X = A + Z ∧ Y = B + Z ∧ ((set_of A, set_of B) ∈ max_strict ∨ (B = {#} ∧ A = {#}))"  using assmsproof (induct)  case pw_leq_empty thus ?case by autonext  case (pw_leq_step x y X Y)  then obtain A B Z where    [simp]: "X = A + Z" "Y = B + Z"       and 1[simp]: "(set_of A, set_of B) ∈ max_strict ∨ (B = {#} ∧ A = {#})"     by auto  from pw_leq_step have "x = y ∨ (x, y) ∈ pair_less"     unfolding pair_leq_def by auto  thus ?case  proof    assume [simp]: "x = y"    have      "{#x#} + X = A + ({#y#}+Z)       ∧ {#y#} + Y = B + ({#y#}+Z)      ∧ ((set_of A, set_of B) ∈ max_strict ∨ (B = {#} ∧ A = {#}))"      by (auto simp: add_ac)    thus ?case by (intro exI)  next    assume A: "(x, y) ∈ pair_less"    let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"    have "{#x#} + X = ?A' + Z"      "{#y#} + Y = ?B' + Z"      by (auto simp add: add_ac)    moreover have       "(set_of ?A', set_of ?B') ∈ max_strict"      using 1 A unfolding max_strict_def       by (auto elim!: max_ext.cases)    ultimately show ?thesis by blast  qedqedlemma   assumes pwleq: "pw_leq Z Z'"  shows ms_strictI: "(set_of A, set_of B) ∈ max_strict ==> (Z + A, Z' + B) ∈ ms_strict"  and   ms_weakI1:  "(set_of A, set_of B) ∈ max_strict ==> (Z + A, Z' + B) ∈ ms_weak"  and   ms_weakI2:  "(Z + {#}, Z' + {#}) ∈ ms_weak"proof -  from pw_leq_split[OF pwleq]   obtain A' B' Z''    where [simp]: "Z = A' + Z''" "Z' = B' + Z''"    and mx_or_empty: "(set_of A', set_of B') ∈ max_strict ∨ (A' = {#} ∧ B' = {#})"    by blast  {    assume max: "(set_of A, set_of B) ∈ max_strict"    from mx_or_empty    have "(Z'' + (A + A'), Z'' + (B + B')) ∈ ms_strict"    proof      assume max': "(set_of A', set_of B') ∈ max_strict"      with max have "(set_of (A + A'), set_of (B + B')) ∈ max_strict"        by (auto simp: max_strict_def intro: max_ext_additive)      thus ?thesis by (rule smsI)     next      assume [simp]: "A' = {#} ∧ B' = {#}"      show ?thesis by (rule smsI) (auto intro: max)    qed    thus "(Z + A, Z' + B) ∈ ms_strict" by (simp add:add_ac)    thus "(Z + A, Z' + B) ∈ ms_weak" by (simp add: ms_weak_def)  }  from mx_or_empty  have "(Z'' + A', Z'' + B') ∈ ms_weak" by (rule wmsI)  thus "(Z + {#}, Z' + {#}) ∈ ms_weak" by (simp add:add_ac)qedlemma empty_neutral: "{#} + x = x" "x + {#} = x"and nonempty_plus: "{# x #} + rs ≠ {#}"and nonempty_single: "{# x #} ≠ {#}"by autosetup {*let  fun msetT T = Type (@{type_name multiset}, [T]);  fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)    | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) \$ x    | mk_mset T (x :: xs) =          Const (@{const_name plus}, msetT T --> msetT T --> msetT T) \$                mk_mset T [x] \$ mk_mset T xs  fun mset_member_tac m i =      (if m <= 0 then           rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i       else           rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)  val mset_nonempty_tac =      rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}  val regroup_munion_conv =      Function_Lib.regroup_conv @{const_abbrev Mempty} @{const_name plus}        (map (fn t => t RS eq_reflection) (@{thms add_ac} @ @{thms empty_neutral}))  fun unfold_pwleq_tac i =    (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))      ORELSE (rtac @{thm pw_leq_lstep} i)      ORELSE (rtac @{thm pw_leq_empty} i)  val set_of_simps = [@{thm set_of_empty}, @{thm set_of_single}, @{thm set_of_union},                      @{thm Un_insert_left}, @{thm Un_empty_left}]in  ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset   {    msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,    mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,    mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_of_simps,    smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},    reduction_pair= @{thm ms_reduction_pair}  })end*}subsection {* Legacy theorem bindings *}lemmas multi_count_eq = multiset_eq_iff [symmetric]lemma union_commute: "M + N = N + (M::'a multiset)"  by (fact add_commute)lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"  by (fact add_assoc)lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"  by (fact add_left_commute)lemmas union_ac = union_assoc union_commute union_lcommlemma union_right_cancel: "M + K = N + K <-> M = (N::'a multiset)"  by (fact add_right_cancel)lemma union_left_cancel: "K + M = K + N <-> M = (N::'a multiset)"  by (fact add_left_cancel)lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y ==> X = Y"  by (fact add_imp_eq)lemma mset_less_trans: "(M::'a multiset) < K ==> K < N ==> M < N"  by (fact order_less_trans)lemma multiset_inter_commute: "A #∩ B = B #∩ A"  by (fact inf.commute)lemma multiset_inter_assoc: "A #∩ (B #∩ C) = A #∩ B #∩ C"  by (fact inf.assoc [symmetric])lemma multiset_inter_left_commute: "A #∩ (B #∩ C) = B #∩ (A #∩ C)"  by (fact inf.left_commute)lemmas multiset_inter_ac =  multiset_inter_commute  multiset_inter_assoc  multiset_inter_left_commutelemma mult_less_not_refl:  "¬ M ⊂# (M::'a::order multiset)"  by (fact multiset_order.less_irrefl)lemma mult_less_trans:  "K ⊂# M ==> M ⊂# N ==> K ⊂# (N::'a::order multiset)"  by (fact multiset_order.less_trans)    lemma mult_less_not_sym:  "M ⊂# N ==> ¬ N ⊂# (M::'a::order multiset)"  by (fact multiset_order.less_not_sym)lemma mult_less_asym:  "M ⊂# N ==> (¬ P ==> N ⊂# (M::'a::order multiset)) ==> P"  by (fact multiset_order.less_asym)ML {*fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T]))                      (Const _ \$ t') =    let      val (maybe_opt, ps) =        Nitpick_Model.dest_plain_fun t' ||> op ~~        ||> map (apsnd (snd o HOLogic.dest_number))      fun elems_for t =        case AList.lookup (op =) ps t of          SOME n => replicate n t        | NONE => [Const (maybe_name, elem_T --> elem_T) \$ t]    in      case maps elems_for (all_values elem_T) @           (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)]            else []) of        [] => Const (@{const_name zero_class.zero}, T)      | ts => foldl1 (fn (t1, t2) =>                         Const (@{const_name plus_class.plus}, T --> T --> T)                         \$ t1 \$ t2)                     (map (curry (op \$) (Const (@{const_name single},                                                elem_T --> T))) ts)    end  | multiset_postproc _ _ _ _ t = t*}declaration {*Nitpick_Model.register_term_postprocessor @{typ "'a multiset"}    multiset_postproc*}hide_const (open) foldend`