src/HOL/Library/Multiset.thy
author bulwahn
Wed Mar 28 10:16:02 2012 +0200 (2012-03-28)
changeset 47179 54b38de0620e
parent 47177 2fa00264392a
child 47198 cfd8ff62eab1
permissions -rw-r--r--
changing more definitions to quotient_definition
     1 (*  Title:      HOL/Library/Multiset.thy
     2     Author:     Tobias Nipkow, Markus Wenzel, Lawrence C Paulson, Norbert Voelker
     3 *)
     4 
     5 header {* (Finite) multisets *}
     6 
     7 theory Multiset
     8 imports Main DAList
     9 begin
    10 
    11 subsection {* The type of multisets *}
    12 
    13 definition "multiset = {f :: 'a => nat. finite {x. f x > 0}}"
    14 
    15 typedef (open) 'a multiset = "multiset :: ('a => nat) set"
    16   morphisms count Abs_multiset
    17   unfolding multiset_def
    18 proof
    19   show "(\<lambda>x. 0::nat) \<in> {f. finite {x. f x > 0}}" by simp
    20 qed
    21 
    22 lemmas multiset_typedef = Abs_multiset_inverse count_inverse count
    23 
    24 abbreviation Melem :: "'a => 'a multiset => bool"  ("(_/ :# _)" [50, 51] 50) where
    25   "a :# M == 0 < count M a"
    26 
    27 notation (xsymbols)
    28   Melem (infix "\<in>#" 50)
    29 
    30 lemma multiset_eq_iff:
    31   "M = N \<longleftrightarrow> (\<forall>a. count M a = count N a)"
    32   by (simp only: count_inject [symmetric] fun_eq_iff)
    33 
    34 lemma multiset_eqI:
    35   "(\<And>x. count A x = count B x) \<Longrightarrow> A = B"
    36   using multiset_eq_iff by auto
    37 
    38 text {*
    39  \medskip Preservation of the representing set @{term multiset}.
    40 *}
    41 
    42 lemma const0_in_multiset:
    43   "(\<lambda>a. 0) \<in> multiset"
    44   by (simp add: multiset_def)
    45 
    46 lemma only1_in_multiset:
    47   "(\<lambda>b. if b = a then n else 0) \<in> multiset"
    48   by (simp add: multiset_def)
    49 
    50 lemma union_preserves_multiset:
    51   "M \<in> multiset \<Longrightarrow> N \<in> multiset \<Longrightarrow> (\<lambda>a. M a + N a) \<in> multiset"
    52   by (simp add: multiset_def)
    53 
    54 lemma diff_preserves_multiset:
    55   assumes "M \<in> multiset"
    56   shows "(\<lambda>a. M a - N a) \<in> multiset"
    57 proof -
    58   have "{x. N x < M x} \<subseteq> {x. 0 < M x}"
    59     by auto
    60   with assms show ?thesis
    61     by (auto simp add: multiset_def intro: finite_subset)
    62 qed
    63 
    64 lemma filter_preserves_multiset:
    65   assumes "M \<in> multiset"
    66   shows "(\<lambda>x. if P x then M x else 0) \<in> multiset"
    67 proof -
    68   have "{x. (P x \<longrightarrow> 0 < M x) \<and> P x} \<subseteq> {x. 0 < M x}"
    69     by auto
    70   with assms show ?thesis
    71     by (auto simp add: multiset_def intro: finite_subset)
    72 qed
    73 
    74 lemmas in_multiset = const0_in_multiset only1_in_multiset
    75   union_preserves_multiset diff_preserves_multiset filter_preserves_multiset
    76 
    77 
    78 subsection {* Representing multisets *}
    79 
    80 text {* Multiset enumeration *}
    81 
    82 instantiation multiset :: (type) "{zero, plus}"
    83 begin
    84 
    85 definition Mempty_def:
    86   "0 = Abs_multiset (\<lambda>a. 0)"
    87 
    88 abbreviation Mempty :: "'a multiset" ("{#}") where
    89   "Mempty \<equiv> 0"
    90 
    91 definition union_def:
    92   "M + N = Abs_multiset (\<lambda>a. count M a + count N a)"
    93 
    94 instance ..
    95 
    96 end
    97 
    98 definition single :: "'a => 'a multiset" where
    99   "single a = Abs_multiset (\<lambda>b. if b = a then 1 else 0)"
   100 
   101 syntax
   102   "_multiset" :: "args => 'a multiset"    ("{#(_)#}")
   103 translations
   104   "{#x, xs#}" == "{#x#} + {#xs#}"
   105   "{#x#}" == "CONST single x"
   106 
   107 lemma count_empty [simp]: "count {#} a = 0"
   108   by (simp add: Mempty_def in_multiset multiset_typedef)
   109 
   110 lemma count_single [simp]: "count {#b#} a = (if b = a then 1 else 0)"
   111   by (simp add: single_def in_multiset multiset_typedef)
   112 
   113 
   114 subsection {* Basic operations *}
   115 
   116 subsubsection {* Union *}
   117 
   118 lemma count_union [simp]: "count (M + N) a = count M a + count N a"
   119   by (simp add: union_def in_multiset multiset_typedef)
   120 
   121 instance multiset :: (type) cancel_comm_monoid_add
   122   by default (simp_all add: multiset_eq_iff)
   123 
   124 
   125 subsubsection {* Difference *}
   126 
   127 instantiation multiset :: (type) minus
   128 begin
   129 
   130 definition diff_def:
   131   "M - N = Abs_multiset (\<lambda>a. count M a - count N a)"
   132 
   133 instance ..
   134 
   135 end
   136 
   137 lemma count_diff [simp]: "count (M - N) a = count M a - count N a"
   138   by (simp add: diff_def in_multiset multiset_typedef)
   139 
   140 lemma diff_empty [simp]: "M - {#} = M \<and> {#} - M = {#}"
   141 by(simp add: multiset_eq_iff)
   142 
   143 lemma diff_cancel[simp]: "A - A = {#}"
   144 by (rule multiset_eqI) simp
   145 
   146 lemma diff_union_cancelR [simp]: "M + N - N = (M::'a multiset)"
   147 by(simp add: multiset_eq_iff)
   148 
   149 lemma diff_union_cancelL [simp]: "N + M - N = (M::'a multiset)"
   150 by(simp add: multiset_eq_iff)
   151 
   152 lemma insert_DiffM:
   153   "x \<in># M \<Longrightarrow> {#x#} + (M - {#x#}) = M"
   154   by (clarsimp simp: multiset_eq_iff)
   155 
   156 lemma insert_DiffM2 [simp]:
   157   "x \<in># M \<Longrightarrow> M - {#x#} + {#x#} = M"
   158   by (clarsimp simp: multiset_eq_iff)
   159 
   160 lemma diff_right_commute:
   161   "(M::'a multiset) - N - Q = M - Q - N"
   162   by (auto simp add: multiset_eq_iff)
   163 
   164 lemma diff_add:
   165   "(M::'a multiset) - (N + Q) = M - N - Q"
   166 by (simp add: multiset_eq_iff)
   167 
   168 lemma diff_union_swap:
   169   "a \<noteq> b \<Longrightarrow> M - {#a#} + {#b#} = M + {#b#} - {#a#}"
   170   by (auto simp add: multiset_eq_iff)
   171 
   172 lemma diff_union_single_conv:
   173   "a \<in># J \<Longrightarrow> I + J - {#a#} = I + (J - {#a#})"
   174   by (simp add: multiset_eq_iff)
   175 
   176 
   177 subsubsection {* Equality of multisets *}
   178 
   179 lemma single_not_empty [simp]: "{#a#} \<noteq> {#} \<and> {#} \<noteq> {#a#}"
   180   by (simp add: multiset_eq_iff)
   181 
   182 lemma single_eq_single [simp]: "{#a#} = {#b#} \<longleftrightarrow> a = b"
   183   by (auto simp add: multiset_eq_iff)
   184 
   185 lemma union_eq_empty [iff]: "M + N = {#} \<longleftrightarrow> M = {#} \<and> N = {#}"
   186   by (auto simp add: multiset_eq_iff)
   187 
   188 lemma empty_eq_union [iff]: "{#} = M + N \<longleftrightarrow> M = {#} \<and> N = {#}"
   189   by (auto simp add: multiset_eq_iff)
   190 
   191 lemma multi_self_add_other_not_self [simp]: "M = M + {#x#} \<longleftrightarrow> False"
   192   by (auto simp add: multiset_eq_iff)
   193 
   194 lemma diff_single_trivial:
   195   "\<not> x \<in># M \<Longrightarrow> M - {#x#} = M"
   196   by (auto simp add: multiset_eq_iff)
   197 
   198 lemma diff_single_eq_union:
   199   "x \<in># M \<Longrightarrow> M - {#x#} = N \<longleftrightarrow> M = N + {#x#}"
   200   by auto
   201 
   202 lemma union_single_eq_diff:
   203   "M + {#x#} = N \<Longrightarrow> M = N - {#x#}"
   204   by (auto dest: sym)
   205 
   206 lemma union_single_eq_member:
   207   "M + {#x#} = N \<Longrightarrow> x \<in># N"
   208   by auto
   209 
   210 lemma union_is_single:
   211   "M + N = {#a#} \<longleftrightarrow> M = {#a#} \<and> N={#} \<or> M = {#} \<and> N = {#a#}" (is "?lhs = ?rhs")
   212 proof
   213   assume ?rhs then show ?lhs by auto
   214 next
   215   assume ?lhs then show ?rhs
   216     by (simp add: multiset_eq_iff split:if_splits) (metis add_is_1)
   217 qed
   218 
   219 lemma single_is_union:
   220   "{#a#} = M + N \<longleftrightarrow> {#a#} = M \<and> N = {#} \<or> M = {#} \<and> {#a#} = N"
   221   by (auto simp add: eq_commute [of "{#a#}" "M + N"] union_is_single)
   222 
   223 lemma add_eq_conv_diff:
   224   "M + {#a#} = N + {#b#} \<longleftrightarrow> M = N \<and> a = b \<or> M = N - {#a#} + {#b#} \<and> N = M - {#b#} + {#a#}"  (is "?lhs = ?rhs")
   225 (* shorter: by (simp add: multiset_eq_iff) fastforce *)
   226 proof
   227   assume ?rhs then show ?lhs
   228   by (auto simp add: add_assoc add_commute [of "{#b#}"])
   229     (drule sym, simp add: add_assoc [symmetric])
   230 next
   231   assume ?lhs
   232   show ?rhs
   233   proof (cases "a = b")
   234     case True with `?lhs` show ?thesis by simp
   235   next
   236     case False
   237     from `?lhs` have "a \<in># N + {#b#}" by (rule union_single_eq_member)
   238     with False have "a \<in># N" by auto
   239     moreover from `?lhs` have "M = N + {#b#} - {#a#}" by (rule union_single_eq_diff)
   240     moreover note False
   241     ultimately show ?thesis by (auto simp add: diff_right_commute [of _ "{#a#}"] diff_union_swap)
   242   qed
   243 qed
   244 
   245 lemma insert_noteq_member: 
   246   assumes BC: "B + {#b#} = C + {#c#}"
   247    and bnotc: "b \<noteq> c"
   248   shows "c \<in># B"
   249 proof -
   250   have "c \<in># C + {#c#}" by simp
   251   have nc: "\<not> c \<in># {#b#}" using bnotc by simp
   252   then have "c \<in># B + {#b#}" using BC by simp
   253   then show "c \<in># B" using nc by simp
   254 qed
   255 
   256 lemma add_eq_conv_ex:
   257   "(M + {#a#} = N + {#b#}) =
   258     (M = N \<and> a = b \<or> (\<exists>K. M = K + {#b#} \<and> N = K + {#a#}))"
   259   by (auto simp add: add_eq_conv_diff)
   260 
   261 
   262 subsubsection {* Pointwise ordering induced by count *}
   263 
   264 instantiation multiset :: (type) ordered_ab_semigroup_add_imp_le
   265 begin
   266 
   267 definition less_eq_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" where
   268   mset_le_def: "A \<le> B \<longleftrightarrow> (\<forall>a. count A a \<le> count B a)"
   269 
   270 definition less_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" where
   271   mset_less_def: "(A::'a multiset) < B \<longleftrightarrow> A \<le> B \<and> A \<noteq> B"
   272 
   273 instance
   274   by default (auto simp add: mset_le_def mset_less_def multiset_eq_iff intro: order_trans antisym)
   275 
   276 end
   277 
   278 lemma mset_less_eqI:
   279   "(\<And>x. count A x \<le> count B x) \<Longrightarrow> A \<le> B"
   280   by (simp add: mset_le_def)
   281 
   282 lemma mset_le_exists_conv:
   283   "(A::'a multiset) \<le> B \<longleftrightarrow> (\<exists>C. B = A + C)"
   284 apply (unfold mset_le_def, rule iffI, rule_tac x = "B - A" in exI)
   285 apply (auto intro: multiset_eq_iff [THEN iffD2])
   286 done
   287 
   288 lemma mset_le_mono_add_right_cancel [simp]:
   289   "(A::'a multiset) + C \<le> B + C \<longleftrightarrow> A \<le> B"
   290   by (fact add_le_cancel_right)
   291 
   292 lemma mset_le_mono_add_left_cancel [simp]:
   293   "C + (A::'a multiset) \<le> C + B \<longleftrightarrow> A \<le> B"
   294   by (fact add_le_cancel_left)
   295 
   296 lemma mset_le_mono_add:
   297   "(A::'a multiset) \<le> B \<Longrightarrow> C \<le> D \<Longrightarrow> A + C \<le> B + D"
   298   by (fact add_mono)
   299 
   300 lemma mset_le_add_left [simp]:
   301   "(A::'a multiset) \<le> A + B"
   302   unfolding mset_le_def by auto
   303 
   304 lemma mset_le_add_right [simp]:
   305   "B \<le> (A::'a multiset) + B"
   306   unfolding mset_le_def by auto
   307 
   308 lemma mset_le_single:
   309   "a :# B \<Longrightarrow> {#a#} \<le> B"
   310   by (simp add: mset_le_def)
   311 
   312 lemma multiset_diff_union_assoc:
   313   "C \<le> B \<Longrightarrow> (A::'a multiset) + B - C = A + (B - C)"
   314   by (simp add: multiset_eq_iff mset_le_def)
   315 
   316 lemma mset_le_multiset_union_diff_commute:
   317   "B \<le> A \<Longrightarrow> (A::'a multiset) - B + C = A + C - B"
   318 by (simp add: multiset_eq_iff mset_le_def)
   319 
   320 lemma diff_le_self[simp]: "(M::'a multiset) - N \<le> M"
   321 by(simp add: mset_le_def)
   322 
   323 lemma mset_lessD: "A < B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
   324 apply (clarsimp simp: mset_le_def mset_less_def)
   325 apply (erule_tac x=x in allE)
   326 apply auto
   327 done
   328 
   329 lemma mset_leD: "A \<le> B \<Longrightarrow> x \<in># A \<Longrightarrow> x \<in># B"
   330 apply (clarsimp simp: mset_le_def mset_less_def)
   331 apply (erule_tac x = x in allE)
   332 apply auto
   333 done
   334   
   335 lemma mset_less_insertD: "(A + {#x#} < B) \<Longrightarrow> (x \<in># B \<and> A < B)"
   336 apply (rule conjI)
   337  apply (simp add: mset_lessD)
   338 apply (clarsimp simp: mset_le_def mset_less_def)
   339 apply safe
   340  apply (erule_tac x = a in allE)
   341  apply (auto split: split_if_asm)
   342 done
   343 
   344 lemma mset_le_insertD: "(A + {#x#} \<le> B) \<Longrightarrow> (x \<in># B \<and> A \<le> B)"
   345 apply (rule conjI)
   346  apply (simp add: mset_leD)
   347 apply (force simp: mset_le_def mset_less_def split: split_if_asm)
   348 done
   349 
   350 lemma mset_less_of_empty[simp]: "A < {#} \<longleftrightarrow> False"
   351   by (auto simp add: mset_less_def mset_le_def multiset_eq_iff)
   352 
   353 lemma multi_psub_of_add_self[simp]: "A < A + {#x#}"
   354   by (auto simp: mset_le_def mset_less_def)
   355 
   356 lemma multi_psub_self[simp]: "(A::'a multiset) < A = False"
   357   by simp
   358 
   359 lemma mset_less_add_bothsides:
   360   "T + {#x#} < S + {#x#} \<Longrightarrow> T < S"
   361   by (fact add_less_imp_less_right)
   362 
   363 lemma mset_less_empty_nonempty:
   364   "{#} < S \<longleftrightarrow> S \<noteq> {#}"
   365   by (auto simp: mset_le_def mset_less_def)
   366 
   367 lemma mset_less_diff_self:
   368   "c \<in># B \<Longrightarrow> B - {#c#} < B"
   369   by (auto simp: mset_le_def mset_less_def multiset_eq_iff)
   370 
   371 
   372 subsubsection {* Intersection *}
   373 
   374 instantiation multiset :: (type) semilattice_inf
   375 begin
   376 
   377 definition inf_multiset :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
   378   multiset_inter_def: "inf_multiset A B = A - (A - B)"
   379 
   380 instance
   381 proof -
   382   have aux: "\<And>m n q :: nat. m \<le> n \<Longrightarrow> m \<le> q \<Longrightarrow> m \<le> n - (n - q)" by arith
   383   show "OFCLASS('a multiset, semilattice_inf_class)"
   384     by default (auto simp add: multiset_inter_def mset_le_def aux)
   385 qed
   386 
   387 end
   388 
   389 abbreviation multiset_inter :: "'a multiset \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" (infixl "#\<inter>" 70) where
   390   "multiset_inter \<equiv> inf"
   391 
   392 lemma multiset_inter_count [simp]:
   393   "count (A #\<inter> B) x = min (count A x) (count B x)"
   394   by (simp add: multiset_inter_def multiset_typedef)
   395 
   396 lemma multiset_inter_single: "a \<noteq> b \<Longrightarrow> {#a#} #\<inter> {#b#} = {#}"
   397   by (rule multiset_eqI) auto
   398 
   399 lemma multiset_union_diff_commute:
   400   assumes "B #\<inter> C = {#}"
   401   shows "A + B - C = A - C + B"
   402 proof (rule multiset_eqI)
   403   fix x
   404   from assms have "min (count B x) (count C x) = 0"
   405     by (auto simp add: multiset_eq_iff)
   406   then have "count B x = 0 \<or> count C x = 0"
   407     by auto
   408   then show "count (A + B - C) x = count (A - C + B) x"
   409     by auto
   410 qed
   411 
   412 
   413 subsubsection {* Filter (with comprehension syntax) *}
   414 
   415 text {* Multiset comprehension *}
   416 
   417 definition filter :: "('a \<Rightarrow> bool) \<Rightarrow> 'a multiset \<Rightarrow> 'a multiset" where
   418   "filter P M = Abs_multiset (\<lambda>x. if P x then count M x else 0)"
   419 
   420 hide_const (open) filter
   421 
   422 lemma count_filter [simp]:
   423   "count (Multiset.filter P M) a = (if P a then count M a else 0)"
   424   by (simp add: filter_def in_multiset multiset_typedef)
   425 
   426 lemma filter_empty [simp]:
   427   "Multiset.filter P {#} = {#}"
   428   by (rule multiset_eqI) simp
   429 
   430 lemma filter_single [simp]:
   431   "Multiset.filter P {#x#} = (if P x then {#x#} else {#})"
   432   by (rule multiset_eqI) simp
   433 
   434 lemma filter_union [simp]:
   435   "Multiset.filter P (M + N) = Multiset.filter P M + Multiset.filter P N"
   436   by (rule multiset_eqI) simp
   437 
   438 lemma filter_diff [simp]:
   439   "Multiset.filter P (M - N) = Multiset.filter P M - Multiset.filter P N"
   440   by (rule multiset_eqI) simp
   441 
   442 lemma filter_inter [simp]:
   443   "Multiset.filter P (M #\<inter> N) = Multiset.filter P M #\<inter> Multiset.filter P N"
   444   by (rule multiset_eqI) simp
   445 
   446 syntax
   447   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ :# _./ _#})")
   448 syntax (xsymbol)
   449   "_MCollect" :: "pttrn \<Rightarrow> 'a multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"    ("(1{# _ \<in># _./ _#})")
   450 translations
   451   "{#x \<in># M. P#}" == "CONST Multiset.filter (\<lambda>x. P) M"
   452 
   453 
   454 subsubsection {* Set of elements *}
   455 
   456 definition set_of :: "'a multiset => 'a set" where
   457   "set_of M = {x. x :# M}"
   458 
   459 lemma set_of_empty [simp]: "set_of {#} = {}"
   460 by (simp add: set_of_def)
   461 
   462 lemma set_of_single [simp]: "set_of {#b#} = {b}"
   463 by (simp add: set_of_def)
   464 
   465 lemma set_of_union [simp]: "set_of (M + N) = set_of M \<union> set_of N"
   466 by (auto simp add: set_of_def)
   467 
   468 lemma set_of_eq_empty_iff [simp]: "(set_of M = {}) = (M = {#})"
   469 by (auto simp add: set_of_def multiset_eq_iff)
   470 
   471 lemma mem_set_of_iff [simp]: "(x \<in> set_of M) = (x :# M)"
   472 by (auto simp add: set_of_def)
   473 
   474 lemma set_of_filter [simp]: "set_of {# x:#M. P x #} = set_of M \<inter> {x. P x}"
   475 by (auto simp add: set_of_def)
   476 
   477 lemma finite_set_of [iff]: "finite (set_of M)"
   478   using count [of M] by (simp add: multiset_def set_of_def)
   479 
   480 lemma finite_Collect_mem [iff]: "finite {x. x :# M}"
   481   unfolding set_of_def[symmetric] by simp
   482 
   483 subsubsection {* Size *}
   484 
   485 instantiation multiset :: (type) size
   486 begin
   487 
   488 definition size_def:
   489   "size M = setsum (count M) (set_of M)"
   490 
   491 instance ..
   492 
   493 end
   494 
   495 lemma size_empty [simp]: "size {#} = 0"
   496 by (simp add: size_def)
   497 
   498 lemma size_single [simp]: "size {#b#} = 1"
   499 by (simp add: size_def)
   500 
   501 lemma setsum_count_Int:
   502   "finite A ==> setsum (count N) (A \<inter> set_of N) = setsum (count N) A"
   503 apply (induct rule: finite_induct)
   504  apply simp
   505 apply (simp add: Int_insert_left set_of_def)
   506 done
   507 
   508 lemma size_union [simp]: "size (M + N::'a multiset) = size M + size N"
   509 apply (unfold size_def)
   510 apply (subgoal_tac "count (M + N) = (\<lambda>a. count M a + count N a)")
   511  prefer 2
   512  apply (rule ext, simp)
   513 apply (simp (no_asm_simp) add: setsum_Un_nat setsum_addf setsum_count_Int)
   514 apply (subst Int_commute)
   515 apply (simp (no_asm_simp) add: setsum_count_Int)
   516 done
   517 
   518 lemma size_eq_0_iff_empty [iff]: "(size M = 0) = (M = {#})"
   519 by (auto simp add: size_def multiset_eq_iff)
   520 
   521 lemma nonempty_has_size: "(S \<noteq> {#}) = (0 < size S)"
   522 by (metis gr0I gr_implies_not0 size_empty size_eq_0_iff_empty)
   523 
   524 lemma size_eq_Suc_imp_elem: "size M = Suc n ==> \<exists>a. a :# M"
   525 apply (unfold size_def)
   526 apply (drule setsum_SucD)
   527 apply auto
   528 done
   529 
   530 lemma size_eq_Suc_imp_eq_union:
   531   assumes "size M = Suc n"
   532   shows "\<exists>a N. M = N + {#a#}"
   533 proof -
   534   from assms obtain a where "a \<in># M"
   535     by (erule size_eq_Suc_imp_elem [THEN exE])
   536   then have "M = M - {#a#} + {#a#}" by simp
   537   then show ?thesis by blast
   538 qed
   539 
   540 
   541 subsection {* Induction and case splits *}
   542 
   543 lemma setsum_decr:
   544   "finite F ==> (0::nat) < f a ==>
   545     setsum (f (a := f a - 1)) F = (if a\<in>F then setsum f F - 1 else setsum f F)"
   546 apply (induct rule: finite_induct)
   547  apply auto
   548 apply (drule_tac a = a in mk_disjoint_insert, auto)
   549 done
   550 
   551 lemma rep_multiset_induct_aux:
   552 assumes 1: "P (\<lambda>a. (0::nat))"
   553   and 2: "!!f b. f \<in> multiset ==> P f ==> P (f (b := f b + 1))"
   554 shows "\<forall>f. f \<in> multiset --> setsum f {x. f x \<noteq> 0} = n --> P f"
   555 apply (unfold multiset_def)
   556 apply (induct_tac n, simp, clarify)
   557  apply (subgoal_tac "f = (\<lambda>a.0)")
   558   apply simp
   559   apply (rule 1)
   560  apply (rule ext, force, clarify)
   561 apply (frule setsum_SucD, clarify)
   562 apply (rename_tac a)
   563 apply (subgoal_tac "finite {x. (f (a := f a - 1)) x > 0}")
   564  prefer 2
   565  apply (rule finite_subset)
   566   prefer 2
   567   apply assumption
   568  apply simp
   569  apply blast
   570 apply (subgoal_tac "f = (f (a := f a - 1))(a := (f (a := f a - 1)) a + 1)")
   571  prefer 2
   572  apply (rule ext)
   573  apply (simp (no_asm_simp))
   574  apply (erule ssubst, rule 2 [unfolded multiset_def], blast)
   575 apply (erule allE, erule impE, erule_tac [2] mp, blast)
   576 apply (simp (no_asm_simp) add: setsum_decr del: fun_upd_apply One_nat_def)
   577 apply (subgoal_tac "{x. x \<noteq> a --> f x \<noteq> 0} = {x. f x \<noteq> 0}")
   578  prefer 2
   579  apply blast
   580 apply (subgoal_tac "{x. x \<noteq> a \<and> f x \<noteq> 0} = {x. f x \<noteq> 0} - {a}")
   581  prefer 2
   582  apply blast
   583 apply (simp add: le_imp_diff_is_add setsum_diff1_nat cong: conj_cong)
   584 done
   585 
   586 theorem rep_multiset_induct:
   587   "f \<in> multiset ==> P (\<lambda>a. 0) ==>
   588     (!!f b. f \<in> multiset ==> P f ==> P (f (b := f b + 1))) ==> P f"
   589 using rep_multiset_induct_aux by blast
   590 
   591 theorem multiset_induct [case_names empty add, induct type: multiset]:
   592 assumes empty: "P {#}"
   593   and add: "!!M x. P M ==> P (M + {#x#})"
   594 shows "P M"
   595 proof -
   596   note defns = union_def single_def Mempty_def
   597   note add' = add [unfolded defns, simplified]
   598   have aux: "\<And>a::'a. count (Abs_multiset (\<lambda>b. if b = a then 1 else 0)) =
   599     (\<lambda>b. if b = a then 1 else 0)" by (simp add: Abs_multiset_inverse in_multiset) 
   600   show ?thesis
   601     apply (rule count_inverse [THEN subst])
   602     apply (rule count [THEN rep_multiset_induct])
   603      apply (rule empty [unfolded defns])
   604     apply (subgoal_tac "f(b := f b + 1) = (\<lambda>a. f a + (if a=b then 1 else 0))")
   605      prefer 2
   606      apply (simp add: fun_eq_iff)
   607     apply (erule ssubst)
   608     apply (erule Abs_multiset_inverse [THEN subst])
   609     apply (drule add')
   610     apply (simp add: aux)
   611     done
   612 qed
   613 
   614 lemma multi_nonempty_split: "M \<noteq> {#} \<Longrightarrow> \<exists>A a. M = A + {#a#}"
   615 by (induct M) auto
   616 
   617 lemma multiset_cases [cases type, case_names empty add]:
   618 assumes em:  "M = {#} \<Longrightarrow> P"
   619 assumes add: "\<And>N x. M = N + {#x#} \<Longrightarrow> P"
   620 shows "P"
   621 proof (cases "M = {#}")
   622   assume "M = {#}" then show ?thesis using em by simp
   623 next
   624   assume "M \<noteq> {#}"
   625   then obtain M' m where "M = M' + {#m#}" 
   626     by (blast dest: multi_nonempty_split)
   627   then show ?thesis using add by simp
   628 qed
   629 
   630 lemma multi_member_split: "x \<in># M \<Longrightarrow> \<exists>A. M = A + {#x#}"
   631 apply (cases M)
   632  apply simp
   633 apply (rule_tac x="M - {#x#}" in exI, simp)
   634 done
   635 
   636 lemma multi_drop_mem_not_eq: "c \<in># B \<Longrightarrow> B - {#c#} \<noteq> B"
   637 by (cases "B = {#}") (auto dest: multi_member_split)
   638 
   639 lemma multiset_partition: "M = {# x:#M. P x #} + {# x:#M. \<not> P x #}"
   640 apply (subst multiset_eq_iff)
   641 apply auto
   642 done
   643 
   644 lemma mset_less_size: "(A::'a multiset) < B \<Longrightarrow> size A < size B"
   645 proof (induct A arbitrary: B)
   646   case (empty M)
   647   then have "M \<noteq> {#}" by (simp add: mset_less_empty_nonempty)
   648   then obtain M' x where "M = M' + {#x#}" 
   649     by (blast dest: multi_nonempty_split)
   650   then show ?case by simp
   651 next
   652   case (add S x T)
   653   have IH: "\<And>B. S < B \<Longrightarrow> size S < size B" by fact
   654   have SxsubT: "S + {#x#} < T" by fact
   655   then have "x \<in># T" and "S < T" by (auto dest: mset_less_insertD)
   656   then obtain T' where T: "T = T' + {#x#}" 
   657     by (blast dest: multi_member_split)
   658   then have "S < T'" using SxsubT 
   659     by (blast intro: mset_less_add_bothsides)
   660   then have "size S < size T'" using IH by simp
   661   then show ?case using T by simp
   662 qed
   663 
   664 
   665 subsubsection {* Strong induction and subset induction for multisets *}
   666 
   667 text {* Well-foundedness of proper subset operator: *}
   668 
   669 text {* proper multiset subset *}
   670 
   671 definition
   672   mset_less_rel :: "('a multiset * 'a multiset) set" where
   673   "mset_less_rel = {(A,B). A < B}"
   674 
   675 lemma multiset_add_sub_el_shuffle: 
   676   assumes "c \<in># B" and "b \<noteq> c" 
   677   shows "B - {#c#} + {#b#} = B + {#b#} - {#c#}"
   678 proof -
   679   from `c \<in># B` obtain A where B: "B = A + {#c#}" 
   680     by (blast dest: multi_member_split)
   681   have "A + {#b#} = A + {#b#} + {#c#} - {#c#}" by simp
   682   then have "A + {#b#} = A + {#c#} + {#b#} - {#c#}" 
   683     by (simp add: add_ac)
   684   then show ?thesis using B by simp
   685 qed
   686 
   687 lemma wf_mset_less_rel: "wf mset_less_rel"
   688 apply (unfold mset_less_rel_def)
   689 apply (rule wf_measure [THEN wf_subset, where f1=size])
   690 apply (clarsimp simp: measure_def inv_image_def mset_less_size)
   691 done
   692 
   693 text {* The induction rules: *}
   694 
   695 lemma full_multiset_induct [case_names less]:
   696 assumes ih: "\<And>B. \<forall>(A::'a multiset). A < B \<longrightarrow> P A \<Longrightarrow> P B"
   697 shows "P B"
   698 apply (rule wf_mset_less_rel [THEN wf_induct])
   699 apply (rule ih, auto simp: mset_less_rel_def)
   700 done
   701 
   702 lemma multi_subset_induct [consumes 2, case_names empty add]:
   703 assumes "F \<le> A"
   704   and empty: "P {#}"
   705   and insert: "\<And>a F. a \<in># A \<Longrightarrow> P F \<Longrightarrow> P (F + {#a#})"
   706 shows "P F"
   707 proof -
   708   from `F \<le> A`
   709   show ?thesis
   710   proof (induct F)
   711     show "P {#}" by fact
   712   next
   713     fix x F
   714     assume P: "F \<le> A \<Longrightarrow> P F" and i: "F + {#x#} \<le> A"
   715     show "P (F + {#x#})"
   716     proof (rule insert)
   717       from i show "x \<in># A" by (auto dest: mset_le_insertD)
   718       from i have "F \<le> A" by (auto dest: mset_le_insertD)
   719       with P show "P F" .
   720     qed
   721   qed
   722 qed
   723 
   724 
   725 subsection {* Alternative representations *}
   726 
   727 subsubsection {* Lists *}
   728 
   729 primrec multiset_of :: "'a list \<Rightarrow> 'a multiset" where
   730   "multiset_of [] = {#}" |
   731   "multiset_of (a # x) = multiset_of x + {# a #}"
   732 
   733 lemma in_multiset_in_set:
   734   "x \<in># multiset_of xs \<longleftrightarrow> x \<in> set xs"
   735   by (induct xs) simp_all
   736 
   737 lemma count_multiset_of:
   738   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
   739   by (induct xs) simp_all
   740 
   741 lemma multiset_of_zero_iff[simp]: "(multiset_of x = {#}) = (x = [])"
   742 by (induct x) auto
   743 
   744 lemma multiset_of_zero_iff_right[simp]: "({#} = multiset_of x) = (x = [])"
   745 by (induct x) auto
   746 
   747 lemma set_of_multiset_of[simp]: "set_of (multiset_of x) = set x"
   748 by (induct x) auto
   749 
   750 lemma mem_set_multiset_eq: "x \<in> set xs = (x :# multiset_of xs)"
   751 by (induct xs) auto
   752 
   753 lemma multiset_of_append [simp]:
   754   "multiset_of (xs @ ys) = multiset_of xs + multiset_of ys"
   755   by (induct xs arbitrary: ys) (auto simp: add_ac)
   756 
   757 lemma multiset_of_filter:
   758   "multiset_of (filter P xs) = {#x :# multiset_of xs. P x #}"
   759   by (induct xs) simp_all
   760 
   761 lemma multiset_of_rev [simp]:
   762   "multiset_of (rev xs) = multiset_of xs"
   763   by (induct xs) simp_all
   764 
   765 lemma surj_multiset_of: "surj multiset_of"
   766 apply (unfold surj_def)
   767 apply (rule allI)
   768 apply (rule_tac M = y in multiset_induct)
   769  apply auto
   770 apply (rule_tac x = "x # xa" in exI)
   771 apply auto
   772 done
   773 
   774 lemma set_count_greater_0: "set x = {a. count (multiset_of x) a > 0}"
   775 by (induct x) auto
   776 
   777 lemma distinct_count_atmost_1:
   778   "distinct x = (! a. count (multiset_of x) a = (if a \<in> set x then 1 else 0))"
   779 apply (induct x, simp, rule iffI, simp_all)
   780 apply (rule conjI)
   781 apply (simp_all add: set_of_multiset_of [THEN sym] del: set_of_multiset_of)
   782 apply (erule_tac x = a in allE, simp, clarify)
   783 apply (erule_tac x = aa in allE, simp)
   784 done
   785 
   786 lemma multiset_of_eq_setD:
   787   "multiset_of xs = multiset_of ys \<Longrightarrow> set xs = set ys"
   788 by (rule) (auto simp add:multiset_eq_iff set_count_greater_0)
   789 
   790 lemma set_eq_iff_multiset_of_eq_distinct:
   791   "distinct x \<Longrightarrow> distinct y \<Longrightarrow>
   792     (set x = set y) = (multiset_of x = multiset_of y)"
   793 by (auto simp: multiset_eq_iff distinct_count_atmost_1)
   794 
   795 lemma set_eq_iff_multiset_of_remdups_eq:
   796    "(set x = set y) = (multiset_of (remdups x) = multiset_of (remdups y))"
   797 apply (rule iffI)
   798 apply (simp add: set_eq_iff_multiset_of_eq_distinct[THEN iffD1])
   799 apply (drule distinct_remdups [THEN distinct_remdups
   800       [THEN set_eq_iff_multiset_of_eq_distinct [THEN iffD2]]])
   801 apply simp
   802 done
   803 
   804 lemma multiset_of_compl_union [simp]:
   805   "multiset_of [x\<leftarrow>xs. P x] + multiset_of [x\<leftarrow>xs. \<not>P x] = multiset_of xs"
   806   by (induct xs) (auto simp: add_ac)
   807 
   808 lemma count_multiset_of_length_filter:
   809   "count (multiset_of xs) x = length (filter (\<lambda>y. x = y) xs)"
   810   by (induct xs) auto
   811 
   812 lemma nth_mem_multiset_of: "i < length ls \<Longrightarrow> (ls ! i) :# multiset_of ls"
   813 apply (induct ls arbitrary: i)
   814  apply simp
   815 apply (case_tac i)
   816  apply auto
   817 done
   818 
   819 lemma multiset_of_remove1[simp]:
   820   "multiset_of (remove1 a xs) = multiset_of xs - {#a#}"
   821 by (induct xs) (auto simp add: multiset_eq_iff)
   822 
   823 lemma multiset_of_eq_length:
   824   assumes "multiset_of xs = multiset_of ys"
   825   shows "length xs = length ys"
   826 using assms
   827 proof (induct xs arbitrary: ys)
   828   case Nil then show ?case by simp
   829 next
   830   case (Cons x xs)
   831   then have "x \<in># multiset_of ys" by (simp add: union_single_eq_member)
   832   then have "x \<in> set ys" by (simp add: in_multiset_in_set)
   833   from Cons.prems [symmetric] have "multiset_of xs = multiset_of (remove1 x ys)"
   834     by simp
   835   with Cons.hyps have "length xs = length (remove1 x ys)" .
   836   with `x \<in> set ys` show ?case
   837     by (auto simp add: length_remove1 dest: length_pos_if_in_set)
   838 qed
   839 
   840 lemma multiset_of_eq_length_filter:
   841   assumes "multiset_of xs = multiset_of ys"
   842   shows "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) ys)"
   843 proof (cases "z \<in># multiset_of xs")
   844   case False
   845   moreover have "\<not> z \<in># multiset_of ys" using assms False by simp
   846   ultimately show ?thesis by (simp add: count_multiset_of_length_filter)
   847 next
   848   case True
   849   moreover have "z \<in># multiset_of ys" using assms True by simp
   850   show ?thesis using assms
   851   proof (induct xs arbitrary: ys)
   852     case Nil then show ?case by simp
   853   next
   854     case (Cons x xs)
   855     from `multiset_of (x # xs) = multiset_of ys` [symmetric]
   856       have *: "multiset_of xs = multiset_of (remove1 x ys)"
   857       and "x \<in> set ys"
   858       by (auto simp add: mem_set_multiset_eq)
   859     from * have "length (filter (\<lambda>x. z = x) xs) = length (filter (\<lambda>y. z = y) (remove1 x ys))" by (rule Cons.hyps)
   860     moreover from `x \<in> set ys` have "length (filter (\<lambda>y. x = y) ys) > 0" by (simp add: filter_empty_conv)
   861     ultimately show ?case using `x \<in> set ys`
   862       by (simp add: filter_remove1) (auto simp add: length_remove1)
   863   qed
   864 qed
   865 
   866 lemma fold_multiset_equiv:
   867   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"
   868     and equiv: "multiset_of xs = multiset_of ys"
   869   shows "fold f xs = fold f ys"
   870 using f equiv [symmetric]
   871 proof (induct xs arbitrary: ys)
   872   case Nil then show ?case by simp
   873 next
   874   case (Cons x xs)
   875   then have *: "set ys = set (x # xs)" by (blast dest: multiset_of_eq_setD)
   876   have "\<And>x y. x \<in> set ys \<Longrightarrow> y \<in> set ys \<Longrightarrow> f x \<circ> f y = f y \<circ> f x" 
   877     by (rule Cons.prems(1)) (simp_all add: *)
   878   moreover from * have "x \<in> set ys" by simp
   879   ultimately have "fold f ys = fold f (remove1 x ys) \<circ> f x" by (fact fold_remove1_split)
   880   moreover from Cons.prems have "fold f xs = fold f (remove1 x ys)" by (auto intro: Cons.hyps)
   881   ultimately show ?case by simp
   882 qed
   883 
   884 context linorder
   885 begin
   886 
   887 lemma multiset_of_insort [simp]:
   888   "multiset_of (insort_key k x xs) = {#x#} + multiset_of xs"
   889   by (induct xs) (simp_all add: ac_simps)
   890  
   891 lemma multiset_of_sort [simp]:
   892   "multiset_of (sort_key k xs) = multiset_of xs"
   893   by (induct xs) (simp_all add: ac_simps)
   894 
   895 text {*
   896   This lemma shows which properties suffice to show that a function
   897   @{text "f"} with @{text "f xs = ys"} behaves like sort.
   898 *}
   899 
   900 lemma properties_for_sort_key:
   901   assumes "multiset_of ys = multiset_of xs"
   902   and "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>x. f k = f x) ys = filter (\<lambda>x. f k = f x) xs"
   903   and "sorted (map f ys)"
   904   shows "sort_key f xs = ys"
   905 using assms
   906 proof (induct xs arbitrary: ys)
   907   case Nil then show ?case by simp
   908 next
   909   case (Cons x xs)
   910   from Cons.prems(2) have
   911     "\<forall>k \<in> set ys. filter (\<lambda>x. f k = f x) (remove1 x ys) = filter (\<lambda>x. f k = f x) xs"
   912     by (simp add: filter_remove1)
   913   with Cons.prems have "sort_key f xs = remove1 x ys"
   914     by (auto intro!: Cons.hyps simp add: sorted_map_remove1)
   915   moreover from Cons.prems have "x \<in> set ys"
   916     by (auto simp add: mem_set_multiset_eq intro!: ccontr)
   917   ultimately show ?case using Cons.prems by (simp add: insort_key_remove1)
   918 qed
   919 
   920 lemma properties_for_sort:
   921   assumes multiset: "multiset_of ys = multiset_of xs"
   922   and "sorted ys"
   923   shows "sort xs = ys"
   924 proof (rule properties_for_sort_key)
   925   from multiset show "multiset_of ys = multiset_of xs" .
   926   from `sorted ys` show "sorted (map (\<lambda>x. x) ys)" by simp
   927   from multiset have "\<And>k. length (filter (\<lambda>y. k = y) ys) = length (filter (\<lambda>x. k = x) xs)"
   928     by (rule multiset_of_eq_length_filter)
   929   then have "\<And>k. replicate (length (filter (\<lambda>y. k = y) ys)) k = replicate (length (filter (\<lambda>x. k = x) xs)) k"
   930     by simp
   931   then show "\<And>k. k \<in> set ys \<Longrightarrow> filter (\<lambda>y. k = y) ys = filter (\<lambda>x. k = x) xs"
   932     by (simp add: replicate_length_filter)
   933 qed
   934 
   935 lemma sort_key_by_quicksort:
   936   "sort_key f xs = sort_key f [x\<leftarrow>xs. f x < f (xs ! (length xs div 2))]
   937     @ [x\<leftarrow>xs. f x = f (xs ! (length xs div 2))]
   938     @ sort_key f [x\<leftarrow>xs. f x > f (xs ! (length xs div 2))]" (is "sort_key f ?lhs = ?rhs")
   939 proof (rule properties_for_sort_key)
   940   show "multiset_of ?rhs = multiset_of ?lhs"
   941     by (rule multiset_eqI) (auto simp add: multiset_of_filter)
   942 next
   943   show "sorted (map f ?rhs)"
   944     by (auto simp add: sorted_append intro: sorted_map_same)
   945 next
   946   fix l
   947   assume "l \<in> set ?rhs"
   948   let ?pivot = "f (xs ! (length xs div 2))"
   949   have *: "\<And>x. f l = f x \<longleftrightarrow> f x = f l" by auto
   950   have "[x \<leftarrow> sort_key f xs . f x = f l] = [x \<leftarrow> xs. f x = f l]"
   951     unfolding filter_sort by (rule properties_for_sort_key) (auto intro: sorted_map_same)
   952   with * have **: "[x \<leftarrow> sort_key f xs . f l = f x] = [x \<leftarrow> xs. f l = f x]" by simp
   953   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
   954   then have "\<And>P. [x \<leftarrow> sort_key f xs . P (f x) ?pivot \<and> f l = f x] =
   955     [x \<leftarrow> sort_key f xs. P (f l) ?pivot \<and> f l = f x]" by simp
   956   note *** = this [of "op <"] this [of "op >"] this [of "op ="]
   957   show "[x \<leftarrow> ?rhs. f l = f x] = [x \<leftarrow> ?lhs. f l = f x]"
   958   proof (cases "f l" ?pivot rule: linorder_cases)
   959     case less
   960     then have "f l \<noteq> ?pivot" and "\<not> f l > ?pivot" by auto
   961     with less show ?thesis
   962       by (simp add: filter_sort [symmetric] ** ***)
   963   next
   964     case equal then show ?thesis
   965       by (simp add: * less_le)
   966   next
   967     case greater
   968     then have "f l \<noteq> ?pivot" and "\<not> f l < ?pivot" by auto
   969     with greater show ?thesis
   970       by (simp add: filter_sort [symmetric] ** ***)
   971   qed
   972 qed
   973 
   974 lemma sort_by_quicksort:
   975   "sort xs = sort [x\<leftarrow>xs. x < xs ! (length xs div 2)]
   976     @ [x\<leftarrow>xs. x = xs ! (length xs div 2)]
   977     @ sort [x\<leftarrow>xs. x > xs ! (length xs div 2)]" (is "sort ?lhs = ?rhs")
   978   using sort_key_by_quicksort [of "\<lambda>x. x", symmetric] by simp
   979 
   980 text {* A stable parametrized quicksort *}
   981 
   982 definition part :: "('b \<Rightarrow> 'a) \<Rightarrow> 'a \<Rightarrow> 'b list \<Rightarrow> 'b list \<times> 'b list \<times> 'b list" where
   983   "part f pivot xs = ([x \<leftarrow> xs. f x < pivot], [x \<leftarrow> xs. f x = pivot], [x \<leftarrow> xs. pivot < f x])"
   984 
   985 lemma part_code [code]:
   986   "part f pivot [] = ([], [], [])"
   987   "part f pivot (x # xs) = (let (lts, eqs, gts) = part f pivot xs; x' = f x in
   988      if x' < pivot then (x # lts, eqs, gts)
   989      else if x' > pivot then (lts, eqs, x # gts)
   990      else (lts, x # eqs, gts))"
   991   by (auto simp add: part_def Let_def split_def)
   992 
   993 lemma sort_key_by_quicksort_code [code]:
   994   "sort_key f xs = (case xs of [] \<Rightarrow> []
   995     | [x] \<Rightarrow> xs
   996     | [x, y] \<Rightarrow> (if f x \<le> f y then xs else [y, x])
   997     | _ \<Rightarrow> (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
   998        in sort_key f lts @ eqs @ sort_key f gts))"
   999 proof (cases xs)
  1000   case Nil then show ?thesis by simp
  1001 next
  1002   case (Cons _ ys) note hyps = Cons show ?thesis
  1003   proof (cases ys)
  1004     case Nil with hyps show ?thesis by simp
  1005   next
  1006     case (Cons _ zs) note hyps = hyps Cons show ?thesis
  1007     proof (cases zs)
  1008       case Nil with hyps show ?thesis by auto
  1009     next
  1010       case Cons 
  1011       from sort_key_by_quicksort [of f xs]
  1012       have "sort_key f xs = (let (lts, eqs, gts) = part f (f (xs ! (length xs div 2))) xs
  1013         in sort_key f lts @ eqs @ sort_key f gts)"
  1014       by (simp only: split_def Let_def part_def fst_conv snd_conv)
  1015       with hyps Cons show ?thesis by (simp only: list.cases)
  1016     qed
  1017   qed
  1018 qed
  1019 
  1020 end
  1021 
  1022 hide_const (open) part
  1023 
  1024 lemma multiset_of_remdups_le: "multiset_of (remdups xs) \<le> multiset_of xs"
  1025   by (induct xs) (auto intro: order_trans)
  1026 
  1027 lemma multiset_of_update:
  1028   "i < length ls \<Longrightarrow> multiset_of (ls[i := v]) = multiset_of ls - {#ls ! i#} + {#v#}"
  1029 proof (induct ls arbitrary: i)
  1030   case Nil then show ?case by simp
  1031 next
  1032   case (Cons x xs)
  1033   show ?case
  1034   proof (cases i)
  1035     case 0 then show ?thesis by simp
  1036   next
  1037     case (Suc i')
  1038     with Cons show ?thesis
  1039       apply simp
  1040       apply (subst add_assoc)
  1041       apply (subst add_commute [of "{#v#}" "{#x#}"])
  1042       apply (subst add_assoc [symmetric])
  1043       apply simp
  1044       apply (rule mset_le_multiset_union_diff_commute)
  1045       apply (simp add: mset_le_single nth_mem_multiset_of)
  1046       done
  1047   qed
  1048 qed
  1049 
  1050 lemma multiset_of_swap:
  1051   "i < length ls \<Longrightarrow> j < length ls \<Longrightarrow>
  1052     multiset_of (ls[j := ls ! i, i := ls ! j]) = multiset_of ls"
  1053   by (cases "i = j") (simp_all add: multiset_of_update nth_mem_multiset_of)
  1054 
  1055 
  1056 subsubsection {* Association lists -- including code generation *}
  1057 
  1058 text {* Preliminaries *}
  1059 
  1060 text {* Raw operations on lists *}
  1061 
  1062 definition join_raw :: "('key \<Rightarrow> 'val \<times> 'val \<Rightarrow> 'val) \<Rightarrow> ('key \<times> 'val) list \<Rightarrow> ('key \<times> 'val) list \<Rightarrow> ('key \<times> 'val) list"
  1063 where
  1064   "join_raw f xs ys = foldr (\<lambda>(k, v). map_default k v (%v'. f k (v', v))) ys xs"
  1065 
  1066 lemma join_raw_Nil [simp]:
  1067   "join_raw f xs [] = xs"
  1068 by (simp add: join_raw_def)
  1069 
  1070 lemma join_raw_Cons [simp]:
  1071   "join_raw f xs ((k, v) # ys) = map_default k v (%v'. f k (v', v)) (join_raw f xs ys)"
  1072 by (simp add: join_raw_def)
  1073 
  1074 lemma map_of_join_raw:
  1075   assumes "distinct (map fst ys)"
  1076   shows "map_of (join_raw f xs ys) x = (case map_of xs x of None => map_of ys x | Some v => (case map_of ys x of None => Some v | Some v' => Some (f x (v, v'))))"
  1077 using assms
  1078 apply (induct ys)
  1079 apply (auto simp add: map_of_map_default split: option.split)
  1080 apply (metis map_of_eq_None_iff option.simps(2) weak_map_of_SomeI)
  1081 by (metis Some_eq_map_of_iff map_of_eq_None_iff option.simps(2))
  1082 
  1083 lemma distinct_join_raw:
  1084   assumes "distinct (map fst xs)"
  1085   shows "distinct (map fst (join_raw f xs ys))"
  1086 using assms
  1087 proof (induct ys)
  1088   case (Cons y ys)
  1089   thus ?case by (cases y) (simp add: distinct_map_default)
  1090 qed auto
  1091 
  1092 definition
  1093   "subtract_entries_raw xs ys = foldr (%(k, v). AList.map_entry k (%v'. v' - v)) ys xs"
  1094 
  1095 lemma map_of_subtract_entries_raw:
  1096   "distinct (map fst ys) ==> map_of (subtract_entries_raw xs ys) x = (case map_of xs x of None => None | Some v => (case map_of ys x of None => Some v | Some v' => Some (v - v')))"
  1097 unfolding subtract_entries_raw_def
  1098 apply (induct ys)
  1099 apply auto
  1100 apply (simp split: option.split)
  1101 apply (simp add: map_of_map_entry)
  1102 apply (auto split: option.split)
  1103 apply (metis map_of_eq_None_iff option.simps(3) option.simps(4))
  1104 by (metis map_of_eq_None_iff option.simps(4) option.simps(5))
  1105 
  1106 lemma distinct_subtract_entries_raw:
  1107   assumes "distinct (map fst xs)"
  1108   shows "distinct (map fst (subtract_entries_raw xs ys))"
  1109 using assms
  1110 unfolding subtract_entries_raw_def by (induct ys) (auto simp add: distinct_map_entry)
  1111 
  1112 text {* Operations on alists with distinct keys *}
  1113 
  1114 quotient_definition join :: "('a \<Rightarrow> 'b \<times> 'b \<Rightarrow> 'b) \<Rightarrow> ('a, 'b) alist \<Rightarrow> ('a, 'b) alist \<Rightarrow> ('a, 'b) alist" 
  1115 where
  1116   "join" is "join_raw :: ('a \<Rightarrow> 'b \<times> 'b \<Rightarrow> 'b) \<Rightarrow> ('a \<times> 'b) list \<Rightarrow> ('a \<times> 'b) list \<Rightarrow> ('a \<times> 'b) list"
  1117 by (simp add: distinct_join_raw)
  1118 
  1119 quotient_definition subtract_entries :: "('a, ('b :: minus)) alist \<Rightarrow> ('a, 'b) alist \<Rightarrow> ('a, 'b) alist"
  1120 where
  1121   "subtract_entries" is "subtract_entries_raw :: ('a \<times> 'b) list \<Rightarrow> ('a \<times> 'b) list \<Rightarrow> ('a \<times> 'b) list" 
  1122 by (simp add: distinct_subtract_entries_raw)
  1123 
  1124 text {* Implementing multisets by means of association lists *}
  1125 
  1126 definition count_of :: "('a \<times> nat) list \<Rightarrow> 'a \<Rightarrow> nat" where
  1127   "count_of xs x = (case map_of xs x of None \<Rightarrow> 0 | Some n \<Rightarrow> n)"
  1128 
  1129 lemma count_of_multiset:
  1130   "count_of xs \<in> multiset"
  1131 proof -
  1132   let ?A = "{x::'a. 0 < (case map_of xs x of None \<Rightarrow> 0\<Colon>nat | Some (n\<Colon>nat) \<Rightarrow> n)}"
  1133   have "?A \<subseteq> dom (map_of xs)"
  1134   proof
  1135     fix x
  1136     assume "x \<in> ?A"
  1137     then have "0 < (case map_of xs x of None \<Rightarrow> 0\<Colon>nat | Some (n\<Colon>nat) \<Rightarrow> n)" by simp
  1138     then have "map_of xs x \<noteq> None" by (cases "map_of xs x") auto
  1139     then show "x \<in> dom (map_of xs)" by auto
  1140   qed
  1141   with finite_dom_map_of [of xs] have "finite ?A"
  1142     by (auto intro: finite_subset)
  1143   then show ?thesis
  1144     by (simp add: count_of_def fun_eq_iff multiset_def)
  1145 qed
  1146 
  1147 lemma count_simps [simp]:
  1148   "count_of [] = (\<lambda>_. 0)"
  1149   "count_of ((x, n) # xs) = (\<lambda>y. if x = y then n else count_of xs y)"
  1150   by (simp_all add: count_of_def fun_eq_iff)
  1151 
  1152 lemma count_of_empty:
  1153   "x \<notin> fst ` set xs \<Longrightarrow> count_of xs x = 0"
  1154   by (induct xs) (simp_all add: count_of_def)
  1155 
  1156 lemma count_of_filter:
  1157   "count_of (List.filter (P \<circ> fst) xs) x = (if P x then count_of xs x else 0)"
  1158   by (induct xs) auto
  1159 
  1160 lemma count_of_map_default [simp]:
  1161   "count_of (map_default x b (%x. x + b) xs) y = (if x = y then count_of xs x + b else count_of xs y)"
  1162 unfolding count_of_def by (simp add: map_of_map_default split: option.split)
  1163 
  1164 lemma count_of_join_raw:
  1165   "distinct (map fst ys) ==> count_of xs x + count_of ys x = count_of (join_raw (%x (x, y). x + y) xs ys) x"
  1166 unfolding count_of_def by (simp add: map_of_join_raw split: option.split)
  1167 
  1168 lemma count_of_subtract_entries_raw:
  1169   "distinct (map fst ys) ==> count_of xs x - count_of ys x = count_of (subtract_entries_raw xs ys) x"
  1170 unfolding count_of_def by (simp add: map_of_subtract_entries_raw split: option.split)
  1171 
  1172 text {* Code equations for multiset operations *}
  1173 
  1174 definition Bag :: "('a, nat) alist \<Rightarrow> 'a multiset" where
  1175   "Bag xs = Abs_multiset (count_of (DAList.impl_of xs))"
  1176 
  1177 code_datatype Bag
  1178 
  1179 lemma count_Bag [simp, code]:
  1180   "count (Bag xs) = count_of (DAList.impl_of xs)"
  1181   by (simp add: Bag_def count_of_multiset Abs_multiset_inverse)
  1182 
  1183 lemma Mempty_Bag [code]:
  1184   "{#} = Bag (DAList.empty)"
  1185   by (simp add: multiset_eq_iff alist.Alist_inverse DAList.empty_def)
  1186 
  1187 lemma single_Bag [code]:
  1188   "{#x#} = Bag (DAList.update x 1 DAList.empty)"
  1189   by (simp add: multiset_eq_iff alist.Alist_inverse update_code_eqn empty_code_eqn)
  1190 
  1191 lemma union_Bag [code]:
  1192   "Bag xs + Bag ys = Bag (join (\<lambda>x (n1, n2). n1 + n2) xs ys)"
  1193 by (rule multiset_eqI) (simp add: count_of_join_raw alist.Alist_inverse distinct_join_raw join_def)
  1194 
  1195 lemma minus_Bag [code]:
  1196   "Bag xs - Bag ys = Bag (subtract_entries xs ys)"
  1197 by (rule multiset_eqI)
  1198   (simp add: count_of_subtract_entries_raw alist.Alist_inverse distinct_subtract_entries_raw subtract_entries_def)
  1199 
  1200 lemma filter_Bag [code]:
  1201   "Multiset.filter P (Bag xs) = Bag (DAList.filter (P \<circ> fst) xs)"
  1202 by (rule multiset_eqI) (simp add: count_of_filter filter_code_eqn)
  1203 
  1204 lemma mset_less_eq_Bag [code]:
  1205   "Bag xs \<le> A \<longleftrightarrow> (\<forall>(x, n) \<in> set (DAList.impl_of xs). count_of (DAList.impl_of xs) x \<le> count A x)"
  1206     (is "?lhs \<longleftrightarrow> ?rhs")
  1207 proof
  1208   assume ?lhs then show ?rhs
  1209     by (auto simp add: mset_le_def)
  1210 next
  1211   assume ?rhs
  1212   show ?lhs
  1213   proof (rule mset_less_eqI)
  1214     fix x
  1215     from `?rhs` have "count_of (DAList.impl_of xs) x \<le> count A x"
  1216       by (cases "x \<in> fst ` set (DAList.impl_of xs)") (auto simp add: count_of_empty)
  1217     then show "count (Bag xs) x \<le> count A x"
  1218       by (simp add: mset_le_def)
  1219   qed
  1220 qed
  1221 
  1222 instantiation multiset :: (equal) equal
  1223 begin
  1224 
  1225 definition
  1226   [code]: "HOL.equal A B \<longleftrightarrow> (A::'a multiset) \<le> B \<and> B \<le> A"
  1227 
  1228 instance
  1229   by default (simp add: equal_multiset_def eq_iff)
  1230 
  1231 end
  1232 
  1233 text {* Quickcheck generators *}
  1234 
  1235 definition (in term_syntax)
  1236   bagify :: "('a\<Colon>typerep, nat) alist \<times> (unit \<Rightarrow> Code_Evaluation.term)
  1237     \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where
  1238   [code_unfold]: "bagify xs = Code_Evaluation.valtermify Bag {\<cdot>} xs"
  1239 
  1240 notation fcomp (infixl "\<circ>>" 60)
  1241 notation scomp (infixl "\<circ>\<rightarrow>" 60)
  1242 
  1243 instantiation multiset :: (random) random
  1244 begin
  1245 
  1246 definition
  1247   "Quickcheck.random i = Quickcheck.random i \<circ>\<rightarrow> (\<lambda>xs. Pair (bagify xs))"
  1248 
  1249 instance ..
  1250 
  1251 end
  1252 
  1253 no_notation fcomp (infixl "\<circ>>" 60)
  1254 no_notation scomp (infixl "\<circ>\<rightarrow>" 60)
  1255 
  1256 instantiation multiset :: (exhaustive) exhaustive
  1257 begin
  1258 
  1259 definition exhaustive_multiset :: "('a multiset => (bool * term list) option) => code_numeral => (bool * term list) option"
  1260 where
  1261   "exhaustive_multiset f i = Quickcheck_Exhaustive.exhaustive (%xs. f (Bag xs)) i"
  1262 
  1263 instance ..
  1264 
  1265 end
  1266 
  1267 instantiation multiset :: (full_exhaustive) full_exhaustive
  1268 begin
  1269 
  1270 definition full_exhaustive_multiset :: "('a multiset * (unit => term) => (bool * term list) option) => code_numeral => (bool * term list) option"
  1271 where
  1272   "full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (%xs. f (bagify xs)) i"
  1273 
  1274 instance ..
  1275 
  1276 end
  1277 
  1278 hide_const (open) bagify
  1279 
  1280 
  1281 subsection {* The multiset order *}
  1282 
  1283 subsubsection {* Well-foundedness *}
  1284 
  1285 definition mult1 :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
  1286   "mult1 r = {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
  1287       (\<forall>b. b :# K --> (b, a) \<in> r)}"
  1288 
  1289 definition mult :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
  1290   "mult r = (mult1 r)\<^sup>+"
  1291 
  1292 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
  1293 by (simp add: mult1_def)
  1294 
  1295 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r ==>
  1296     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
  1297     (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K)"
  1298   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
  1299 proof (unfold mult1_def)
  1300   let ?r = "\<lambda>K a. \<forall>b. b :# K --> (b, a) \<in> r"
  1301   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
  1302   let ?case1 = "?case1 {(N, M). ?R N M}"
  1303 
  1304   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
  1305   then have "\<exists>a' M0' K.
  1306       M0 + {#a#} = M0' + {#a'#} \<and> N = M0' + K \<and> ?r K a'" by simp
  1307   then show "?case1 \<or> ?case2"
  1308   proof (elim exE conjE)
  1309     fix a' M0' K
  1310     assume N: "N = M0' + K" and r: "?r K a'"
  1311     assume "M0 + {#a#} = M0' + {#a'#}"
  1312     then have "M0 = M0' \<and> a = a' \<or>
  1313         (\<exists>K'. M0 = K' + {#a'#} \<and> M0' = K' + {#a#})"
  1314       by (simp only: add_eq_conv_ex)
  1315     then show ?thesis
  1316     proof (elim disjE conjE exE)
  1317       assume "M0 = M0'" "a = a'"
  1318       with N r have "?r K a \<and> N = M0 + K" by simp
  1319       then have ?case2 .. then show ?thesis ..
  1320     next
  1321       fix K'
  1322       assume "M0' = K' + {#a#}"
  1323       with N have n: "N = K' + K + {#a#}" by (simp add: add_ac)
  1324 
  1325       assume "M0 = K' + {#a'#}"
  1326       with r have "?R (K' + K) M0" by blast
  1327       with n have ?case1 by simp then show ?thesis ..
  1328     qed
  1329   qed
  1330 qed
  1331 
  1332 lemma all_accessible: "wf r ==> \<forall>M. M \<in> acc (mult1 r)"
  1333 proof
  1334   let ?R = "mult1 r"
  1335   let ?W = "acc ?R"
  1336   {
  1337     fix M M0 a
  1338     assume M0: "M0 \<in> ?W"
  1339       and wf_hyp: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
  1340       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R --> M + {#a#} \<in> ?W"
  1341     have "M0 + {#a#} \<in> ?W"
  1342     proof (rule accI [of "M0 + {#a#}"])
  1343       fix N
  1344       assume "(N, M0 + {#a#}) \<in> ?R"
  1345       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
  1346           (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K))"
  1347         by (rule less_add)
  1348       then show "N \<in> ?W"
  1349       proof (elim exE disjE conjE)
  1350         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
  1351         from acc_hyp have "(M, M0) \<in> ?R --> M + {#a#} \<in> ?W" ..
  1352         from this and `(M, M0) \<in> ?R` have "M + {#a#} \<in> ?W" ..
  1353         then show "N \<in> ?W" by (simp only: N)
  1354       next
  1355         fix K
  1356         assume N: "N = M0 + K"
  1357         assume "\<forall>b. b :# K --> (b, a) \<in> r"
  1358         then have "M0 + K \<in> ?W"
  1359         proof (induct K)
  1360           case empty
  1361           from M0 show "M0 + {#} \<in> ?W" by simp
  1362         next
  1363           case (add K x)
  1364           from add.prems have "(x, a) \<in> r" by simp
  1365           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
  1366           moreover from add have "M0 + K \<in> ?W" by simp
  1367           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
  1368           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: add_assoc)
  1369         qed
  1370         then show "N \<in> ?W" by (simp only: N)
  1371       qed
  1372     qed
  1373   } note tedious_reasoning = this
  1374 
  1375   assume wf: "wf r"
  1376   fix M
  1377   show "M \<in> ?W"
  1378   proof (induct M)
  1379     show "{#} \<in> ?W"
  1380     proof (rule accI)
  1381       fix b assume "(b, {#}) \<in> ?R"
  1382       with not_less_empty show "b \<in> ?W" by contradiction
  1383     qed
  1384 
  1385     fix M a assume "M \<in> ?W"
  1386     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
  1387     proof induct
  1388       fix a
  1389       assume r: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
  1390       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
  1391       proof
  1392         fix M assume "M \<in> ?W"
  1393         then show "M + {#a#} \<in> ?W"
  1394           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
  1395       qed
  1396     qed
  1397     from this and `M \<in> ?W` show "M + {#a#} \<in> ?W" ..
  1398   qed
  1399 qed
  1400 
  1401 theorem wf_mult1: "wf r ==> wf (mult1 r)"
  1402 by (rule acc_wfI) (rule all_accessible)
  1403 
  1404 theorem wf_mult: "wf r ==> wf (mult r)"
  1405 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
  1406 
  1407 
  1408 subsubsection {* Closure-free presentation *}
  1409 
  1410 text {* One direction. *}
  1411 
  1412 lemma mult_implies_one_step:
  1413   "trans r ==> (M, N) \<in> mult r ==>
  1414     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
  1415     (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r)"
  1416 apply (unfold mult_def mult1_def set_of_def)
  1417 apply (erule converse_trancl_induct, clarify)
  1418  apply (rule_tac x = M0 in exI, simp, clarify)
  1419 apply (case_tac "a :# K")
  1420  apply (rule_tac x = I in exI)
  1421  apply (simp (no_asm))
  1422  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
  1423  apply (simp (no_asm_simp) add: add_assoc [symmetric])
  1424  apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong)
  1425  apply (simp add: diff_union_single_conv)
  1426  apply (simp (no_asm_use) add: trans_def)
  1427  apply blast
  1428 apply (subgoal_tac "a :# I")
  1429  apply (rule_tac x = "I - {#a#}" in exI)
  1430  apply (rule_tac x = "J + {#a#}" in exI)
  1431  apply (rule_tac x = "K + Ka" in exI)
  1432  apply (rule conjI)
  1433   apply (simp add: multiset_eq_iff split: nat_diff_split)
  1434  apply (rule conjI)
  1435   apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong, simp)
  1436   apply (simp add: multiset_eq_iff split: nat_diff_split)
  1437  apply (simp (no_asm_use) add: trans_def)
  1438  apply blast
  1439 apply (subgoal_tac "a :# (M0 + {#a#})")
  1440  apply simp
  1441 apply (simp (no_asm))
  1442 done
  1443 
  1444 lemma one_step_implies_mult_aux:
  1445   "trans r ==>
  1446     \<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))
  1447       --> (I + K, I + J) \<in> mult r"
  1448 apply (induct_tac n, auto)
  1449 apply (frule size_eq_Suc_imp_eq_union, clarify)
  1450 apply (rename_tac "J'", simp)
  1451 apply (erule notE, auto)
  1452 apply (case_tac "J' = {#}")
  1453  apply (simp add: mult_def)
  1454  apply (rule r_into_trancl)
  1455  apply (simp add: mult1_def set_of_def, blast)
  1456 txt {* Now we know @{term "J' \<noteq> {#}"}. *}
  1457 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
  1458 apply (erule_tac P = "\<forall>k \<in> set_of K. ?P k" in rev_mp)
  1459 apply (erule ssubst)
  1460 apply (simp add: Ball_def, auto)
  1461 apply (subgoal_tac
  1462   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
  1463     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
  1464  prefer 2
  1465  apply force
  1466 apply (simp (no_asm_use) add: add_assoc [symmetric] mult_def)
  1467 apply (erule trancl_trans)
  1468 apply (rule r_into_trancl)
  1469 apply (simp add: mult1_def set_of_def)
  1470 apply (rule_tac x = a in exI)
  1471 apply (rule_tac x = "I + J'" in exI)
  1472 apply (simp add: add_ac)
  1473 done
  1474 
  1475 lemma one_step_implies_mult:
  1476   "trans r ==> J \<noteq> {#} ==> \<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r
  1477     ==> (I + K, I + J) \<in> mult r"
  1478 using one_step_implies_mult_aux by blast
  1479 
  1480 
  1481 subsubsection {* Partial-order properties *}
  1482 
  1483 definition less_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<#" 50) where
  1484   "M' <# M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
  1485 
  1486 definition le_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<=#" 50) where
  1487   "M' <=# M \<longleftrightarrow> M' <# M \<or> M' = M"
  1488 
  1489 notation (xsymbols) less_multiset (infix "\<subset>#" 50)
  1490 notation (xsymbols) le_multiset (infix "\<subseteq>#" 50)
  1491 
  1492 interpretation multiset_order: order le_multiset less_multiset
  1493 proof -
  1494   have irrefl: "\<And>M :: 'a multiset. \<not> M \<subset># M"
  1495   proof
  1496     fix M :: "'a multiset"
  1497     assume "M \<subset># M"
  1498     then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def)
  1499     have "trans {(x'::'a, x). x' < x}"
  1500       by (rule transI) simp
  1501     moreover note MM
  1502     ultimately have "\<exists>I J K. M = I + J \<and> M = I + K
  1503       \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_of K. \<exists>j\<in>set_of J. (k, j) \<in> {(x, y). x < y})"
  1504       by (rule mult_implies_one_step)
  1505     then obtain I J K where "M = I + J" and "M = I + K"
  1506       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
  1507     then have aux1: "K \<noteq> {#}" and aux2: "\<forall>k\<in>set_of K. \<exists>j\<in>set_of K. k < j" by auto
  1508     have "finite (set_of K)" by simp
  1509     moreover note aux2
  1510     ultimately have "set_of K = {}"
  1511       by (induct rule: finite_induct) (auto intro: order_less_trans)
  1512     with aux1 show False by simp
  1513   qed
  1514   have trans: "\<And>K M N :: 'a multiset. K \<subset># M \<Longrightarrow> M \<subset># N \<Longrightarrow> K \<subset># N"
  1515     unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
  1516   show "class.order (le_multiset :: 'a multiset \<Rightarrow> _) less_multiset"
  1517     by default (auto simp add: le_multiset_def irrefl dest: trans)
  1518 qed
  1519 
  1520 lemma mult_less_irrefl [elim!]: "M \<subset># (M::'a::order multiset) ==> R"
  1521   by simp
  1522 
  1523 
  1524 subsubsection {* Monotonicity of multiset union *}
  1525 
  1526 lemma mult1_union: "(B, D) \<in> mult1 r ==> (C + B, C + D) \<in> mult1 r"
  1527 apply (unfold mult1_def)
  1528 apply auto
  1529 apply (rule_tac x = a in exI)
  1530 apply (rule_tac x = "C + M0" in exI)
  1531 apply (simp add: add_assoc)
  1532 done
  1533 
  1534 lemma union_less_mono2: "B \<subset># D ==> C + B \<subset># C + (D::'a::order multiset)"
  1535 apply (unfold less_multiset_def mult_def)
  1536 apply (erule trancl_induct)
  1537  apply (blast intro: mult1_union)
  1538 apply (blast intro: mult1_union trancl_trans)
  1539 done
  1540 
  1541 lemma union_less_mono1: "B \<subset># D ==> B + C \<subset># D + (C::'a::order multiset)"
  1542 apply (subst add_commute [of B C])
  1543 apply (subst add_commute [of D C])
  1544 apply (erule union_less_mono2)
  1545 done
  1546 
  1547 lemma union_less_mono:
  1548   "A \<subset># C ==> B \<subset># D ==> A + B \<subset># C + (D::'a::order multiset)"
  1549   by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)
  1550 
  1551 interpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multiset
  1552 proof
  1553 qed (auto simp add: le_multiset_def intro: union_less_mono2)
  1554 
  1555 
  1556 subsection {* The fold combinator *}
  1557 
  1558 text {*
  1559   The intended behaviour is
  1560   @{text "fold_mset f z {#x\<^isub>1, ..., x\<^isub>n#} = f x\<^isub>1 (\<dots> (f x\<^isub>n z)\<dots>)"}
  1561   if @{text f} is associative-commutative. 
  1562 *}
  1563 
  1564 text {*
  1565   The graph of @{text "fold_mset"}, @{text "z"}: the start element,
  1566   @{text "f"}: folding function, @{text "A"}: the multiset, @{text
  1567   "y"}: the result.
  1568 *}
  1569 inductive 
  1570   fold_msetG :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b \<Rightarrow> bool" 
  1571   for f :: "'a \<Rightarrow> 'b \<Rightarrow> 'b" 
  1572   and z :: 'b
  1573 where
  1574   emptyI [intro]:  "fold_msetG f z {#} z"
  1575 | insertI [intro]: "fold_msetG f z A y \<Longrightarrow> fold_msetG f z (A + {#x#}) (f x y)"
  1576 
  1577 inductive_cases empty_fold_msetGE [elim!]: "fold_msetG f z {#} x"
  1578 inductive_cases insert_fold_msetGE: "fold_msetG f z (A + {#}) y" 
  1579 
  1580 definition
  1581   fold_mset :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b" where
  1582   "fold_mset f z A = (THE x. fold_msetG f z A x)"
  1583 
  1584 lemma Diff1_fold_msetG:
  1585   "fold_msetG f z (A - {#x#}) y \<Longrightarrow> x \<in># A \<Longrightarrow> fold_msetG f z A (f x y)"
  1586 apply (frule_tac x = x in fold_msetG.insertI)
  1587 apply auto
  1588 done
  1589 
  1590 lemma fold_msetG_nonempty: "\<exists>x. fold_msetG f z A x"
  1591 apply (induct A)
  1592  apply blast
  1593 apply clarsimp
  1594 apply (drule_tac x = x in fold_msetG.insertI)
  1595 apply auto
  1596 done
  1597 
  1598 lemma fold_mset_empty[simp]: "fold_mset f z {#} = z"
  1599 unfolding fold_mset_def by blast
  1600 
  1601 context comp_fun_commute
  1602 begin
  1603 
  1604 lemma fold_msetG_determ:
  1605   "fold_msetG f z A x \<Longrightarrow> fold_msetG f z A y \<Longrightarrow> y = x"
  1606 proof (induct arbitrary: x y z rule: full_multiset_induct)
  1607   case (less M x\<^isub>1 x\<^isub>2 Z)
  1608   have IH: "\<forall>A. A < M \<longrightarrow> 
  1609     (\<forall>x x' x''. fold_msetG f x'' A x \<longrightarrow> fold_msetG f x'' A x'
  1610                \<longrightarrow> x' = x)" by fact
  1611   have Mfoldx\<^isub>1: "fold_msetG f Z M x\<^isub>1" and Mfoldx\<^isub>2: "fold_msetG f Z M x\<^isub>2" by fact+
  1612   show ?case
  1613   proof (rule fold_msetG.cases [OF Mfoldx\<^isub>1])
  1614     assume "M = {#}" and "x\<^isub>1 = Z"
  1615     then show ?case using Mfoldx\<^isub>2 by auto 
  1616   next
  1617     fix B b u
  1618     assume "M = B + {#b#}" and "x\<^isub>1 = f b u" and Bu: "fold_msetG f Z B u"
  1619     then have MBb: "M = B + {#b#}" and x\<^isub>1: "x\<^isub>1 = f b u" by auto
  1620     show ?case
  1621     proof (rule fold_msetG.cases [OF Mfoldx\<^isub>2])
  1622       assume "M = {#}" "x\<^isub>2 = Z"
  1623       then show ?case using Mfoldx\<^isub>1 by auto
  1624     next
  1625       fix C c v
  1626       assume "M = C + {#c#}" and "x\<^isub>2 = f c v" and Cv: "fold_msetG f Z C v"
  1627       then have MCc: "M = C + {#c#}" and x\<^isub>2: "x\<^isub>2 = f c v" by auto
  1628       then have CsubM: "C < M" by simp
  1629       from MBb have BsubM: "B < M" by simp
  1630       show ?case
  1631       proof cases
  1632         assume *: "b = c"
  1633         then have "B = C" using MBb MCc by auto
  1634         with * show ?thesis using Bu Cv x\<^isub>1 x\<^isub>2 CsubM IH by auto
  1635       next
  1636         assume diff: "b \<noteq> c"
  1637         let ?D = "B - {#c#}"
  1638         have cinB: "c \<in># B" and binC: "b \<in># C" using MBb MCc diff
  1639           by (auto intro: insert_noteq_member dest: sym)
  1640         have "B - {#c#} < B" using cinB by (rule mset_less_diff_self)
  1641         then have DsubM: "?D < M" using BsubM by (blast intro: order_less_trans)
  1642         from MBb MCc have "B + {#b#} = C + {#c#}" by blast
  1643         then have [simp]: "B + {#b#} - {#c#} = C"
  1644           using MBb MCc binC cinB by auto
  1645         have B: "B = ?D + {#c#}" and C: "C = ?D + {#b#}"
  1646           using MBb MCc diff binC cinB
  1647           by (auto simp: multiset_add_sub_el_shuffle)
  1648         then obtain d where Dfoldd: "fold_msetG f Z ?D d"
  1649           using fold_msetG_nonempty by iprover
  1650         then have "fold_msetG f Z B (f c d)" using cinB
  1651           by (rule Diff1_fold_msetG)
  1652         then have "f c d = u" using IH BsubM Bu by blast
  1653         moreover 
  1654         have "fold_msetG f Z C (f b d)" using binC cinB diff Dfoldd
  1655           by (auto simp: multiset_add_sub_el_shuffle 
  1656             dest: fold_msetG.insertI [where x=b])
  1657         then have "f b d = v" using IH CsubM Cv by blast
  1658         ultimately show ?thesis using x\<^isub>1 x\<^isub>2
  1659           by (auto simp: fun_left_comm)
  1660       qed
  1661     qed
  1662   qed
  1663 qed
  1664         
  1665 lemma fold_mset_insert_aux:
  1666   "(fold_msetG f z (A + {#x#}) v) =
  1667     (\<exists>y. fold_msetG f z A y \<and> v = f x y)"
  1668 apply (rule iffI)
  1669  prefer 2
  1670  apply blast
  1671 apply (rule_tac A1=A and f1=f in fold_msetG_nonempty [THEN exE])
  1672 apply (blast intro: fold_msetG_determ)
  1673 done
  1674 
  1675 lemma fold_mset_equality: "fold_msetG f z A y \<Longrightarrow> fold_mset f z A = y"
  1676 unfolding fold_mset_def by (blast intro: fold_msetG_determ)
  1677 
  1678 lemma fold_mset_insert:
  1679   "fold_mset f z (A + {#x#}) = f x (fold_mset f z A)"
  1680 apply (simp add: fold_mset_def fold_mset_insert_aux)
  1681 apply (rule the_equality)
  1682  apply (auto cong add: conj_cong 
  1683      simp add: fold_mset_def [symmetric] fold_mset_equality fold_msetG_nonempty)
  1684 done
  1685 
  1686 lemma fold_mset_commute: "f x (fold_mset f z A) = fold_mset f (f x z) A"
  1687 by (induct A) (auto simp: fold_mset_insert fun_left_comm [of x])
  1688 
  1689 lemma fold_mset_single [simp]: "fold_mset f z {#x#} = f x z"
  1690 using fold_mset_insert [of z "{#}"] by simp
  1691 
  1692 lemma fold_mset_union [simp]:
  1693   "fold_mset f z (A+B) = fold_mset f (fold_mset f z A) B"
  1694 proof (induct A)
  1695   case empty then show ?case by simp
  1696 next
  1697   case (add A x)
  1698   have "A + {#x#} + B = (A+B) + {#x#}" by (simp add: add_ac)
  1699   then have "fold_mset f z (A + {#x#} + B) = f x (fold_mset f z (A + B))" 
  1700     by (simp add: fold_mset_insert)
  1701   also have "\<dots> = fold_mset f (fold_mset f z (A + {#x#})) B"
  1702     by (simp add: fold_mset_commute[of x,symmetric] add fold_mset_insert)
  1703   finally show ?case .
  1704 qed
  1705 
  1706 lemma fold_mset_fusion:
  1707   assumes "comp_fun_commute g"
  1708   shows "(\<And>x y. h (g x y) = f x (h y)) \<Longrightarrow> h (fold_mset g w A) = fold_mset f (h w) A" (is "PROP ?P")
  1709 proof -
  1710   interpret comp_fun_commute g by (fact assms)
  1711   show "PROP ?P" by (induct A) auto
  1712 qed
  1713 
  1714 lemma fold_mset_rec:
  1715   assumes "a \<in># A" 
  1716   shows "fold_mset f z A = f a (fold_mset f z (A - {#a#}))"
  1717 proof -
  1718   from assms obtain A' where "A = A' + {#a#}"
  1719     by (blast dest: multi_member_split)
  1720   then show ?thesis by simp
  1721 qed
  1722 
  1723 end
  1724 
  1725 text {*
  1726   A note on code generation: When defining some function containing a
  1727   subterm @{term"fold_mset F"}, code generation is not automatic. When
  1728   interpreting locale @{text left_commutative} with @{text F}, the
  1729   would be code thms for @{const fold_mset} become thms like
  1730   @{term"fold_mset F z {#} = z"} where @{text F} is not a pattern but
  1731   contains defined symbols, i.e.\ is not a code thm. Hence a separate
  1732   constant with its own code thms needs to be introduced for @{text
  1733   F}. See the image operator below.
  1734 *}
  1735 
  1736 
  1737 subsection {* Image *}
  1738 
  1739 definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where
  1740   "image_mset f = fold_mset (op + o single o f) {#}"
  1741 
  1742 interpretation image_fun_commute: comp_fun_commute "op + o single o f" for f
  1743 proof qed (simp add: add_ac fun_eq_iff)
  1744 
  1745 lemma image_mset_empty [simp]: "image_mset f {#} = {#}"
  1746 by (simp add: image_mset_def)
  1747 
  1748 lemma image_mset_single [simp]: "image_mset f {#x#} = {#f x#}"
  1749 by (simp add: image_mset_def)
  1750 
  1751 lemma image_mset_insert:
  1752   "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"
  1753 by (simp add: image_mset_def add_ac)
  1754 
  1755 lemma image_mset_union [simp]:
  1756   "image_mset f (M+N) = image_mset f M + image_mset f N"
  1757 apply (induct N)
  1758  apply simp
  1759 apply (simp add: add_assoc [symmetric] image_mset_insert)
  1760 done
  1761 
  1762 lemma size_image_mset [simp]: "size (image_mset f M) = size M"
  1763 by (induct M) simp_all
  1764 
  1765 lemma image_mset_is_empty_iff [simp]: "image_mset f M = {#} \<longleftrightarrow> M = {#}"
  1766 by (cases M) auto
  1767 
  1768 syntax
  1769   "_comprehension1_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
  1770       ("({#_/. _ :# _#})")
  1771 translations
  1772   "{#e. x:#M#}" == "CONST image_mset (%x. e) M"
  1773 
  1774 syntax
  1775   "_comprehension2_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
  1776       ("({#_/ | _ :# _./ _#})")
  1777 translations
  1778   "{#e | x:#M. P#}" => "{#e. x :# {# x:#M. P#}#}"
  1779 
  1780 text {*
  1781   This allows to write not just filters like @{term "{#x:#M. x<c#}"}
  1782   but also images like @{term "{#x+x. x:#M #}"} and @{term [source]
  1783   "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as
  1784   @{term "{#x+x|x:#M. x<c#}"}.
  1785 *}
  1786 
  1787 enriched_type image_mset: image_mset
  1788 proof -
  1789   fix f g show "image_mset f \<circ> image_mset g = image_mset (f \<circ> g)"
  1790   proof
  1791     fix A
  1792     show "(image_mset f \<circ> image_mset g) A = image_mset (f \<circ> g) A"
  1793       by (induct A) simp_all
  1794   qed
  1795   show "image_mset id = id"
  1796   proof
  1797     fix A
  1798     show "image_mset id A = id A"
  1799       by (induct A) simp_all
  1800   qed
  1801 qed
  1802 
  1803 
  1804 subsection {* Termination proofs with multiset orders *}
  1805 
  1806 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
  1807   and multi_member_this: "x \<in># {# x #} + XS"
  1808   and multi_member_last: "x \<in># {# x #}"
  1809   by auto
  1810 
  1811 definition "ms_strict = mult pair_less"
  1812 definition "ms_weak = ms_strict \<union> Id"
  1813 
  1814 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
  1815 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
  1816 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
  1817 
  1818 lemma smsI:
  1819   "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
  1820   unfolding ms_strict_def
  1821 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
  1822 
  1823 lemma wmsI:
  1824   "(set_of A, set_of B) \<in> max_strict \<or> A = {#} \<and> B = {#}
  1825   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
  1826 unfolding ms_weak_def ms_strict_def
  1827 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
  1828 
  1829 inductive pw_leq
  1830 where
  1831   pw_leq_empty: "pw_leq {#} {#}"
  1832 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
  1833 
  1834 lemma pw_leq_lstep:
  1835   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
  1836 by (drule pw_leq_step) (rule pw_leq_empty, simp)
  1837 
  1838 lemma pw_leq_split:
  1839   assumes "pw_leq X Y"
  1840   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 = {#}))"
  1841   using assms
  1842 proof (induct)
  1843   case pw_leq_empty thus ?case by auto
  1844 next
  1845   case (pw_leq_step x y X Y)
  1846   then obtain A B Z where
  1847     [simp]: "X = A + Z" "Y = B + Z" 
  1848       and 1[simp]: "(set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#})" 
  1849     by auto
  1850   from pw_leq_step have "x = y \<or> (x, y) \<in> pair_less" 
  1851     unfolding pair_leq_def by auto
  1852   thus ?case
  1853   proof
  1854     assume [simp]: "x = y"
  1855     have
  1856       "{#x#} + X = A + ({#y#}+Z) 
  1857       \<and> {#y#} + Y = B + ({#y#}+Z)
  1858       \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
  1859       by (auto simp: add_ac)
  1860     thus ?case by (intro exI)
  1861   next
  1862     assume A: "(x, y) \<in> pair_less"
  1863     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
  1864     have "{#x#} + X = ?A' + Z"
  1865       "{#y#} + Y = ?B' + Z"
  1866       by (auto simp add: add_ac)
  1867     moreover have 
  1868       "(set_of ?A', set_of ?B') \<in> max_strict"
  1869       using 1 A unfolding max_strict_def 
  1870       by (auto elim!: max_ext.cases)
  1871     ultimately show ?thesis by blast
  1872   qed
  1873 qed
  1874 
  1875 lemma 
  1876   assumes pwleq: "pw_leq Z Z'"
  1877   shows ms_strictI: "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
  1878   and   ms_weakI1:  "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
  1879   and   ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
  1880 proof -
  1881   from pw_leq_split[OF pwleq] 
  1882   obtain A' B' Z''
  1883     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
  1884     and mx_or_empty: "(set_of A', set_of B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
  1885     by blast
  1886   {
  1887     assume max: "(set_of A, set_of B) \<in> max_strict"
  1888     from mx_or_empty
  1889     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
  1890     proof
  1891       assume max': "(set_of A', set_of B') \<in> max_strict"
  1892       with max have "(set_of (A + A'), set_of (B + B')) \<in> max_strict"
  1893         by (auto simp: max_strict_def intro: max_ext_additive)
  1894       thus ?thesis by (rule smsI) 
  1895     next
  1896       assume [simp]: "A' = {#} \<and> B' = {#}"
  1897       show ?thesis by (rule smsI) (auto intro: max)
  1898     qed
  1899     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add:add_ac)
  1900     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
  1901   }
  1902   from mx_or_empty
  1903   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
  1904   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add:add_ac)
  1905 qed
  1906 
  1907 lemma empty_neutral: "{#} + x = x" "x + {#} = x"
  1908 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
  1909 and nonempty_single: "{# x #} \<noteq> {#}"
  1910 by auto
  1911 
  1912 setup {*
  1913 let
  1914   fun msetT T = Type (@{type_name multiset}, [T]);
  1915 
  1916   fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)
  1917     | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) $ x
  1918     | mk_mset T (x :: xs) =
  1919           Const (@{const_name plus}, msetT T --> msetT T --> msetT T) $
  1920                 mk_mset T [x] $ mk_mset T xs
  1921 
  1922   fun mset_member_tac m i =
  1923       (if m <= 0 then
  1924            rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i
  1925        else
  1926            rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)
  1927 
  1928   val mset_nonempty_tac =
  1929       rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}
  1930 
  1931   val regroup_munion_conv =
  1932       Function_Lib.regroup_conv @{const_abbrev Mempty} @{const_name plus}
  1933         (map (fn t => t RS eq_reflection) (@{thms add_ac} @ @{thms empty_neutral}))
  1934 
  1935   fun unfold_pwleq_tac i =
  1936     (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))
  1937       ORELSE (rtac @{thm pw_leq_lstep} i)
  1938       ORELSE (rtac @{thm pw_leq_empty} i)
  1939 
  1940   val set_of_simps = [@{thm set_of_empty}, @{thm set_of_single}, @{thm set_of_union},
  1941                       @{thm Un_insert_left}, @{thm Un_empty_left}]
  1942 in
  1943   ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset 
  1944   {
  1945     msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
  1946     mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
  1947     mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_of_simps,
  1948     smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
  1949     reduction_pair= @{thm ms_reduction_pair}
  1950   })
  1951 end
  1952 *}
  1953 
  1954 
  1955 subsection {* Legacy theorem bindings *}
  1956 
  1957 lemmas multi_count_eq = multiset_eq_iff [symmetric]
  1958 
  1959 lemma union_commute: "M + N = N + (M::'a multiset)"
  1960   by (fact add_commute)
  1961 
  1962 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
  1963   by (fact add_assoc)
  1964 
  1965 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
  1966   by (fact add_left_commute)
  1967 
  1968 lemmas union_ac = union_assoc union_commute union_lcomm
  1969 
  1970 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
  1971   by (fact add_right_cancel)
  1972 
  1973 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
  1974   by (fact add_left_cancel)
  1975 
  1976 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
  1977   by (fact add_imp_eq)
  1978 
  1979 lemma mset_less_trans: "(M::'a multiset) < K \<Longrightarrow> K < N \<Longrightarrow> M < N"
  1980   by (fact order_less_trans)
  1981 
  1982 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
  1983   by (fact inf.commute)
  1984 
  1985 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
  1986   by (fact inf.assoc [symmetric])
  1987 
  1988 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
  1989   by (fact inf.left_commute)
  1990 
  1991 lemmas multiset_inter_ac =
  1992   multiset_inter_commute
  1993   multiset_inter_assoc
  1994   multiset_inter_left_commute
  1995 
  1996 lemma mult_less_not_refl:
  1997   "\<not> M \<subset># (M::'a::order multiset)"
  1998   by (fact multiset_order.less_irrefl)
  1999 
  2000 lemma mult_less_trans:
  2001   "K \<subset># M ==> M \<subset># N ==> K \<subset># (N::'a::order multiset)"
  2002   by (fact multiset_order.less_trans)
  2003     
  2004 lemma mult_less_not_sym:
  2005   "M \<subset># N ==> \<not> N \<subset># (M::'a::order multiset)"
  2006   by (fact multiset_order.less_not_sym)
  2007 
  2008 lemma mult_less_asym:
  2009   "M \<subset># N ==> (\<not> P ==> N \<subset># (M::'a::order multiset)) ==> P"
  2010   by (fact multiset_order.less_asym)
  2011 
  2012 ML {*
  2013 fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T]))
  2014                       (Const _ $ t') =
  2015     let
  2016       val (maybe_opt, ps) =
  2017         Nitpick_Model.dest_plain_fun t' ||> op ~~
  2018         ||> map (apsnd (snd o HOLogic.dest_number))
  2019       fun elems_for t =
  2020         case AList.lookup (op =) ps t of
  2021           SOME n => replicate n t
  2022         | NONE => [Const (maybe_name, elem_T --> elem_T) $ t]
  2023     in
  2024       case maps elems_for (all_values elem_T) @
  2025            (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)]
  2026             else []) of
  2027         [] => Const (@{const_name zero_class.zero}, T)
  2028       | ts => foldl1 (fn (t1, t2) =>
  2029                          Const (@{const_name plus_class.plus}, T --> T --> T)
  2030                          $ t1 $ t2)
  2031                      (map (curry (op $) (Const (@{const_name single},
  2032                                                 elem_T --> T))) ts)
  2033     end
  2034   | multiset_postproc _ _ _ _ t = t
  2035 *}
  2036 
  2037 declaration {*
  2038 Nitpick_Model.register_term_postprocessor @{typ "'a multiset"}
  2039     multiset_postproc
  2040 *}
  2041 
  2042 end