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