src/HOL/Library/Multiset.thy
author bulwahn
Wed Mar 28 10:00:52 2012 +0200 (2012-03-28)
changeset 47177 2fa00264392a
parent 47143 212f7a975d49
child 47179 54b38de0620e
permissions -rw-r--r--
using abstract code equations for proofs of code equations in Multiset
     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 *}
  1113 
  1114 definition join
  1115 where
  1116   "join f xs ys = DAList.Alist (join_raw f (DAList.impl_of xs) (DAList.impl_of ys))" 
  1117 
  1118 lemma [code abstract]:
  1119   "DAList.impl_of (join f xs ys) = join_raw f (DAList.impl_of xs) (DAList.impl_of ys)"
  1120 unfolding join_def by (simp add: Alist_inverse distinct_join_raw)
  1121 
  1122 definition subtract_entries
  1123 where
  1124   "subtract_entries xs ys = DAList.Alist (subtract_entries_raw (DAList.impl_of xs) (DAList.impl_of ys))"
  1125 
  1126 lemma [code abstract]:
  1127   "DAList.impl_of (subtract_entries xs ys) = subtract_entries_raw (DAList.impl_of xs) (DAList.impl_of ys)"
  1128 unfolding subtract_entries_def by (simp add: Alist_inverse distinct_subtract_entries_raw)
  1129 
  1130 text {* Implementing multisets by means of association lists *}
  1131 
  1132 definition count_of :: "('a \<times> nat) list \<Rightarrow> 'a \<Rightarrow> nat" where
  1133   "count_of xs x = (case map_of xs x of None \<Rightarrow> 0 | Some n \<Rightarrow> n)"
  1134 
  1135 lemma count_of_multiset:
  1136   "count_of xs \<in> multiset"
  1137 proof -
  1138   let ?A = "{x::'a. 0 < (case map_of xs x of None \<Rightarrow> 0\<Colon>nat | Some (n\<Colon>nat) \<Rightarrow> n)}"
  1139   have "?A \<subseteq> dom (map_of xs)"
  1140   proof
  1141     fix x
  1142     assume "x \<in> ?A"
  1143     then have "0 < (case map_of xs x of None \<Rightarrow> 0\<Colon>nat | Some (n\<Colon>nat) \<Rightarrow> n)" by simp
  1144     then have "map_of xs x \<noteq> None" by (cases "map_of xs x") auto
  1145     then show "x \<in> dom (map_of xs)" by auto
  1146   qed
  1147   with finite_dom_map_of [of xs] have "finite ?A"
  1148     by (auto intro: finite_subset)
  1149   then show ?thesis
  1150     by (simp add: count_of_def fun_eq_iff multiset_def)
  1151 qed
  1152 
  1153 lemma count_simps [simp]:
  1154   "count_of [] = (\<lambda>_. 0)"
  1155   "count_of ((x, n) # xs) = (\<lambda>y. if x = y then n else count_of xs y)"
  1156   by (simp_all add: count_of_def fun_eq_iff)
  1157 
  1158 lemma count_of_empty:
  1159   "x \<notin> fst ` set xs \<Longrightarrow> count_of xs x = 0"
  1160   by (induct xs) (simp_all add: count_of_def)
  1161 
  1162 lemma count_of_filter:
  1163   "count_of (List.filter (P \<circ> fst) xs) x = (if P x then count_of xs x else 0)"
  1164   by (induct xs) auto
  1165 
  1166 lemma count_of_map_default [simp]:
  1167   "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)"
  1168 unfolding count_of_def by (simp add: map_of_map_default split: option.split)
  1169 
  1170 lemma count_of_join_raw:
  1171   "distinct (map fst ys) ==> count_of xs x + count_of ys x = count_of (join_raw (%x (x, y). x + y) xs ys) x"
  1172 unfolding count_of_def by (simp add: map_of_join_raw split: option.split)
  1173 
  1174 lemma count_of_subtract_entries_raw:
  1175   "distinct (map fst ys) ==> count_of xs x - count_of ys x = count_of (subtract_entries_raw xs ys) x"
  1176 unfolding count_of_def by (simp add: map_of_subtract_entries_raw split: option.split)
  1177 
  1178 text {* Code equations for multiset operations *}
  1179 
  1180 definition Bag :: "('a, nat) alist \<Rightarrow> 'a multiset" where
  1181   "Bag xs = Abs_multiset (count_of (DAList.impl_of xs))"
  1182 
  1183 code_datatype Bag
  1184 
  1185 lemma count_Bag [simp, code]:
  1186   "count (Bag xs) = count_of (DAList.impl_of xs)"
  1187   by (simp add: Bag_def count_of_multiset Abs_multiset_inverse)
  1188 
  1189 lemma Mempty_Bag [code]:
  1190   "{#} = Bag (DAList.empty)"
  1191   by (simp add: multiset_eq_iff alist.Alist_inverse DAList.empty_def)
  1192 
  1193 lemma single_Bag [code]:
  1194   "{#x#} = Bag (DAList.update x 1 DAList.empty)"
  1195   by (simp add: multiset_eq_iff alist.Alist_inverse update_code_eqn empty_code_eqn)
  1196 
  1197 lemma union_Bag [code]:
  1198   "Bag xs + Bag ys = Bag (join (\<lambda>x (n1, n2). n1 + n2) xs ys)"
  1199 by (rule multiset_eqI) (simp add: count_of_join_raw alist.Alist_inverse distinct_join_raw join_def)
  1200 
  1201 lemma minus_Bag [code]:
  1202   "Bag xs - Bag ys = Bag (subtract_entries xs ys)"
  1203 by (rule multiset_eqI)
  1204   (simp add: count_of_subtract_entries_raw alist.Alist_inverse distinct_subtract_entries_raw subtract_entries_def)
  1205 
  1206 lemma filter_Bag [code]:
  1207   "Multiset.filter P (Bag xs) = Bag (DAList.filter (P \<circ> fst) xs)"
  1208 by (rule multiset_eqI) (simp add: count_of_filter filter_code_eqn)
  1209 
  1210 lemma mset_less_eq_Bag [code]:
  1211   "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)"
  1212     (is "?lhs \<longleftrightarrow> ?rhs")
  1213 proof
  1214   assume ?lhs then show ?rhs
  1215     by (auto simp add: mset_le_def)
  1216 next
  1217   assume ?rhs
  1218   show ?lhs
  1219   proof (rule mset_less_eqI)
  1220     fix x
  1221     from `?rhs` have "count_of (DAList.impl_of xs) x \<le> count A x"
  1222       by (cases "x \<in> fst ` set (DAList.impl_of xs)") (auto simp add: count_of_empty)
  1223     then show "count (Bag xs) x \<le> count A x"
  1224       by (simp add: mset_le_def)
  1225   qed
  1226 qed
  1227 
  1228 instantiation multiset :: (equal) equal
  1229 begin
  1230 
  1231 definition
  1232   [code]: "HOL.equal A B \<longleftrightarrow> (A::'a multiset) \<le> B \<and> B \<le> A"
  1233 
  1234 instance
  1235   by default (simp add: equal_multiset_def eq_iff)
  1236 
  1237 end
  1238 
  1239 text {* Quickcheck generators *}
  1240 
  1241 definition (in term_syntax)
  1242   bagify :: "('a\<Colon>typerep, nat) alist \<times> (unit \<Rightarrow> Code_Evaluation.term)
  1243     \<Rightarrow> 'a multiset \<times> (unit \<Rightarrow> Code_Evaluation.term)" where
  1244   [code_unfold]: "bagify xs = Code_Evaluation.valtermify Bag {\<cdot>} xs"
  1245 
  1246 notation fcomp (infixl "\<circ>>" 60)
  1247 notation scomp (infixl "\<circ>\<rightarrow>" 60)
  1248 
  1249 instantiation multiset :: (random) random
  1250 begin
  1251 
  1252 definition
  1253   "Quickcheck.random i = Quickcheck.random i \<circ>\<rightarrow> (\<lambda>xs. Pair (bagify xs))"
  1254 
  1255 instance ..
  1256 
  1257 end
  1258 
  1259 no_notation fcomp (infixl "\<circ>>" 60)
  1260 no_notation scomp (infixl "\<circ>\<rightarrow>" 60)
  1261 
  1262 instantiation multiset :: (exhaustive) exhaustive
  1263 begin
  1264 
  1265 definition exhaustive_multiset :: "('a multiset => (bool * term list) option) => code_numeral => (bool * term list) option"
  1266 where
  1267   "exhaustive_multiset f i = Quickcheck_Exhaustive.exhaustive (%xs. f (Bag xs)) i"
  1268 
  1269 instance ..
  1270 
  1271 end
  1272 
  1273 instantiation multiset :: (full_exhaustive) full_exhaustive
  1274 begin
  1275 
  1276 definition full_exhaustive_multiset :: "('a multiset * (unit => term) => (bool * term list) option) => code_numeral => (bool * term list) option"
  1277 where
  1278   "full_exhaustive_multiset f i = Quickcheck_Exhaustive.full_exhaustive (%xs. f (bagify xs)) i"
  1279 
  1280 instance ..
  1281 
  1282 end
  1283 
  1284 hide_const (open) bagify
  1285 
  1286 
  1287 subsection {* The multiset order *}
  1288 
  1289 subsubsection {* Well-foundedness *}
  1290 
  1291 definition mult1 :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
  1292   "mult1 r = {(N, M). \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and>
  1293       (\<forall>b. b :# K --> (b, a) \<in> r)}"
  1294 
  1295 definition mult :: "('a \<times> 'a) set => ('a multiset \<times> 'a multiset) set" where
  1296   "mult r = (mult1 r)\<^sup>+"
  1297 
  1298 lemma not_less_empty [iff]: "(M, {#}) \<notin> mult1 r"
  1299 by (simp add: mult1_def)
  1300 
  1301 lemma less_add: "(N, M0 + {#a#}) \<in> mult1 r ==>
  1302     (\<exists>M. (M, M0) \<in> mult1 r \<and> N = M + {#a#}) \<or>
  1303     (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K)"
  1304   (is "_ \<Longrightarrow> ?case1 (mult1 r) \<or> ?case2")
  1305 proof (unfold mult1_def)
  1306   let ?r = "\<lambda>K a. \<forall>b. b :# K --> (b, a) \<in> r"
  1307   let ?R = "\<lambda>N M. \<exists>a M0 K. M = M0 + {#a#} \<and> N = M0 + K \<and> ?r K a"
  1308   let ?case1 = "?case1 {(N, M). ?R N M}"
  1309 
  1310   assume "(N, M0 + {#a#}) \<in> {(N, M). ?R N M}"
  1311   then have "\<exists>a' M0' K.
  1312       M0 + {#a#} = M0' + {#a'#} \<and> N = M0' + K \<and> ?r K a'" by simp
  1313   then show "?case1 \<or> ?case2"
  1314   proof (elim exE conjE)
  1315     fix a' M0' K
  1316     assume N: "N = M0' + K" and r: "?r K a'"
  1317     assume "M0 + {#a#} = M0' + {#a'#}"
  1318     then have "M0 = M0' \<and> a = a' \<or>
  1319         (\<exists>K'. M0 = K' + {#a'#} \<and> M0' = K' + {#a#})"
  1320       by (simp only: add_eq_conv_ex)
  1321     then show ?thesis
  1322     proof (elim disjE conjE exE)
  1323       assume "M0 = M0'" "a = a'"
  1324       with N r have "?r K a \<and> N = M0 + K" by simp
  1325       then have ?case2 .. then show ?thesis ..
  1326     next
  1327       fix K'
  1328       assume "M0' = K' + {#a#}"
  1329       with N have n: "N = K' + K + {#a#}" by (simp add: add_ac)
  1330 
  1331       assume "M0 = K' + {#a'#}"
  1332       with r have "?R (K' + K) M0" by blast
  1333       with n have ?case1 by simp then show ?thesis ..
  1334     qed
  1335   qed
  1336 qed
  1337 
  1338 lemma all_accessible: "wf r ==> \<forall>M. M \<in> acc (mult1 r)"
  1339 proof
  1340   let ?R = "mult1 r"
  1341   let ?W = "acc ?R"
  1342   {
  1343     fix M M0 a
  1344     assume M0: "M0 \<in> ?W"
  1345       and wf_hyp: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
  1346       and acc_hyp: "\<forall>M. (M, M0) \<in> ?R --> M + {#a#} \<in> ?W"
  1347     have "M0 + {#a#} \<in> ?W"
  1348     proof (rule accI [of "M0 + {#a#}"])
  1349       fix N
  1350       assume "(N, M0 + {#a#}) \<in> ?R"
  1351       then have "((\<exists>M. (M, M0) \<in> ?R \<and> N = M + {#a#}) \<or>
  1352           (\<exists>K. (\<forall>b. b :# K --> (b, a) \<in> r) \<and> N = M0 + K))"
  1353         by (rule less_add)
  1354       then show "N \<in> ?W"
  1355       proof (elim exE disjE conjE)
  1356         fix M assume "(M, M0) \<in> ?R" and N: "N = M + {#a#}"
  1357         from acc_hyp have "(M, M0) \<in> ?R --> M + {#a#} \<in> ?W" ..
  1358         from this and `(M, M0) \<in> ?R` have "M + {#a#} \<in> ?W" ..
  1359         then show "N \<in> ?W" by (simp only: N)
  1360       next
  1361         fix K
  1362         assume N: "N = M0 + K"
  1363         assume "\<forall>b. b :# K --> (b, a) \<in> r"
  1364         then have "M0 + K \<in> ?W"
  1365         proof (induct K)
  1366           case empty
  1367           from M0 show "M0 + {#} \<in> ?W" by simp
  1368         next
  1369           case (add K x)
  1370           from add.prems have "(x, a) \<in> r" by simp
  1371           with wf_hyp have "\<forall>M \<in> ?W. M + {#x#} \<in> ?W" by blast
  1372           moreover from add have "M0 + K \<in> ?W" by simp
  1373           ultimately have "(M0 + K) + {#x#} \<in> ?W" ..
  1374           then show "M0 + (K + {#x#}) \<in> ?W" by (simp only: add_assoc)
  1375         qed
  1376         then show "N \<in> ?W" by (simp only: N)
  1377       qed
  1378     qed
  1379   } note tedious_reasoning = this
  1380 
  1381   assume wf: "wf r"
  1382   fix M
  1383   show "M \<in> ?W"
  1384   proof (induct M)
  1385     show "{#} \<in> ?W"
  1386     proof (rule accI)
  1387       fix b assume "(b, {#}) \<in> ?R"
  1388       with not_less_empty show "b \<in> ?W" by contradiction
  1389     qed
  1390 
  1391     fix M a assume "M \<in> ?W"
  1392     from wf have "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
  1393     proof induct
  1394       fix a
  1395       assume r: "!!b. (b, a) \<in> r ==> (\<forall>M \<in> ?W. M + {#b#} \<in> ?W)"
  1396       show "\<forall>M \<in> ?W. M + {#a#} \<in> ?W"
  1397       proof
  1398         fix M assume "M \<in> ?W"
  1399         then show "M + {#a#} \<in> ?W"
  1400           by (rule acc_induct) (rule tedious_reasoning [OF _ r])
  1401       qed
  1402     qed
  1403     from this and `M \<in> ?W` show "M + {#a#} \<in> ?W" ..
  1404   qed
  1405 qed
  1406 
  1407 theorem wf_mult1: "wf r ==> wf (mult1 r)"
  1408 by (rule acc_wfI) (rule all_accessible)
  1409 
  1410 theorem wf_mult: "wf r ==> wf (mult r)"
  1411 unfolding mult_def by (rule wf_trancl) (rule wf_mult1)
  1412 
  1413 
  1414 subsubsection {* Closure-free presentation *}
  1415 
  1416 text {* One direction. *}
  1417 
  1418 lemma mult_implies_one_step:
  1419   "trans r ==> (M, N) \<in> mult r ==>
  1420     \<exists>I J K. N = I + J \<and> M = I + K \<and> J \<noteq> {#} \<and>
  1421     (\<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r)"
  1422 apply (unfold mult_def mult1_def set_of_def)
  1423 apply (erule converse_trancl_induct, clarify)
  1424  apply (rule_tac x = M0 in exI, simp, clarify)
  1425 apply (case_tac "a :# K")
  1426  apply (rule_tac x = I in exI)
  1427  apply (simp (no_asm))
  1428  apply (rule_tac x = "(K - {#a#}) + Ka" in exI)
  1429  apply (simp (no_asm_simp) add: add_assoc [symmetric])
  1430  apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong)
  1431  apply (simp add: diff_union_single_conv)
  1432  apply (simp (no_asm_use) add: trans_def)
  1433  apply blast
  1434 apply (subgoal_tac "a :# I")
  1435  apply (rule_tac x = "I - {#a#}" in exI)
  1436  apply (rule_tac x = "J + {#a#}" in exI)
  1437  apply (rule_tac x = "K + Ka" in exI)
  1438  apply (rule conjI)
  1439   apply (simp add: multiset_eq_iff split: nat_diff_split)
  1440  apply (rule conjI)
  1441   apply (drule_tac f = "\<lambda>M. M - {#a#}" in arg_cong, simp)
  1442   apply (simp add: multiset_eq_iff split: nat_diff_split)
  1443  apply (simp (no_asm_use) add: trans_def)
  1444  apply blast
  1445 apply (subgoal_tac "a :# (M0 + {#a#})")
  1446  apply simp
  1447 apply (simp (no_asm))
  1448 done
  1449 
  1450 lemma one_step_implies_mult_aux:
  1451   "trans r ==>
  1452     \<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))
  1453       --> (I + K, I + J) \<in> mult r"
  1454 apply (induct_tac n, auto)
  1455 apply (frule size_eq_Suc_imp_eq_union, clarify)
  1456 apply (rename_tac "J'", simp)
  1457 apply (erule notE, auto)
  1458 apply (case_tac "J' = {#}")
  1459  apply (simp add: mult_def)
  1460  apply (rule r_into_trancl)
  1461  apply (simp add: mult1_def set_of_def, blast)
  1462 txt {* Now we know @{term "J' \<noteq> {#}"}. *}
  1463 apply (cut_tac M = K and P = "\<lambda>x. (x, a) \<in> r" in multiset_partition)
  1464 apply (erule_tac P = "\<forall>k \<in> set_of K. ?P k" in rev_mp)
  1465 apply (erule ssubst)
  1466 apply (simp add: Ball_def, auto)
  1467 apply (subgoal_tac
  1468   "((I + {# x :# K. (x, a) \<in> r #}) + {# x :# K. (x, a) \<notin> r #},
  1469     (I + {# x :# K. (x, a) \<in> r #}) + J') \<in> mult r")
  1470  prefer 2
  1471  apply force
  1472 apply (simp (no_asm_use) add: add_assoc [symmetric] mult_def)
  1473 apply (erule trancl_trans)
  1474 apply (rule r_into_trancl)
  1475 apply (simp add: mult1_def set_of_def)
  1476 apply (rule_tac x = a in exI)
  1477 apply (rule_tac x = "I + J'" in exI)
  1478 apply (simp add: add_ac)
  1479 done
  1480 
  1481 lemma one_step_implies_mult:
  1482   "trans r ==> J \<noteq> {#} ==> \<forall>k \<in> set_of K. \<exists>j \<in> set_of J. (k, j) \<in> r
  1483     ==> (I + K, I + J) \<in> mult r"
  1484 using one_step_implies_mult_aux by blast
  1485 
  1486 
  1487 subsubsection {* Partial-order properties *}
  1488 
  1489 definition less_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<#" 50) where
  1490   "M' <# M \<longleftrightarrow> (M', M) \<in> mult {(x', x). x' < x}"
  1491 
  1492 definition le_multiset :: "'a\<Colon>order multiset \<Rightarrow> 'a multiset \<Rightarrow> bool" (infix "<=#" 50) where
  1493   "M' <=# M \<longleftrightarrow> M' <# M \<or> M' = M"
  1494 
  1495 notation (xsymbols) less_multiset (infix "\<subset>#" 50)
  1496 notation (xsymbols) le_multiset (infix "\<subseteq>#" 50)
  1497 
  1498 interpretation multiset_order: order le_multiset less_multiset
  1499 proof -
  1500   have irrefl: "\<And>M :: 'a multiset. \<not> M \<subset># M"
  1501   proof
  1502     fix M :: "'a multiset"
  1503     assume "M \<subset># M"
  1504     then have MM: "(M, M) \<in> mult {(x, y). x < y}" by (simp add: less_multiset_def)
  1505     have "trans {(x'::'a, x). x' < x}"
  1506       by (rule transI) simp
  1507     moreover note MM
  1508     ultimately have "\<exists>I J K. M = I + J \<and> M = I + K
  1509       \<and> J \<noteq> {#} \<and> (\<forall>k\<in>set_of K. \<exists>j\<in>set_of J. (k, j) \<in> {(x, y). x < y})"
  1510       by (rule mult_implies_one_step)
  1511     then obtain I J K where "M = I + J" and "M = I + K"
  1512       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
  1513     then have aux1: "K \<noteq> {#}" and aux2: "\<forall>k\<in>set_of K. \<exists>j\<in>set_of K. k < j" by auto
  1514     have "finite (set_of K)" by simp
  1515     moreover note aux2
  1516     ultimately have "set_of K = {}"
  1517       by (induct rule: finite_induct) (auto intro: order_less_trans)
  1518     with aux1 show False by simp
  1519   qed
  1520   have trans: "\<And>K M N :: 'a multiset. K \<subset># M \<Longrightarrow> M \<subset># N \<Longrightarrow> K \<subset># N"
  1521     unfolding less_multiset_def mult_def by (blast intro: trancl_trans)
  1522   show "class.order (le_multiset :: 'a multiset \<Rightarrow> _) less_multiset"
  1523     by default (auto simp add: le_multiset_def irrefl dest: trans)
  1524 qed
  1525 
  1526 lemma mult_less_irrefl [elim!]: "M \<subset># (M::'a::order multiset) ==> R"
  1527   by simp
  1528 
  1529 
  1530 subsubsection {* Monotonicity of multiset union *}
  1531 
  1532 lemma mult1_union: "(B, D) \<in> mult1 r ==> (C + B, C + D) \<in> mult1 r"
  1533 apply (unfold mult1_def)
  1534 apply auto
  1535 apply (rule_tac x = a in exI)
  1536 apply (rule_tac x = "C + M0" in exI)
  1537 apply (simp add: add_assoc)
  1538 done
  1539 
  1540 lemma union_less_mono2: "B \<subset># D ==> C + B \<subset># C + (D::'a::order multiset)"
  1541 apply (unfold less_multiset_def mult_def)
  1542 apply (erule trancl_induct)
  1543  apply (blast intro: mult1_union)
  1544 apply (blast intro: mult1_union trancl_trans)
  1545 done
  1546 
  1547 lemma union_less_mono1: "B \<subset># D ==> B + C \<subset># D + (C::'a::order multiset)"
  1548 apply (subst add_commute [of B C])
  1549 apply (subst add_commute [of D C])
  1550 apply (erule union_less_mono2)
  1551 done
  1552 
  1553 lemma union_less_mono:
  1554   "A \<subset># C ==> B \<subset># D ==> A + B \<subset># C + (D::'a::order multiset)"
  1555   by (blast intro!: union_less_mono1 union_less_mono2 multiset_order.less_trans)
  1556 
  1557 interpretation multiset_order: ordered_ab_semigroup_add plus le_multiset less_multiset
  1558 proof
  1559 qed (auto simp add: le_multiset_def intro: union_less_mono2)
  1560 
  1561 
  1562 subsection {* The fold combinator *}
  1563 
  1564 text {*
  1565   The intended behaviour is
  1566   @{text "fold_mset f z {#x\<^isub>1, ..., x\<^isub>n#} = f x\<^isub>1 (\<dots> (f x\<^isub>n z)\<dots>)"}
  1567   if @{text f} is associative-commutative. 
  1568 *}
  1569 
  1570 text {*
  1571   The graph of @{text "fold_mset"}, @{text "z"}: the start element,
  1572   @{text "f"}: folding function, @{text "A"}: the multiset, @{text
  1573   "y"}: the result.
  1574 *}
  1575 inductive 
  1576   fold_msetG :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b \<Rightarrow> bool" 
  1577   for f :: "'a \<Rightarrow> 'b \<Rightarrow> 'b" 
  1578   and z :: 'b
  1579 where
  1580   emptyI [intro]:  "fold_msetG f z {#} z"
  1581 | insertI [intro]: "fold_msetG f z A y \<Longrightarrow> fold_msetG f z (A + {#x#}) (f x y)"
  1582 
  1583 inductive_cases empty_fold_msetGE [elim!]: "fold_msetG f z {#} x"
  1584 inductive_cases insert_fold_msetGE: "fold_msetG f z (A + {#}) y" 
  1585 
  1586 definition
  1587   fold_mset :: "('a \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'b \<Rightarrow> 'a multiset \<Rightarrow> 'b" where
  1588   "fold_mset f z A = (THE x. fold_msetG f z A x)"
  1589 
  1590 lemma Diff1_fold_msetG:
  1591   "fold_msetG f z (A - {#x#}) y \<Longrightarrow> x \<in># A \<Longrightarrow> fold_msetG f z A (f x y)"
  1592 apply (frule_tac x = x in fold_msetG.insertI)
  1593 apply auto
  1594 done
  1595 
  1596 lemma fold_msetG_nonempty: "\<exists>x. fold_msetG f z A x"
  1597 apply (induct A)
  1598  apply blast
  1599 apply clarsimp
  1600 apply (drule_tac x = x in fold_msetG.insertI)
  1601 apply auto
  1602 done
  1603 
  1604 lemma fold_mset_empty[simp]: "fold_mset f z {#} = z"
  1605 unfolding fold_mset_def by blast
  1606 
  1607 context comp_fun_commute
  1608 begin
  1609 
  1610 lemma fold_msetG_determ:
  1611   "fold_msetG f z A x \<Longrightarrow> fold_msetG f z A y \<Longrightarrow> y = x"
  1612 proof (induct arbitrary: x y z rule: full_multiset_induct)
  1613   case (less M x\<^isub>1 x\<^isub>2 Z)
  1614   have IH: "\<forall>A. A < M \<longrightarrow> 
  1615     (\<forall>x x' x''. fold_msetG f x'' A x \<longrightarrow> fold_msetG f x'' A x'
  1616                \<longrightarrow> x' = x)" by fact
  1617   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+
  1618   show ?case
  1619   proof (rule fold_msetG.cases [OF Mfoldx\<^isub>1])
  1620     assume "M = {#}" and "x\<^isub>1 = Z"
  1621     then show ?case using Mfoldx\<^isub>2 by auto 
  1622   next
  1623     fix B b u
  1624     assume "M = B + {#b#}" and "x\<^isub>1 = f b u" and Bu: "fold_msetG f Z B u"
  1625     then have MBb: "M = B + {#b#}" and x\<^isub>1: "x\<^isub>1 = f b u" by auto
  1626     show ?case
  1627     proof (rule fold_msetG.cases [OF Mfoldx\<^isub>2])
  1628       assume "M = {#}" "x\<^isub>2 = Z"
  1629       then show ?case using Mfoldx\<^isub>1 by auto
  1630     next
  1631       fix C c v
  1632       assume "M = C + {#c#}" and "x\<^isub>2 = f c v" and Cv: "fold_msetG f Z C v"
  1633       then have MCc: "M = C + {#c#}" and x\<^isub>2: "x\<^isub>2 = f c v" by auto
  1634       then have CsubM: "C < M" by simp
  1635       from MBb have BsubM: "B < M" by simp
  1636       show ?case
  1637       proof cases
  1638         assume *: "b = c"
  1639         then have "B = C" using MBb MCc by auto
  1640         with * show ?thesis using Bu Cv x\<^isub>1 x\<^isub>2 CsubM IH by auto
  1641       next
  1642         assume diff: "b \<noteq> c"
  1643         let ?D = "B - {#c#}"
  1644         have cinB: "c \<in># B" and binC: "b \<in># C" using MBb MCc diff
  1645           by (auto intro: insert_noteq_member dest: sym)
  1646         have "B - {#c#} < B" using cinB by (rule mset_less_diff_self)
  1647         then have DsubM: "?D < M" using BsubM by (blast intro: order_less_trans)
  1648         from MBb MCc have "B + {#b#} = C + {#c#}" by blast
  1649         then have [simp]: "B + {#b#} - {#c#} = C"
  1650           using MBb MCc binC cinB by auto
  1651         have B: "B = ?D + {#c#}" and C: "C = ?D + {#b#}"
  1652           using MBb MCc diff binC cinB
  1653           by (auto simp: multiset_add_sub_el_shuffle)
  1654         then obtain d where Dfoldd: "fold_msetG f Z ?D d"
  1655           using fold_msetG_nonempty by iprover
  1656         then have "fold_msetG f Z B (f c d)" using cinB
  1657           by (rule Diff1_fold_msetG)
  1658         then have "f c d = u" using IH BsubM Bu by blast
  1659         moreover 
  1660         have "fold_msetG f Z C (f b d)" using binC cinB diff Dfoldd
  1661           by (auto simp: multiset_add_sub_el_shuffle 
  1662             dest: fold_msetG.insertI [where x=b])
  1663         then have "f b d = v" using IH CsubM Cv by blast
  1664         ultimately show ?thesis using x\<^isub>1 x\<^isub>2
  1665           by (auto simp: fun_left_comm)
  1666       qed
  1667     qed
  1668   qed
  1669 qed
  1670         
  1671 lemma fold_mset_insert_aux:
  1672   "(fold_msetG f z (A + {#x#}) v) =
  1673     (\<exists>y. fold_msetG f z A y \<and> v = f x y)"
  1674 apply (rule iffI)
  1675  prefer 2
  1676  apply blast
  1677 apply (rule_tac A1=A and f1=f in fold_msetG_nonempty [THEN exE])
  1678 apply (blast intro: fold_msetG_determ)
  1679 done
  1680 
  1681 lemma fold_mset_equality: "fold_msetG f z A y \<Longrightarrow> fold_mset f z A = y"
  1682 unfolding fold_mset_def by (blast intro: fold_msetG_determ)
  1683 
  1684 lemma fold_mset_insert:
  1685   "fold_mset f z (A + {#x#}) = f x (fold_mset f z A)"
  1686 apply (simp add: fold_mset_def fold_mset_insert_aux)
  1687 apply (rule the_equality)
  1688  apply (auto cong add: conj_cong 
  1689      simp add: fold_mset_def [symmetric] fold_mset_equality fold_msetG_nonempty)
  1690 done
  1691 
  1692 lemma fold_mset_commute: "f x (fold_mset f z A) = fold_mset f (f x z) A"
  1693 by (induct A) (auto simp: fold_mset_insert fun_left_comm [of x])
  1694 
  1695 lemma fold_mset_single [simp]: "fold_mset f z {#x#} = f x z"
  1696 using fold_mset_insert [of z "{#}"] by simp
  1697 
  1698 lemma fold_mset_union [simp]:
  1699   "fold_mset f z (A+B) = fold_mset f (fold_mset f z A) B"
  1700 proof (induct A)
  1701   case empty then show ?case by simp
  1702 next
  1703   case (add A x)
  1704   have "A + {#x#} + B = (A+B) + {#x#}" by (simp add: add_ac)
  1705   then have "fold_mset f z (A + {#x#} + B) = f x (fold_mset f z (A + B))" 
  1706     by (simp add: fold_mset_insert)
  1707   also have "\<dots> = fold_mset f (fold_mset f z (A + {#x#})) B"
  1708     by (simp add: fold_mset_commute[of x,symmetric] add fold_mset_insert)
  1709   finally show ?case .
  1710 qed
  1711 
  1712 lemma fold_mset_fusion:
  1713   assumes "comp_fun_commute g"
  1714   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")
  1715 proof -
  1716   interpret comp_fun_commute g by (fact assms)
  1717   show "PROP ?P" by (induct A) auto
  1718 qed
  1719 
  1720 lemma fold_mset_rec:
  1721   assumes "a \<in># A" 
  1722   shows "fold_mset f z A = f a (fold_mset f z (A - {#a#}))"
  1723 proof -
  1724   from assms obtain A' where "A = A' + {#a#}"
  1725     by (blast dest: multi_member_split)
  1726   then show ?thesis by simp
  1727 qed
  1728 
  1729 end
  1730 
  1731 text {*
  1732   A note on code generation: When defining some function containing a
  1733   subterm @{term"fold_mset F"}, code generation is not automatic. When
  1734   interpreting locale @{text left_commutative} with @{text F}, the
  1735   would be code thms for @{const fold_mset} become thms like
  1736   @{term"fold_mset F z {#} = z"} where @{text F} is not a pattern but
  1737   contains defined symbols, i.e.\ is not a code thm. Hence a separate
  1738   constant with its own code thms needs to be introduced for @{text
  1739   F}. See the image operator below.
  1740 *}
  1741 
  1742 
  1743 subsection {* Image *}
  1744 
  1745 definition image_mset :: "('a \<Rightarrow> 'b) \<Rightarrow> 'a multiset \<Rightarrow> 'b multiset" where
  1746   "image_mset f = fold_mset (op + o single o f) {#}"
  1747 
  1748 interpretation image_fun_commute: comp_fun_commute "op + o single o f" for f
  1749 proof qed (simp add: add_ac fun_eq_iff)
  1750 
  1751 lemma image_mset_empty [simp]: "image_mset f {#} = {#}"
  1752 by (simp add: image_mset_def)
  1753 
  1754 lemma image_mset_single [simp]: "image_mset f {#x#} = {#f x#}"
  1755 by (simp add: image_mset_def)
  1756 
  1757 lemma image_mset_insert:
  1758   "image_mset f (M + {#a#}) = image_mset f M + {#f a#}"
  1759 by (simp add: image_mset_def add_ac)
  1760 
  1761 lemma image_mset_union [simp]:
  1762   "image_mset f (M+N) = image_mset f M + image_mset f N"
  1763 apply (induct N)
  1764  apply simp
  1765 apply (simp add: add_assoc [symmetric] image_mset_insert)
  1766 done
  1767 
  1768 lemma size_image_mset [simp]: "size (image_mset f M) = size M"
  1769 by (induct M) simp_all
  1770 
  1771 lemma image_mset_is_empty_iff [simp]: "image_mset f M = {#} \<longleftrightarrow> M = {#}"
  1772 by (cases M) auto
  1773 
  1774 syntax
  1775   "_comprehension1_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> 'a multiset"
  1776       ("({#_/. _ :# _#})")
  1777 translations
  1778   "{#e. x:#M#}" == "CONST image_mset (%x. e) M"
  1779 
  1780 syntax
  1781   "_comprehension2_mset" :: "'a \<Rightarrow> 'b \<Rightarrow> 'b multiset \<Rightarrow> bool \<Rightarrow> 'a multiset"
  1782       ("({#_/ | _ :# _./ _#})")
  1783 translations
  1784   "{#e | x:#M. P#}" => "{#e. x :# {# x:#M. P#}#}"
  1785 
  1786 text {*
  1787   This allows to write not just filters like @{term "{#x:#M. x<c#}"}
  1788   but also images like @{term "{#x+x. x:#M #}"} and @{term [source]
  1789   "{#x+x|x:#M. x<c#}"}, where the latter is currently displayed as
  1790   @{term "{#x+x|x:#M. x<c#}"}.
  1791 *}
  1792 
  1793 enriched_type image_mset: image_mset
  1794 proof -
  1795   fix f g show "image_mset f \<circ> image_mset g = image_mset (f \<circ> g)"
  1796   proof
  1797     fix A
  1798     show "(image_mset f \<circ> image_mset g) A = image_mset (f \<circ> g) A"
  1799       by (induct A) simp_all
  1800   qed
  1801   show "image_mset id = id"
  1802   proof
  1803     fix A
  1804     show "image_mset id A = id A"
  1805       by (induct A) simp_all
  1806   qed
  1807 qed
  1808 
  1809 
  1810 subsection {* Termination proofs with multiset orders *}
  1811 
  1812 lemma multi_member_skip: "x \<in># XS \<Longrightarrow> x \<in># {# y #} + XS"
  1813   and multi_member_this: "x \<in># {# x #} + XS"
  1814   and multi_member_last: "x \<in># {# x #}"
  1815   by auto
  1816 
  1817 definition "ms_strict = mult pair_less"
  1818 definition "ms_weak = ms_strict \<union> Id"
  1819 
  1820 lemma ms_reduction_pair: "reduction_pair (ms_strict, ms_weak)"
  1821 unfolding reduction_pair_def ms_strict_def ms_weak_def pair_less_def
  1822 by (auto intro: wf_mult1 wf_trancl simp: mult_def)
  1823 
  1824 lemma smsI:
  1825   "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z + B) \<in> ms_strict"
  1826   unfolding ms_strict_def
  1827 by (rule one_step_implies_mult) (auto simp add: max_strict_def pair_less_def elim!:max_ext.cases)
  1828 
  1829 lemma wmsI:
  1830   "(set_of A, set_of B) \<in> max_strict \<or> A = {#} \<and> B = {#}
  1831   \<Longrightarrow> (Z + A, Z + B) \<in> ms_weak"
  1832 unfolding ms_weak_def ms_strict_def
  1833 by (auto simp add: pair_less_def max_strict_def elim!:max_ext.cases intro: one_step_implies_mult)
  1834 
  1835 inductive pw_leq
  1836 where
  1837   pw_leq_empty: "pw_leq {#} {#}"
  1838 | pw_leq_step:  "\<lbrakk>(x,y) \<in> pair_leq; pw_leq X Y \<rbrakk> \<Longrightarrow> pw_leq ({#x#} + X) ({#y#} + Y)"
  1839 
  1840 lemma pw_leq_lstep:
  1841   "(x, y) \<in> pair_leq \<Longrightarrow> pw_leq {#x#} {#y#}"
  1842 by (drule pw_leq_step) (rule pw_leq_empty, simp)
  1843 
  1844 lemma pw_leq_split:
  1845   assumes "pw_leq X Y"
  1846   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 = {#}))"
  1847   using assms
  1848 proof (induct)
  1849   case pw_leq_empty thus ?case by auto
  1850 next
  1851   case (pw_leq_step x y X Y)
  1852   then obtain A B Z where
  1853     [simp]: "X = A + Z" "Y = B + Z" 
  1854       and 1[simp]: "(set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#})" 
  1855     by auto
  1856   from pw_leq_step have "x = y \<or> (x, y) \<in> pair_less" 
  1857     unfolding pair_leq_def by auto
  1858   thus ?case
  1859   proof
  1860     assume [simp]: "x = y"
  1861     have
  1862       "{#x#} + X = A + ({#y#}+Z) 
  1863       \<and> {#y#} + Y = B + ({#y#}+Z)
  1864       \<and> ((set_of A, set_of B) \<in> max_strict \<or> (B = {#} \<and> A = {#}))"
  1865       by (auto simp: add_ac)
  1866     thus ?case by (intro exI)
  1867   next
  1868     assume A: "(x, y) \<in> pair_less"
  1869     let ?A' = "{#x#} + A" and ?B' = "{#y#} + B"
  1870     have "{#x#} + X = ?A' + Z"
  1871       "{#y#} + Y = ?B' + Z"
  1872       by (auto simp add: add_ac)
  1873     moreover have 
  1874       "(set_of ?A', set_of ?B') \<in> max_strict"
  1875       using 1 A unfolding max_strict_def 
  1876       by (auto elim!: max_ext.cases)
  1877     ultimately show ?thesis by blast
  1878   qed
  1879 qed
  1880 
  1881 lemma 
  1882   assumes pwleq: "pw_leq Z Z'"
  1883   shows ms_strictI: "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_strict"
  1884   and   ms_weakI1:  "(set_of A, set_of B) \<in> max_strict \<Longrightarrow> (Z + A, Z' + B) \<in> ms_weak"
  1885   and   ms_weakI2:  "(Z + {#}, Z' + {#}) \<in> ms_weak"
  1886 proof -
  1887   from pw_leq_split[OF pwleq] 
  1888   obtain A' B' Z''
  1889     where [simp]: "Z = A' + Z''" "Z' = B' + Z''"
  1890     and mx_or_empty: "(set_of A', set_of B') \<in> max_strict \<or> (A' = {#} \<and> B' = {#})"
  1891     by blast
  1892   {
  1893     assume max: "(set_of A, set_of B) \<in> max_strict"
  1894     from mx_or_empty
  1895     have "(Z'' + (A + A'), Z'' + (B + B')) \<in> ms_strict"
  1896     proof
  1897       assume max': "(set_of A', set_of B') \<in> max_strict"
  1898       with max have "(set_of (A + A'), set_of (B + B')) \<in> max_strict"
  1899         by (auto simp: max_strict_def intro: max_ext_additive)
  1900       thus ?thesis by (rule smsI) 
  1901     next
  1902       assume [simp]: "A' = {#} \<and> B' = {#}"
  1903       show ?thesis by (rule smsI) (auto intro: max)
  1904     qed
  1905     thus "(Z + A, Z' + B) \<in> ms_strict" by (simp add:add_ac)
  1906     thus "(Z + A, Z' + B) \<in> ms_weak" by (simp add: ms_weak_def)
  1907   }
  1908   from mx_or_empty
  1909   have "(Z'' + A', Z'' + B') \<in> ms_weak" by (rule wmsI)
  1910   thus "(Z + {#}, Z' + {#}) \<in> ms_weak" by (simp add:add_ac)
  1911 qed
  1912 
  1913 lemma empty_neutral: "{#} + x = x" "x + {#} = x"
  1914 and nonempty_plus: "{# x #} + rs \<noteq> {#}"
  1915 and nonempty_single: "{# x #} \<noteq> {#}"
  1916 by auto
  1917 
  1918 setup {*
  1919 let
  1920   fun msetT T = Type (@{type_name multiset}, [T]);
  1921 
  1922   fun mk_mset T [] = Const (@{const_abbrev Mempty}, msetT T)
  1923     | mk_mset T [x] = Const (@{const_name single}, T --> msetT T) $ x
  1924     | mk_mset T (x :: xs) =
  1925           Const (@{const_name plus}, msetT T --> msetT T --> msetT T) $
  1926                 mk_mset T [x] $ mk_mset T xs
  1927 
  1928   fun mset_member_tac m i =
  1929       (if m <= 0 then
  1930            rtac @{thm multi_member_this} i ORELSE rtac @{thm multi_member_last} i
  1931        else
  1932            rtac @{thm multi_member_skip} i THEN mset_member_tac (m - 1) i)
  1933 
  1934   val mset_nonempty_tac =
  1935       rtac @{thm nonempty_plus} ORELSE' rtac @{thm nonempty_single}
  1936 
  1937   val regroup_munion_conv =
  1938       Function_Lib.regroup_conv @{const_abbrev Mempty} @{const_name plus}
  1939         (map (fn t => t RS eq_reflection) (@{thms add_ac} @ @{thms empty_neutral}))
  1940 
  1941   fun unfold_pwleq_tac i =
  1942     (rtac @{thm pw_leq_step} i THEN (fn st => unfold_pwleq_tac (i + 1) st))
  1943       ORELSE (rtac @{thm pw_leq_lstep} i)
  1944       ORELSE (rtac @{thm pw_leq_empty} i)
  1945 
  1946   val set_of_simps = [@{thm set_of_empty}, @{thm set_of_single}, @{thm set_of_union},
  1947                       @{thm Un_insert_left}, @{thm Un_empty_left}]
  1948 in
  1949   ScnpReconstruct.multiset_setup (ScnpReconstruct.Multiset 
  1950   {
  1951     msetT=msetT, mk_mset=mk_mset, mset_regroup_conv=regroup_munion_conv,
  1952     mset_member_tac=mset_member_tac, mset_nonempty_tac=mset_nonempty_tac,
  1953     mset_pwleq_tac=unfold_pwleq_tac, set_of_simps=set_of_simps,
  1954     smsI'= @{thm ms_strictI}, wmsI2''= @{thm ms_weakI2}, wmsI1= @{thm ms_weakI1},
  1955     reduction_pair= @{thm ms_reduction_pair}
  1956   })
  1957 end
  1958 *}
  1959 
  1960 
  1961 subsection {* Legacy theorem bindings *}
  1962 
  1963 lemmas multi_count_eq = multiset_eq_iff [symmetric]
  1964 
  1965 lemma union_commute: "M + N = N + (M::'a multiset)"
  1966   by (fact add_commute)
  1967 
  1968 lemma union_assoc: "(M + N) + K = M + (N + (K::'a multiset))"
  1969   by (fact add_assoc)
  1970 
  1971 lemma union_lcomm: "M + (N + K) = N + (M + (K::'a multiset))"
  1972   by (fact add_left_commute)
  1973 
  1974 lemmas union_ac = union_assoc union_commute union_lcomm
  1975 
  1976 lemma union_right_cancel: "M + K = N + K \<longleftrightarrow> M = (N::'a multiset)"
  1977   by (fact add_right_cancel)
  1978 
  1979 lemma union_left_cancel: "K + M = K + N \<longleftrightarrow> M = (N::'a multiset)"
  1980   by (fact add_left_cancel)
  1981 
  1982 lemma multi_union_self_other_eq: "(A::'a multiset) + X = A + Y \<Longrightarrow> X = Y"
  1983   by (fact add_imp_eq)
  1984 
  1985 lemma mset_less_trans: "(M::'a multiset) < K \<Longrightarrow> K < N \<Longrightarrow> M < N"
  1986   by (fact order_less_trans)
  1987 
  1988 lemma multiset_inter_commute: "A #\<inter> B = B #\<inter> A"
  1989   by (fact inf.commute)
  1990 
  1991 lemma multiset_inter_assoc: "A #\<inter> (B #\<inter> C) = A #\<inter> B #\<inter> C"
  1992   by (fact inf.assoc [symmetric])
  1993 
  1994 lemma multiset_inter_left_commute: "A #\<inter> (B #\<inter> C) = B #\<inter> (A #\<inter> C)"
  1995   by (fact inf.left_commute)
  1996 
  1997 lemmas multiset_inter_ac =
  1998   multiset_inter_commute
  1999   multiset_inter_assoc
  2000   multiset_inter_left_commute
  2001 
  2002 lemma mult_less_not_refl:
  2003   "\<not> M \<subset># (M::'a::order multiset)"
  2004   by (fact multiset_order.less_irrefl)
  2005 
  2006 lemma mult_less_trans:
  2007   "K \<subset># M ==> M \<subset># N ==> K \<subset># (N::'a::order multiset)"
  2008   by (fact multiset_order.less_trans)
  2009     
  2010 lemma mult_less_not_sym:
  2011   "M \<subset># N ==> \<not> N \<subset># (M::'a::order multiset)"
  2012   by (fact multiset_order.less_not_sym)
  2013 
  2014 lemma mult_less_asym:
  2015   "M \<subset># N ==> (\<not> P ==> N \<subset># (M::'a::order multiset)) ==> P"
  2016   by (fact multiset_order.less_asym)
  2017 
  2018 ML {*
  2019 fun multiset_postproc _ maybe_name all_values (T as Type (_, [elem_T]))
  2020                       (Const _ $ t') =
  2021     let
  2022       val (maybe_opt, ps) =
  2023         Nitpick_Model.dest_plain_fun t' ||> op ~~
  2024         ||> map (apsnd (snd o HOLogic.dest_number))
  2025       fun elems_for t =
  2026         case AList.lookup (op =) ps t of
  2027           SOME n => replicate n t
  2028         | NONE => [Const (maybe_name, elem_T --> elem_T) $ t]
  2029     in
  2030       case maps elems_for (all_values elem_T) @
  2031            (if maybe_opt then [Const (Nitpick_Model.unrep (), elem_T)]
  2032             else []) of
  2033         [] => Const (@{const_name zero_class.zero}, T)
  2034       | ts => foldl1 (fn (t1, t2) =>
  2035                          Const (@{const_name plus_class.plus}, T --> T --> T)
  2036                          $ t1 $ t2)
  2037                      (map (curry (op $) (Const (@{const_name single},
  2038                                                 elem_T --> T))) ts)
  2039     end
  2040   | multiset_postproc _ _ _ _ t = t
  2041 *}
  2042 
  2043 declaration {*
  2044 Nitpick_Model.register_term_postprocessor @{typ "'a multiset"}
  2045     multiset_postproc
  2046 *}
  2047 
  2048 end