src/HOL/Library/Multiset.thy
author wenzelm
Mon Jun 29 15:36:29 2015 +0200 (2015-06-29)
changeset 60606 e5cb9271e339
parent 60515 484559628038
child 60607 d440af2e584f
permissions -rw-r--r--
more symbols;
tuned proofs;
tuned ML;
     1 (*  Title:      HOL/Library/Multiset.thy
     2     Author:     Tobias Nipkow, Markus Wenzel, Lawrence C Paulson, Norbert Voelker
     3     Author:     Andrei Popescu, TU Muenchen
     4     Author:     Jasmin Blanchette, Inria, LORIA, MPII
     5     Author:     Dmitriy Traytel, TU Muenchen
     6     Author:     Mathias Fleury, MPII
     7 *)
     8 
     9 section \<open>(Finite) multisets\<close>
    10 
    11 theory Multiset
    12 imports Main
    13 begin
    14 
    15 subsection \<open>The type of multisets\<close>
    16 
    17 definition "multiset = {f :: 'a \<Rightarrow> nat. finite {x. f x > 0}}"
    18 
    19 typedef 'a multiset = "multiset :: ('a \<Rightarrow> nat) set"
    20   morphisms count Abs_multiset
    21   unfolding multiset_def
    22 proof
    23   show "(\<lambda>x. 0::nat) \<in> {f. finite {x. f x > 0}}" by simp
    24 qed
    25 
    26 setup_lifting type_definition_multiset
    27 
    28 abbreviation Melem :: "'a \<Rightarrow> 'a multiset \<Rightarrow> bool"  ("(_/ :# _)" [50, 51] 50) where
    29   "a :# M == 0 < count M a"
    30 
    31 notation (xsymbols)
    32   Melem (infix "\<in>#" 50)
    33 
    34 lemma multiset_eq_iff: "M = N \<longleftrightarrow> (\<forall>a. count M a = count N a)"
    35   by (simp only: count_inject [symmetric] fun_eq_iff)
    36 
    37 lemma multiset_eqI: "(\<And>x. count A x = count B x) \<Longrightarrow> A = B"
    38   using multiset_eq_iff by auto
    39 
    40 text \<open>Preservation of the representing set @{term multiset}.\<close>
    41 
    42 lemma const0_in_multiset: "(\<lambda>a. 0) \<in> multiset"
    43   by (simp add: multiset_def)
    44 
    45 lemma only1_in_multiset: "(\<lambda>b. if b = a then n else 0) \<in> multiset"
    46   by (simp add: multiset_def)
    47 
    48 lemma union_preserves_multiset: "M \<in> multiset \<Longrightarrow> N \<in> multiset \<Longrightarrow> (\<lambda>a. M a + N a) \<in> multiset"
    49   by (simp add: multiset_def)
    50 
    51 lemma diff_preserves_multiset:
    52   assumes "M \<in> multiset"
    53   shows "(\<lambda>a. M a - N a) \<in> multiset"
    54 proof -
    55   have "{x. N x < M x} \<subseteq> {x. 0 < M x}"
    56     by auto
    57   with assms show ?thesis
    58     by (auto simp add: multiset_def intro: finite_subset)
    59 qed
    60 
    61 lemma filter_preserves_multiset:
    62   assumes "M \<in> multiset"
    63   shows "(\<lambda>x. if P x then M x else 0) \<in> multiset"
    64 proof -
    65   have "{x. (P x \<longrightarrow> 0 < M x) \<and> P x} \<subseteq> {x. 0 < M x}"
    66     by auto
    67   with assms show ?thesis
    68     by (auto simp add: multiset_def intro: finite_subset)
    69 qed
    70 
    71 lemmas in_multiset = const0_in_multiset only1_in_multiset
    72   union_preserves_multiset diff_preserves_multiset filter_preserves_multiset
    73 
    74 
    75 subsection \<open>Representing multisets\<close>
    76 
    77 text \<open>Multiset enumeration\<close>
    78 
    79 instantiation multiset :: (type) cancel_comm_monoid_add
    80 begin
    81 
    82 lift_definition zero_multiset :: "'a multiset" is "\<lambda>a. 0"
    83 by (rule const0_in_multiset)
    84 
    85 abbreviation Mempty :: "'a multiset" ("{#}") where
    86   "Mempty \<equiv> 0"
    87 
    88 lift_definition plus_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" is "\<lambda>M N. (\<lambda>a. M a + N a)"
    89 by (rule union_preserves_multiset)
    90 
    91 lift_definition minus_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" is "\<lambda> M N. \<lambda>a. M a - N a"
    92 by (rule diff_preserves_multiset)
    93 
    94 instance
    95   by default (transfer, simp add: fun_eq_iff)+
    96 
    97 end
    98 
    99 lift_definition single :: "'a \<Rightarrow> 'a multiset" is "\<lambda>a b. if b = a then 1 else 0"
   100 by (rule only1_in_multiset)
   101 
   102 syntax
   103   "_multiset" :: "args \<Rightarrow> 'a multiset"    ("{#(_)#}")
   104 translations
   105   "{#x, xs#}" == "{#x#} + {#xs#}"
   106   "{#x#}" == "CONST single x"
   107 
   108 lemma count_empty [simp]: "count {#} a = 0"
   109   by (simp add: zero_multiset.rep_eq)
   110 
   111 lemma count_single [simp]: "count {#b#} a = (if b = a then 1 else 0)"
   112   by (simp add: single.rep_eq)
   113 
   114 
   115 subsection \<open>Basic operations\<close>
   116 
   117 subsubsection \<open>Union\<close>
   118 
   119 lemma count_union [simp]: "count (M + N) a = count M a + count N a"
   120   by (simp add: plus_multiset.rep_eq)
   121 
   122 
   123 subsubsection \<open>Difference\<close>
   124 
   125 instantiation multiset :: (type) comm_monoid_diff
   126 begin
   127 
   128 instance
   129   by default (transfer; simp add: fun_eq_iff)
   130 
   131 end
   132 
   133 lemma count_diff [simp]: "count (M - N) a = count M a - count N a"
   134   by (simp add: minus_multiset.rep_eq)
   135 
   136 lemma diff_empty [simp]: "M - {#} = M \<and> {#} - M = {#}"
   137   by rule (fact Groups.diff_zero, fact Groups.zero_diff)
   138 
   139 lemma diff_cancel[simp]: "A - A = {#}"
   140   by (fact Groups.diff_cancel)
   141 
   142 lemma diff_union_cancelR [simp]: "M + N - N = (M::'a multiset)"
   143   by (fact add_diff_cancel_right')
   144 
   145 lemma diff_union_cancelL [simp]: "N + M - N = (M::'a multiset)"
   146   by (fact add_diff_cancel_left')
   147 
   148 lemma diff_right_commute:
   149   fixes M N Q :: "'a multiset"
   150   shows "M - N - Q = M - Q - N"
   151   by (fact diff_right_commute)
   152 
   153 lemma diff_add:
   154   fixes M N Q :: "'a multiset"
   155   shows "M - (N + Q) = M - N - Q"
   156   by (rule sym) (fact diff_diff_add)
   157 
   158 lemma insert_DiffM: "x \<in># M \<Longrightarrow> {#x#} + (M - {#x#}) = M"
   159   by (clarsimp simp: multiset_eq_iff)
   160 
   161 lemma insert_DiffM2 [simp]: "x \<in># M \<Longrightarrow> M - {#x#} + {#x#} = M"
   162   by (clarsimp simp: multiset_eq_iff)
   163 
   164 lemma diff_union_swap: "a \<noteq> b \<Longrightarrow> M - {#a#} + {#b#} = M + {#b#} - {#a#}"
   165   by (auto simp add: multiset_eq_iff)
   166 
   167 lemma diff_union_single_conv: "a \<in># J \<Longrightarrow> I + J - {#a#} = I + (J - {#a#})"
   168   by (simp add: multiset_eq_iff)
   169 
   170 
   171 subsubsection \<open>Equality of multisets\<close>
   172 
   173 lemma single_not_empty [simp]: "{#a#} \<noteq> {#} \<and> {#} \<noteq> {#a#}"
   174   by (simp add: multiset_eq_iff)
   175 
   176 lemma single_eq_single [simp]: "{#a#} = {#b#} \<longleftrightarrow> a = b"
   177   by (auto simp add: multiset_eq_iff)
   178 
   179 lemma union_eq_empty [iff]: "M + N = {#} \<longleftrightarrow> M = {#} \<and> N = {#}"
   180   by (auto simp add: multiset_eq_iff)
   181 
   182 lemma empty_eq_union [iff]: "{#} = M + N \<longleftrightarrow> M = {#} \<and> N = {#}"
   183   by (auto simp add: multiset_eq_iff)
   184 
   185 lemma multi_self_add_other_not_self [simp]: "M = M + {#x#} \<longleftrightarrow> False"
   186   by (auto simp add: multiset_eq_iff)
   187 
   188 lemma diff_single_trivial: "\<not> x \<in># M \<Longrightarrow> M - {#x#} = M"
   189   by (auto simp add: multiset_eq_iff)
   190 
   191 lemma diff_single_eq_union: "x \<in># M \<Longrightarrow> M - {#x#} = N \<longleftrightarrow> M = N + {#x#}"
   192   by auto
   193 
   194 lemma union_single_eq_diff: "M + {#x#} = N \<Longrightarrow> M = N - {#x#}"
   195   by (auto dest: sym)
   196 
   197 lemma union_single_eq_member: "M + {#x#} = N \<Longrightarrow> x \<in># N"
   198   by auto
   199 
   200 lemma union_is_single: "M + N = {#a#} \<longleftrightarrow> M = {#a#} \<and> N={#} \<or> M = {#} \<and> N = {#a#}"
   201   (is "?lhs = ?rhs")
   202 proof
   203   show ?lhs if ?rhs using that by auto
   204   show ?rhs if ?lhs
   205     using that by (simp add: multiset_eq_iff split: if_splits) (metis add_is_1)
   206 qed
   207 
   208 lemma single_is_union: "{#a#} = M + N \<longleftrightarrow> {#a#} = M \<and> N = {#} \<or> M = {#} \<and> {#a#} = N"
   209   by (auto simp add: eq_commute [of "{#a#}" "M + N"] union_is_single)
   210 
   211 lemma add_eq_conv_diff:
   212   "M + {#a#} = N + {#b#} \<longleftrightarrow> M = N \<and> a = b \<or> M = N - {#a#} + {#b#} \<and> N = M - {#b#} + {#a#}"
   213   (is "?lhs \<longleftrightarrow> ?rhs")
   214 (* shorter: by (simp add: multiset_eq_iff) fastforce *)
   215 proof
   216   show ?lhs if ?rhs
   217     using that
   218     by (auto simp add: add.assoc add.commute [of "{#b#}"])
   219       (drule sym, simp add: add.assoc [symmetric])
   220   show ?rhs if ?lhs
   221   proof (cases "a = b")
   222     case True with \<open>?lhs\<close> show ?thesis by simp
   223   next
   224     case False
   225     from \<open>?lhs\<close> have "a \<in># N + {#b#}" by (rule union_single_eq_member)
   226     with False have "a \<in># N" by auto
   227     moreover from \<open>?lhs\<close> have "M = N + {#b#} - {#a#}" by (rule union_single_eq_diff)
   228     moreover note False
   229     ultimately show ?thesis by (auto simp add: diff_right_commute [of _ "{#a#}"] diff_union_swap)
   230   qed
   231 qed
   232 
   233 lemma insert_noteq_member:
   234   assumes BC: "B + {#b#} = C + {#c#}"
   235    and bnotc: "b \<noteq> c"
   236   shows "c \<in># B"
   237 proof -
   238   have "c \<in># C + {#c#}" by simp
   239   have nc: "\<not> c \<in># {#b#}" using bnotc by simp
   240   then have "c \<in># B + {#b#}" using BC by simp
   241   then show "c \<in># B" using nc by simp
   242 qed
   243 
   244 lemma add_eq_conv_ex:
   245   "(M + {#a#} = N + {#b#}) =
   246     (M = N \<and> a = b \<or> (\<exists>K. M = K + {#b#} \<and> N = K + {#a#}))"
   247   by (auto simp add: add_eq_conv_diff)
   248 
   249 lemma multi_member_split: "x \<in># M \<Longrightarrow> \<exists>A. M = A + {#x#}"
   250   by (rule_tac x = "M - {#x#}" in exI, simp)
   251 
   252 lemma multiset_add_sub_el_shuffle:
   253   assumes "c \<in># B"
   254     and "b \<noteq> c"
   255   shows "B - {#c#} + {#b#} = B + {#b#} - {#c#}"
   256 proof -
   257   from \<open>c \<in># B\<close> obtain A where B: "B = A + {#c#}"
   258     by (blast dest: multi_member_split)
   259   have "A + {#b#} = A + {#b#} + {#c#} - {#c#}" by simp
   260   then have "A + {#b#} = A + {#c#} + {#b#} - {#c#}"
   261     by (simp add: ac_simps)
   262   then show ?thesis using B by simp
   263 qed
   264 
   265 
   266 subsubsection \<open>Pointwise ordering induced by count\<close>
   267 
   268 definition subseteq_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<=#" 50) where
   269 "subseteq_mset A B = (\<forall>a. count A a \<le> count B a)"
   270 
   271 definition subset_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<#" 50) where
   272 "subset_mset A B = (A <=# B \<and> A \<noteq> B)"
   273 
   274 notation subseteq_mset (infix "\<le>#" 50)
   275 notation (xsymbols) subseteq_mset (infix "\<subseteq>#" 50)
   276 
   277 notation (xsymbols) subset_mset (infix "\<subset>#" 50)
   278 
   279 interpretation subset_mset: ordered_ab_semigroup_add_imp_le "op +" "op -" "op \<subseteq>#" "op \<subset>#"
   280   by default (auto simp add: subset_mset_def subseteq_mset_def multiset_eq_iff intro: order_trans antisym)
   281 
   282 lemma mset_less_eqI: "(\<And>x. count A x \<le> count B x) \<Longrightarrow> A \<le># B"
   283   by (simp add: subseteq_mset_def)
   284 
   285 lemma mset_le_exists_conv: "(A::'a multiset) \<le># B \<longleftrightarrow> (\<exists>C. B = A + C)"
   286 apply (unfold subseteq_mset_def, rule iffI, rule_tac x = "B - A" in exI)
   287 apply (auto intro: multiset_eq_iff [THEN iffD2])
   288 done
   289 
   290 interpretation subset_mset: ordered_cancel_comm_monoid_diff  "op +" "op -" 0 "op \<le>#" "op <#"
   291   by default (simp, fact mset_le_exists_conv)
   292 
   293 lemma mset_le_mono_add_right_cancel [simp]: "(A::'a multiset) + C \<le># B + C \<longleftrightarrow> A \<le># B"
   294   by (fact subset_mset.add_le_cancel_right)
   295 
   296 lemma mset_le_mono_add_left_cancel [simp]: "C + (A::'a multiset) \<le># C + B \<longleftrightarrow> A \<le># B"
   297   by (fact subset_mset.add_le_cancel_left)
   298 
   299 lemma mset_le_mono_add: "(A::'a multiset) \<le># B \<Longrightarrow> C \<le># D \<Longrightarrow> A + C \<le># B + D"
   300   by (fact subset_mset.add_mono)
   301 
   302 lemma mset_le_add_left [simp]: "(A::'a multiset) \<le># A + B"
   303   unfolding subseteq_mset_def by auto
   304 
   305 lemma mset_le_add_right [simp]: "B \<le># (A::'a multiset) + B"
   306   unfolding subseteq_mset_def by auto
   307 
   308 lemma mset_le_single: "a :# B \<Longrightarrow> {#a#} \<le># B"
   309   by (simp add: subseteq_mset_def)
   310 
   311 lemma multiset_diff_union_assoc:
   312   fixes A B C D :: "'a multiset"
   313   shows "C \<le># B \<Longrightarrow> A + B - C = A + (B - C)"
   314   by (simp add: subset_mset.diff_add_assoc)
   315 
   316 lemma mset_le_multiset_union_diff_commute:
   317   fixes A B C D :: "'a multiset"
   318   shows "B \<le># A \<Longrightarrow> A - B + C = A + C - B"
   319 by (simp add: subset_mset.add_diff_assoc2)
   320 
   321 lemma diff_le_self[simp]: "(M::'a multiset) - N \<le># M"
   322 by(simp add: subseteq_mset_def)
   323 
   324 lemma mset_lessD: "A <# B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
   325 apply (clarsimp simp: subset_mset_def subseteq_mset_def)
   326 apply (erule_tac x=x in allE)
   327 apply auto
   328 done
   329 
   330 lemma mset_leD: "A \<le># B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
   331 apply (clarsimp simp: subset_mset_def subseteq_mset_def)
   332 apply (erule_tac x = x in allE)
   333 apply auto
   334 done
   335 
   336 lemma mset_less_insertD: "(A + {#x#} <# B) \<Longrightarrow> (x \<in># B \<and> A <# B)"
   337 apply (rule conjI)
   338  apply (simp add: mset_lessD)
   339 apply (clarsimp simp: subset_mset_def subseteq_mset_def)
   340 apply safe
   341  apply (erule_tac x = a in allE)
   342  apply (auto split: split_if_asm)
   343 done
   344 
   345 lemma mset_le_insertD: "(A + {#x#} \<le># B) \<Longrightarrow> (x \<in># B \<and> A \<le># B)"
   346 apply (rule conjI)
   347  apply (simp add: mset_leD)
   348 apply (force simp: subset_mset_def subseteq_mset_def split: split_if_asm)
   349 done
   350 
   351 lemma mset_less_of_empty[simp]: "A <# {#} \<longleftrightarrow> False"
   352   by (auto simp add: subseteq_mset_def subset_mset_def multiset_eq_iff)
   353 
   354 lemma empty_le[simp]: "{#} \<le># A"
   355   unfolding mset_le_exists_conv by auto
   356 
   357 lemma le_empty[simp]: "(M \<le># {#}) = (M = {#})"
   358   unfolding mset_le_exists_conv by auto
   359 
   360 lemma multi_psub_of_add_self[simp]: "A <# A + {#x#}"
   361   by (auto simp: subset_mset_def subseteq_mset_def)
   362 
   363 lemma multi_psub_self[simp]: "(A::'a multiset) <# A = False"
   364   by simp
   365 
   366 lemma mset_less_add_bothsides: "N + {#x#} <# M + {#x#} \<Longrightarrow> N <# M"
   367   by (fact subset_mset.add_less_imp_less_right)
   368 
   369 lemma mset_less_empty_nonempty: "{#} <# S \<longleftrightarrow> S \<noteq> {#}"
   370   by (auto simp: subset_mset_def subseteq_mset_def)
   371 
   372 lemma mset_less_diff_self: "c \<in># B \<Longrightarrow> B - {#c#} <# B"
   373   by (auto simp: subset_mset_def subseteq_mset_def multiset_eq_iff)
   374 
   375 
   376 subsubsection \<open>Intersection\<close>
   377 
   378 definition inf_subset_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<inter>" 70) where
   379   multiset_inter_def: "inf_subset_mset A B = A - (A - B)"
   380 
   381 interpretation subset_mset: semilattice_inf inf_subset_mset "op \<le>#" "op <#"
   382 proof -
   383    have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> m \<le> q \<Longrightarrow> m \<le> n - (n - q)" by arith
   384    show "class.semilattice_inf op #\<inter> op \<le># op <#"
   385      by default (auto simp add: multiset_inter_def subseteq_mset_def aux)
   386 qed
   387 
   388 
   389 lemma multiset_inter_count [simp]:
   390   fixes A B :: "'a multiset"
   391   shows "count (A #\<inter> B) x = min (count A x) (count B x)"
   392   by (simp add: multiset_inter_def)
   393 
   394 lemma multiset_inter_single: "a \<noteq> b \<Longrightarrow> {#a#} #\<inter> {#b#} = {#}"
   395   by (rule multiset_eqI) auto
   396 
   397 lemma multiset_union_diff_commute:
   398   assumes "B #\<inter> C = {#}"
   399   shows "A + B - C = A - C + B"
   400 proof (rule multiset_eqI)
   401   fix x
   402   from assms have "min (count B x) (count C x) = 0"
   403     by (auto simp add: multiset_eq_iff)
   404   then have "count B x = 0 \<or> count C x = 0"
   405     by auto
   406   then show "count (A + B - C) x = count (A - C + B) x"
   407     by auto
   408 qed
   409 
   410 lemma empty_inter [simp]: "{#} #\<inter> M = {#}"
   411   by (simp add: multiset_eq_iff)
   412 
   413 lemma inter_empty [simp]: "M #\<inter> {#} = {#}"
   414   by (simp add: multiset_eq_iff)
   415 
   416 lemma inter_add_left1: "\<not> x \<in># N \<Longrightarrow> (M + {#x#}) #\<inter> N = M #\<inter> N"
   417   by (simp add: multiset_eq_iff)
   418 
   419 lemma inter_add_left2: "x \<in># N \<Longrightarrow> (M + {#x#}) #\<inter> N = (M #\<inter> (N - {#x#})) + {#x#}"
   420   by (simp add: multiset_eq_iff)
   421 
   422 lemma inter_add_right1: "\<not> x \<in># N \<Longrightarrow> N #\<inter> (M + {#x#}) = N #\<inter> M"
   423   by (simp add: multiset_eq_iff)
   424 
   425 lemma inter_add_right2: "x \<in># N \<Longrightarrow> N #\<inter> (M + {#x#}) = ((N - {#x#}) #\<inter> M) + {#x#}"
   426   by (simp add: multiset_eq_iff)
   427 
   428 
   429 subsubsection \<open>Bounded union\<close>
   430 definition sup_subset_mset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset"(infixl "#\<union>" 70)  where
   431   "sup_subset_mset A B = A + (B - A)"
   432 
   433 interpretation subset_mset: semilattice_sup sup_subset_mset "op \<le>#" "op <#"
   434 proof -
   435   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> q \<le> n \<Longrightarrow> m + (q - m) \<le> n" by arith
   436   show "class.semilattice_sup op #\<union> op \<le># op <#"
   437     by default (auto simp add: sup_subset_mset_def subseteq_mset_def aux)
   438 qed
   439 
   440 lemma sup_subset_mset_count [simp]: "count (A #\<union> B) x = max (count A x) (count B x)"
   441   by (simp add: sup_subset_mset_def)
   442 
   443 lemma empty_sup [simp]: "{#} #\<union> M = M"
   444   by (simp add: multiset_eq_iff)
   445 
   446 lemma sup_empty [simp]: "M #\<union> {#} = M"
   447   by (simp add: multiset_eq_iff)
   448 
   449 lemma sup_add_left1: "\<not> x \<in># N \<Longrightarrow> (M + {#x#}) #\<union> N = (M #\<union> N) + {#x#}"
   450   by (simp add: multiset_eq_iff)
   451 
   452 lemma sup_add_left2: "x \<in># N \<Longrightarrow> (M + {#x#}) #\<union> N = (M #\<union> (N - {#x#})) + {#x#}"
   453   by (simp add: multiset_eq_iff)
   454 
   455 lemma sup_add_right1: "\<not> x \<in># N \<Longrightarrow> N #\<union> (M + {#x#}) = (N #\<union> M) + {#x#}"
   456   by (simp add: multiset_eq_iff)
   457 
   458 lemma sup_add_right2: "x \<in># N \<Longrightarrow> N #\<union> (M + {#x#}) = ((N - {#x#}) #\<union> M) + {#x#}"
   459   by (simp add: multiset_eq_iff)
   460 
   461 subsubsection \<open>Subset is an order\<close>
   462 interpretation subset_mset: order "op \<le>#" "op <#" by unfold_locales auto
   463 
   464 subsubsection \<open>Filter (with comprehension syntax)\<close>
   465 
   466 text \<open>Multiset comprehension\<close>
   467 
   468 lift_definition filter_mset :: "('a \<Rightarrow> bool) \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset"
   469 is "\<lambda>P M. \<lambda>x. if P x then M x else 0"
   470 by (rule filter_preserves_multiset)
   471 
   472 lemma count_filter_mset [simp]: "count (filter_mset P M) a = (if P a then count M a else 0)"
   473   by (simp add: filter_mset.rep_eq)
   474 
   475 lemma filter_empty_mset [simp]: "filter_mset P {#} = {#}"
   476   by (rule multiset_eqI) simp
   477 
   478 lemma filter_single_mset [simp]: "filter_mset P {#x#} = (if P x then {#x#} else {#})"
   479   by (rule multiset_eqI) simp
   480 
   481 lemma filter_union_mset [simp]: "filter_mset P (M + N) = filter_mset P M + filter_mset P N"
   482   by (rule multiset_eqI) simp
   483 
   484 lemma filter_diff_mset [simp]: "filter_mset P (M - N) = filter_mset P M - filter_mset P N"
   485   by (rule multiset_eqI) simp
   486 
   487 lemma filter_inter_mset [simp]: "filter_mset P (M #\<inter> N) = filter_mset P M #\<inter> filter_mset P N"
   488   by (rule multiset_eqI) simp
   489 
   490 lemma multiset_filter_subset[simp]: "filter_mset f M \<le># M"
   491   by (simp add: mset_less_eqI)
   492 
   493 lemma multiset_filter_mono:
   494   assumes "A \<le># B"
   495   shows "filter_mset f A \<le># filter_mset f B"
   496 proof -
   497   from assms[unfolded mset_le_exists_conv]
   498   obtain C where B: "B = A + C" by auto
   499   show ?thesis unfolding B by auto
   500 qed
   501 
   502 syntax
   503   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ :# _./ _#})")
   504 syntax (xsymbol)
   505   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ \<in># _./ _#})")
   506 translations
   507   "{#x \<in># M. P#}" == "CONST filter_mset (\<lambda>x. P) M"
   508 
   509 
   510 subsubsection \<open>Set of elements\<close>
   511 
   512 definition set_mset :: "'a multiset \<Rightarrow> 'a set"
   513   where "set_mset M = {x. x :# M}"
   514 
   515 lemma set_mset_empty [simp]: "set_mset {#} = {}"
   516 by (simp add: set_mset_def)
   517 
   518 lemma set_mset_single [simp]: "set_mset {#b#} = {b}"
   519 by (simp add: set_mset_def)
   520 
   521 lemma set_mset_union [simp]: "set_mset (M + N) = set_mset M \<union> set_mset N"
   522 by (auto simp add: set_mset_def)
   523 
   524 lemma set_mset_eq_empty_iff [simp]: "(set_mset M = {}) = (M = {#})"
   525 by (auto simp add: set_mset_def multiset_eq_iff)
   526 
   527 lemma mem_set_mset_iff [simp]: "(x \<in> set_mset M) = (x :# M)"
   528 by (auto simp add: set_mset_def)
   529 
   530 lemma set_mset_filter [simp]: "set_mset {# x:#M. P x #} = set_mset M \<inter> {x. P x}"
   531 by (auto simp add: set_mset_def)
   532 
   533 lemma finite_set_mset [iff]: "finite (set_mset M)"
   534   using count [of M] by (simp add: multiset_def set_mset_def)
   535 
   536 lemma finite_Collect_mem [iff]: "finite {x. x :# M}"
   537   unfolding set_mset_def[symmetric] by simp
   538 
   539 lemma set_mset_mono: "A \<le># B \<Longrightarrow> set_mset A \<subseteq> set_mset B"
   540   by (metis mset_leD subsetI mem_set_mset_iff)
   541 
   542 lemma ball_set_mset_iff: "(\<forall>x \<in> set_mset M. P x) \<longleftrightarrow> (\<forall>x. x \<in># M \<longrightarrow> P x)"
   543   by auto
   544 
   545 
   546 subsubsection \<open>Size\<close>
   547 
   548 definition wcount where "wcount f M = (\<lambda>x. count M x * Suc (f x))"
   549 
   550 lemma wcount_union: "wcount f (M + N) a = wcount f M a + wcount f N a"
   551   by (auto simp: wcount_def add_mult_distrib)
   552 
   553 definition size_multiset :: "('a \<Rightarrow> nat) \<Rightarrow> 'a multiset \<Rightarrow> nat" where
   554   "size_multiset f M = setsum (wcount f M) (set_mset M)"
   555 
   556 lemmas size_multiset_eq = size_multiset_def[unfolded wcount_def]
   557 
   558 instantiation multiset :: (type) size
   559 begin
   560 
   561 definition size_multiset where
   562   size_multiset_overloaded_def: "size_multiset = Multiset.size_multiset (\<lambda>_. 0)"
   563 instance ..
   564 
   565 end
   566 
   567 lemmas size_multiset_overloaded_eq =
   568   size_multiset_overloaded_def[THEN fun_cong, unfolded size_multiset_eq, simplified]
   569 
   570 lemma size_multiset_empty [simp]: "size_multiset f {#} = 0"
   571 by (simp add: size_multiset_def)
   572 
   573 lemma size_empty [simp]: "size {#} = 0"
   574 by (simp add: size_multiset_overloaded_def)
   575 
   576 lemma size_multiset_single [simp]: "size_multiset f {#b#} = Suc (f b)"
   577 by (simp add: size_multiset_eq)
   578 
   579 lemma size_single [simp]: "size {#b#} = 1"
   580 by (simp add: size_multiset_overloaded_def)
   581 
   582 lemma setsum_wcount_Int:
   583   "finite A \<Longrightarrow> setsum (wcount f N) (A \<inter> set_mset N) = setsum (wcount f N) A"
   584 apply (induct rule: finite_induct)
   585  apply simp
   586 apply (simp add: Int_insert_left set_mset_def wcount_def)
   587 done
   588 
   589 lemma size_multiset_union [simp]:
   590   "size_multiset f (M + N::'a multiset) = size_multiset f M + size_multiset f N"
   591 apply (simp add: size_multiset_def setsum_Un_nat setsum.distrib setsum_wcount_Int wcount_union)
   592 apply (subst Int_commute)
   593 apply (simp add: setsum_wcount_Int)
   594 done
   595 
   596 lemma size_union [simp]: "size (M + N::'a multiset) = size M + size N"
   597 by (auto simp add: size_multiset_overloaded_def)
   598 
   599 lemma size_multiset_eq_0_iff_empty [iff]: "(size_multiset f M = 0) = (M = {#})"
   600 by (auto simp add: size_multiset_eq multiset_eq_iff)
   601 
   602 lemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})"
   603 by (auto simp add: size_multiset_overloaded_def)
   604 
   605 lemma nonempty_has_size: "(S \<noteq> {#}) = (0 < size S)"
   606 by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)
   607 
   608 lemma size_eq_Suc_imp_elem: "size M = Suc n \<Longrightarrow> \<exists>a. a :# M"
   609 apply (unfold size_multiset_overloaded_eq)
   610 apply (drule setsum_SucD)
   611 apply auto
   612 done
   613 
   614 lemma size_eq_Suc_imp_eq_union:
   615   assumes "size M = Suc n"
   616   shows "\<exists>a N. M = N + {#a#}"
   617 proof -
   618   from assms obtain a where "a \<in># M"
   619     by (erule size_eq_Suc_imp_elem [THEN exE])
   620   then have "M = M - {#a#} + {#a#}" by simp
   621   then show ?thesis by blast
   622 qed
   623 
   624 lemma size_mset_mono:
   625   fixes A B :: "'a multiset"
   626   assumes "A \<le># B"
   627   shows "size A \<le> size B"
   628 proof -
   629   from assms[unfolded mset_le_exists_conv]
   630   obtain C where B: "B = A + C" by auto
   631   show ?thesis unfolding B by (induct C) auto
   632 qed
   633 
   634 lemma size_filter_mset_lesseq[simp]: "size (filter_mset f M) \<le> size M"
   635 by (rule size_mset_mono[OF multiset_filter_subset])
   636 
   637 lemma size_Diff_submset:
   638   "M \<le># M' \<Longrightarrow> size (M' - M) = size M' - size(M::'a multiset)"
   639 by (metis add_diff_cancel_left' size_union mset_le_exists_conv)
   640 
   641 subsection \<open>Induction and case splits\<close>
   642 
   643 theorem multiset_induct [case_names empty add, induct type: multiset]:
   644   assumes empty: "P {#}"
   645   assumes add: "\<And>M x. P M \<Longrightarrow> P (M + {#x#})"
   646   shows "P M"
   647 proof (induct n \<equiv> "size M" arbitrary: M)
   648   case 0 thus "P M" by (simp add: empty)
   649 next
   650   case (Suc k)
   651   obtain N x where "M = N + {#x#}"
   652     using \<open>Suc k = size M\<close> [symmetric]
   653     using size_eq_Suc_imp_eq_union by fast
   654   with Suc add show "P M" by simp
   655 qed
   656 
   657 lemma multi_nonempty_split: "M \<noteq> {#} \<Longrightarrow> \<exists>A a. M = A + {#a#}"
   658 by (induct M) auto
   659 
   660 lemma multiset_cases [cases type]:
   661   obtains (empty) "M = {#}"
   662     | (add) N x where "M = N + {#x#}"
   663   using assms by (induct M) simp_all
   664 
   665 lemma multi_drop_mem_not_eq: "c \<in># B \<Longrightarrow> B - {#c#} \<noteq> B"
   666 by (cases "B = {#}") (auto dest: multi_member_split)
   667 
   668 lemma multiset_partition: "M = {# x:#M. P x #} + {# x:#M. \<not> P x #}"
   669 apply (subst multiset_eq_iff)
   670 apply auto
   671 done
   672 
   673 lemma mset_less_size: "(A::'a multiset) <# B \<Longrightarrow> size A < size B"
   674 proof (induct A arbitrary: B)
   675   case (empty M)
   676   then have "M \<noteq> {#}" by (simp add: mset_less_empty_nonempty)
   677   then obtain M' x where "M = M' + {#x#}"
   678     by (blast dest: multi_nonempty_split)
   679   then show ?case by simp
   680 next
   681   case (add S x T)
   682   have IH: "\<And>B. S <# B \<Longrightarrow> size S < size B" by fact
   683   have SxsubT: "S + {#x#} <# T" by fact
   684   then have "x \<in># T" and "S <# T" by (auto dest: mset_less_insertD)
   685   then obtain T' where T: "T = T' + {#x#}"
   686     by (blast dest: multi_member_split)
   687   then have "S <# T'" using SxsubT
   688     by (blast intro: mset_less_add_bothsides)
   689   then have "size S < size T'" using IH by simp
   690   then show ?case using T by simp
   691 qed
   692 
   693 
   694 lemma size_1_singleton_mset: "size M = 1 \<Longrightarrow> \<exists>a. M = {#a#}"
   695 by (cases M) auto
   696 
   697 subsubsection \<open>Strong induction and subset induction for multisets\<close>
   698 
   699 text \<open>Well-foundedness of strict subset relation\<close>
   700 
   701 lemma wf_less_mset_rel: "wf {(M, N :: 'a multiset). M <# N}"
   702 apply (rule wf_measure [THEN wf_subset, where f1=size])
   703 apply (clarsimp simp: measure_def inv_image_def mset_less_size)
   704 done
   705 
   706 lemma full_multiset_induct [case_names less]:
   707 assumes ih: "\<And>B. \<forall>(A::'a multiset). A <# B \<longrightarrow> P A \<Longrightarrow> P B"
   708 shows "P B"
   709 apply (rule wf_less_mset_rel [THEN wf_induct])
   710 apply (rule ih, auto)
   711 done
   712 
   713 lemma multi_subset_induct [consumes 2, case_names empty add]:
   714   assumes "F \<le># A"
   715     and empty: "P {#}"
   716     and insert: "\<And>a F. a \<in># A \<Longrightarrow> P F \<Longrightarrow> P (F + {#a#})"
   717   shows "P F"
   718 proof -
   719   from \<open>F \<le># A\<close>
   720   show ?thesis
   721   proof (induct F)
   722     show "P {#}" by fact
   723   next
   724     fix x F
   725     assume P: "F \<le># A \<Longrightarrow> P F" and i: "F + {#x#} \<le># A"
   726     show "P (F + {#x#})"
   727     proof (rule insert)
   728       from i show "x \<in># A" by (auto dest: mset_le_insertD)
   729       from i have "F \<le># A" by (auto dest: mset_le_insertD)
   730       with P show "P F" .
   731     qed
   732   qed
   733 qed
   734 
   735 
   736 subsection \<open>The fold combinator\<close>
   737 
   738 definition fold_mset :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b"
   739 where
   740   "fold_mset f s M = Finite_Set.fold (\<lambda>x. f x ^^ count M x) s (set_mset M)"
   741 
   742 lemma fold_mset_empty [simp]: "fold_mset f s {#} = s"
   743   by (simp add: fold_mset_def)
   744 
   745 context comp_fun_commute
   746 begin
   747 
   748 lemma fold_mset_insert: "fold_mset f s (M + {#x#}) = f x (fold_mset f s M)"
   749 proof -
   750   interpret mset: comp_fun_commute "\<lambda>y. f y ^^ count M y"
   751     by (fact comp_fun_commute_funpow)
   752   interpret mset_union: comp_fun_commute "\<lambda>y. f y ^^ count (M + {#x#}) y"
   753     by (fact comp_fun_commute_funpow)
   754   show ?thesis
   755   proof (cases "x \<in> set_mset M")
   756     case False
   757     then have *: "count (M + {#x#}) x = 1" by simp
   758     from False have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s (set_mset M) =
   759       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s (set_mset M)"
   760       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
   761     with False * show ?thesis
   762       by (simp add: fold_mset_def del: count_union)
   763   next
   764     case True
   765     def N \<equiv> "set_mset M - {x}"
   766     from N_def True have *: "set_mset M = insert x N" "x \<notin> N" "finite N" by auto
   767     then have "Finite_Set.fold (\<lambda>y. f y ^^ count (M + {#x#}) y) s N =
   768       Finite_Set.fold (\<lambda>y. f y ^^ count M y) s N"
   769       by (auto intro!: Finite_Set.fold_cong comp_fun_commute_funpow)
   770     with * show ?thesis by (simp add: fold_mset_def del: count_union) simp
   771   qed
   772 qed
   773 
   774 corollary fold_mset_single [simp]: "fold_mset f s {#x#} = f x s"
   775 proof -
   776   have "fold_mset f s ({#} + {#x#}) = f x s" by (simp only: fold_mset_insert) simp
   777   then show ?thesis by simp
   778 qed
   779 
   780 lemma fold_mset_fun_left_comm: "f x (fold_mset f s M) = fold_mset f (f x s) M"
   781   by (induct M) (simp_all add: fold_mset_insert fun_left_comm)
   782 
   783 lemma fold_mset_union [simp]: "fold_mset f s (M + N) = fold_mset f (fold_mset f s M) N"
   784 proof (induct M)
   785   case empty then show ?case by simp
   786 next
   787   case (add M x)
   788   have "M + {#x#} + N = (M + N) + {#x#}"
   789     by (simp add: ac_simps)
   790   with add show ?case by (simp add: fold_mset_insert fold_mset_fun_left_comm)
   791 qed
   792 
   793 lemma fold_mset_fusion:
   794   assumes "comp_fun_commute g"
   795     and *: "\<And>x y. h (g x y) = f x (h y)"
   796   shows "h (fold_mset g w A) = fold_mset f (h w) A"
   797 proof -
   798   interpret comp_fun_commute g by (fact assms)
   799   from * show ?thesis by (induct A) auto
   800 qed
   801 
   802 end
   803 
   804 text \<open>
   805   A note on code generation: When defining some function containing a
   806   subterm @{term "fold_mset F"}, code generation is not automatic. When
   807   interpreting locale @{text left_commutative} with @{text F}, the
   808   would be code thms for @{const fold_mset} become thms like
   809   @{term "fold_mset F z {#} = z"} where @{text F} is not a pattern but
   810   contains defined symbols, i.e.\ is not a code thm. Hence a separate
   811   constant with its own code thms needs to be introduced for @{text
   812   F}. See the image operator below.
   813 \<close>
   814 
   815 
   816 subsection \<open>Image\<close>
   817 
   818 definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where
   819   "image_mset f = fold_mset (plus o single o f) {#}"
   820 
   821 lemma comp_fun_commute_mset_image: "comp_fun_commute (plus o single o f)"
   822 proof
   823 qed (simp add: ac_simps fun_eq_iff)
   824 
   825 lemma image_mset_empty [simp]: "image_mset f {#} = {#}"
   826   by (simp add: image_mset_def)
   827 
   828 lemma image_mset_single [simp]: "image_mset f {#x#} = {#f x#}"
   829 proof -
   830   interpret comp_fun_commute "plus o single o f"
   831     by (fact comp_fun_commute_mset_image)
   832   show ?thesis by (simp add: image_mset_def)
   833 qed
   834 
   835 lemma image_mset_union [simp]: "image_mset f (M + N) = image_mset f M + image_mset f N"
   836 proof -
   837   interpret comp_fun_commute "plus o single o f"
   838     by (fact comp_fun_commute_mset_image)
   839   show ?thesis by (induct N) (simp_all add: image_mset_def ac_simps)
   840 qed
   841 
   842 corollary image_mset_insert: "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"
   843   by simp
   844 
   845 lemma set_image_mset [simp]: "set_mset (image_mset f M) = image f (set_mset M)"
   846   by (induct M) simp_all
   847 
   848 lemma size_image_mset [simp]: "size (image_mset f M) = size M"
   849   by (induct M) simp_all
   850 
   851 lemma image_mset_is_empty_iff [simp]: "image_mset f M = {#} \<longleftrightarrow> M = {#}"
   852   by (cases M) auto
   853 
   854 syntax
   855   "_comprehension1_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
   856       ("({#_/. _ :# _#})")
   857 translations
   858   "{#e. x:#M#}" == "CONST image_mset (\<lambda>x. e) M"
   859 
   860 syntax (xsymbols)
   861   "_comprehension2_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
   862       ("({#_/. _ \<in># _#})")
   863 translations
   864   "{#e. x \<in># M#}" == "CONST image_mset (\<lambda>x. e) M"
   865 
   866 syntax
   867   "_comprehension3_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
   868       ("({#_/ | _ :# _./ _#})")
   869 translations
   870   "{#e | x:#M. P#}" \<rightharpoonup> "{#e. x :# {# x:#M. P#}#}"
   871 
   872 syntax
   873   "_comprehension4_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
   874       ("({#_/ | _ \<in># _./ _#})")
   875 translations
   876   "{#e | x\<in>#M. P#}" \<rightharpoonup> "{#e. x \<in># {# x\<in>#M. P#}#}"
   877 
   878 text \<open>
   879   This allows to write not just filters like @{term "{#x:#M. x<c#}"}
   880   but also images like @{term "{#x+x. x:#M #}"} and @{term [source]
   881   "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as
   882   @{term "{#x+x|x:#M. x<c#}"}.
   883 \<close>
   884 
   885 lemma in_image_mset: "y \<in># {#f x. x \<in># M#} \<longleftrightarrow> y \<in> f ` set_mset M"
   886 by (metis mem_set_mset_iff set_image_mset)
   887 
   888 functor image_mset: image_mset
   889 proof -
   890   fix f g show "image_mset f \<circ> image_mset g = image_mset (f \<circ> g)"
   891   proof
   892     fix A
   893     show "(image_mset f \<circ> image_mset g) A = image_mset (f \<circ> g) A"
   894       by (induct A) simp_all
   895   qed
   896   show "image_mset id = id"
   897   proof
   898     fix A
   899     show "image_mset id A = id A"
   900       by (induct A) simp_all
   901   qed
   902 qed
   903 
   904 declare
   905   image_mset.id [simp]
   906   image_mset.identity [simp]
   907 
   908 lemma image_mset_id[simp]: "image_mset id x = x"
   909   unfolding id_def by auto
   910 
   911 lemma image_mset_cong: "(\<And>x. x \<in># M \<Longrightarrow> f x = g x) \<Longrightarrow> {#f x. x \<in># M#} = {#g x. x \<in># M#}"
   912   by (induct M) auto
   913 
   914 lemma image_mset_cong_pair:
   915   "(\<forall>x y. (x, y) \<in># M \<longrightarrow> f x y = g x y) \<Longrightarrow> {#f x y. (x, y) \<in># M#} = {#g x y. (x, y) \<in># M#}"
   916   by (metis image_mset_cong split_cong)
   917 
   918 
   919 subsection \<open>Further conversions\<close>
   920 
   921 primrec mset :: "'a list \<Rightarrow> 'a multiset" where
   922   "mset [] = {#}" |
   923   "mset (a # x) = mset x + {# a #}"
   924 
   925 lemma in_multiset_in_set:
   926   "x \<in># mset xs \<longleftrightarrow> x \<in> set xs"
   927   by (induct xs) simp_all
   928 
   929 lemma count_mset:
   930   "count (mset xs) x = length (filter (\<lambda>y. x = y) xs)"
   931   by (induct xs) simp_all
   932 
   933 lemma mset_zero_iff[simp]: "(mset x = {#}) = (x = [])"
   934   by (induct x) auto
   935 
   936 lemma mset_zero_iff_right[simp]: "({#} = mset x) = (x = [])"
   937 by (induct x) auto
   938 
   939 lemma set_mset_mset[simp]: "set_mset (mset x) = set x"
   940 by (induct x) auto
   941 
   942 lemma mem_set_multiset_eq: "x \<in> set xs = (x :# mset xs)"
   943 by (induct xs) auto
   944 
   945 lemma size_mset [simp]: "size (mset xs) = length xs"
   946   by (induct xs) simp_all
   947 
   948 lemma mset_append [simp]: "mset (xs @ ys) = mset xs + mset ys"
   949   by (induct xs arbitrary: ys) (auto simp: ac_simps)
   950 
   951 lemma mset_filter: "mset (filter P xs) = {#x :# mset xs. P x #}"
   952   by (induct xs) simp_all
   953 
   954 lemma mset_rev [simp]:
   955   "mset (rev xs) = mset xs"
   956   by (induct xs) simp_all
   957 
   958 lemma surj_mset: "surj mset"
   959 apply (unfold surj_def)
   960 apply (rule allI)
   961 apply (rule_tac M = y in multiset_induct)
   962  apply auto
   963 apply (rule_tac x = "x # xa" in exI)
   964 apply auto
   965 done
   966 
   967 lemma set_count_greater_0: "set x = {a. count (mset x) a > 0}"
   968 by (induct x) auto
   969 
   970 lemma distinct_count_atmost_1:
   971   "distinct x = (\<forall>a. count (mset x) a = (if a \<in> set x then 1 else 0))"
   972 apply (induct x, simp, rule iffI, simp_all)
   973 apply (rename_tac a b)
   974 apply (rule conjI)
   975 apply (simp_all add: set_mset_mset [THEN sym] del: set_mset_mset)
   976 apply (erule_tac x = a in allE, simp, clarify)
   977 apply (erule_tac x = aa in allE, simp)
   978 done
   979 
   980 lemma mset_eq_setD: "mset xs = mset ys \<Longrightarrow> set xs = set ys"
   981 by (rule) (auto simp add:multiset_eq_iff set_count_greater_0)
   982 
   983 lemma set_eq_iff_mset_eq_distinct:
   984   "distinct x \<Longrightarrow> distinct y \<Longrightarrow>
   985     (set x = set y) = (mset x = mset y)"
   986 by (auto simp: multiset_eq_iff distinct_count_atmost_1)
   987 
   988 lemma set_eq_iff_mset_remdups_eq:
   989    "(set x = set y) = (mset (remdups x) = mset (remdups y))"
   990 apply (rule iffI)
   991 apply (simp add: set_eq_iff_mset_eq_distinct[THEN iffD1])
   992 apply (drule distinct_remdups [THEN distinct_remdups
   993       [THEN set_eq_iff_mset_eq_distinct [THEN iffD2]]])
   994 apply simp
   995 done
   996 
   997 lemma mset_compl_union [simp]: "mset [x\<leftarrow>xs. P x] + mset [x\<leftarrow>xs. \<not>P x] = mset xs"
   998   by (induct xs) (auto simp: ac_simps)
   999 
  1000 lemma nth_mem_mset: "i < length ls \<Longrightarrow> (ls ! i) :# mset ls"
  1001 apply (induct ls arbitrary: i)
  1002  apply simp
  1003 apply (case_tac i)
  1004  apply auto
  1005 done
  1006 
  1007 lemma mset_remove1[simp]: "mset (remove1 a xs) = mset xs - {#a#}"
  1008 by (induct xs) (auto simp add: multiset_eq_iff)
  1009 
  1010 lemma mset_eq_length:
  1011   assumes "mset xs = mset ys"
  1012   shows "length xs = length ys"
  1013   using assms by (metis size_mset)
  1014 
  1015 lemma mset_eq_length_filter:
  1016   assumes "mset xs = mset ys"
  1017   shows "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) ys)"
  1018   using assms by (metis count_mset)
  1019 
  1020 lemma fold_multiset_equiv:
  1021   assumes f: "\<And>x y. x \<in> set xs \<Longrightarrow> y \<in> set xs \<Longrightarrow> f x \<circ> f y = f y \<circ> f x"
  1022     and equiv: "mset xs = mset ys"
  1023   shows "List.fold f xs = List.fold f ys"
  1024   using f equiv [symmetric]
  1025 proof (induct xs arbitrary: ys)
  1026   case Nil then show ?case by simp
  1027 next
  1028   case (Cons x xs)
  1029   then have *: "set ys = set (x # xs)" by (blast dest: mset_eq_setD)
  1030   have "\<And>x y. x \<in> set ys \<Longrightarrow> y \<in> set ys \<Longrightarrow> f x \<circ> f y = f y \<circ> f x"
  1031     by (rule Cons.prems(1)) (simp_all add: *)
  1032   moreover from * have "x \<in> set ys" by simp
  1033   ultimately have "List.fold f ys = List.fold f (remove1 x ys) \<circ> f x" by (fact fold_remove1_split)
  1034   moreover from Cons.prems have "List.fold f xs = List.fold f (remove1 x ys)" by (auto intro: Cons.hyps)
  1035   ultimately show ?case by simp
  1036 qed
  1037 
  1038 lemma mset_insort [simp]: "mset (insort x xs) = mset xs + {#x#}"
  1039   by (induct xs) (simp_all add: ac_simps)
  1040 
  1041 lemma mset_map: "mset (map f xs) = image_mset f (mset xs)"
  1042   by (induct xs) simp_all
  1043 
  1044 definition mset_set :: "'a set \<Rightarrow> 'a multiset"
  1045 where
  1046   "mset_set = folding.F (\<lambda>x M. {#x#} + M) {#}"
  1047 
  1048 interpretation mset_set!: folding "\<lambda>x M. {#x#} + M" "{#}"
  1049 where
  1050   "folding.F (\<lambda>x M. {#x#} + M) {#} = mset_set"
  1051 proof -
  1052   interpret comp_fun_commute "\<lambda>x M. {#x#} + M" by default (simp add: fun_eq_iff ac_simps)
  1053   show "folding (\<lambda>x M. {#x#} + M)" by default (fact comp_fun_commute)
  1054   from mset_set_def show "folding.F (\<lambda>x M. {#x#} + M) {#} = mset_set" ..
  1055 qed
  1056 
  1057 lemma count_mset_set [simp]:
  1058   "finite A \<Longrightarrow> x \<in> A \<Longrightarrow> count (mset_set A) x = 1" (is "PROP ?P")
  1059   "\<not> finite A \<Longrightarrow> count (mset_set A) x = 0" (is "PROP ?Q")
  1060   "x \<notin> A \<Longrightarrow> count (mset_set A) x = 0" (is "PROP ?R")
  1061 proof -
  1062   have *: "count (mset_set A) x = 0" if "x \<notin> A" for A
  1063   proof (cases "finite A")
  1064     case False then show ?thesis by simp
  1065   next
  1066     case True from True \<open>x \<notin> A\<close> show ?thesis by (induct A) auto
  1067   qed
  1068   then show "PROP ?P" "PROP ?Q" "PROP ?R"
  1069   by (auto elim!: Set.set_insert)
  1070 qed -- \<open>TODO: maybe define @{const mset_set} also in terms of @{const Abs_multiset}\<close>
  1071 
  1072 lemma elem_mset_set[simp, intro]: "finite A \<Longrightarrow> x \<in># mset_set A \<longleftrightarrow> x \<in> A"
  1073   by (induct A rule: finite_induct) simp_all
  1074 
  1075 context linorder
  1076 begin
  1077 
  1078 definition sorted_list_of_multiset :: "'a multiset \<Rightarrow> 'a list"
  1079 where
  1080   "sorted_list_of_multiset M = fold_mset insort [] M"
  1081 
  1082 lemma sorted_list_of_multiset_empty [simp]:
  1083   "sorted_list_of_multiset {#} = []"
  1084   by (simp add: sorted_list_of_multiset_def)
  1085 
  1086 lemma sorted_list_of_multiset_singleton [simp]:
  1087   "sorted_list_of_multiset {#x#} = [x]"
  1088 proof -
  1089   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
  1090   show ?thesis by (simp add: sorted_list_of_multiset_def)
  1091 qed
  1092 
  1093 lemma sorted_list_of_multiset_insert [simp]:
  1094   "sorted_list_of_multiset (M + {#x#}) = List.insort x (sorted_list_of_multiset M)"
  1095 proof -
  1096   interpret comp_fun_commute insort by (fact comp_fun_commute_insort)
  1097   show ?thesis by (simp add: sorted_list_of_multiset_def)
  1098 qed
  1099 
  1100 end
  1101 
  1102 lemma mset_sorted_list_of_multiset [simp]:
  1103   "mset (sorted_list_of_multiset M) = M"
  1104 by (induct M) simp_all
  1105 
  1106 lemma sorted_list_of_multiset_mset [simp]:
  1107   "sorted_list_of_multiset (mset xs) = sort xs"
  1108 by (induct xs) simp_all
  1109 
  1110 lemma finite_set_mset_mset_set[simp]:
  1111   "finite A \<Longrightarrow> set_mset (mset_set A) = A"
  1112 by (induct A rule: finite_induct) simp_all
  1113 
  1114 lemma infinite_set_mset_mset_set:
  1115   "\<not> finite A \<Longrightarrow> set_mset (mset_set A) = {}"
  1116 by simp
  1117 
  1118 lemma set_sorted_list_of_multiset [simp]:
  1119   "set (sorted_list_of_multiset M) = set_mset M"
  1120 by (induct M) (simp_all add: set_insort)
  1121 
  1122 lemma sorted_list_of_mset_set [simp]:
  1123   "sorted_list_of_multiset (mset_set A) = sorted_list_of_set A"
  1124 by (cases "finite A") (induct A rule: finite_induct, simp_all add: ac_simps)
  1125 
  1126 
  1127 subsection \<open>Big operators\<close>
  1128 
  1129 no_notation times (infixl "*" 70)
  1130 no_notation Groups.one ("1")
  1131 
  1132 locale comm_monoid_mset = comm_monoid
  1133 begin
  1134 
  1135 definition F :: "'a multiset \<Rightarrow> 'a"
  1136   where eq_fold: "F M = fold_mset f 1 M"
  1137 
  1138 lemma empty [simp]: "F {#} = 1"
  1139   by (simp add: eq_fold)
  1140 
  1141 lemma singleton [simp]:
  1142   "F {#x#} = x"
  1143 proof -
  1144   interpret comp_fun_commute
  1145     by default (simp add: fun_eq_iff left_commute)
  1146   show ?thesis by (simp add: eq_fold)
  1147 qed
  1148 
  1149 lemma union [simp]: "F (M + N) = F M * F N"
  1150 proof -
  1151   interpret comp_fun_commute f
  1152     by default (simp add: fun_eq_iff left_commute)
  1153   show ?thesis by (induct N) (simp_all add: left_commute eq_fold)
  1154 qed
  1155 
  1156 end
  1157 
  1158 lemma comp_fun_commute_plus_mset[simp]: "comp_fun_commute (op + \<Colon> 'a multiset \<Rightarrow> _ \<Rightarrow> _)"
  1159   by default (simp add: add_ac comp_def)
  1160 
  1161 declare comp_fun_commute.fold_mset_insert[OF comp_fun_commute_plus_mset, simp]
  1162 
  1163 lemma in_mset_fold_plus_iff[iff]: "x \<in># fold_mset (op +) M NN \<longleftrightarrow> x \<in># M \<or> (\<exists>N. N \<in># NN \<and> x \<in># N)"
  1164   by (induct NN) auto
  1165 
  1166 notation times (infixl "*" 70)
  1167 notation Groups.one ("1")
  1168 
  1169 context comm_monoid_add
  1170 begin
  1171 
  1172 definition msetsum :: "'a multiset \<Rightarrow> 'a"
  1173   where "msetsum = comm_monoid_mset.F plus 0"
  1174 
  1175 sublocale msetsum!: comm_monoid_mset plus 0
  1176   where "comm_monoid_mset.F plus 0 = msetsum"
  1177 proof -
  1178   show "comm_monoid_mset plus 0" ..
  1179   from msetsum_def show "comm_monoid_mset.F plus 0 = msetsum" ..
  1180 qed
  1181 
  1182 lemma setsum_unfold_msetsum:
  1183   "setsum f A = msetsum (image_mset f (mset_set A))"
  1184   by (cases "finite A") (induct A rule: finite_induct, simp_all)
  1185 
  1186 end
  1187 
  1188 lemma msetsum_diff:
  1189   fixes M N :: "('a \<Colon> ordered_cancel_comm_monoid_diff) multiset"
  1190   shows "N \<le># M \<Longrightarrow> msetsum (M - N) = msetsum M - msetsum N"
  1191   by (metis add_diff_cancel_right' msetsum.union subset_mset.diff_add)
  1192 
  1193 lemma size_eq_msetsum: "size M = msetsum (image_mset (\<lambda>_. 1) M)"
  1194 proof (induct M)
  1195   case empty then show ?case by simp
  1196 next
  1197   case (add M x) then show ?case
  1198     by (cases "x \<in> set_mset M")
  1199       (simp_all del: mem_set_mset_iff add: size_multiset_overloaded_eq setsum.distrib setsum.delta' insert_absorb, simp)
  1200 qed
  1201 
  1202 
  1203 abbreviation Union_mset :: "'a multiset multiset \<Rightarrow> 'a multiset" where
  1204   "Union_mset MM \<equiv> msetsum MM"
  1205 
  1206 notation (xsymbols) Union_mset ("\<Union>#_" [900] 900)
  1207 
  1208 lemma set_mset_Union_mset[simp]: "set_mset (\<Union># MM) = (\<Union>M \<in> set_mset MM. set_mset M)"
  1209   by (induct MM) auto
  1210 
  1211 lemma in_Union_mset_iff[iff]: "x \<in># \<Union># MM \<longleftrightarrow> (\<exists>M. M \<in># MM \<and> x \<in># M)"
  1212   by (induct MM) auto
  1213 
  1214 syntax
  1215   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
  1216       ("(3SUM _:#_. _)" [0, 51, 10] 10)
  1217 
  1218 syntax (xsymbols)
  1219   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
  1220       ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10)
  1221 
  1222 syntax (HTML output)
  1223   "_msetsum_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_add"
  1224       ("(3\<Sum>_\<in>#_. _)" [0, 51, 10] 10)
  1225 
  1226 translations
  1227   "SUM i :# A. b" == "CONST msetsum (CONST image_mset (\<lambda>i. b) A)"
  1228 
  1229 context comm_monoid_mult
  1230 begin
  1231 
  1232 definition msetprod :: "'a multiset \<Rightarrow> 'a"
  1233   where "msetprod = comm_monoid_mset.F times 1"
  1234 
  1235 sublocale msetprod!: comm_monoid_mset times 1
  1236   where "comm_monoid_mset.F times 1 = msetprod"
  1237 proof -
  1238   show "comm_monoid_mset times 1" ..
  1239   show "comm_monoid_mset.F times 1 = msetprod" using msetprod_def ..
  1240 qed
  1241 
  1242 lemma msetprod_empty:
  1243   "msetprod {#} = 1"
  1244   by (fact msetprod.empty)
  1245 
  1246 lemma msetprod_singleton:
  1247   "msetprod {#x#} = x"
  1248   by (fact msetprod.singleton)
  1249 
  1250 lemma msetprod_Un:
  1251   "msetprod (A + B) = msetprod A * msetprod B"
  1252   by (fact msetprod.union)
  1253 
  1254 lemma setprod_unfold_msetprod:
  1255   "setprod f A = msetprod (image_mset f (mset_set A))"
  1256   by (cases "finite A") (induct A rule: finite_induct, simp_all)
  1257 
  1258 lemma msetprod_multiplicity:
  1259   "msetprod M = setprod (\<lambda>x. x ^ count M x) (set_mset M)"
  1260   by (simp add: fold_mset_def setprod.eq_fold msetprod.eq_fold funpow_times_power comp_def)
  1261 
  1262 end
  1263 
  1264 syntax
  1265   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
  1266       ("(3PROD _:#_. _)" [0, 51, 10] 10)
  1267 
  1268 syntax (xsymbols)
  1269   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
  1270       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
  1271 
  1272 syntax (HTML output)
  1273   "_msetprod_image" :: "pttrn \<Rightarrow> 'b set \<Rightarrow> 'a \<Rightarrow> 'a::comm_monoid_mult"
  1274       ("(3\<Prod>_\<in>#_. _)" [0, 51, 10] 10)
  1275 
  1276 translations
  1277   "PROD i :# A. b" == "CONST msetprod (CONST image_mset (\<lambda>i. b) A)"
  1278 
  1279 lemma (in comm_semiring_1) dvd_msetprod:
  1280   assumes "x \<in># A"
  1281   shows "x dvd msetprod A"
  1282 proof -
  1283   from assms have "A = (A - {#x#}) + {#x#}" by simp
  1284   then obtain B where "A = B + {#x#}" ..
  1285   then show ?thesis by simp
  1286 qed
  1287 
  1288 
  1289 subsection \<open>Replicate operation\<close>
  1290 
  1291 definition replicate_mset :: "nat \<Rightarrow> 'a \<Rightarrow> 'a multiset" where
  1292   "replicate_mset n x = ((op + {#x#}) ^^ n) {#}"
  1293 
  1294 lemma replicate_mset_0[simp]: "replicate_mset 0 x = {#}"
  1295   unfolding replicate_mset_def by simp
  1296 
  1297 lemma replicate_mset_Suc[simp]: "replicate_mset (Suc n) x = replicate_mset n x + {#x#}"
  1298   unfolding replicate_mset_def by (induct n) (auto intro: add.commute)
  1299 
  1300 lemma in_replicate_mset[simp]: "x \<in># replicate_mset n y \<longleftrightarrow> n > 0 \<and> x = y"
  1301   unfolding replicate_mset_def by (induct n) simp_all
  1302 
  1303 lemma count_replicate_mset[simp]: "count (replicate_mset n x) y = (if y = x then n else 0)"
  1304   unfolding replicate_mset_def by (induct n) simp_all
  1305 
  1306 lemma set_mset_replicate_mset_subset[simp]: "set_mset (replicate_mset n x) = (if n = 0 then {} else {x})"
  1307   by (auto split: if_splits)
  1308 
  1309 lemma size_replicate_mset[simp]: "size (replicate_mset n M) = n"
  1310   by (induct n, simp_all)
  1311 
  1312 lemma count_le_replicate_mset_le: "n \<le> count M x \<longleftrightarrow> replicate_mset n x \<le># M"
  1313   by (auto simp add: assms mset_less_eqI) (metis count_replicate_mset subseteq_mset_def)
  1314 
  1315 
  1316 lemma filter_eq_replicate_mset: "{#y \<in># D. y = x#} = replicate_mset (count D x) x"
  1317   by (induct D) simp_all
  1318 
  1319 
  1320 subsection \<open>Alternative representations\<close>
  1321 
  1322 subsubsection \<open>Lists\<close>
  1323 
  1324 context linorder
  1325 begin
  1326 
  1327 lemma mset_insort [simp]:
  1328   "mset (insort_key k x xs) = {#x#} + mset xs"
  1329   by (induct xs) (simp_all add: ac_simps)
  1330 
  1331 lemma mset_sort [simp]:
  1332   "mset (sort_key k xs) = mset xs"
  1333   by (induct xs) (simp_all add: ac_simps)
  1334 
  1335 text \<open>
  1336   This lemma shows which properties suffice to show that a function
  1337   @{text "f"} with @{text "f xs = ys"} behaves like sort.
  1338 \<close>
  1339 
  1340 lemma properties_for_sort_key:
  1341   assumes "mset ys = mset xs"
  1342     and "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>x. f k = f x) ys = filter (\<lambda>x. f k = f x) xs"
  1343     and "sorted (map f ys)"
  1344   shows "sort_key f xs = ys"
  1345   using assms
  1346 proof (induct xs arbitrary: ys)
  1347   case Nil then show ?case by simp
  1348 next
  1349   case (Cons x xs)
  1350   from Cons.prems(2) have
  1351     "\<forall>k \<in> set ys. filter (\<lambda>x. f k = f x) (remove1 x ys) = filter (\<lambda>x. f k = f x) xs"
  1352     by (simp add: filter_remove1)
  1353   with Cons.prems have "sort_key f xs = remove1 x ys"
  1354     by (auto intro!: Cons.hyps simp add: sorted_map_remove1)
  1355   moreover from Cons.prems have "x \<in> set ys"
  1356     by (auto simp add: mem_set_multiset_eq intro!: ccontr)
  1357   ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)
  1358 qed
  1359 
  1360 lemma properties_for_sort:
  1361   assumes multiset: "mset ys = mset xs"
  1362     and "sorted ys"
  1363   shows "sort xs = ys"
  1364 proof (rule properties_for_sort_key)
  1365   from multiset show "mset ys = mset xs" .
  1366   from \<open>sorted ys\<close> show "sorted (map (\<lambda>x. x) ys)" by simp
  1367   from multiset have "\<And>k. length (filter (\<lambda>y. k = y) ys) = length (filter (\<lambda>x. k = x) xs)"
  1368     by (rule mset_eq_length_filter)
  1369   then have "\<And>k. replicate (length (filter (\<lambda>y. k = y) ys)) k = replicate (length (filter (\<lambda>x. k = x) xs)) k"
  1370     by simp
  1371   then show "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>y. k = y) ys = filter (\<lambda>x. k = x) xs"
  1372     by (simp add: replicate_length_filter)
  1373 qed
  1374 
  1375 lemma sort_key_by_quicksort:
  1376   "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))]
  1377     @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))]
  1378     @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs")
  1379 proof (rule properties_for_sort_key)
  1380   show "mset ?rhs = mset ?lhs"
  1381     by (rule multiset_eqI) (auto simp add: mset_filter)
  1382   show "sorted (map f ?rhs)"
  1383     by (auto simp add: sorted_append intro: sorted_map_same)
  1384 next
  1385   fix l
  1386   assume "l \<in> set ?rhs"
  1387   let ?pivot = "f (xs ! (length xs div 2))"
  1388   have *: "\<And>x. f l = f x \<longleftrightarrow> f x = f l" by auto
  1389   have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]"
  1390     unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)
  1391   with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp
  1392   have "\<And>x P. P (f x) ?pivot \<and> f l = f x \<longleftrightarrow> P (f l) ?pivot \<and> f l = f x" by auto
  1393   then have "\<And>P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot \<and> f l = f x] =
  1394     [x \<leftarrow> sort_key f xs. P (f l) ?pivot \<and> f l = f x]" by simp
  1395   note *** = this [of "op <"] this [of "op >"] this [of "op ="]
  1396   show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]"
  1397   proof (cases "f l" ?pivot rule: linorder_cases)
  1398     case less
  1399     then have "f l \<noteq> ?pivot" and "\<not> f l > ?pivot" by auto
  1400     with less show ?thesis
  1401       by (simp add: filter_sort [symmetric] ** ***)
  1402   next
  1403     case equal then show ?thesis
  1404       by (simp add: * less_le)
  1405   next
  1406     case greater
  1407     then have "f l \<noteq> ?pivot" and "\<not> f l < ?pivot" by auto
  1408     with greater show ?thesis
  1409       by (simp add: filter_sort [symmetric] ** ***)
  1410   qed
  1411 qed
  1412 
  1413 lemma sort_by_quicksort:
  1414   "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)]
  1415     @ [x\<leftarrow>xs. x = xs ! (length xs div 2)]
  1416     @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs")
  1417   using sort_key_by_quicksort [of "\<lambda>x. x", symmetric] by simp
  1418 
  1419 text \<open>A stable parametrized quicksort\<close>
  1420 
  1421 definition part :: "('b \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> 'b list \<times> 'b list \<times> 'b list" where
  1422   "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])"
  1423 
  1424 lemma part_code [code]:
  1425   "part f pivot [] = ([], [], [])"
  1426   "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in
  1427      if x' < pivot then (x # lts, eqs, gts)
  1428      else if x' > pivot then (lts, eqs, x # gts)
  1429      else (lts, x # eqs, gts))"
  1430   by (auto simp add: part_def Let_def split_def)
  1431 
  1432 lemma sort_key_by_quicksort_code [code]:
  1433   "sort_key f xs =
  1434     (case xs of
  1435       [] \<Rightarrow> []
  1436     | [x] \<Rightarrow> xs
  1437     | [x, y] \<Rightarrow> (if f x \<le> f y then xs else [y, x])
  1438     | _ \<Rightarrow>
  1439         let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
  1440         in sort_key f lts @ eqs @ sort_key f gts)"
  1441 proof (cases xs)
  1442   case Nil then show ?thesis by simp
  1443 next
  1444   case (Cons _ ys) note hyps = Cons show ?thesis
  1445   proof (cases ys)
  1446     case Nil with hyps show ?thesis by simp
  1447   next
  1448     case (Cons _ zs) note hyps = hyps Cons show ?thesis
  1449     proof (cases zs)
  1450       case Nil with hyps show ?thesis by auto
  1451     next
  1452       case Cons
  1453       from sort_key_by_quicksort [of f xs]
  1454       have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
  1455         in sort_key f lts @ eqs @ sort_key f gts)"
  1456       by (simp only: split_def Let_def part_def fst_conv snd_conv)
  1457       with hyps Cons show ?thesis by (simp only: list.cases)
  1458     qed
  1459   qed
  1460 qed
  1461 
  1462 end
  1463 
  1464 hide_const (open) part
  1465 
  1466 lemma mset_remdups_le: "mset (remdups xs) \<le># mset xs"
  1467   by (induct xs) (auto intro: subset_mset.order_trans)
  1468 
  1469 lemma mset_update:
  1470   "i < length ls \<Longrightarrow> mset (ls[i := v]) = mset ls - {#ls ! i#} + {#v#}"
  1471 proof (induct ls arbitrary: i)
  1472   case Nil then show ?case by simp
  1473 next
  1474   case (Cons x xs)
  1475   show ?case
  1476   proof (cases i)
  1477     case 0 then show ?thesis by simp
  1478   next
  1479     case (Suc i')
  1480     with Cons show ?thesis
  1481       apply simp
  1482       apply (subst add.assoc)
  1483       apply (subst add.commute [of "{#v#}" "{#x#}"])
  1484       apply (subst add.assoc [symmetric])
  1485       apply simp
  1486       apply (rule mset_le_multiset_union_diff_commute)
  1487       apply (simp add: mset_le_single nth_mem_mset)
  1488       done
  1489   qed
  1490 qed
  1491 
  1492 lemma mset_swap:
  1493   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
  1494     mset (ls[j := ls ! i, i := ls ! j]) = mset ls"
  1495   by (cases "i = j") (simp_all add: mset_update nth_mem_mset)
  1496 
  1497 
  1498 subsection \<open>The multiset order\<close>
  1499 
  1500 subsubsection \<open>Well-foundedness\<close>
  1501 
  1502 definition mult1 :: "('a \<times> 'a) set \<Rightarrow> ('a multiset \<times> 'a multiset) set" where
  1503   "mult1 r = {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
  1504       (\<forall>b. b :# K \<longrightarrow> (b, a) \<in> r)}"
  1505 
  1506 definition mult :: "('a \<times> 'a) set \<Rightarrow> ('a multiset \<times> 'a multiset) set" where
  1507   "mult r = (mult1 r)\<^sup>+"
  1508 
  1509 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
  1510 by (simp add: mult1_def)
  1511 
  1512 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r \<Longrightarrow>
  1513     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
  1514     (\<exists>K. (\<forall>b. b :# K \<longrightarrow> (b, a) \<in> r) \<and> N = M0 + K)"
  1515   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
  1516 proof (unfold mult1_def)
  1517   let ?r = "\<lambda>K a. \<forall>b. b :# K \<longrightarrow> (b, a) \<in> r"
  1518   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
  1519   let ?case1 = "?case1 {(N, M). ?R N M}"
  1520 
  1521   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
  1522   then obtain a' M0' K where M0: "M0 + {#a#} = M0' + {#a'#}" and N: "N = M0' + K" and r: "?r K a'"
  1523     by auto
  1524   show "?case1 \<or> ?case2"
  1525   proof -
  1526     from M0 consider "M0 = M0'" "a = a'"
  1527       | K' where "M0 = K' + {#a'#}" "M0' = K' + {#a#}"
  1528       by atomize_elim (simp only: add_eq_conv_ex)
  1529     then show ?thesis
  1530     proof cases
  1531       case 1
  1532       with N r have "?r K a \<and> N = M0 + K" by simp
  1533       then have ?case2 ..
  1534       then show ?thesis ..
  1535     next
  1536       case 2
  1537       from N 2(2) have n: "N = K' + K + {#a#}" by (simp add: ac_simps)
  1538       with r 2(1) have "?R (K' + K) M0" by blast
  1539       with n have ?case1 by simp
  1540       then show ?thesis ..
  1541     qed
  1542   qed
  1543 qed
  1544 
  1545 lemma all_accessible: "wf r \<Longrightarrow> \<forall>M. M \<in> Wellfounded.acc (mult1 r)"
  1546 proof
  1547   let ?R = "mult1 r"
  1548   let ?W = "Wellfounded.acc ?R"
  1549   {
  1550     fix M M0 a
  1551     assume M0: "M0 \<in> ?W"
  1552       and wf_hyp: "\<And>b. (b, a) \<in> r \<Longrightarrow> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
  1553       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R \<longrightarrow> M + {#a#} \<in> ?W"
  1554     have "M0 + {#a#} \<in> ?W"
  1555     proof (rule accI [of "M0 + {#a#}"])
  1556       fix N
  1557       assume "(N, M0 + {#a#}) \<in> ?R"
  1558       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
  1559           (\<exists>K. (\<forall>b. b :# K \<longrightarrow> (b, a) \<in> r) \<and> N = M0 + K))"
  1560         by (rule less_add)
  1561       then show "N \<in> ?W"
  1562       proof (elim exE disjE conjE)
  1563         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
  1564         from acc_hyp have "(M, M0) \<in> ?R \<longrightarrow> M + {#a#} \<in> ?W" ..
  1565         from this and \<open>(M, M0) \<in> ?R\<close> have "M + {#a#} \<in> ?W" ..
  1566         then show "N \<in> ?W" by (simp only: N)
  1567       next
  1568         fix K
  1569         assume N: "N = M0 + K"
  1570         assume "\<forall>b. b :# K \<longrightarrow> (b, a) \<in> r"
  1571         then have "M0 + K \<in> ?W"
  1572         proof (induct K)
  1573           case empty
  1574           from M0 show "M0 + {#} \<in> ?W" by simp
  1575         next
  1576           case (add K x)
  1577           from add.prems have "(x, a) \<in> r" by simp
  1578           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
  1579           moreover from add have "M0 + K \<in> ?W" by simp
  1580           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
  1581           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: add.assoc)
  1582         qed
  1583         then show "N \<in> ?W" by (simp only: N)
  1584       qed
  1585     qed
  1586   } note tedious_reasoning = this
  1587 
  1588   assume wf: "wf r"
  1589   fix M
  1590   show "M \<in> ?W"
  1591   proof (induct M)
  1592     show "{#} \<in> ?W"
  1593     proof (rule accI)
  1594       fix b assume "(b, {#}) \<in> ?R"
  1595       with not_less_empty show "b \<in> ?W" by contradiction
  1596     qed
  1597 
  1598     fix M a assume "M \<in> ?W"
  1599     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
  1600     proof induct
  1601       fix a
  1602       assume r: "\<And>b. (b, a) \<in> r \<Longrightarrow> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
  1603       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
  1604       proof
  1605         fix M assume "M \<in> ?W"
  1606         then show "M + {#a#} \<in> ?W"
  1607           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
  1608       qed
  1609     qed
  1610     from this and \<open>M \<in> ?W\<close> show "M + {#a#} \<in> ?W" ..
  1611   qed
  1612 qed
  1613 
  1614 theorem wf_mult1: "wf r \<Longrightarrow> wf (mult1 r)"
  1615 by (rule acc_wfI) (rule all_accessible)
  1616 
  1617 theorem wf_mult: "wf r \<Longrightarrow> wf (mult r)"
  1618 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
  1619 
  1620 
  1621 subsubsection \<open>Closure-free presentation\<close>
  1622 
  1623 text \<open>One direction.\<close>
  1624 
  1625 lemma mult_implies_one_step:
  1626   "trans r \<Longrightarrow> (M, N) \<in> mult r \<Longrightarrow>
  1627     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
  1628     (\<forall>k \<in> set_mset K. \<exists>j \<in> set_mset J. (k, j) \<in> r)"
  1629 apply (unfold mult_def mult1_def set_mset_def)
  1630 apply (erule converse_trancl_induct, clarify)
  1631  apply (rule_tac x = M0 in exI, simp, clarify)
  1632 apply (case_tac "a :# K")
  1633  apply (rule_tac x = I in exI)
  1634  apply (simp (no_asm))
  1635  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
  1636  apply (simp (no_asm_simp) add: add.assoc [symmetric])
  1637  apply (drule_tac f = "\<lambda>M. M - {#a#}" and x="S + T" for S T in arg_cong)
  1638  apply (simp add: diff_union_single_conv)
  1639  apply (simp (no_asm_use) add: trans_def)
  1640  apply blast
  1641 apply (subgoal_tac "a :# I")
  1642  apply (rule_tac x = "I - {#a#}" in exI)
  1643  apply (rule_tac x = "J + {#a#}" in exI)
  1644  apply (rule_tac x = "K + Ka" in exI)
  1645  apply (rule conjI)
  1646   apply (simp add: multiset_eq_iff split: nat_diff_split)
  1647  apply (rule conjI)
  1648   apply (drule_tac f = "\<lambda>M. M - {#a#}" and x="S + T" for S T in arg_cong, simp)
  1649   apply (simp add: multiset_eq_iff split: nat_diff_split)
  1650  apply (simp (no_asm_use) add: trans_def)
  1651  apply blast
  1652 apply (subgoal_tac "a :# (M0 + {#a#})")
  1653  apply simp
  1654 apply (simp (no_asm))
  1655 done
  1656 
  1657 lemma one_step_implies_mult_aux:
  1658   "trans r \<Longrightarrow>
  1659     \<forall>I J K. size J = n \<and> J \<noteq> {#} \<and> (\<forall>k \<in> set_mset K. \<exists>j \<in> set_mset J. (k, j) \<in> r)
  1660       \<longrightarrow> (I + K, I + J) \<in> mult r"
  1661 apply (induct_tac n, auto)
  1662 apply (frule size_eq_Suc_imp_eq_union, clarify)
  1663 apply (rename_tac "J'", simp)
  1664 apply (erule notE, auto)
  1665 apply (case_tac "J' = {#}")
  1666  apply (simp add: mult_def)
  1667  apply (rule r_into_trancl)
  1668  apply (simp add: mult1_def set_mset_def, blast)
  1669 txt \<open>Now we know @{term "J' \<noteq> {#}"}.\<close>
  1670 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
  1671 apply (erule_tac P = "\<forall>k \<in> set_mset K. P k" for P in rev_mp)
  1672 apply (erule ssubst)
  1673 apply (simp add: Ball_def, auto)
  1674 apply (subgoal_tac
  1675   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
  1676     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
  1677  prefer 2
  1678  apply force
  1679 apply (simp (no_asm_use) add: add.assoc [symmetric] mult_def)
  1680 apply (erule trancl_trans)
  1681 apply (rule r_into_trancl)
  1682 apply (simp add: mult1_def set_mset_def)
  1683 apply (rule_tac x = a in exI)
  1684 apply (rule_tac x = "I + J'" in exI)
  1685 apply (simp add: ac_simps)
  1686 done
  1687 
  1688 lemma one_step_implies_mult:
  1689   "trans r \<Longrightarrow> J \<noteq> {#} \<Longrightarrow> \<forall>k \<in> set_mset K. \<exists>j \<in> set_mset J. (k, j) \<in> r
  1690     \<Longrightarrow> (I + K, I + J) \<in> mult r"
  1691 using one_step_implies_mult_aux by blast
  1692 
  1693 
  1694 subsubsection \<open>Partial-order properties\<close>
  1695 
  1696 definition less_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "#<#" 50) where
  1697   "M' #<# M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
  1698 
  1699 definition le_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "#<=#" 50) where
  1700   "M' #<=# M \<longleftrightarrow> M' #<# M \<or> M' = M"
  1701 
  1702 notation (xsymbols) less_multiset (infix "#\<subset>#" 50)
  1703 notation (xsymbols) le_multiset (infix "#\<subseteq>#" 50)
  1704 
  1705 interpretation multiset_order: order le_multiset less_multiset
  1706 proof -
  1707   have irrefl: "\<not> M #\<subset># M" for M :: "'a multiset"
  1708   proof
  1709     assume "M #\<subset># M"
  1710     then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def)
  1711     have "trans {(x'::'a, x). x' < x}"
  1712       by (rule transI) simp
  1713     moreover note MM
  1714     ultimately have "\<exists>I J K. M = I + J \<and> M = I + K
  1715       \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_mset K. \<exists>j\<in>set_mset J. (k, j) \<in> {(x, y). x < y})"
  1716       by (rule mult_implies_one_step)
  1717     then obtain I J K where "M = I + J" and "M = I + K"
  1718       and "J \<noteq> {#}" and "(\<forall>k\<in>set_mset K. \<exists>j\<in>set_mset J. (k, j) \<in> {(x, y). x < y})" by blast
  1719     then have aux1: "K \<noteq> {#}" and aux2: "\<forall>k\<in>set_mset K. \<exists>j\<in>set_mset K. k < j" by auto
  1720     have "finite (set_mset K)" by simp
  1721     moreover note aux2
  1722     ultimately have "set_mset K = {}"
  1723       by (induct rule: finite_induct) (auto intro: order_less_trans)
  1724     with aux1 show False by simp
  1725   qed
  1726   have trans: "\<And>K M N :: 'a multiset. K #\<subset># M \<Longrightarrow> M #\<subset># N \<Longrightarrow> K #\<subset># N"
  1727     unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
  1728   show "class.order (le_multiset :: 'a multiset \<Rightarrow> _) less_multiset"
  1729     by default (auto simp add: le_multiset_def irrefl dest: trans)
  1730 qed
  1731 
  1732 lemma mult_less_irrefl [elim!]: "M #\<subset># (M::'a::order multiset) \<Longrightarrow> R"
  1733   by simp
  1734 
  1735 
  1736 subsubsection \<open>Monotonicity of multiset union\<close>
  1737 
  1738 lemma mult1_union: "(B, D) \<in> mult1 r \<Longrightarrow> (C + B, C + D) \<in> mult1 r"
  1739 apply (unfold mult1_def)
  1740 apply auto
  1741 apply (rule_tac x = a in exI)
  1742 apply (rule_tac x = "C + M0" in exI)
  1743 apply (simp add: add.assoc)
  1744 done
  1745 
  1746 lemma union_less_mono2: "B #\<subset># D \<Longrightarrow> C + B #\<subset># C + (D::'a::order multiset)"
  1747 apply (unfold less_multiset_def mult_def)
  1748 apply (erule trancl_induct)
  1749  apply (blast intro: mult1_union)
  1750 apply (blast intro: mult1_union trancl_trans)
  1751 done
  1752 
  1753 lemma union_less_mono1: "B #\<subset># D \<Longrightarrow> B + C #\<subset># D + (C::'a::order multiset)"
  1754 apply (subst add.commute [of B C])
  1755 apply (subst add.commute [of D C])
  1756 apply (erule union_less_mono2)
  1757 done
  1758 
  1759 lemma union_less_mono:
  1760   fixes A B C D :: "'a::order multiset"
  1761   shows "A #\<subset># C \<Longrightarrow> B #\<subset># D \<Longrightarrow> A + B #\<subset># C + D"
  1762   by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)
  1763 
  1764 interpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multiset
  1765   by default (auto simp add: le_multiset_def intro: union_less_mono2)
  1766 
  1767 
  1768 subsubsection \<open>Termination proofs with multiset orders\<close>
  1769 
  1770 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
  1771   and multi_member_this: "x \<in># {# x #} + XS"
  1772   and multi_member_last: "x \<in># {# x #}"
  1773   by auto
  1774 
  1775 definition "ms_strict = mult pair_less"
  1776 definition "ms_weak = ms_strict \<union> Id"
  1777 
  1778 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
  1779 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
  1780 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
  1781 
  1782 lemma smsI:
  1783   "(set_mset A, set_mset B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
  1784   unfolding ms_strict_def
  1785 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
  1786 
  1787 lemma wmsI:
  1788   "(set_mset A, set_mset B) \<in> max_strict \<or> A = {#} \<and> B = {#}
  1789   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
  1790 unfolding ms_weak_def ms_strict_def
  1791 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
  1792 
  1793 inductive pw_leq
  1794 where
  1795   pw_leq_empty: "pw_leq {#} {#}"
  1796 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
  1797 
  1798 lemma pw_leq_lstep:
  1799   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
  1800 by (drule pw_leq_step) (rule pw_leq_empty, simp)
  1801 
  1802 lemma pw_leq_split:
  1803   assumes "pw_leq X Y"
  1804   shows "\<exists>A B Z. X = A + Z \<and> Y = B + Z \<and> ((set_mset A, set_mset B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
  1805   using assms
  1806 proof induct
  1807   case pw_leq_empty thus ?case by auto
  1808 next
  1809   case (pw_leq_step x y X Y)
  1810   then obtain A B Z where
  1811     [simp]: "X = A + Z" "Y = B + Z"
  1812       and 1[simp]: "(set_mset A, set_mset B) \<in> max_strict \<or> (B = {#} \<and> A = {#})"
  1813     by auto
  1814   from pw_leq_step consider "x = y" | "(x, y) \<in> pair_less"
  1815     unfolding pair_leq_def by auto
  1816   thus ?case
  1817   proof cases
  1818     case [simp]: 1
  1819     have "{#x#} + X = A + ({#y#}+Z) \<and> {#y#} + Y = B + ({#y#}+Z) \<and>
  1820       ((set_mset A, set_mset B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
  1821       by (auto simp: ac_simps)
  1822     thus ?thesis by blast
  1823   next
  1824     case 2
  1825     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
  1826     have "{#x#} + X = ?A' + Z"
  1827       "{#y#} + Y = ?B' + Z"
  1828       by (auto simp add: ac_simps)
  1829     moreover have
  1830       "(set_mset ?A', set_mset ?B') \<in> max_strict"
  1831       using 1 2 unfolding max_strict_def
  1832       by (auto elim!: max_ext.cases)
  1833     ultimately show ?thesis by blast
  1834   qed
  1835 qed
  1836 
  1837 lemma
  1838   assumes pwleq: "pw_leq Z Z'"
  1839   shows ms_strictI: "(set_mset A, set_mset B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
  1840     and ms_weakI1:  "(set_mset A, set_mset B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
  1841     and ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
  1842 proof -
  1843   from pw_leq_split[OF pwleq]
  1844   obtain A' B' Z''
  1845     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
  1846     and mx_or_empty: "(set_mset A', set_mset B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
  1847     by blast
  1848   {
  1849     assume max: "(set_mset A, set_mset B) \<in> max_strict"
  1850     from mx_or_empty
  1851     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
  1852     proof
  1853       assume max': "(set_mset A', set_mset B') \<in> max_strict"
  1854       with max have "(set_mset (A + A'), set_mset (B + B')) \<in> max_strict"
  1855         by (auto simp: max_strict_def intro: max_ext_additive)
  1856       thus ?thesis by (rule smsI)
  1857     next
  1858       assume [simp]: "A' = {#} \<and> B' = {#}"
  1859       show ?thesis by (rule smsI) (auto intro: max)
  1860     qed
  1861     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add: ac_simps)
  1862     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
  1863   }
  1864   from mx_or_empty
  1865   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
  1866   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add:ac_simps)
  1867 qed
  1868 
  1869 lemma empty_neutral: "{#} + x = x" "x + {#} = x"
  1870 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
  1871 and nonempty_single: "{# x #} \<noteq> {#}"
  1872 by auto
  1873 
  1874 setup \<open>
  1875   let
  1876     fun msetT T = Type (@{type_name multiset}, [T]);
  1877 
  1878     fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)
  1879       | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) $ x
  1880       | mk_mset T (x :: xs) =
  1881             Const (@{const_name plus}, msetT T --> msetT T --> msetT T) $
  1882                   mk_mset T [x] $ mk_mset T xs
  1883 
  1884     fun mset_member_tac m i =
  1885       if m <= 0 then
  1886         rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i
  1887       else
  1888         rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i
  1889 
  1890     val mset_nonempty_tac =
  1891       rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}
  1892 
  1893     fun regroup_munion_conv ctxt =
  1894       Function_Lib.regroup_conv ctxt @{const_abbrev Mempty} @{const_name plus}
  1895         (map (fn t => t RS eq_reflection) (@{thms ac_simps} @ @{thms empty_neutral}))
  1896 
  1897     fun unfold_pwleq_tac i =
  1898       (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))
  1899         ORELSE (rtac @{thm pw_leq_lstep} i)
  1900         ORELSE (rtac @{thm pw_leq_empty} i)
  1901 
  1902     val set_mset_simps = [@{thm set_mset_empty}, @{thm set_mset_single}, @{thm set_mset_union},
  1903                         @{thm Un_insert_left}, @{thm Un_empty_left}]
  1904   in
  1905     ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset
  1906     {
  1907       msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
  1908       mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
  1909       mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_mset_simps,
  1910       smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
  1911       reduction_pair= @{thm ms_reduction_pair}
  1912     })
  1913   end
  1914 \<close>
  1915 
  1916 
  1917 subsection \<open>Legacy theorem bindings\<close>
  1918 
  1919 lemmas multi_count_eq = multiset_eq_iff [symmetric]
  1920 
  1921 lemma union_commute: "M + N = N + (M::'a multiset)"
  1922   by (fact add.commute)
  1923 
  1924 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
  1925   by (fact add.assoc)
  1926 
  1927 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
  1928   by (fact add.left_commute)
  1929 
  1930 lemmas union_ac = union_assoc union_commute union_lcomm
  1931 
  1932 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
  1933   by (fact add_right_cancel)
  1934 
  1935 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
  1936   by (fact add_left_cancel)
  1937 
  1938 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
  1939   by (fact add_left_imp_eq)
  1940 
  1941 lemma mset_less_trans: "(M::'a multiset) <# K \<Longrightarrow> K <# N \<Longrightarrow> M <# N"
  1942   by (fact subset_mset.less_trans)
  1943 
  1944 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
  1945   by (fact subset_mset.inf.commute)
  1946 
  1947 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
  1948   by (fact subset_mset.inf.assoc [symmetric])
  1949 
  1950 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
  1951   by (fact subset_mset.inf.left_commute)
  1952 
  1953 lemmas multiset_inter_ac =
  1954   multiset_inter_commute
  1955   multiset_inter_assoc
  1956   multiset_inter_left_commute
  1957 
  1958 lemma mult_less_not_refl: "\<not> M #\<subset># (M::'a::order multiset)"
  1959   by (fact multiset_order.less_irrefl)
  1960 
  1961 lemma mult_less_trans: "K #\<subset># M \<Longrightarrow> M #\<subset># N \<Longrightarrow> K #\<subset># (N::'a::order multiset)"
  1962   by (fact multiset_order.less_trans)
  1963 
  1964 lemma mult_less_not_sym: "M #\<subset># N \<Longrightarrow> \<not> N #\<subset># (M::'a::order multiset)"
  1965   by (fact multiset_order.less_not_sym)
  1966 
  1967 lemma mult_less_asym: "M #\<subset># N \<Longrightarrow> (\<not> P \<Longrightarrow> N #\<subset># (M::'a::order multiset)) \<Longrightarrow> P"
  1968   by (fact multiset_order.less_asym)
  1969 
  1970 declaration \<open>
  1971   let
  1972     fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T])) (Const _ $ t') =
  1973           let
  1974             val (maybe_opt, ps) =
  1975               Nitpick_Model.dest_plain_fun t'
  1976               ||> op ~~
  1977               ||> map (apsnd (snd o HOLogic.dest_number))
  1978             fun elems_for t =
  1979               (case AList.lookup (op =) ps t of
  1980                 SOME n => replicate n t
  1981               | NONE => [Const (maybe_name, elem_T --> elem_T) $ t])
  1982           in
  1983             (case maps elems_for (all_values elem_T) @
  1984                  (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)] else []) of
  1985               [] => Const (@{const_name zero_class.zero}, T)
  1986             | ts =>
  1987                 foldl1 (fn (t1, t2) =>
  1988                     Const (@{const_name plus_class.plus}, T --> T --> T) $ t1 $ t2)
  1989                   (map (curry (op $) (Const (@{const_name single}, elem_T --> T))) ts))
  1990           end
  1991       | multiset_postproc _ _ _ _ t = t
  1992   in Nitpick_Model.register_term_postprocessor @{typ "'a multiset"} multiset_postproc end
  1993 \<close>
  1994 
  1995 
  1996 subsection \<open>Naive implementation using lists\<close>
  1997 
  1998 code_datatype mset
  1999 
  2000 lemma [code]: "{#} = mset []"
  2001   by simp
  2002 
  2003 lemma [code]: "{#x#} = mset [x]"
  2004   by simp
  2005 
  2006 lemma union_code [code]: "mset xs + mset ys = mset (xs @ ys)"
  2007   by simp
  2008 
  2009 lemma [code]: "image_mset f (mset xs) = mset (map f xs)"
  2010   by (simp add: mset_map)
  2011 
  2012 lemma [code]: "filter_mset f (mset xs) = mset (filter f xs)"
  2013   by (simp add: mset_filter)
  2014 
  2015 lemma [code]: "mset xs - mset ys = mset (fold remove1 ys xs)"
  2016   by (rule sym, induct ys arbitrary: xs) (simp_all add: diff_add diff_right_commute)
  2017 
  2018 lemma [code]:
  2019   "mset xs #\<inter> mset ys =
  2020     mset (snd (fold (\<lambda>x (ys, zs).
  2021       if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, [])))"
  2022 proof -
  2023   have "\<And>zs. mset (snd (fold (\<lambda>x (ys, zs).
  2024     if x \<in> set ys then (remove1 x ys, x # zs) else (ys, zs)) xs (ys, zs))) =
  2025       (mset xs #\<inter> mset ys) + mset zs"
  2026     by (induct xs arbitrary: ys)
  2027       (auto simp add: mem_set_multiset_eq inter_add_right1 inter_add_right2 ac_simps)
  2028   then show ?thesis by simp
  2029 qed
  2030 
  2031 lemma [code]:
  2032   "mset xs #\<union> mset ys =
  2033     mset (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, [])))"
  2034 proof -
  2035   have "\<And>zs. mset (split append (fold (\<lambda>x (ys, zs). (remove1 x ys, x # zs)) xs (ys, zs))) =
  2036       (mset xs #\<union> mset ys) + mset zs"
  2037     by (induct xs arbitrary: ys) (simp_all add: multiset_eq_iff)
  2038   then show ?thesis by simp
  2039 qed
  2040 
  2041 declare in_multiset_in_set [code_unfold]
  2042 
  2043 lemma [code]: "count (mset xs) x = fold (\<lambda>y. if x = y then Suc else id) xs 0"
  2044 proof -
  2045   have "\<And>n. fold (\<lambda>y. if x = y then Suc else id) xs n = count (mset xs) x + n"
  2046     by (induct xs) simp_all
  2047   then show ?thesis by simp
  2048 qed
  2049 
  2050 declare set_mset_mset [code]
  2051 
  2052 declare sorted_list_of_multiset_mset [code]
  2053 
  2054 lemma [code]: -- \<open>not very efficient, but representation-ignorant!\<close>
  2055   "mset_set A = mset (sorted_list_of_set A)"
  2056   apply (cases "finite A")
  2057   apply simp_all
  2058   apply (induct A rule: finite_induct)
  2059   apply (simp_all add: add.commute)
  2060   done
  2061 
  2062 declare size_mset [code]
  2063 
  2064 fun ms_lesseq_impl :: "'a list \<Rightarrow> 'a list \<Rightarrow> bool option" where
  2065   "ms_lesseq_impl [] ys = Some (ys \<noteq> [])"
  2066 | "ms_lesseq_impl (Cons x xs) ys = (case List.extract (op = x) ys of
  2067      None \<Rightarrow> None
  2068    | Some (ys1,_,ys2) \<Rightarrow> ms_lesseq_impl xs (ys1 @ ys2))"
  2069 
  2070 lemma ms_lesseq_impl: "(ms_lesseq_impl xs ys = None \<longleftrightarrow> \<not> mset xs \<le># mset ys) \<and>
  2071   (ms_lesseq_impl xs ys = Some True \<longleftrightarrow> mset xs <# mset ys) \<and>
  2072   (ms_lesseq_impl xs ys = Some False \<longrightarrow> mset xs = mset ys)"
  2073 proof (induct xs arbitrary: ys)
  2074   case (Nil ys)
  2075   show ?case by (auto simp: mset_less_empty_nonempty)
  2076 next
  2077   case (Cons x xs ys)
  2078   show ?case
  2079   proof (cases "List.extract (op = x) ys")
  2080     case None
  2081     hence x: "x \<notin> set ys" by (simp add: extract_None_iff)
  2082     {
  2083       assume "mset (x # xs) \<le># mset ys"
  2084       from set_mset_mono[OF this] x have False by simp
  2085     } note nle = this
  2086     moreover
  2087     {
  2088       assume "mset (x # xs) <# mset ys"
  2089       hence "mset (x # xs) \<le># mset ys" by auto
  2090       from nle[OF this] have False .
  2091     }
  2092     ultimately show ?thesis using None by auto
  2093   next
  2094     case (Some res)
  2095     obtain ys1 y ys2 where res: "res = (ys1,y,ys2)" by (cases res, auto)
  2096     note Some = Some[unfolded res]
  2097     from extract_SomeE[OF Some] have "ys = ys1 @ x # ys2" by simp
  2098     hence id: "mset ys = mset (ys1 @ ys2) + {#x#}"
  2099       by (auto simp: ac_simps)
  2100     show ?thesis unfolding ms_lesseq_impl.simps
  2101       unfolding Some option.simps split
  2102       unfolding id
  2103       using Cons[of "ys1 @ ys2"]
  2104       unfolding subset_mset_def subseteq_mset_def by auto
  2105   qed
  2106 qed
  2107 
  2108 lemma [code]: "mset xs \<le># mset ys \<longleftrightarrow> ms_lesseq_impl xs ys \<noteq> None"
  2109   using ms_lesseq_impl[of xs ys] by (cases "ms_lesseq_impl xs ys", auto)
  2110 
  2111 lemma [code]: "mset xs <# mset ys \<longleftrightarrow> ms_lesseq_impl xs ys = Some True"
  2112   using ms_lesseq_impl[of xs ys] by (cases "ms_lesseq_impl xs ys", auto)
  2113 
  2114 instantiation multiset :: (equal) equal
  2115 begin
  2116 
  2117 definition
  2118   [code del]: "HOL.equal A (B :: 'a multiset) \<longleftrightarrow> A = B"
  2119 lemma [code]: "HOL.equal (mset xs) (mset ys) \<longleftrightarrow> ms_lesseq_impl xs ys = Some False"
  2120   unfolding equal_multiset_def
  2121   using ms_lesseq_impl[of xs ys] by (cases "ms_lesseq_impl xs ys", auto)
  2122 
  2123 instance
  2124   by default (simp add: equal_multiset_def)
  2125 end
  2126 
  2127 lemma [code]: "msetsum (mset xs) = listsum xs"
  2128   by (induct xs) (simp_all add: add.commute)
  2129 
  2130 lemma [code]: "msetprod (mset xs) = fold times xs 1"
  2131 proof -
  2132   have "\<And>x. fold times xs x = msetprod (mset xs) * x"
  2133     by (induct xs) (simp_all add: mult.assoc)
  2134   then show ?thesis by simp
  2135 qed
  2136 
  2137 text \<open>
  2138   Exercise for the casual reader: add implementations for @{const le_multiset}
  2139   and @{const less_multiset} (multiset order).
  2140 \<close>
  2141 
  2142 text \<open>Quickcheck generators\<close>
  2143 
  2144 definition (in term_syntax)
  2145   msetify :: "'a\<Colon>typerep list \<times> (unit \<Rightarrow> Code_Evaluation.term)
  2146     \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where
  2147   [code_unfold]: "msetify xs = Code_Evaluation.valtermify mset {\<cdot>} xs"
  2148 
  2149 notation fcomp (infixl "\<circ>>" 60)
  2150 notation scomp (infixl "\<circ>\<rightarrow>" 60)
  2151 
  2152 instantiation multiset :: (random) random
  2153 begin
  2154 
  2155 definition
  2156   "Quickcheck_Random.random i = Quickcheck_Random.random i \<circ>\<rightarrow> (\<lambda>xs. Pair (msetify xs))"
  2157 
  2158 instance ..
  2159 
  2160 end
  2161 
  2162 no_notation fcomp (infixl "\<circ>>" 60)
  2163 no_notation scomp (infixl "\<circ>\<rightarrow>" 60)
  2164 
  2165 instantiation multiset :: (full_exhaustive) full_exhaustive
  2166 begin
  2167 
  2168 definition full_exhaustive_multiset :: "('a multiset \<times> (unit \<Rightarrow> term) \<Rightarrow> (bool \<times> term list) option) \<Rightarrow> natural \<Rightarrow> (bool \<times> term list) option"
  2169 where
  2170   "full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (\<lambda>xs. f (msetify xs)) i"
  2171 
  2172 instance ..
  2173 
  2174 end
  2175 
  2176 hide_const (open) msetify
  2177 
  2178 
  2179 subsection \<open>BNF setup\<close>
  2180 
  2181 definition rel_mset where
  2182   "rel_mset R X Y \<longleftrightarrow> (\<exists>xs ys. mset xs = X \<and> mset ys = Y \<and> list_all2 R xs ys)"
  2183 
  2184 lemma mset_zip_take_Cons_drop_twice:
  2185   assumes "length xs = length ys" "j \<le> length xs"
  2186   shows "mset (zip (take j xs @ x # drop j xs) (take j ys @ y # drop j ys)) =
  2187     mset (zip xs ys) + {#(x, y)#}"
  2188   using assms
  2189 proof (induct xs ys arbitrary: x y j rule: list_induct2)
  2190   case Nil
  2191   thus ?case
  2192     by simp
  2193 next
  2194   case (Cons x xs y ys)
  2195   thus ?case
  2196   proof (cases "j = 0")
  2197     case True
  2198     thus ?thesis
  2199       by simp
  2200   next
  2201     case False
  2202     then obtain k where k: "j = Suc k"
  2203       by (case_tac j) simp
  2204     hence "k \<le> length xs"
  2205       using Cons.prems by auto
  2206     hence "mset (zip (take k xs @ x # drop k xs) (take k ys @ y # drop k ys)) =
  2207       mset (zip xs ys) + {#(x, y)#}"
  2208       by (rule Cons.hyps(2))
  2209     thus ?thesis
  2210       unfolding k by (auto simp: add.commute union_lcomm)
  2211   qed
  2212 qed
  2213 
  2214 lemma ex_mset_zip_left:
  2215   assumes "length xs = length ys" "mset xs' = mset xs"
  2216   shows "\<exists>ys'. length ys' = length xs' \<and> mset (zip xs' ys') = mset (zip xs ys)"
  2217 using assms
  2218 proof (induct xs ys arbitrary: xs' rule: list_induct2)
  2219   case Nil
  2220   thus ?case
  2221     by auto
  2222 next
  2223   case (Cons x xs y ys xs')
  2224   obtain j where j_len: "j < length xs'" and nth_j: "xs' ! j = x"
  2225     by (metis Cons.prems in_set_conv_nth list.set_intros(1) mset_eq_setD)
  2226 
  2227   def xsa \<equiv> "take j xs' @ drop (Suc j) xs'"
  2228   have "mset xs' = {#x#} + mset xsa"
  2229     unfolding xsa_def using j_len nth_j
  2230     by (metis (no_types) ab_semigroup_add_class.add_ac(1) append_take_drop_id Cons_nth_drop_Suc
  2231       mset.simps(2) union_code add.commute)
  2232   hence ms_x: "mset xsa = mset xs"
  2233     by (metis Cons.prems add.commute add_right_imp_eq mset.simps(2))
  2234   then obtain ysa where
  2235     len_a: "length ysa = length xsa" and ms_a: "mset (zip xsa ysa) = mset (zip xs ys)"
  2236     using Cons.hyps(2) by blast
  2237 
  2238   def ys' \<equiv> "take j ysa @ y # drop j ysa"
  2239   have xs': "xs' = take j xsa @ x # drop j xsa"
  2240     using ms_x j_len nth_j Cons.prems xsa_def
  2241     by (metis append_eq_append_conv append_take_drop_id diff_Suc_Suc Cons_nth_drop_Suc length_Cons
  2242       length_drop size_mset)
  2243   have j_len': "j \<le> length xsa"
  2244     using j_len xs' xsa_def
  2245     by (metis add_Suc_right append_take_drop_id length_Cons length_append less_eq_Suc_le not_less)
  2246   have "length ys' = length xs'"
  2247     unfolding ys'_def using Cons.prems len_a ms_x
  2248     by (metis add_Suc_right append_take_drop_id length_Cons length_append mset_eq_length)
  2249   moreover have "mset (zip xs' ys') = mset (zip (x # xs) (y # ys))"
  2250     unfolding xs' ys'_def
  2251     by (rule trans[OF mset_zip_take_Cons_drop_twice])
  2252       (auto simp: len_a ms_a j_len' add.commute)
  2253   ultimately show ?case
  2254     by blast
  2255 qed
  2256 
  2257 lemma list_all2_reorder_left_invariance:
  2258   assumes rel: "list_all2 R xs ys" and ms_x: "mset xs' = mset xs"
  2259   shows "\<exists>ys'. list_all2 R xs' ys' \<and> mset ys' = mset ys"
  2260 proof -
  2261   have len: "length xs = length ys"
  2262     using rel list_all2_conv_all_nth by auto
  2263   obtain ys' where
  2264     len': "length xs' = length ys'" and ms_xy: "mset (zip xs' ys') = mset (zip xs ys)"
  2265     using len ms_x by (metis ex_mset_zip_left)
  2266   have "list_all2 R xs' ys'"
  2267     using assms(1) len' ms_xy unfolding list_all2_iff by (blast dest: mset_eq_setD)
  2268   moreover have "mset ys' = mset ys"
  2269     using len len' ms_xy map_snd_zip mset_map by metis
  2270   ultimately show ?thesis
  2271     by blast
  2272 qed
  2273 
  2274 lemma ex_mset: "\<exists>xs. mset xs = X"
  2275   by (induct X) (simp, metis mset.simps(2))
  2276 
  2277 bnf "'a multiset"
  2278   map: image_mset
  2279   sets: set_mset
  2280   bd: natLeq
  2281   wits: "{#}"
  2282   rel: rel_mset
  2283 proof -
  2284   show "image_mset id = id"
  2285     by (rule image_mset.id)
  2286   show "image_mset (g \<circ> f) = image_mset g \<circ> image_mset f" for f g
  2287     unfolding comp_def by (rule ext) (simp add: comp_def image_mset.compositionality)
  2288   show "(\<And>z. z \<in> set_mset X \<Longrightarrow> f z = g z) \<Longrightarrow> image_mset f X = image_mset g X" for f g X
  2289     by (induct X) (simp_all (no_asm),
  2290       metis One_nat_def Un_iff count_single mem_set_mset_iff set_mset_union zero_less_Suc)
  2291   show "set_mset \<circ> image_mset f = op ` f \<circ> set_mset" for f
  2292     by auto
  2293   show "card_order natLeq"
  2294     by (rule natLeq_card_order)
  2295   show "BNF_Cardinal_Arithmetic.cinfinite natLeq"
  2296     by (rule natLeq_cinfinite)
  2297   show "ordLeq3 (card_of (set_mset X)) natLeq" for X
  2298     by transfer
  2299       (auto intro!: ordLess_imp_ordLeq simp: finite_iff_ordLess_natLeq[symmetric] multiset_def)
  2300   show "rel_mset R OO rel_mset S \<le> rel_mset (R OO S)" for R S
  2301     unfolding rel_mset_def[abs_def] OO_def
  2302     apply clarify
  2303     apply (rename_tac X Z Y xs ys' ys zs)
  2304     apply (drule_tac xs = ys' and ys = zs and xs' = ys in list_all2_reorder_left_invariance)
  2305     apply (auto intro: list_all2_trans)
  2306     done
  2307   show "rel_mset R =
  2308     (BNF_Def.Grp {x. set_mset x \<subseteq> {(x, y). R x y}} (image_mset fst))\<inverse>\<inverse> OO
  2309     BNF_Def.Grp {x. set_mset x \<subseteq> {(x, y). R x y}} (image_mset snd)" for R
  2310     unfolding rel_mset_def[abs_def] BNF_Def.Grp_def OO_def
  2311     apply (rule ext)+
  2312     apply auto
  2313      apply (rule_tac x = "mset (zip xs ys)" in exI; auto)
  2314         apply (metis list_all2_lengthD map_fst_zip mset_map)
  2315        apply (auto simp: list_all2_iff)[1]
  2316       apply (metis list_all2_lengthD map_snd_zip mset_map)
  2317      apply (auto simp: list_all2_iff)[1]
  2318     apply (rename_tac XY)
  2319     apply (cut_tac X = XY in ex_mset)
  2320     apply (erule exE)
  2321     apply (rename_tac xys)
  2322     apply (rule_tac x = "map fst xys" in exI)
  2323     apply (auto simp: mset_map)
  2324     apply (rule_tac x = "map snd xys" in exI)
  2325     apply (auto simp: mset_map list_all2I subset_eq zip_map_fst_snd)
  2326     done
  2327   show "z \<in> set_mset {#} \<Longrightarrow> False" for z
  2328     by auto
  2329 qed
  2330 
  2331 inductive rel_mset'
  2332 where
  2333   Zero[intro]: "rel_mset' R {#} {#}"
  2334 | Plus[intro]: "\<lbrakk>R a b; rel_mset' R M N\<rbrakk> \<Longrightarrow> rel_mset' R (M + {#a#}) (N + {#b#})"
  2335 
  2336 lemma rel_mset_Zero: "rel_mset R {#} {#}"
  2337 unfolding rel_mset_def Grp_def by auto
  2338 
  2339 declare multiset.count[simp]
  2340 declare Abs_multiset_inverse[simp]
  2341 declare multiset.count_inverse[simp]
  2342 declare union_preserves_multiset[simp]
  2343 
  2344 lemma rel_mset_Plus:
  2345   assumes ab: "R a b"
  2346     and MN: "rel_mset R M N"
  2347   shows "rel_mset R (M + {#a#}) (N + {#b#})"
  2348 proof -
  2349   have "\<exists>ya. image_mset fst y + {#a#} = image_mset fst ya \<and>
  2350     image_mset snd y + {#b#} = image_mset snd ya \<and>
  2351     set_mset ya \<subseteq> {(x, y). R x y}"
  2352     if "R a b" and "set_mset y \<subseteq> {(x, y). R x y}" for y
  2353     using that by (intro exI[of _ "y + {#(a,b)#}"]) auto
  2354   thus ?thesis
  2355   using assms
  2356   unfolding multiset.rel_compp_Grp Grp_def by blast
  2357 qed
  2358 
  2359 lemma rel_mset'_imp_rel_mset: "rel_mset' R M N \<Longrightarrow> rel_mset R M N"
  2360 apply(induct rule: rel_mset'.induct)
  2361 using rel_mset_Zero rel_mset_Plus by auto
  2362 
  2363 lemma rel_mset_size: "rel_mset R M N \<Longrightarrow> size M = size N"
  2364 unfolding multiset.rel_compp_Grp Grp_def by auto
  2365 
  2366 lemma multiset_induct2[case_names empty addL addR]:
  2367 assumes empty: "P {#} {#}"
  2368 and addL: "\<And>M N a. P M N \<Longrightarrow> P (M + {#a#}) N"
  2369 and addR: "\<And>M N a. P M N \<Longrightarrow> P M (N + {#a#})"
  2370 shows "P M N"
  2371 apply(induct N rule: multiset_induct)
  2372   apply(induct M rule: multiset_induct, rule empty, erule addL)
  2373   apply(induct M rule: multiset_induct, erule addR, erule addR)
  2374 done
  2375 
  2376 lemma multiset_induct2_size[consumes 1, case_names empty add]:
  2377   assumes c: "size M = size N"
  2378     and empty: "P {#} {#}"
  2379     and add: "\<And>M N a b. P M N \<Longrightarrow> P (M + {#a#}) (N + {#b#})"
  2380   shows "P M N"
  2381 using c proof(induct M arbitrary: N rule: measure_induct_rule[of size])
  2382   case (less M)
  2383   show ?case
  2384   proof(cases "M = {#}")
  2385     case True hence "N = {#}" using less.prems by auto
  2386     thus ?thesis using True empty by auto
  2387   next
  2388     case False then obtain M1 a where M: "M = M1 + {#a#}" by (metis multi_nonempty_split)
  2389     have "N \<noteq> {#}" using False less.prems by auto
  2390     then obtain N1 b where N: "N = N1 + {#b#}" by (metis multi_nonempty_split)
  2391     have "size M1 = size N1" using less.prems unfolding M N by auto
  2392     thus ?thesis using M N less.hyps add by auto
  2393   qed
  2394 qed
  2395 
  2396 lemma msed_map_invL:
  2397   assumes "image_mset f (M + {#a#}) = N"
  2398   shows "\<exists>N1. N = N1 + {#f a#} \<and> image_mset f M = N1"
  2399 proof -
  2400   have "f a \<in># N"
  2401     using assms multiset.set_map[of f "M + {#a#}"] by auto
  2402   then obtain N1 where N: "N = N1 + {#f a#}" using multi_member_split by metis
  2403   have "image_mset f M = N1" using assms unfolding N by simp
  2404   thus ?thesis using N by blast
  2405 qed
  2406 
  2407 lemma msed_map_invR:
  2408   assumes "image_mset f M = N + {#b#}"
  2409   shows "\<exists>M1 a. M = M1 + {#a#} \<and> f a = b \<and> image_mset f M1 = N"
  2410 proof -
  2411   obtain a where a: "a \<in># M" and fa: "f a = b"
  2412     using multiset.set_map[of f M] unfolding assms
  2413     by (metis image_iff mem_set_mset_iff union_single_eq_member)
  2414   then obtain M1 where M: "M = M1 + {#a#}" using multi_member_split by metis
  2415   have "image_mset f M1 = N" using assms unfolding M fa[symmetric] by simp
  2416   thus ?thesis using M fa by blast
  2417 qed
  2418 
  2419 lemma msed_rel_invL:
  2420   assumes "rel_mset R (M + {#a#}) N"
  2421   shows "\<exists>N1 b. N = N1 + {#b#} \<and> R a b \<and> rel_mset R M N1"
  2422 proof -
  2423   obtain K where KM: "image_mset fst K = M + {#a#}"
  2424     and KN: "image_mset snd K = N" and sK: "set_mset K \<subseteq> {(a, b). R a b}"
  2425     using assms
  2426     unfolding multiset.rel_compp_Grp Grp_def by auto
  2427   obtain K1 ab where K: "K = K1 + {#ab#}" and a: "fst ab = a"
  2428     and K1M: "image_mset fst K1 = M" using msed_map_invR[OF KM] by auto
  2429   obtain N1 where N: "N = N1 + {#snd ab#}" and K1N1: "image_mset snd K1 = N1"
  2430     using msed_map_invL[OF KN[unfolded K]] by auto
  2431   have Rab: "R a (snd ab)" using sK a unfolding K by auto
  2432   have "rel_mset R M N1" using sK K1M K1N1
  2433     unfolding K multiset.rel_compp_Grp Grp_def by auto
  2434   thus ?thesis using N Rab by auto
  2435 qed
  2436 
  2437 lemma msed_rel_invR:
  2438   assumes "rel_mset R M (N + {#b#})"
  2439   shows "\<exists>M1 a. M = M1 + {#a#} \<and> R a b \<and> rel_mset R M1 N"
  2440 proof -
  2441   obtain K where KN: "image_mset snd K = N + {#b#}"
  2442     and KM: "image_mset fst K = M" and sK: "set_mset K \<subseteq> {(a, b). R a b}"
  2443     using assms
  2444     unfolding multiset.rel_compp_Grp Grp_def by auto
  2445   obtain K1 ab where K: "K = K1 + {#ab#}" and b: "snd ab = b"
  2446     and K1N: "image_mset snd K1 = N" using msed_map_invR[OF KN] by auto
  2447   obtain M1 where M: "M = M1 + {#fst ab#}" and K1M1: "image_mset fst K1 = M1"
  2448     using msed_map_invL[OF KM[unfolded K]] by auto
  2449   have Rab: "R (fst ab) b" using sK b unfolding K by auto
  2450   have "rel_mset R M1 N" using sK K1N K1M1
  2451     unfolding K multiset.rel_compp_Grp Grp_def by auto
  2452   thus ?thesis using M Rab by auto
  2453 qed
  2454 
  2455 lemma rel_mset_imp_rel_mset':
  2456   assumes "rel_mset R M N"
  2457   shows "rel_mset' R M N"
  2458 using assms proof(induct M arbitrary: N rule: measure_induct_rule[of size])
  2459   case (less M)
  2460   have c: "size M = size N" using rel_mset_size[OF less.prems] .
  2461   show ?case
  2462   proof(cases "M = {#}")
  2463     case True hence "N = {#}" using c by simp
  2464     thus ?thesis using True rel_mset'.Zero by auto
  2465   next
  2466     case False then obtain M1 a where M: "M = M1 + {#a#}" by (metis multi_nonempty_split)
  2467     obtain N1 b where N: "N = N1 + {#b#}" and R: "R a b" and ms: "rel_mset R M1 N1"
  2468       using msed_rel_invL[OF less.prems[unfolded M]] by auto
  2469     have "rel_mset' R M1 N1" using less.hyps[of M1 N1] ms unfolding M by simp
  2470     thus ?thesis using rel_mset'.Plus[of R a b, OF R] unfolding M N by simp
  2471   qed
  2472 qed
  2473 
  2474 lemma rel_mset_rel_mset': "rel_mset R M N = rel_mset' R M N"
  2475 using rel_mset_imp_rel_mset' rel_mset'_imp_rel_mset by auto
  2476 
  2477 text \<open>The main end product for rel_mset: inductive characterization:\<close>
  2478 theorems rel_mset_induct[case_names empty add, induct pred: rel_mset] =
  2479   rel_mset'.induct[unfolded rel_mset_rel_mset'[symmetric]]
  2480 
  2481 
  2482 subsection \<open>Size setup\<close>
  2483 
  2484 lemma multiset_size_o_map: "size_multiset g \<circ> image_mset f = size_multiset (g \<circ> f)"
  2485   unfolding o_apply by (rule ext) (induct_tac, auto)
  2486 
  2487 setup \<open>
  2488   BNF_LFP_Size.register_size_global @{type_name multiset} @{const_name size_multiset}
  2489     @{thms size_multiset_empty size_multiset_single size_multiset_union size_empty size_single
  2490       size_union}
  2491     @{thms multiset_size_o_map}
  2492 \<close>
  2493 
  2494 hide_const (open) wcount
  2495 
  2496 end