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