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