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