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